@mostra/server 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # @mostra/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ What a Mostra artifact's server code imports: who a call is for, progress and log lines for the
4
+ page, named secrets, signals and host events, the artifact's shared state, cancellation, and live
5
+ sources. It works inside the artifact's worker, which Mostra starts for every version with
6
+ `"use server"` modules or a `live.ts`; it needs no installation in the artifact.
7
+
8
+ ```ts
9
+ "use server";
10
+ import { abortSignal, progress, secret, signal } from "@mostra/server";
11
+
12
+ export async function sendReply(messageId: string, body: string) {
13
+ progress({ message: "Sending…" });
14
+ const response = await fetch("https://mail.example/api/send", {
15
+ method: "POST",
16
+ headers: { authorization: `Bearer ${secret("MAIL_TOKEN")}`, "idempotency-key": messageId },
17
+ body: JSON.stringify({ messageId, body }),
18
+ signal: abortSignal,
19
+ });
20
+ if (!response.ok) throw new Error(`Mail API returned ${response.status}`);
21
+ signal("reply-sent", { messageId });
22
+ return { sent: true };
23
+ }
24
+ ```
25
+
26
+ Part of [Mostra](https://github.com/mostra-dev/mostra), the agent artifact runtime. Apache-2.0.
package/dist/host.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { a as parseDuration, i as liveSourceOptions, n as LiveSourceOptions } from "./live-BLUwPFXE.js";
2
+ import { FieldOp, MutationResult } from "@mostra/protocol";
3
+ //#region src/context.d.ts
4
+ /** One call as server code sees it. */
5
+ interface ServerCallContext {
6
+ /** `call`: a plain call, no durable record. `run`: an action run (D54). */
7
+ readonly kind: "call" | "run";
8
+ /** The channel's ID of the call: progress, logs and signals name it. */
9
+ readonly callId: string;
10
+ /** The action run, for `kind: "run"`. */
11
+ readonly runId?: string;
12
+ /** Who the call is for. */
13
+ readonly viewer?: {
14
+ readonly id: string;
15
+ readonly name?: string;
16
+ };
17
+ /** True only during `verify`'s smoke test (D55). */
18
+ readonly dryRun: boolean;
19
+ /** Aborted when the run is cancelled or the caller goes away (AC-04). */
20
+ readonly signal: AbortSignal;
21
+ }
22
+ /** The artifact's shared state as the supervisor answers it. */
23
+ interface StateSnapshot {
24
+ /** The state document's revision. */
25
+ readonly revision: string;
26
+ /** Its fields by ID. */
27
+ readonly fields: Readonly<Record<string, {
28
+ readonly value?: unknown;
29
+ readonly deleted?: boolean;
30
+ }>>;
31
+ }
32
+ /** What `@mostra/server` needs from the process it runs in: the worker implements it. */
33
+ interface ServerHost {
34
+ /** The secret's value; throws an error with `code: "MOSTRA_SECRET_MISSING"` when there is none. */
35
+ secret(name: string): string;
36
+ /** Reports a call's progress. */
37
+ progress(callId: string, progress: {
38
+ fraction?: number;
39
+ message?: string;
40
+ }): void;
41
+ /** Adds a line to a call's log, or to the worker's own outside calls. */
42
+ log(callId: string | undefined, line: string): void;
43
+ /** Raises a signal (already checked). */
44
+ signal(callId: string | undefined, name: string, payload: unknown): void;
45
+ /** Appends a host event (already checked). */
46
+ emit(callId: string | undefined, type: string, payload: unknown): void;
47
+ /** Reads the artifact's shared state. */
48
+ stateGet(ids: readonly string[] | undefined): Promise<StateSnapshot>;
49
+ /** Writes the artifact's shared state as the agent. */
50
+ statePatch(callId: string | undefined, ops: readonly FieldOp[], options: {
51
+ readonly mutationId?: string;
52
+ readonly baseRevision?: string;
53
+ }): Promise<MutationResult>;
54
+ }
55
+ /** Installs the process's {@link ServerHost}; the worker calls it once, before loading code. */
56
+ export declare function installServerHost(host: ServerHost): void;
57
+ /** The current call, or `undefined` outside any (module scope, a timer started at load). */
58
+ export declare function currentCall(): ServerCallContext | undefined;
59
+ /** Runs `fn` as `context`: everything it awaits sees the same call. */
60
+ export declare function runWithContext<T>(context: ServerCallContext, fn: () => T): T;
61
+ //#endregion
62
+ export { type LiveSourceOptions, type ServerCallContext, type ServerHost, type StateSnapshot, liveSourceOptions, parseDuration };
63
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","names":[],"sources":["../src/context.ts"],"mappings":";;;;UAUiB;;WAEN;;WAEA;;WAEA;;WAEA;aAAoB;aAAqB;;;WAEzC;;WAEA,QAAQ;;;UAIF;;WAEN;;WAEA,QAAQ,SACf;aAA0B;aAA0B;;;;UAKvC;;EAEf,OAAO;;EAEP,SAAS,gBAAgB;IAAY;IAAmB;;;EAExD,IAAI,4BAA4B;;EAEhC,OAAO,4BAA4B,cAAc;;EAEjD,KAAK,4BAA4B,cAAc;;EAE/C,SAAS,qCAAqC,QAAQ;;EAEtD,WACE,4BACA,cAAc,WACd;aAAoB;aAA8B;MACjD,QAAQ;;;wBAOG,kBAAkB,MAAM;;wBAkBxB,eAAe;;wBAKf,eAAe,GAAG,SAAS,mBAAmB,UAAU,IAAI"}
package/dist/host.js ADDED
@@ -0,0 +1,2 @@
1
+ import { a as installServerHost, i as currentCall, n as liveSourceOptions, o as runWithContext, r as parseDuration } from "./live-2VU8jmOO.js";
2
+ export { currentCall, installServerHost, liveSourceOptions, parseDuration, runWithContext };
@@ -0,0 +1,95 @@
1
+ import { n as LiveSourceOptions, r as defineLive, t as LiveSource } from "./live-BLUwPFXE.js";
2
+ //#region src/index.d.ts
3
+ /** Any JSON value. */
4
+ export type Json = string | number | boolean | null | Json[] | {
5
+ [key: string]: Json;
6
+ };
7
+ /** An error with a Mostra diagnostic code, as `@mostra/server` throws them. */
8
+ export declare class MostraServerError extends Error {
9
+ /** The diagnostic code, such as `MOSTRA_SECRET_MISSING`. */
10
+ readonly code: string;
11
+ constructor(code: string, message: string);
12
+ }
13
+ /**
14
+ * Whether this call is `verify`'s smoke test (D55). An action that checks it opts into the smoke
15
+ * test, and should then return without real effects; one that never calls it is skipped there.
16
+ */
17
+ export declare function dryRun(): boolean;
18
+ /** Reports the run's progress to every page following it (ephemeral, never an event). */
19
+ export declare function progress(p: {
20
+ fraction?: number;
21
+ message?: string;
22
+ }): void;
23
+ /**
24
+ * Adds a line to the run's log (kept with the run, capped at 1 MB, D47); outside a run, to the
25
+ * worker's own log. Secrets are redacted from it.
26
+ */
27
+ export declare function log(line: string): void;
28
+ /**
29
+ * A secret's value, by name (D44): from the host's `secrets` port, the artifact's own secrets or
30
+ * the home's shared ones. Never put the value in a result, a log or a signal.
31
+ *
32
+ * @throws MostraServerError `MOSTRA_SECRET_MISSING` when no store holds it.
33
+ */
34
+ export declare function secret(name: string): string;
35
+ /**
36
+ * Raises a named signal for the host's attention (IN-09): one durable `signal.raised` event with
37
+ * `source: "action"` and this run as its causation. Mostra wakes no one by itself (D10).
38
+ *
39
+ * @throws MostraServerError `MOSTRA_SUBMIT_SIGNAL_INVALID` for a bad name or a payload over 64 KiB.
40
+ */
41
+ export declare function signal(name: string, payload?: Json): void;
42
+ /**
43
+ * Appends a host event, `host.<name>`, to the event log (AC-05), which hosts filter for.
44
+ *
45
+ * @throws MostraServerError `MOSTRA_ACTION_EVENT_INVALID` for a bad type or a payload over 64 KiB.
46
+ */
47
+ export declare function emit(type: `host.${string}`, payload?: Json): void;
48
+ /** Who the call is for; `undefined` in live producers and outside calls. */
49
+ export declare function viewer(): {
50
+ id: string;
51
+ name?: string;
52
+ } | undefined;
53
+ /**
54
+ * The current call's cancellation (AC-04): aborted when a page cancels the run or the caller goes
55
+ * away. Pass it to `fetch` and other cancellable work. Outside a call it never aborts. Listeners
56
+ * added to it run in the call that added them, so they read `abortSignal.reason` of that call.
57
+ */
58
+ export declare const abortSignal: AbortSignal;
59
+ /** Options of a state write. */
60
+ export interface StateWriteOptions {
61
+ /** The change's ID: a retry with the same ID and contents returns the recorded result. */
62
+ readonly mutationId?: string;
63
+ /** The revision you read: a field changed after it is a conflict and keeps its value. */
64
+ readonly baseRevision?: string;
65
+ }
66
+ /** The artifact's shared state, as server code reads and writes it. */
67
+ export interface ServerState {
68
+ /** A field's value, or `undefined` when it isn't set. */
69
+ get<T>(id: string): Promise<T | undefined>;
70
+ /**
71
+ * Sets one field.
72
+ *
73
+ * @throws MostraServerError `MOSTRA_FIELD_CONFLICT` when the field changed after `baseRevision`.
74
+ */
75
+ set<T>(id: string, value: T, options?: StateWriteOptions): Promise<{
76
+ revision: string;
77
+ }>;
78
+ /** Sets and deletes several fields under one revision; conflicting ones are listed. */
79
+ patch(ops: readonly {
80
+ id: string;
81
+ value?: Json;
82
+ delete?: true;
83
+ }[], options?: StateWriteOptions): Promise<{
84
+ revision: string;
85
+ conflicts: string[];
86
+ }>;
87
+ }
88
+ /**
89
+ * The artifact's shared state (D63): the artifact-scoped fields every viewer sees, written through
90
+ * the same compare-and-set as viewers' edits, as the agent. Each write appends `state.changed`.
91
+ */
92
+ export declare const state: ServerState;
93
+ //#endregion
94
+ export { type LiveSource, type LiveSourceOptions, defineLive };
95
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;YAmCY,0CAA0C;GAA0B,cAAA;;;qBAGnE,0BAA0B;;WAE5B;EACT,YAAY,cAAc;;;;;;wBA0BZ;;wBAKA,SAAS;EAAK;EAAmB;;;;;;wBAcjC,IAAI;;;;;;;wBAUJ,OAAO;;;;;;;wBAUP,OAAO,cAAc,UAAU;;;;;;wBAgB/B,KAAK,wBAAwB,UAAU;;wBAavC;EAAY;EAAY;;;;;;;qBAyC3B,aAAa;;iBA8BT;;WAEN;;WAEA;;;iBAIM;;EAEf,IAAI,GAAG,aAAa,QAAQ;;;;;;EAM5B,IAAI,GAAG,YAAY,OAAO,GAAG,UAAU,oBAAoB;IAAU;;;EAErE,MACE;IAAgB;IAAY,QAAQ;IAAM;OAC1C,UAAU,oBACT;IAAU;IAAkB;;;;;;;qBAOpB,OAAO"}
package/dist/index.js ADDED
@@ -0,0 +1,195 @@
1
+ import { i as currentCall, s as serverHost, t as defineLive } from "./live-2VU8jmOO.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { SIGNAL_NAME_PATTERN, canonicalJson } from "@mostra/protocol";
4
+ //#region src/index.ts
5
+ /**
6
+ * `@mostra/server`: what server code imports (INTERFACES §2.4). Inside `"use server"` functions and
7
+ * live sources, it tells who the call is for, reports progress and log lines to the page, reads
8
+ * secrets, raises signals and host events, and reads and writes the artifact's shared state.
9
+ * Server code runs with full capability (D05, AC-01): it can read files, start processes and call
10
+ * any network service; this package only adds what Mostra knows.
11
+ *
12
+ * ```ts
13
+ * "use server";
14
+ * import { abortSignal, dryRun, progress, secret, signal } from "@mostra/server";
15
+ *
16
+ * export async function sendReply(messageId: string, body: string) {
17
+ * if (dryRun()) return { messageId, sent: false };
18
+ * progress({ message: "Sending…" });
19
+ * const response = await fetch("https://mail.example/api/send", {
20
+ * method: "POST",
21
+ * headers: { authorization: `Bearer ${secret("MAIL_TOKEN")}`, "idempotency-key": messageId },
22
+ * body: JSON.stringify({ messageId, body }),
23
+ * signal: abortSignal,
24
+ * });
25
+ * if (!response.ok) throw new Error(`Mail API returned ${response.status}`);
26
+ * signal("reply-sent", { messageId });
27
+ * return { messageId, sent: true };
28
+ * }
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ /** An error with a Mostra diagnostic code, as `@mostra/server` throws them. */
34
+ var MostraServerError = class extends Error {
35
+ /** The diagnostic code, such as `MOSTRA_SECRET_MISSING`. */
36
+ code;
37
+ constructor(code, message) {
38
+ super(message);
39
+ this.name = "MostraServerError";
40
+ this.code = code;
41
+ }
42
+ };
43
+ const PAYLOAD_MAX = 65536;
44
+ function checkPayload(code, what, payload) {
45
+ if (payload === void 0) return;
46
+ let text;
47
+ try {
48
+ text = canonicalJson(payload);
49
+ } catch {
50
+ throw new MostraServerError(code, `The payload of ${what} isn't JSON.`);
51
+ }
52
+ if (Buffer.byteLength(text, "utf8") > PAYLOAD_MAX) throw new MostraServerError(code, `The payload of ${what} is larger than 64 KiB of JSON.`);
53
+ }
54
+ /**
55
+ * Whether this call is `verify`'s smoke test (D55). An action that checks it opts into the smoke
56
+ * test, and should then return without real effects; one that never calls it is skipped there.
57
+ */
58
+ function dryRun() {
59
+ return currentCall()?.dryRun ?? false;
60
+ }
61
+ /** Reports the run's progress to every page following it (ephemeral, never an event). */
62
+ function progress(p) {
63
+ const call = currentCall();
64
+ if (!call) return;
65
+ const fraction = p.fraction === void 0 ? void 0 : Math.min(1, Math.max(0, p.fraction));
66
+ serverHost().progress(call.callId, {
67
+ ...fraction === void 0 || Number.isNaN(fraction) ? {} : { fraction },
68
+ ...p.message === void 0 ? {} : { message: String(p.message).slice(0, 1e3) }
69
+ });
70
+ }
71
+ /**
72
+ * Adds a line to the run's log (kept with the run, capped at 1 MB, D47); outside a run, to the
73
+ * worker's own log. Secrets are redacted from it.
74
+ */
75
+ function log(line) {
76
+ serverHost().log(currentCall()?.callId, String(line));
77
+ }
78
+ /**
79
+ * A secret's value, by name (D44): from the host's `secrets` port, the artifact's own secrets or
80
+ * the home's shared ones. Never put the value in a result, a log or a signal.
81
+ *
82
+ * @throws MostraServerError `MOSTRA_SECRET_MISSING` when no store holds it.
83
+ */
84
+ function secret(name) {
85
+ return serverHost().secret(name);
86
+ }
87
+ /**
88
+ * Raises a named signal for the host's attention (IN-09): one durable `signal.raised` event with
89
+ * `source: "action"` and this run as its causation. Mostra wakes no one by itself (D10).
90
+ *
91
+ * @throws MostraServerError `MOSTRA_SUBMIT_SIGNAL_INVALID` for a bad name or a payload over 64 KiB.
92
+ */
93
+ function signal(name, payload) {
94
+ if (typeof name !== "string" || !SIGNAL_NAME_PATTERN.test(name) || name === "submit") throw new MostraServerError("MOSTRA_SUBMIT_SIGNAL_INVALID", `${JSON.stringify(name).slice(0, 80)} isn't a signal name: 1 to 64 letters, digits, ".", "_" and "-", and not "submit".`);
95
+ checkPayload("MOSTRA_SUBMIT_SIGNAL_INVALID", `the signal ${name}`, payload);
96
+ serverHost().signal(currentCall()?.callId, name, payload);
97
+ }
98
+ /**
99
+ * Appends a host event, `host.<name>`, to the event log (AC-05), which hosts filter for.
100
+ *
101
+ * @throws MostraServerError `MOSTRA_ACTION_EVENT_INVALID` for a bad type or a payload over 64 KiB.
102
+ */
103
+ function emit(type, payload) {
104
+ const name = typeof type === "string" && type.startsWith("host.") ? type.slice(5) : "";
105
+ if (!SIGNAL_NAME_PATTERN.test(name)) throw new MostraServerError("MOSTRA_ACTION_EVENT_INVALID", `${JSON.stringify(type).slice(0, 80)} isn't a host event type: "host." and 1 to 64 letters, digits, ".", "_" and "-".`);
106
+ checkPayload("MOSTRA_ACTION_EVENT_INVALID", `the event ${type}`, payload);
107
+ serverHost().emit(currentCall()?.callId, type, payload);
108
+ }
109
+ /** Who the call is for; `undefined` in live producers and outside calls. */
110
+ function viewer() {
111
+ const who = currentCall()?.viewer;
112
+ return who ? { ...who } : void 0;
113
+ }
114
+ const idle = new AbortController().signal;
115
+ /**
116
+ * The bound copies of listeners, per signal: each call has its own signal, so a listener added in
117
+ * two calls (a module-level callback, say) gets a copy bound to each call's context, and removing
118
+ * it from one call's signal finds that call's copy.
119
+ */
120
+ const boundListeners = /* @__PURE__ */ new WeakMap();
121
+ /** A listener that runs in the call it was added in, as `await`ed code does. */
122
+ function bindListener(target, listener) {
123
+ if (typeof listener !== "function" && (typeof listener !== "object" || listener === null)) return listener;
124
+ let perSignal = boundListeners.get(target);
125
+ if (!perSignal) {
126
+ perSignal = /* @__PURE__ */ new WeakMap();
127
+ boundListeners.set(target, perSignal);
128
+ }
129
+ let bound = perSignal.get(listener);
130
+ if (!bound) {
131
+ const handle = typeof listener === "function" ? listener : (event) => listener.handleEvent(event);
132
+ bound = AsyncLocalStorage.bind(handle);
133
+ perSignal.set(listener, bound);
134
+ }
135
+ return bound;
136
+ }
137
+ /**
138
+ * The current call's cancellation (AC-04): aborted when a page cancels the run or the caller goes
139
+ * away. Pass it to `fetch` and other cancellable work. Outside a call it never aborts. Listeners
140
+ * added to it run in the call that added them, so they read `abortSignal.reason` of that call.
141
+ */
142
+ const abortSignal = new Proxy(idle, {
143
+ get(_target, property) {
144
+ const target = currentCall()?.signal ?? idle;
145
+ if (property === "addEventListener" || property === "removeEventListener") {
146
+ const method = target[property].bind(target);
147
+ return (type, listener, options) => method(type, bindListener(target, listener), options);
148
+ }
149
+ const value = Reflect.get(target, property, target);
150
+ return typeof value === "function" ? value.bind(target) : value;
151
+ },
152
+ set(_target, property, value) {
153
+ const target = currentCall()?.signal ?? idle;
154
+ return Reflect.set(target, property, property === "onabort" ? bindListener(target, value) : value, target);
155
+ },
156
+ has(_target, property) {
157
+ return Reflect.has(currentCall()?.signal ?? idle, property);
158
+ }
159
+ });
160
+ /**
161
+ * The artifact's shared state (D63): the artifact-scoped fields every viewer sees, written through
162
+ * the same compare-and-set as viewers' edits, as the agent. Each write appends `state.changed`.
163
+ */
164
+ const state = {
165
+ async get(id) {
166
+ const field = (await serverHost().stateGet([id])).fields[id];
167
+ return field && !field.deleted ? field.value : void 0;
168
+ },
169
+ async set(id, value, options = {}) {
170
+ const result = await serverHost().statePatch(currentCall()?.callId, [{
171
+ id,
172
+ value
173
+ }], options);
174
+ if (result.conflicts.length > 0) throw new MostraServerError("MOSTRA_FIELD_CONFLICT", `The state field ${id} changed after revision ${options.baseRevision ?? "?"}; read it again and decide.`);
175
+ return { revision: result.revision };
176
+ },
177
+ async patch(ops, options = {}) {
178
+ const fieldOps = ops.map((op) => op.delete ? {
179
+ id: op.id,
180
+ delete: true
181
+ } : {
182
+ id: op.id,
183
+ value: op.value
184
+ });
185
+ const result = await serverHost().statePatch(currentCall()?.callId, fieldOps, options);
186
+ return {
187
+ revision: result.revision,
188
+ conflicts: result.conflicts.map((conflict) => conflict.id)
189
+ };
190
+ }
191
+ };
192
+ //#endregion
193
+ export { MostraServerError, abortSignal, defineLive, dryRun, emit, log, progress, secret, signal, state, viewer };
194
+
195
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `@mostra/server`: what server code imports (INTERFACES §2.4). Inside `\"use server\"` functions and\n * live sources, it tells who the call is for, reports progress and log lines to the page, reads\n * secrets, raises signals and host events, and reads and writes the artifact's shared state.\n * Server code runs with full capability (D05, AC-01): it can read files, start processes and call\n * any network service; this package only adds what Mostra knows.\n *\n * ```ts\n * \"use server\";\n * import { abortSignal, dryRun, progress, secret, signal } from \"@mostra/server\";\n *\n * export async function sendReply(messageId: string, body: string) {\n * if (dryRun()) return { messageId, sent: false };\n * progress({ message: \"Sending…\" });\n * const response = await fetch(\"https://mail.example/api/send\", {\n * method: \"POST\",\n * headers: { authorization: `Bearer ${secret(\"MAIL_TOKEN\")}`, \"idempotency-key\": messageId },\n * body: JSON.stringify({ messageId, body }),\n * signal: abortSignal,\n * });\n * if (!response.ok) throw new Error(`Mail API returned ${response.status}`);\n * signal(\"reply-sent\", { messageId });\n * return { messageId, sent: true };\n * }\n * ```\n *\n * @packageDocumentation\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { canonicalJson, type FieldOp, SIGNAL_NAME_PATTERN } from \"@mostra/protocol\";\nimport { currentCall, serverHost } from \"./context.ts\";\n\nexport { defineLive, type LiveSource, type LiveSourceOptions } from \"./live.ts\";\n\n/** Any JSON value. */\nexport type Json = string | number | boolean | null | Json[] | { [key: string]: Json };\n\n/** An error with a Mostra diagnostic code, as `@mostra/server` throws them. */\nexport class MostraServerError extends Error {\n /** The diagnostic code, such as `MOSTRA_SECRET_MISSING`. */\n readonly code: string;\n constructor(code: string, message: string) {\n super(message);\n this.name = \"MostraServerError\";\n this.code = code;\n }\n}\n\nconst PAYLOAD_MAX = 64 * 1024;\n\nfunction checkPayload(code: string, what: string, payload: unknown): void {\n if (payload === undefined) return;\n let text: string;\n try {\n text = canonicalJson(payload);\n } catch {\n throw new MostraServerError(code, `The payload of ${what} isn't JSON.`);\n }\n if (Buffer.byteLength(text, \"utf8\") > PAYLOAD_MAX) {\n throw new MostraServerError(code, `The payload of ${what} is larger than 64 KiB of JSON.`);\n }\n}\n\n/**\n * Whether this call is `verify`'s smoke test (D55). An action that checks it opts into the smoke\n * test, and should then return without real effects; one that never calls it is skipped there.\n */\nexport function dryRun(): boolean {\n return currentCall()?.dryRun ?? false;\n}\n\n/** Reports the run's progress to every page following it (ephemeral, never an event). */\nexport function progress(p: { fraction?: number; message?: string }): void {\n const call = currentCall();\n if (!call) return;\n const fraction = p.fraction === undefined ? undefined : Math.min(1, Math.max(0, p.fraction));\n serverHost().progress(call.callId, {\n ...(fraction === undefined || Number.isNaN(fraction) ? {} : { fraction }),\n ...(p.message === undefined ? {} : { message: String(p.message).slice(0, 1000) }),\n });\n}\n\n/**\n * Adds a line to the run's log (kept with the run, capped at 1 MB, D47); outside a run, to the\n * worker's own log. Secrets are redacted from it.\n */\nexport function log(line: string): void {\n serverHost().log(currentCall()?.callId, String(line));\n}\n\n/**\n * A secret's value, by name (D44): from the host's `secrets` port, the artifact's own secrets or\n * the home's shared ones. Never put the value in a result, a log or a signal.\n *\n * @throws MostraServerError `MOSTRA_SECRET_MISSING` when no store holds it.\n */\nexport function secret(name: string): string {\n return serverHost().secret(name);\n}\n\n/**\n * Raises a named signal for the host's attention (IN-09): one durable `signal.raised` event with\n * `source: \"action\"` and this run as its causation. Mostra wakes no one by itself (D10).\n *\n * @throws MostraServerError `MOSTRA_SUBMIT_SIGNAL_INVALID` for a bad name or a payload over 64 KiB.\n */\nexport function signal(name: string, payload?: Json): void {\n if (typeof name !== \"string\" || !SIGNAL_NAME_PATTERN.test(name) || name === \"submit\") {\n throw new MostraServerError(\n \"MOSTRA_SUBMIT_SIGNAL_INVALID\",\n `${JSON.stringify(name).slice(0, 80)} isn't a signal name: 1 to 64 letters, digits, \".\", \"_\" and \"-\", and not \"submit\".`,\n );\n }\n checkPayload(\"MOSTRA_SUBMIT_SIGNAL_INVALID\", `the signal ${name}`, payload);\n serverHost().signal(currentCall()?.callId, name, payload);\n}\n\n/**\n * Appends a host event, `host.<name>`, to the event log (AC-05), which hosts filter for.\n *\n * @throws MostraServerError `MOSTRA_ACTION_EVENT_INVALID` for a bad type or a payload over 64 KiB.\n */\nexport function emit(type: `host.${string}`, payload?: Json): void {\n const name = typeof type === \"string\" && type.startsWith(\"host.\") ? type.slice(5) : \"\";\n if (!SIGNAL_NAME_PATTERN.test(name)) {\n throw new MostraServerError(\n \"MOSTRA_ACTION_EVENT_INVALID\",\n `${JSON.stringify(type).slice(0, 80)} isn't a host event type: \"host.\" and 1 to 64 letters, digits, \".\", \"_\" and \"-\".`,\n );\n }\n checkPayload(\"MOSTRA_ACTION_EVENT_INVALID\", `the event ${type}`, payload);\n serverHost().emit(currentCall()?.callId, type, payload);\n}\n\n/** Who the call is for; `undefined` in live producers and outside calls. */\nexport function viewer(): { id: string; name?: string } | undefined {\n const who = currentCall()?.viewer;\n return who ? { ...who } : undefined;\n}\n\nconst idle = new AbortController().signal;\n\n/**\n * The bound copies of listeners, per signal: each call has its own signal, so a listener added in\n * two calls (a module-level callback, say) gets a copy bound to each call's context, and removing\n * it from one call's signal finds that call's copy.\n */\nconst boundListeners = new WeakMap<AbortSignal, WeakMap<object, (event: Event) => void>>();\n\n/** A listener that runs in the call it was added in, as `await`ed code does. */\nfunction bindListener(target: AbortSignal, listener: unknown): unknown {\n if (typeof listener !== \"function\" && (typeof listener !== \"object\" || listener === null)) {\n return listener;\n }\n let perSignal = boundListeners.get(target);\n if (!perSignal) {\n perSignal = new WeakMap();\n boundListeners.set(target, perSignal);\n }\n let bound = perSignal.get(listener);\n if (!bound) {\n const handle =\n typeof listener === \"function\"\n ? (listener as (event: Event) => void)\n : (event: Event) => (listener as { handleEvent(event: Event): void }).handleEvent(event);\n bound = AsyncLocalStorage.bind(handle);\n perSignal.set(listener, bound);\n }\n return bound;\n}\n\n/**\n * The current call's cancellation (AC-04): aborted when a page cancels the run or the caller goes\n * away. Pass it to `fetch` and other cancellable work. Outside a call it never aborts. Listeners\n * added to it run in the call that added them, so they read `abortSignal.reason` of that call.\n */\nexport const abortSignal: AbortSignal = new Proxy(idle, {\n get(_target, property) {\n const target = currentCall()?.signal ?? idle;\n if (property === \"addEventListener\" || property === \"removeEventListener\") {\n const method = target[property].bind(target) as (\n type: string,\n listener: unknown,\n options?: unknown,\n ) => void;\n return (type: string, listener: unknown, options?: unknown) =>\n method(type, bindListener(target, listener), options);\n }\n const value: unknown = Reflect.get(target, property, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n set(_target, property, value) {\n const target = currentCall()?.signal ?? idle;\n return Reflect.set(\n target,\n property,\n property === \"onabort\" ? bindListener(target, value) : value,\n target,\n );\n },\n has(_target, property) {\n return Reflect.has(currentCall()?.signal ?? idle, property);\n },\n});\n\n/** Options of a state write. */\nexport interface StateWriteOptions {\n /** The change's ID: a retry with the same ID and contents returns the recorded result. */\n readonly mutationId?: string;\n /** The revision you read: a field changed after it is a conflict and keeps its value. */\n readonly baseRevision?: string;\n}\n\n/** The artifact's shared state, as server code reads and writes it. */\nexport interface ServerState {\n /** A field's value, or `undefined` when it isn't set. */\n get<T>(id: string): Promise<T | undefined>;\n /**\n * Sets one field.\n *\n * @throws MostraServerError `MOSTRA_FIELD_CONFLICT` when the field changed after `baseRevision`.\n */\n set<T>(id: string, value: T, options?: StateWriteOptions): Promise<{ revision: string }>;\n /** Sets and deletes several fields under one revision; conflicting ones are listed. */\n patch(\n ops: readonly { id: string; value?: Json; delete?: true }[],\n options?: StateWriteOptions,\n ): Promise<{ revision: string; conflicts: string[] }>;\n}\n\n/**\n * The artifact's shared state (D63): the artifact-scoped fields every viewer sees, written through\n * the same compare-and-set as viewers' edits, as the agent. Each write appends `state.changed`.\n */\nexport const state: ServerState = {\n async get<T>(id: string): Promise<T | undefined> {\n const snapshot = await serverHost().stateGet([id]);\n const field = snapshot.fields[id];\n return field && !field.deleted ? (field.value as T) : undefined;\n },\n async set<T>(id: string, value: T, options: StateWriteOptions = {}) {\n const result = await serverHost().statePatch(\n currentCall()?.callId,\n [{ id, value } as FieldOp],\n options,\n );\n if (result.conflicts.length > 0) {\n throw new MostraServerError(\n \"MOSTRA_FIELD_CONFLICT\",\n `The state field ${id} changed after revision ${options.baseRevision ?? \"?\"}; read it again and decide.`,\n );\n }\n return { revision: result.revision };\n },\n async patch(ops, options: StateWriteOptions = {}) {\n const fieldOps = ops.map((op) =>\n op.delete\n ? ({ id: op.id, delete: true } as FieldOp)\n : ({ id: op.id, value: op.value } as FieldOp),\n );\n const result = await serverHost().statePatch(currentCall()?.callId, fieldOps, options);\n return {\n revision: result.revision,\n conflicts: result.conflicts.map((conflict) => conflict.id),\n };\n },\n};\n"],"mappings":"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"}
@@ -0,0 +1,64 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ //#region src/context.ts
3
+ /**
4
+ * The request context of server code (D19 seam 3): which call is running, for whom, and how to
5
+ * reach the supervisor. Every call runs inside `AsyncLocalStorage`, so concurrent calls in one
6
+ * worker each see their own viewer, run and `abortSignal` across every `await`. The worker installs
7
+ * the {@link ServerHost} once; this module never does I/O of its own.
8
+ */
9
+ const storage = new AsyncLocalStorage();
10
+ let installed;
11
+ /** Installs the process's {@link ServerHost}; the worker calls it once, before loading code. */
12
+ function installServerHost(host) {
13
+ installed = host;
14
+ }
15
+ /** The installed host, or an error naming where server code must run. */
16
+ function serverHost() {
17
+ if (!installed) throw Object.assign(/* @__PURE__ */ new Error("@mostra/server works only inside an artifact's worker: call it from a \"use server\" function or a live source."), { code: "MOSTRA_TARGET_UNAVAILABLE" });
18
+ return installed;
19
+ }
20
+ /** The current call, or `undefined` outside any (module scope, a timer started at load). */
21
+ function currentCall() {
22
+ return storage.getStore();
23
+ }
24
+ /** Runs `fn` as `context`: everything it awaits sees the same call. */
25
+ function runWithContext(context, fn) {
26
+ return storage.run(context, fn);
27
+ }
28
+ //#endregion
29
+ //#region src/live.ts
30
+ /**
31
+ * Declares a live source (D56). Export it from `live.ts`; its export name is its key.
32
+ *
33
+ * ```ts
34
+ * export const inbox = defineLive({ refresh: "5m", load: async () => fetchInbox() });
35
+ * export const prices = defineLive({ stream: (signal) => tickerFeed(signal), ring: 3600 });
36
+ * ```
37
+ */
38
+ function defineLive(source) {
39
+ if (!source.load && !source.stream) throw new TypeError("defineLive needs a load function, a stream function, or both.");
40
+ if (source.refresh !== void 0) parseDuration(source.refresh);
41
+ if (source.ring !== void 0 && (!Number.isInteger(source.ring) || source.ring < 1)) throw new TypeError("defineLive's ring is the number of values to keep: a positive integer.");
42
+ return { "~mostra.live": source };
43
+ }
44
+ /** The options of a live source, or `undefined` for anything `defineLive` didn't make. */
45
+ function liveSourceOptions(value) {
46
+ if (typeof value !== "object" || value === null) return void 0;
47
+ const options = value["~mostra.live"];
48
+ return typeof options === "object" && options !== null ? options : void 0;
49
+ }
50
+ /** `"5s"`, `"10m"`, `"24h"` → milliseconds; from 1 s to 24 h. */
51
+ function parseDuration(text) {
52
+ const match = /^(\d+)(s|m|h)$/.exec(text);
53
+ const ms = match ? Number(match[1]) * {
54
+ s: 1e3,
55
+ m: 6e4,
56
+ h: 36e5
57
+ }[match[2]] : NaN;
58
+ if (!(ms >= 1e3 && ms <= 864e5)) throw new TypeError(`defineLive's refresh is a duration from "1s" to "24h", such as "30s" or "5m"; got ${JSON.stringify(text)}.`);
59
+ return ms;
60
+ }
61
+ //#endregion
62
+ export { installServerHost as a, currentCall as i, liveSourceOptions as n, runWithContext as o, parseDuration as r, serverHost as s, defineLive as t };
63
+
64
+ //# sourceMappingURL=live-2VU8jmOO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-2VU8jmOO.js","names":[],"sources":["../src/context.ts","../src/live.ts"],"sourcesContent":["/**\n * The request context of server code (D19 seam 3): which call is running, for whom, and how to\n * reach the supervisor. Every call runs inside `AsyncLocalStorage`, so concurrent calls in one\n * worker each see their own viewer, run and `abortSignal` across every `await`. The worker installs\n * the {@link ServerHost} once; this module never does I/O of its own.\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { FieldOp, MutationResult } from \"@mostra/protocol\";\n\n/** One call as server code sees it. */\nexport interface ServerCallContext {\n /** `call`: a plain call, no durable record. `run`: an action run (D54). */\n readonly kind: \"call\" | \"run\";\n /** The channel's ID of the call: progress, logs and signals name it. */\n readonly callId: string;\n /** The action run, for `kind: \"run\"`. */\n readonly runId?: string;\n /** Who the call is for. */\n readonly viewer?: { readonly id: string; readonly name?: string };\n /** True only during `verify`'s smoke test (D55). */\n readonly dryRun: boolean;\n /** Aborted when the run is cancelled or the caller goes away (AC-04). */\n readonly signal: AbortSignal;\n}\n\n/** The artifact's shared state as the supervisor answers it. */\nexport interface StateSnapshot {\n /** The state document's revision. */\n readonly revision: string;\n /** Its fields by ID. */\n readonly fields: Readonly<\n Record<string, { readonly value?: unknown; readonly deleted?: boolean }>\n >;\n}\n\n/** What `@mostra/server` needs from the process it runs in: the worker implements it. */\nexport interface ServerHost {\n /** The secret's value; throws an error with `code: \"MOSTRA_SECRET_MISSING\"` when there is none. */\n secret(name: string): string;\n /** Reports a call's progress. */\n progress(callId: string, progress: { fraction?: number; message?: string }): void;\n /** Adds a line to a call's log, or to the worker's own outside calls. */\n log(callId: string | undefined, line: string): void;\n /** Raises a signal (already checked). */\n signal(callId: string | undefined, name: string, payload: unknown): void;\n /** Appends a host event (already checked). */\n emit(callId: string | undefined, type: string, payload: unknown): void;\n /** Reads the artifact's shared state. */\n stateGet(ids: readonly string[] | undefined): Promise<StateSnapshot>;\n /** Writes the artifact's shared state as the agent. */\n statePatch(\n callId: string | undefined,\n ops: readonly FieldOp[],\n options: { readonly mutationId?: string; readonly baseRevision?: string },\n ): Promise<MutationResult>;\n}\n\nconst storage = new AsyncLocalStorage<ServerCallContext>();\nlet installed: ServerHost | undefined;\n\n/** Installs the process's {@link ServerHost}; the worker calls it once, before loading code. */\nexport function installServerHost(host: ServerHost): void {\n installed = host;\n}\n\n/** The installed host, or an error naming where server code must run. */\nexport function serverHost(): ServerHost {\n if (!installed) {\n throw Object.assign(\n new Error(\n '@mostra/server works only inside an artifact\\'s worker: call it from a \"use server\" function or a live source.',\n ),\n { code: \"MOSTRA_TARGET_UNAVAILABLE\" },\n );\n }\n return installed;\n}\n\n/** The current call, or `undefined` outside any (module scope, a timer started at load). */\nexport function currentCall(): ServerCallContext | undefined {\n return storage.getStore();\n}\n\n/** Runs `fn` as `context`: everything it awaits sees the same call. */\nexport function runWithContext<T>(context: ServerCallContext, fn: () => T): T {\n return storage.run(context, fn);\n}\n","/**\n * Live sources (D56): `live.ts` exports `defineLive(…)` producers, which the artifact's worker runs\n * while someone views them, a host subscribes, or always with `always: true` (D63).\n */\n\n/** How a live source produces its values. */\nexport interface LiveSourceOptions<T> {\n /** Loads the current value: on start, on every `refresh`, and when a `watch`ed file changes. */\n readonly load?: () => Promise<T>;\n /** How often `load` runs again: `\"5s\"` to `\"24h\"` (`s`, `m` or `h`). */\n readonly refresh?: string;\n /** Files whose changes run `load` again: globs relative to the artifact's source. */\n readonly watch?: string | readonly string[];\n /** Produces values as they come; `signal` aborts when the source stops. */\n readonly stream?: (signal: AbortSignal) => AsyncIterable<T>;\n /** Keep producing while nobody views the artifact (D63). */\n readonly always?: boolean;\n /** Keep the last N values for append mode (`useLive(key, { mode: \"append\" })`, AC-08). */\n readonly ring?: number;\n}\n\n/** A live source, as `defineLive` returns it. Pages read it with `useLive(key)`. */\nexport interface LiveSource<T> {\n /** The source's options, for the worker. */\n readonly \"~mostra.live\": LiveSourceOptions<T>;\n /** The value type, for `useLive`'s types (never set at run time). */\n readonly __value?: T;\n}\n\n/**\n * Declares a live source (D56). Export it from `live.ts`; its export name is its key.\n *\n * ```ts\n * export const inbox = defineLive({ refresh: \"5m\", load: async () => fetchInbox() });\n * export const prices = defineLive({ stream: (signal) => tickerFeed(signal), ring: 3600 });\n * ```\n */\nexport function defineLive<T>(source: LiveSourceOptions<T>): LiveSource<T> {\n if (!source.load && !source.stream) {\n throw new TypeError(\"defineLive needs a load function, a stream function, or both.\");\n }\n if (source.refresh !== undefined) parseDuration(source.refresh);\n if (source.ring !== undefined && (!Number.isInteger(source.ring) || source.ring < 1)) {\n throw new TypeError(\"defineLive's ring is the number of values to keep: a positive integer.\");\n }\n return { \"~mostra.live\": source };\n}\n\n/** The options of a live source, or `undefined` for anything `defineLive` didn't make. */\nexport function liveSourceOptions(value: unknown): LiveSourceOptions<unknown> | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const options = (value as { \"~mostra.live\"?: unknown })[\"~mostra.live\"];\n return typeof options === \"object\" && options !== null\n ? (options as LiveSourceOptions<unknown>)\n : undefined;\n}\n\n/** `\"5s\"`, `\"10m\"`, `\"24h\"` → milliseconds; from 1 s to 24 h. */\nexport function parseDuration(text: string): number {\n const match = /^(\\d+)(s|m|h)$/.exec(text);\n const unit = { s: 1_000, m: 60_000, h: 3_600_000 } as const;\n const ms = match ? Number(match[1]) * unit[match[2] as keyof typeof unit] : Number.NaN;\n if (!(ms >= 1_000 && ms <= 86_400_000)) {\n throw new TypeError(\n `defineLive's refresh is a duration from \"1s\" to \"24h\", such as \"30s\" or \"5m\"; got ${JSON.stringify(text)}.`,\n );\n }\n return ms;\n}\n"],"mappings":";;;;;;;;AAyDA,MAAM,UAAU,IAAI,kBAAqC;AACzD,IAAI;;AAGJ,SAAgB,kBAAkB,MAAwB;CACxD,YAAY;AACd;;AAGA,SAAgB,aAAyB;CACvC,IAAI,CAAC,WACH,MAAM,OAAO,uBACX,IAAI,MACF,iHACF,GACA,EAAE,MAAM,4BAA4B,CACtC;CAEF,OAAO;AACT;;AAGA,SAAgB,cAA6C;CAC3D,OAAO,QAAQ,SAAS;AAC1B;;AAGA,SAAgB,eAAkB,SAA4B,IAAgB;CAC5E,OAAO,QAAQ,IAAI,SAAS,EAAE;AAChC;;;;;;;;;;;ACjDA,SAAgB,WAAc,QAA6C;CACzE,IAAI,CAAC,OAAO,QAAQ,CAAC,OAAO,QAC1B,MAAM,IAAI,UAAU,+DAA+D;CAErF,IAAI,OAAO,YAAY,KAAA,GAAW,cAAc,OAAO,OAAO;CAC9D,IAAI,OAAO,SAAS,KAAA,MAAc,CAAC,OAAO,UAAU,OAAO,IAAI,KAAK,OAAO,OAAO,IAChF,MAAM,IAAI,UAAU,wEAAwE;CAE9F,OAAO,EAAE,gBAAgB,OAAO;AAClC;;AAGA,SAAgB,kBAAkB,OAAwD;CACxF,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,UAAW,MAAuC;CACxD,OAAO,OAAO,YAAY,YAAY,YAAY,OAC7C,UACD,KAAA;AACN;;AAGA,SAAgB,cAAc,MAAsB;CAClD,MAAM,QAAQ,iBAAiB,KAAK,IAAI;CAExC,MAAM,KAAK,QAAQ,OAAO,MAAM,EAAE,IAAI;EADvB,GAAG;EAAO,GAAG;EAAQ,GAAG;CACE,EAAE,MAAM,MAA2B;CAC5E,IAAI,EAAE,MAAM,OAAS,MAAM,QACzB,MAAM,IAAI,UACR,qFAAqF,KAAK,UAAU,IAAI,EAAE,EAC5G;CAEF,OAAO;AACT"}
@@ -0,0 +1,43 @@
1
+ //#region src/live.d.ts
2
+ /**
3
+ * Live sources (D56): `live.ts` exports `defineLive(…)` producers, which the artifact's worker runs
4
+ * while someone views them, a host subscribes, or always with `always: true` (D63).
5
+ */
6
+ /** How a live source produces its values. */
7
+ interface LiveSourceOptions<T> {
8
+ /** Loads the current value: on start, on every `refresh`, and when a `watch`ed file changes. */
9
+ readonly load?: () => Promise<T>;
10
+ /** How often `load` runs again: `"5s"` to `"24h"` (`s`, `m` or `h`). */
11
+ readonly refresh?: string;
12
+ /** Files whose changes run `load` again: globs relative to the artifact's source. */
13
+ readonly watch?: string | readonly string[];
14
+ /** Produces values as they come; `signal` aborts when the source stops. */
15
+ readonly stream?: (signal: AbortSignal) => AsyncIterable<T>;
16
+ /** Keep producing while nobody views the artifact (D63). */
17
+ readonly always?: boolean;
18
+ /** Keep the last N values for append mode (`useLive(key, { mode: "append" })`, AC-08). */
19
+ readonly ring?: number;
20
+ }
21
+ /** A live source, as `defineLive` returns it. Pages read it with `useLive(key)`. */
22
+ interface LiveSource<T> {
23
+ /** The source's options, for the worker. */
24
+ readonly "~mostra.live": LiveSourceOptions<T>;
25
+ /** The value type, for `useLive`'s types (never set at run time). */
26
+ readonly __value?: T;
27
+ }
28
+ /**
29
+ * Declares a live source (D56). Export it from `live.ts`; its export name is its key.
30
+ *
31
+ * ```ts
32
+ * export const inbox = defineLive({ refresh: "5m", load: async () => fetchInbox() });
33
+ * export const prices = defineLive({ stream: (signal) => tickerFeed(signal), ring: 3600 });
34
+ * ```
35
+ */
36
+ declare function defineLive<T>(source: LiveSourceOptions<T>): LiveSource<T>;
37
+ /** The options of a live source, or `undefined` for anything `defineLive` didn't make. */
38
+ declare function liveSourceOptions(value: unknown): LiveSourceOptions<unknown> | undefined;
39
+ /** `"5s"`, `"10m"`, `"24h"` → milliseconds; from 1 s to 24 h. */
40
+ declare function parseDuration(text: string): number;
41
+ //#endregion
42
+ export { parseDuration as a, liveSourceOptions as i, LiveSourceOptions as n, defineLive as r, LiveSource as t };
43
+ //# sourceMappingURL=live-BLUwPFXE.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live-BLUwPFXE.d.ts","names":[],"sources":["../src/live.ts"],"mappings":";;;;;;UAMiB,kBAAkB;;WAExB,aAAa,QAAQ;;WAErB;;WAEA;;WAEA,UAAU,QAAQ,gBAAgB,cAAc;;WAEhD;;WAEA;;;UAIM,WAAW;;WAEjB,gBAAgB,kBAAkB;;WAElC,UAAU;;;;;;;;;;iBAWL,WAAW,GAAG,QAAQ,kBAAkB,KAAK,WAAW;;iBAYxD,kBAAkB,iBAAiB;;iBASnC,cAAc"}
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@mostra/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "What server code imports: the request context, progress, secrets, signals, host events, artifact state and live sources.",
5
+ "license": "Apache-2.0",
6
+ "author": "The Mostra Authors",
7
+ "homepage": "https://github.com/mostra-dev/mostra/tree/main/packages/server#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/mostra-dev/mostra.git",
11
+ "directory": "packages/server"
12
+ },
13
+ "bugs": "https://github.com/mostra-dev/mostra/issues",
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "exports": {
17
+ ".": {
18
+ "@mostra/source": "./src/index.ts",
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./host": {
23
+ "@mostra/source": "./src/host.ts",
24
+ "types": "./dist/host.d.ts",
25
+ "default": "./dist/host.js"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "src",
32
+ "!src/**/*.test.ts"
33
+ ],
34
+ "engines": {
35
+ "node": ">=24"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "provenance": true
40
+ },
41
+ "dependencies": {
42
+ "@mostra/protocol": "0.1.0"
43
+ },
44
+ "devDependencies": {
45
+ "@mostra/tools": "0.0.0",
46
+ "@types/node": "24.19.1",
47
+ "tsdown": "0.23.0",
48
+ "typescript": "7.0.2",
49
+ "vitest": "5.0.3"
50
+ },
51
+ "scripts": {
52
+ "build": "tsdown",
53
+ "typecheck": "tsc -b",
54
+ "test": "vitest run",
55
+ "api": "mostra-tools api"
56
+ }
6
57
  }
package/src/context.ts ADDED
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The request context of server code (D19 seam 3): which call is running, for whom, and how to
3
+ * reach the supervisor. Every call runs inside `AsyncLocalStorage`, so concurrent calls in one
4
+ * worker each see their own viewer, run and `abortSignal` across every `await`. The worker installs
5
+ * the {@link ServerHost} once; this module never does I/O of its own.
6
+ */
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import type { FieldOp, MutationResult } from "@mostra/protocol";
9
+
10
+ /** One call as server code sees it. */
11
+ export interface ServerCallContext {
12
+ /** `call`: a plain call, no durable record. `run`: an action run (D54). */
13
+ readonly kind: "call" | "run";
14
+ /** The channel's ID of the call: progress, logs and signals name it. */
15
+ readonly callId: string;
16
+ /** The action run, for `kind: "run"`. */
17
+ readonly runId?: string;
18
+ /** Who the call is for. */
19
+ readonly viewer?: { readonly id: string; readonly name?: string };
20
+ /** True only during `verify`'s smoke test (D55). */
21
+ readonly dryRun: boolean;
22
+ /** Aborted when the run is cancelled or the caller goes away (AC-04). */
23
+ readonly signal: AbortSignal;
24
+ }
25
+
26
+ /** The artifact's shared state as the supervisor answers it. */
27
+ export interface StateSnapshot {
28
+ /** The state document's revision. */
29
+ readonly revision: string;
30
+ /** Its fields by ID. */
31
+ readonly fields: Readonly<
32
+ Record<string, { readonly value?: unknown; readonly deleted?: boolean }>
33
+ >;
34
+ }
35
+
36
+ /** What `@mostra/server` needs from the process it runs in: the worker implements it. */
37
+ export interface ServerHost {
38
+ /** The secret's value; throws an error with `code: "MOSTRA_SECRET_MISSING"` when there is none. */
39
+ secret(name: string): string;
40
+ /** Reports a call's progress. */
41
+ progress(callId: string, progress: { fraction?: number; message?: string }): void;
42
+ /** Adds a line to a call's log, or to the worker's own outside calls. */
43
+ log(callId: string | undefined, line: string): void;
44
+ /** Raises a signal (already checked). */
45
+ signal(callId: string | undefined, name: string, payload: unknown): void;
46
+ /** Appends a host event (already checked). */
47
+ emit(callId: string | undefined, type: string, payload: unknown): void;
48
+ /** Reads the artifact's shared state. */
49
+ stateGet(ids: readonly string[] | undefined): Promise<StateSnapshot>;
50
+ /** Writes the artifact's shared state as the agent. */
51
+ statePatch(
52
+ callId: string | undefined,
53
+ ops: readonly FieldOp[],
54
+ options: { readonly mutationId?: string; readonly baseRevision?: string },
55
+ ): Promise<MutationResult>;
56
+ }
57
+
58
+ const storage = new AsyncLocalStorage<ServerCallContext>();
59
+ let installed: ServerHost | undefined;
60
+
61
+ /** Installs the process's {@link ServerHost}; the worker calls it once, before loading code. */
62
+ export function installServerHost(host: ServerHost): void {
63
+ installed = host;
64
+ }
65
+
66
+ /** The installed host, or an error naming where server code must run. */
67
+ export function serverHost(): ServerHost {
68
+ if (!installed) {
69
+ throw Object.assign(
70
+ new Error(
71
+ '@mostra/server works only inside an artifact\'s worker: call it from a "use server" function or a live source.',
72
+ ),
73
+ { code: "MOSTRA_TARGET_UNAVAILABLE" },
74
+ );
75
+ }
76
+ return installed;
77
+ }
78
+
79
+ /** The current call, or `undefined` outside any (module scope, a timer started at load). */
80
+ export function currentCall(): ServerCallContext | undefined {
81
+ return storage.getStore();
82
+ }
83
+
84
+ /** Runs `fn` as `context`: everything it awaits sees the same call. */
85
+ export function runWithContext<T>(context: ServerCallContext, fn: () => T): T {
86
+ return storage.run(context, fn);
87
+ }
package/src/host.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@mostra/server/host`: what an artifact's worker uses to run server code: the request context
3
+ * (D19 seam 3), the bridge to the supervisor and the live sources `live.ts` declares. Artifact code
4
+ * never imports it.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ export {
9
+ currentCall,
10
+ installServerHost,
11
+ runWithContext,
12
+ type ServerCallContext,
13
+ type ServerHost,
14
+ type StateSnapshot,
15
+ } from "./context.ts";
16
+ export { type LiveSourceOptions, liveSourceOptions, parseDuration } from "./live.ts";
package/src/index.ts ADDED
@@ -0,0 +1,267 @@
1
+ /**
2
+ * `@mostra/server`: what server code imports (INTERFACES §2.4). Inside `"use server"` functions and
3
+ * live sources, it tells who the call is for, reports progress and log lines to the page, reads
4
+ * secrets, raises signals and host events, and reads and writes the artifact's shared state.
5
+ * Server code runs with full capability (D05, AC-01): it can read files, start processes and call
6
+ * any network service; this package only adds what Mostra knows.
7
+ *
8
+ * ```ts
9
+ * "use server";
10
+ * import { abortSignal, dryRun, progress, secret, signal } from "@mostra/server";
11
+ *
12
+ * export async function sendReply(messageId: string, body: string) {
13
+ * if (dryRun()) return { messageId, sent: false };
14
+ * progress({ message: "Sending…" });
15
+ * const response = await fetch("https://mail.example/api/send", {
16
+ * method: "POST",
17
+ * headers: { authorization: `Bearer ${secret("MAIL_TOKEN")}`, "idempotency-key": messageId },
18
+ * body: JSON.stringify({ messageId, body }),
19
+ * signal: abortSignal,
20
+ * });
21
+ * if (!response.ok) throw new Error(`Mail API returned ${response.status}`);
22
+ * signal("reply-sent", { messageId });
23
+ * return { messageId, sent: true };
24
+ * }
25
+ * ```
26
+ *
27
+ * @packageDocumentation
28
+ */
29
+ import { AsyncLocalStorage } from "node:async_hooks";
30
+ import { canonicalJson, type FieldOp, SIGNAL_NAME_PATTERN } from "@mostra/protocol";
31
+ import { currentCall, serverHost } from "./context.ts";
32
+
33
+ export { defineLive, type LiveSource, type LiveSourceOptions } from "./live.ts";
34
+
35
+ /** Any JSON value. */
36
+ export type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
37
+
38
+ /** An error with a Mostra diagnostic code, as `@mostra/server` throws them. */
39
+ export class MostraServerError extends Error {
40
+ /** The diagnostic code, such as `MOSTRA_SECRET_MISSING`. */
41
+ readonly code: string;
42
+ constructor(code: string, message: string) {
43
+ super(message);
44
+ this.name = "MostraServerError";
45
+ this.code = code;
46
+ }
47
+ }
48
+
49
+ const PAYLOAD_MAX = 64 * 1024;
50
+
51
+ function checkPayload(code: string, what: string, payload: unknown): void {
52
+ if (payload === undefined) return;
53
+ let text: string;
54
+ try {
55
+ text = canonicalJson(payload);
56
+ } catch {
57
+ throw new MostraServerError(code, `The payload of ${what} isn't JSON.`);
58
+ }
59
+ if (Buffer.byteLength(text, "utf8") > PAYLOAD_MAX) {
60
+ throw new MostraServerError(code, `The payload of ${what} is larger than 64 KiB of JSON.`);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Whether this call is `verify`'s smoke test (D55). An action that checks it opts into the smoke
66
+ * test, and should then return without real effects; one that never calls it is skipped there.
67
+ */
68
+ export function dryRun(): boolean {
69
+ return currentCall()?.dryRun ?? false;
70
+ }
71
+
72
+ /** Reports the run's progress to every page following it (ephemeral, never an event). */
73
+ export function progress(p: { fraction?: number; message?: string }): void {
74
+ const call = currentCall();
75
+ if (!call) return;
76
+ const fraction = p.fraction === undefined ? undefined : Math.min(1, Math.max(0, p.fraction));
77
+ serverHost().progress(call.callId, {
78
+ ...(fraction === undefined || Number.isNaN(fraction) ? {} : { fraction }),
79
+ ...(p.message === undefined ? {} : { message: String(p.message).slice(0, 1000) }),
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Adds a line to the run's log (kept with the run, capped at 1 MB, D47); outside a run, to the
85
+ * worker's own log. Secrets are redacted from it.
86
+ */
87
+ export function log(line: string): void {
88
+ serverHost().log(currentCall()?.callId, String(line));
89
+ }
90
+
91
+ /**
92
+ * A secret's value, by name (D44): from the host's `secrets` port, the artifact's own secrets or
93
+ * the home's shared ones. Never put the value in a result, a log or a signal.
94
+ *
95
+ * @throws MostraServerError `MOSTRA_SECRET_MISSING` when no store holds it.
96
+ */
97
+ export function secret(name: string): string {
98
+ return serverHost().secret(name);
99
+ }
100
+
101
+ /**
102
+ * Raises a named signal for the host's attention (IN-09): one durable `signal.raised` event with
103
+ * `source: "action"` and this run as its causation. Mostra wakes no one by itself (D10).
104
+ *
105
+ * @throws MostraServerError `MOSTRA_SUBMIT_SIGNAL_INVALID` for a bad name or a payload over 64 KiB.
106
+ */
107
+ export function signal(name: string, payload?: Json): void {
108
+ if (typeof name !== "string" || !SIGNAL_NAME_PATTERN.test(name) || name === "submit") {
109
+ throw new MostraServerError(
110
+ "MOSTRA_SUBMIT_SIGNAL_INVALID",
111
+ `${JSON.stringify(name).slice(0, 80)} isn't a signal name: 1 to 64 letters, digits, ".", "_" and "-", and not "submit".`,
112
+ );
113
+ }
114
+ checkPayload("MOSTRA_SUBMIT_SIGNAL_INVALID", `the signal ${name}`, payload);
115
+ serverHost().signal(currentCall()?.callId, name, payload);
116
+ }
117
+
118
+ /**
119
+ * Appends a host event, `host.<name>`, to the event log (AC-05), which hosts filter for.
120
+ *
121
+ * @throws MostraServerError `MOSTRA_ACTION_EVENT_INVALID` for a bad type or a payload over 64 KiB.
122
+ */
123
+ export function emit(type: `host.${string}`, payload?: Json): void {
124
+ const name = typeof type === "string" && type.startsWith("host.") ? type.slice(5) : "";
125
+ if (!SIGNAL_NAME_PATTERN.test(name)) {
126
+ throw new MostraServerError(
127
+ "MOSTRA_ACTION_EVENT_INVALID",
128
+ `${JSON.stringify(type).slice(0, 80)} isn't a host event type: "host." and 1 to 64 letters, digits, ".", "_" and "-".`,
129
+ );
130
+ }
131
+ checkPayload("MOSTRA_ACTION_EVENT_INVALID", `the event ${type}`, payload);
132
+ serverHost().emit(currentCall()?.callId, type, payload);
133
+ }
134
+
135
+ /** Who the call is for; `undefined` in live producers and outside calls. */
136
+ export function viewer(): { id: string; name?: string } | undefined {
137
+ const who = currentCall()?.viewer;
138
+ return who ? { ...who } : undefined;
139
+ }
140
+
141
+ const idle = new AbortController().signal;
142
+
143
+ /**
144
+ * The bound copies of listeners, per signal: each call has its own signal, so a listener added in
145
+ * two calls (a module-level callback, say) gets a copy bound to each call's context, and removing
146
+ * it from one call's signal finds that call's copy.
147
+ */
148
+ const boundListeners = new WeakMap<AbortSignal, WeakMap<object, (event: Event) => void>>();
149
+
150
+ /** A listener that runs in the call it was added in, as `await`ed code does. */
151
+ function bindListener(target: AbortSignal, listener: unknown): unknown {
152
+ if (typeof listener !== "function" && (typeof listener !== "object" || listener === null)) {
153
+ return listener;
154
+ }
155
+ let perSignal = boundListeners.get(target);
156
+ if (!perSignal) {
157
+ perSignal = new WeakMap();
158
+ boundListeners.set(target, perSignal);
159
+ }
160
+ let bound = perSignal.get(listener);
161
+ if (!bound) {
162
+ const handle =
163
+ typeof listener === "function"
164
+ ? (listener as (event: Event) => void)
165
+ : (event: Event) => (listener as { handleEvent(event: Event): void }).handleEvent(event);
166
+ bound = AsyncLocalStorage.bind(handle);
167
+ perSignal.set(listener, bound);
168
+ }
169
+ return bound;
170
+ }
171
+
172
+ /**
173
+ * The current call's cancellation (AC-04): aborted when a page cancels the run or the caller goes
174
+ * away. Pass it to `fetch` and other cancellable work. Outside a call it never aborts. Listeners
175
+ * added to it run in the call that added them, so they read `abortSignal.reason` of that call.
176
+ */
177
+ export const abortSignal: AbortSignal = new Proxy(idle, {
178
+ get(_target, property) {
179
+ const target = currentCall()?.signal ?? idle;
180
+ if (property === "addEventListener" || property === "removeEventListener") {
181
+ const method = target[property].bind(target) as (
182
+ type: string,
183
+ listener: unknown,
184
+ options?: unknown,
185
+ ) => void;
186
+ return (type: string, listener: unknown, options?: unknown) =>
187
+ method(type, bindListener(target, listener), options);
188
+ }
189
+ const value: unknown = Reflect.get(target, property, target);
190
+ return typeof value === "function" ? value.bind(target) : value;
191
+ },
192
+ set(_target, property, value) {
193
+ const target = currentCall()?.signal ?? idle;
194
+ return Reflect.set(
195
+ target,
196
+ property,
197
+ property === "onabort" ? bindListener(target, value) : value,
198
+ target,
199
+ );
200
+ },
201
+ has(_target, property) {
202
+ return Reflect.has(currentCall()?.signal ?? idle, property);
203
+ },
204
+ });
205
+
206
+ /** Options of a state write. */
207
+ export interface StateWriteOptions {
208
+ /** The change's ID: a retry with the same ID and contents returns the recorded result. */
209
+ readonly mutationId?: string;
210
+ /** The revision you read: a field changed after it is a conflict and keeps its value. */
211
+ readonly baseRevision?: string;
212
+ }
213
+
214
+ /** The artifact's shared state, as server code reads and writes it. */
215
+ export interface ServerState {
216
+ /** A field's value, or `undefined` when it isn't set. */
217
+ get<T>(id: string): Promise<T | undefined>;
218
+ /**
219
+ * Sets one field.
220
+ *
221
+ * @throws MostraServerError `MOSTRA_FIELD_CONFLICT` when the field changed after `baseRevision`.
222
+ */
223
+ set<T>(id: string, value: T, options?: StateWriteOptions): Promise<{ revision: string }>;
224
+ /** Sets and deletes several fields under one revision; conflicting ones are listed. */
225
+ patch(
226
+ ops: readonly { id: string; value?: Json; delete?: true }[],
227
+ options?: StateWriteOptions,
228
+ ): Promise<{ revision: string; conflicts: string[] }>;
229
+ }
230
+
231
+ /**
232
+ * The artifact's shared state (D63): the artifact-scoped fields every viewer sees, written through
233
+ * the same compare-and-set as viewers' edits, as the agent. Each write appends `state.changed`.
234
+ */
235
+ export const state: ServerState = {
236
+ async get<T>(id: string): Promise<T | undefined> {
237
+ const snapshot = await serverHost().stateGet([id]);
238
+ const field = snapshot.fields[id];
239
+ return field && !field.deleted ? (field.value as T) : undefined;
240
+ },
241
+ async set<T>(id: string, value: T, options: StateWriteOptions = {}) {
242
+ const result = await serverHost().statePatch(
243
+ currentCall()?.callId,
244
+ [{ id, value } as FieldOp],
245
+ options,
246
+ );
247
+ if (result.conflicts.length > 0) {
248
+ throw new MostraServerError(
249
+ "MOSTRA_FIELD_CONFLICT",
250
+ `The state field ${id} changed after revision ${options.baseRevision ?? "?"}; read it again and decide.`,
251
+ );
252
+ }
253
+ return { revision: result.revision };
254
+ },
255
+ async patch(ops, options: StateWriteOptions = {}) {
256
+ const fieldOps = ops.map((op) =>
257
+ op.delete
258
+ ? ({ id: op.id, delete: true } as FieldOp)
259
+ : ({ id: op.id, value: op.value } as FieldOp),
260
+ );
261
+ const result = await serverHost().statePatch(currentCall()?.callId, fieldOps, options);
262
+ return {
263
+ revision: result.revision,
264
+ conflicts: result.conflicts.map((conflict) => conflict.id),
265
+ };
266
+ },
267
+ };
package/src/live.ts ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Live sources (D56): `live.ts` exports `defineLive(…)` producers, which the artifact's worker runs
3
+ * while someone views them, a host subscribes, or always with `always: true` (D63).
4
+ */
5
+
6
+ /** How a live source produces its values. */
7
+ export interface LiveSourceOptions<T> {
8
+ /** Loads the current value: on start, on every `refresh`, and when a `watch`ed file changes. */
9
+ readonly load?: () => Promise<T>;
10
+ /** How often `load` runs again: `"5s"` to `"24h"` (`s`, `m` or `h`). */
11
+ readonly refresh?: string;
12
+ /** Files whose changes run `load` again: globs relative to the artifact's source. */
13
+ readonly watch?: string | readonly string[];
14
+ /** Produces values as they come; `signal` aborts when the source stops. */
15
+ readonly stream?: (signal: AbortSignal) => AsyncIterable<T>;
16
+ /** Keep producing while nobody views the artifact (D63). */
17
+ readonly always?: boolean;
18
+ /** Keep the last N values for append mode (`useLive(key, { mode: "append" })`, AC-08). */
19
+ readonly ring?: number;
20
+ }
21
+
22
+ /** A live source, as `defineLive` returns it. Pages read it with `useLive(key)`. */
23
+ export interface LiveSource<T> {
24
+ /** The source's options, for the worker. */
25
+ readonly "~mostra.live": LiveSourceOptions<T>;
26
+ /** The value type, for `useLive`'s types (never set at run time). */
27
+ readonly __value?: T;
28
+ }
29
+
30
+ /**
31
+ * Declares a live source (D56). Export it from `live.ts`; its export name is its key.
32
+ *
33
+ * ```ts
34
+ * export const inbox = defineLive({ refresh: "5m", load: async () => fetchInbox() });
35
+ * export const prices = defineLive({ stream: (signal) => tickerFeed(signal), ring: 3600 });
36
+ * ```
37
+ */
38
+ export function defineLive<T>(source: LiveSourceOptions<T>): LiveSource<T> {
39
+ if (!source.load && !source.stream) {
40
+ throw new TypeError("defineLive needs a load function, a stream function, or both.");
41
+ }
42
+ if (source.refresh !== undefined) parseDuration(source.refresh);
43
+ if (source.ring !== undefined && (!Number.isInteger(source.ring) || source.ring < 1)) {
44
+ throw new TypeError("defineLive's ring is the number of values to keep: a positive integer.");
45
+ }
46
+ return { "~mostra.live": source };
47
+ }
48
+
49
+ /** The options of a live source, or `undefined` for anything `defineLive` didn't make. */
50
+ export function liveSourceOptions(value: unknown): LiveSourceOptions<unknown> | undefined {
51
+ if (typeof value !== "object" || value === null) return undefined;
52
+ const options = (value as { "~mostra.live"?: unknown })["~mostra.live"];
53
+ return typeof options === "object" && options !== null
54
+ ? (options as LiveSourceOptions<unknown>)
55
+ : undefined;
56
+ }
57
+
58
+ /** `"5s"`, `"10m"`, `"24h"` → milliseconds; from 1 s to 24 h. */
59
+ export function parseDuration(text: string): number {
60
+ const match = /^(\d+)(s|m|h)$/.exec(text);
61
+ const unit = { s: 1_000, m: 60_000, h: 3_600_000 } as const;
62
+ const ms = match ? Number(match[1]) * unit[match[2] as keyof typeof unit] : Number.NaN;
63
+ if (!(ms >= 1_000 && ms <= 86_400_000)) {
64
+ throw new TypeError(
65
+ `defineLive's refresh is a duration from "1s" to "24h", such as "30s" or "5m"; got ${JSON.stringify(text)}.`,
66
+ );
67
+ }
68
+ return ms;
69
+ }