@runlane/react 0.0.0-stage → 0.5.1
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 +202 -0
- package/dist/index.cjs +400 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +86 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +86 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +396 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +75 -3
- package/README.md +0 -3
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 [2026] Abhishek Bhardwaj
|
|
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/dist/index.cjs
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
let react = require("react");
|
|
4
|
+
let _runlane_contracts_realtime = require("@runlane/contracts/realtime");
|
|
5
|
+
let _runlane_realtime_client = require("@runlane/realtime/client");
|
|
6
|
+
// src/latest.ts
|
|
7
|
+
function useLatest(value) {
|
|
8
|
+
const ref = (0, react.useRef)(value);
|
|
9
|
+
(0, react.useLayoutEffect)(() => {
|
|
10
|
+
ref.current = value;
|
|
11
|
+
});
|
|
12
|
+
return ref;
|
|
13
|
+
}
|
|
14
|
+
// src/provider.ts
|
|
15
|
+
const ClientContext = (0, react.createContext)(void 0);
|
|
16
|
+
function useClient(client) {
|
|
17
|
+
const provided = (0, react.useContext)(ClientContext);
|
|
18
|
+
const resolved = client ?? provided;
|
|
19
|
+
if (resolved === void 0) throw new _runlane_contracts_realtime.RunlaneError({
|
|
20
|
+
code: _runlane_contracts_realtime.ErrorCode.ConfigurationInvalid,
|
|
21
|
+
message: "Wrap the view in RunlaneProvider or pass a client option to the hook."
|
|
22
|
+
});
|
|
23
|
+
return resolved;
|
|
24
|
+
}
|
|
25
|
+
/** Owns one client per base URL and fetch function; callback changes keep readers open. */
|
|
26
|
+
function RunlaneProvider({ children, ...options }) {
|
|
27
|
+
const latest = useLatest(options);
|
|
28
|
+
const { baseUrl, fetch } = options;
|
|
29
|
+
const client = (0, react.useMemo)(() => {
|
|
30
|
+
let owned;
|
|
31
|
+
const refresh = (request) => {
|
|
32
|
+
const callback = latest.current.refreshAccessToken;
|
|
33
|
+
if (callback === void 0) throw new _runlane_contracts_realtime.RunlaneError({
|
|
34
|
+
code: _runlane_contracts_realtime.ErrorCode.AccessDenied,
|
|
35
|
+
message: "No access token refresher is configured."
|
|
36
|
+
});
|
|
37
|
+
return callback(request);
|
|
38
|
+
};
|
|
39
|
+
function getClient() {
|
|
40
|
+
if (owned !== void 0) return owned;
|
|
41
|
+
let url;
|
|
42
|
+
try {
|
|
43
|
+
url = new URL(baseUrl, typeof location === "undefined" ? void 0 : location.href);
|
|
44
|
+
} catch (cause) {
|
|
45
|
+
throw new _runlane_contracts_realtime.RunlaneError({
|
|
46
|
+
code: _runlane_contracts_realtime.ErrorCode.ConfigurationInvalid,
|
|
47
|
+
message: "baseUrl must resolve to an HTTP or HTTPS URL.",
|
|
48
|
+
cause
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
owned = (0, _runlane_realtime_client.createRunlaneClient)({
|
|
52
|
+
baseUrl: url.href,
|
|
53
|
+
fetch,
|
|
54
|
+
get refreshAccessToken() {
|
|
55
|
+
return latest.current.refreshAccessToken === void 0 ? void 0 : refresh;
|
|
56
|
+
},
|
|
57
|
+
get telemetry() {
|
|
58
|
+
return latest.current.telemetry;
|
|
59
|
+
},
|
|
60
|
+
get onTelemetryError() {
|
|
61
|
+
return latest.current.onTelemetryError;
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
return owned;
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
subscribe(runId, input) {
|
|
68
|
+
return getClient().subscribe(runId, input);
|
|
69
|
+
},
|
|
70
|
+
readStream(runId, name, input) {
|
|
71
|
+
return getClient().readStream(runId, name, input);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}, [
|
|
75
|
+
baseUrl,
|
|
76
|
+
fetch,
|
|
77
|
+
latest
|
|
78
|
+
]);
|
|
79
|
+
return (0, react.createElement)(ClientContext.Provider, { value: client }, children);
|
|
80
|
+
}
|
|
81
|
+
// src/reader-store.ts
|
|
82
|
+
function createReaderStore(initial, read, options) {
|
|
83
|
+
const serverState = {
|
|
84
|
+
value: initial,
|
|
85
|
+
error: void 0,
|
|
86
|
+
isConnected: false
|
|
87
|
+
};
|
|
88
|
+
let state = serverState;
|
|
89
|
+
let stopReader;
|
|
90
|
+
return {
|
|
91
|
+
getSnapshot: () => state,
|
|
92
|
+
getServerSnapshot: () => serverState,
|
|
93
|
+
stop: () => stopReader?.(),
|
|
94
|
+
subscribe: (notify) => {
|
|
95
|
+
const controller = new AbortController();
|
|
96
|
+
const { signal } = controller;
|
|
97
|
+
let pending = serverState;
|
|
98
|
+
let timer;
|
|
99
|
+
let completed = false;
|
|
100
|
+
state = serverState;
|
|
101
|
+
const flush = () => {
|
|
102
|
+
clearTimeout(timer);
|
|
103
|
+
timer = void 0;
|
|
104
|
+
if (signal.aborted || state === pending) return;
|
|
105
|
+
state = pending;
|
|
106
|
+
notify();
|
|
107
|
+
};
|
|
108
|
+
const schedule = () => {
|
|
109
|
+
timer ??= setTimeout(flush, options.throttle());
|
|
110
|
+
};
|
|
111
|
+
const complete = (error) => {
|
|
112
|
+
if (signal.aborted || completed) return;
|
|
113
|
+
completed = true;
|
|
114
|
+
flush();
|
|
115
|
+
options.onComplete?.(pending.value, error);
|
|
116
|
+
};
|
|
117
|
+
const stop = () => {
|
|
118
|
+
if (signal.aborted) return;
|
|
119
|
+
pending = {
|
|
120
|
+
...pending,
|
|
121
|
+
isConnected: false
|
|
122
|
+
};
|
|
123
|
+
flush();
|
|
124
|
+
controller.abort();
|
|
125
|
+
};
|
|
126
|
+
stopReader = stop;
|
|
127
|
+
read({
|
|
128
|
+
signal,
|
|
129
|
+
flush,
|
|
130
|
+
complete,
|
|
131
|
+
update: (reduce) => {
|
|
132
|
+
if (!signal.aborted) {
|
|
133
|
+
const value = reduce(pending.value);
|
|
134
|
+
if (!Object.is(value, pending.value)) {
|
|
135
|
+
pending = {
|
|
136
|
+
...pending,
|
|
137
|
+
value
|
|
138
|
+
};
|
|
139
|
+
schedule();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return pending.value;
|
|
143
|
+
},
|
|
144
|
+
onConnectionChange: (change) => {
|
|
145
|
+
if (signal.aborted) return;
|
|
146
|
+
pending = {
|
|
147
|
+
...pending,
|
|
148
|
+
isConnected: change.state === _runlane_contracts_realtime.RealtimeConnectionState.Open
|
|
149
|
+
};
|
|
150
|
+
if (change.state === _runlane_contracts_realtime.RealtimeConnectionState.Closed) flush();
|
|
151
|
+
else schedule();
|
|
152
|
+
options.onConnectionChange?.(change);
|
|
153
|
+
}
|
|
154
|
+
}).then(() => {
|
|
155
|
+
if (signal.aborted) return;
|
|
156
|
+
if (pending.isConnected) pending = {
|
|
157
|
+
...pending,
|
|
158
|
+
isConnected: false
|
|
159
|
+
};
|
|
160
|
+
flush();
|
|
161
|
+
}).catch((cause) => {
|
|
162
|
+
if (signal.aborted) return;
|
|
163
|
+
pending = {
|
|
164
|
+
...pending,
|
|
165
|
+
isConnected: false,
|
|
166
|
+
error: readerError(cause)
|
|
167
|
+
};
|
|
168
|
+
flush();
|
|
169
|
+
try {
|
|
170
|
+
complete(pending.error);
|
|
171
|
+
} catch (cause) {
|
|
172
|
+
pending = {
|
|
173
|
+
...pending,
|
|
174
|
+
error: readerError(cause)
|
|
175
|
+
};
|
|
176
|
+
flush();
|
|
177
|
+
}
|
|
178
|
+
controller.abort();
|
|
179
|
+
});
|
|
180
|
+
return stop;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function useReader(store) {
|
|
185
|
+
const latest = useLatest(store);
|
|
186
|
+
const stop = (0, react.useCallback)(() => latest.current.stop(), [latest]);
|
|
187
|
+
return {
|
|
188
|
+
...(0, react.useSyncExternalStore)(store.subscribe, store.getSnapshot, store.getServerSnapshot),
|
|
189
|
+
stop
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
function readerError(cause) {
|
|
193
|
+
return cause instanceof _runlane_contracts_realtime.RunlaneError ? cause : new _runlane_contracts_realtime.RunlaneError({
|
|
194
|
+
code: _runlane_contracts_realtime.ErrorCode.InternalError,
|
|
195
|
+
message: "Run reader failed.",
|
|
196
|
+
cause
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
// src/run-state.ts
|
|
200
|
+
function reduceRun(state, event) {
|
|
201
|
+
if (event.type === _runlane_contracts_realtime.RunSubscriptionEventType.Snapshot) {
|
|
202
|
+
const { run } = event;
|
|
203
|
+
return {
|
|
204
|
+
id: run.id,
|
|
205
|
+
environment: run.environment,
|
|
206
|
+
taskId: run.taskId,
|
|
207
|
+
status: run.status,
|
|
208
|
+
attempts: run.counters.attempts,
|
|
209
|
+
eventSequence: run.eventSequence,
|
|
210
|
+
version: run.version,
|
|
211
|
+
output: run.output,
|
|
212
|
+
failure: run.failure,
|
|
213
|
+
meta: run.meta
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
if (state === void 0) return state;
|
|
217
|
+
switch (event.type) {
|
|
218
|
+
case _runlane_contracts_realtime.RunSubscriptionEventType.Status: return {
|
|
219
|
+
...state,
|
|
220
|
+
status: event.status,
|
|
221
|
+
attempts: event.attempts,
|
|
222
|
+
eventSequence: event.eventSequence,
|
|
223
|
+
version: event.version,
|
|
224
|
+
output: event.output,
|
|
225
|
+
failure: event.failure
|
|
226
|
+
};
|
|
227
|
+
case _runlane_contracts_realtime.RunSubscriptionEventType.Meta: return {
|
|
228
|
+
...state,
|
|
229
|
+
eventSequence: event.eventSequence,
|
|
230
|
+
meta: {
|
|
231
|
+
...state.meta,
|
|
232
|
+
...event.patch
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
case _runlane_contracts_realtime.RunSubscriptionEventType.Stream: return state;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
// src/stream-state.ts
|
|
239
|
+
/** Whether a named reader retains the latest attempt or all attempts. */
|
|
240
|
+
let RunStreamMode = /* @__PURE__ */ function(RunStreamMode) {
|
|
241
|
+
RunStreamMode["Latest"] = "latest";
|
|
242
|
+
RunStreamMode["All"] = "all";
|
|
243
|
+
return RunStreamMode;
|
|
244
|
+
}({});
|
|
245
|
+
function reduceStream(state, record, mode, maxParts) {
|
|
246
|
+
const attempts = mode === "latest" && record.type === _runlane_contracts_realtime.RunStreamRecordType.AttemptStarted ? [] : [...state.attempts];
|
|
247
|
+
const previous = attempts.at(-1);
|
|
248
|
+
const current = previous?.attempt === record.attempt ? previous : {
|
|
249
|
+
attempt: record.attempt,
|
|
250
|
+
parts: []
|
|
251
|
+
};
|
|
252
|
+
if (current === previous) attempts.pop();
|
|
253
|
+
switch (record.type) {
|
|
254
|
+
case _runlane_contracts_realtime.RunStreamRecordType.AttemptStarted:
|
|
255
|
+
attempts.push(current);
|
|
256
|
+
break;
|
|
257
|
+
case _runlane_contracts_realtime.RunStreamRecordType.Chunk:
|
|
258
|
+
attempts.push({
|
|
259
|
+
...current,
|
|
260
|
+
parts: [...current.parts, record.value]
|
|
261
|
+
});
|
|
262
|
+
break;
|
|
263
|
+
case _runlane_contracts_realtime.RunStreamRecordType.AttemptClosed: attempts.push({
|
|
264
|
+
...current,
|
|
265
|
+
closeReason: record.reason
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
const evicted = evictParts(attempts, maxParts);
|
|
269
|
+
return {
|
|
270
|
+
attempts,
|
|
271
|
+
truncated: state.truncated || evicted
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function evictParts(attempts, maxParts) {
|
|
275
|
+
const excessAttempts = Math.max(0, attempts.length - maxParts);
|
|
276
|
+
attempts.splice(0, excessAttempts);
|
|
277
|
+
let excess = attempts.reduce((total, attempt) => total + attempt.parts.length, 0) - maxParts;
|
|
278
|
+
const evicted = excessAttempts > 0 || excess > 0;
|
|
279
|
+
while (excess > 0) {
|
|
280
|
+
const oldest = attempts[0];
|
|
281
|
+
if (oldest === void 0) break;
|
|
282
|
+
if (oldest.parts.length <= excess) {
|
|
283
|
+
attempts.shift();
|
|
284
|
+
excess -= oldest.parts.length;
|
|
285
|
+
} else {
|
|
286
|
+
attempts[0] = {
|
|
287
|
+
...oldest,
|
|
288
|
+
parts: oldest.parts.slice(excess)
|
|
289
|
+
};
|
|
290
|
+
excess = 0;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return evicted;
|
|
294
|
+
}
|
|
295
|
+
// src/index.ts
|
|
296
|
+
/** Subscribe to a snapshot and apply status, metadata, and stream deltas in delivery order. */
|
|
297
|
+
function useRun(runId, { client: supplied, enabled = true, accessToken, onComplete, onConnectionChange, throttle = _runlane_contracts_realtime.contractDefaults.realtime.renderThrottle } = {}) {
|
|
298
|
+
const client = useClient(supplied);
|
|
299
|
+
const latest = useReaderOptions({
|
|
300
|
+
accessToken,
|
|
301
|
+
throttle,
|
|
302
|
+
onComplete,
|
|
303
|
+
onConnectionChange
|
|
304
|
+
});
|
|
305
|
+
const { value: run, error, isConnected, stop } = useReader((0, react.useMemo)(() => createReaderStore(void 0, async (options) => {
|
|
306
|
+
if (!enabled || runId === void 0) return;
|
|
307
|
+
for await (const event of client.subscribe(runId, {
|
|
308
|
+
streams: false,
|
|
309
|
+
accessToken: latest.current.accessToken,
|
|
310
|
+
signal: options.signal,
|
|
311
|
+
onConnectionChange: options.onConnectionChange
|
|
312
|
+
})) {
|
|
313
|
+
const run = options.update((state) => reduceRun(state, event));
|
|
314
|
+
if (run !== void 0 && _runlane_contracts_realtime.runStatusValues.isTerminal(run.status)) options.complete();
|
|
315
|
+
}
|
|
316
|
+
}, {
|
|
317
|
+
throttle: () => latest.current.throttleMs,
|
|
318
|
+
onComplete: (run, error) => latest.current.onComplete?.(run, error),
|
|
319
|
+
onConnectionChange: (change) => latest.current.onConnectionChange?.(change)
|
|
320
|
+
}), [
|
|
321
|
+
runId,
|
|
322
|
+
client,
|
|
323
|
+
enabled
|
|
324
|
+
]));
|
|
325
|
+
return {
|
|
326
|
+
run,
|
|
327
|
+
error,
|
|
328
|
+
isConnected,
|
|
329
|
+
stop
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
/** Read a task-declared stream. The server validates parts when writing them. */
|
|
333
|
+
function useRunStream(runId, name, { client: supplied, accessToken, onData, onConnectionChange, throttle = _runlane_contracts_realtime.contractDefaults.realtime.renderThrottle, enabled = true, mode = "latest", maxParts = _runlane_contracts_realtime.contractDefaults.realtime.clientMaxParts } = {}) {
|
|
334
|
+
const client = useClient(supplied);
|
|
335
|
+
const latest = useReaderOptions({
|
|
336
|
+
accessToken,
|
|
337
|
+
onData,
|
|
338
|
+
onConnectionChange,
|
|
339
|
+
throttle
|
|
340
|
+
});
|
|
341
|
+
validatePartLimit(maxParts);
|
|
342
|
+
const { value, error, isConnected, stop } = useReader((0, react.useMemo)(() => createReaderStore({
|
|
343
|
+
attempts: [],
|
|
344
|
+
truncated: false
|
|
345
|
+
}, async (options) => {
|
|
346
|
+
if (!enabled || runId === void 0) return;
|
|
347
|
+
for await (const record of client.readStream(runId, name, {
|
|
348
|
+
accessToken: latest.current.accessToken,
|
|
349
|
+
signal: options.signal,
|
|
350
|
+
onConnectionChange: options.onConnectionChange
|
|
351
|
+
})) {
|
|
352
|
+
if (options.signal.aborted) return;
|
|
353
|
+
options.update((state) => reduceStream(state, record, mode, maxParts));
|
|
354
|
+
if (record.type === _runlane_contracts_realtime.RunStreamRecordType.Chunk) latest.current.onData?.(record.value);
|
|
355
|
+
if (record.type === _runlane_contracts_realtime.RunStreamRecordType.AttemptClosed) options.flush();
|
|
356
|
+
}
|
|
357
|
+
}, {
|
|
358
|
+
throttle: () => latest.current.throttleMs,
|
|
359
|
+
onConnectionChange: (change) => latest.current.onConnectionChange?.(change)
|
|
360
|
+
}), [
|
|
361
|
+
runId,
|
|
362
|
+
name,
|
|
363
|
+
client,
|
|
364
|
+
enabled,
|
|
365
|
+
mode,
|
|
366
|
+
maxParts
|
|
367
|
+
]));
|
|
368
|
+
return {
|
|
369
|
+
...value,
|
|
370
|
+
parts: value.attempts.at(-1)?.parts ?? [],
|
|
371
|
+
error,
|
|
372
|
+
isConnected,
|
|
373
|
+
stop
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
const throttleSchema = (0, _runlane_contracts_realtime.createDurationSchema)("throttle must be a positive DurationString that resolves to whole milliseconds.");
|
|
377
|
+
function useReaderOptions(options) {
|
|
378
|
+
const result = throttleSchema.safeParse(options.throttle);
|
|
379
|
+
if (!result.success) throw new _runlane_contracts_realtime.RunlaneError({
|
|
380
|
+
code: _runlane_contracts_realtime.ErrorCode.ConfigurationInvalid,
|
|
381
|
+
message: "Invalid render throttle.",
|
|
382
|
+
cause: result.error
|
|
383
|
+
});
|
|
384
|
+
return useLatest({
|
|
385
|
+
...options,
|
|
386
|
+
throttleMs: result.data.milliseconds
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
function validatePartLimit(maxParts) {
|
|
390
|
+
if (!Number.isSafeInteger(maxParts) || maxParts < 1 || maxParts > _runlane_contracts_realtime.contractDefaults.realtime.clientMaxPartsLimit) throw new _runlane_contracts_realtime.RunlaneError({
|
|
391
|
+
code: _runlane_contracts_realtime.ErrorCode.ConfigurationInvalid,
|
|
392
|
+
message: "maxParts must be a positive safe integer no greater than realtime.clientMaxPartsLimit."
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
exports.RunStreamMode = RunStreamMode;
|
|
396
|
+
exports.RunlaneProvider = RunlaneProvider;
|
|
397
|
+
exports.useRun = useRun;
|
|
398
|
+
exports.useRunStream = useRunStream;
|
|
399
|
+
|
|
400
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["useRef","createContext","useContext","RunlaneError","ErrorCode","useMemo","createRunlaneClient","createElement","RealtimeConnectionState","useCallback","useSyncExternalStore","RunlaneError","ErrorCode","RunSubscriptionEventType","RunStreamRecordType","contractDefaults","useMemo","runStatusValues","RunStreamRecordType","createDurationSchema","RunlaneError","ErrorCode"],"sources":["../src/latest.ts","../src/provider.ts","../src/reader-store.ts","../src/run-state.ts","../src/stream-state.ts","../src/index.ts"],"sourcesContent":["import { useLayoutEffect, useRef } from 'react'\n\n// Readers observe committed options without making callbacks part of their identity.\nexport function useLatest<T>(value: T) {\n const ref = useRef(value)\n useLayoutEffect(() => {\n ref.current = value\n })\n return ref\n}\n","import { createContext, createElement, useContext, useMemo, type ReactNode } from 'react'\n\nimport { ErrorCode, RunlaneError, type RunlaneIdInput, type RunStreamName } from '@runlane/contracts/realtime'\nimport {\n createRunlaneClient,\n type RunlaneClient,\n type RunlaneClientOptions,\n type RunlaneClientReadOptions,\n} from '@runlane/realtime/client'\n\nimport { useLatest } from './latest.js'\n\nconst ClientContext = createContext<RunlaneClient | undefined>(undefined)\n\nexport function useClient(client: RunlaneClient | undefined): RunlaneClient {\n const provided = useContext(ClientContext)\n const resolved = client ?? provided\n if (resolved === undefined)\n throw new RunlaneError({\n code: ErrorCode.ConfigurationInvalid,\n message: 'Wrap the view in RunlaneProvider or pass a client option to the hook.',\n })\n return resolved\n}\n\n/** Shared client configuration. Each hook still owns an independent reader. */\nexport interface RunlaneProviderProps extends RunlaneClientOptions {\n readonly children?: ReactNode\n}\n\n/** Owns one client per base URL and fetch function; callback changes keep readers open. */\nexport function RunlaneProvider({ children, ...options }: RunlaneProviderProps) {\n const latest = useLatest(options)\n const { baseUrl, fetch } = options\n const client = useMemo(() => {\n let owned: RunlaneClient | undefined\n const refresh: NonNullable<RunlaneClientOptions['refreshAccessToken']> = (request) => {\n const callback = latest.current.refreshAccessToken\n if (callback === undefined)\n throw new RunlaneError({ code: ErrorCode.AccessDenied, message: 'No access token refresher is configured.' })\n return callback(request)\n }\n // Delay construction until a committed reader starts: relative URLs need the browser origin,\n // which is absent during server rendering. All readers share this same client.\n function getClient(): RunlaneClient {\n if (owned !== undefined) return owned\n let url: URL\n try {\n url = new URL(baseUrl, typeof location === 'undefined' ? undefined : location.href)\n } catch (cause) {\n throw new RunlaneError({\n code: ErrorCode.ConfigurationInvalid,\n message: 'baseUrl must resolve to an HTTP or HTTPS URL.',\n cause,\n })\n }\n owned = createRunlaneClient({\n baseUrl: url.href,\n fetch,\n get refreshAccessToken() {\n return latest.current.refreshAccessToken === undefined ? undefined : refresh\n },\n get telemetry() {\n return latest.current.telemetry\n },\n get onTelemetryError() {\n return latest.current.onTelemetryError\n },\n })\n return owned\n }\n return {\n subscribe<TTask = undefined>(runId: RunlaneIdInput, input?: RunlaneClientReadOptions) {\n return getClient().subscribe<TTask>(runId, input)\n },\n readStream<TTask = undefined, TName extends RunStreamName<TTask> = RunStreamName<TTask>>(\n runId: RunlaneIdInput,\n name: TName,\n input?: RunlaneClientReadOptions,\n ) {\n return getClient().readStream<TTask, TName>(runId, name, input)\n },\n } satisfies RunlaneClient\n }, [baseUrl, fetch, latest])\n return createElement(ClientContext.Provider, { value: client }, children)\n}\n","import { useCallback, useSyncExternalStore } from 'react'\n\nimport {\n ErrorCode,\n RealtimeConnectionState,\n RunlaneError,\n type RealtimeConnectionChange,\n} from '@runlane/contracts/realtime'\n\nimport { useLatest } from './latest.js'\n\n/** Cached immutable snapshot for one hook-owned external store. */\ninterface ReaderState<T> {\n readonly value: T\n readonly error: RunlaneError | undefined\n readonly isConnected: boolean\n}\n\n// Each store belongs to one hook identity. Each subscription cycle has its own abort fence,\n// including Strict Mode's setup/cleanup/setup and Activity hide/show on the same store.\nexport function createReaderStore<T>(\n initial: T,\n read: (options: {\n signal: AbortSignal\n update: (reduce: (value: T) => T) => T\n complete: () => void\n flush: () => void\n onConnectionChange: (change: RealtimeConnectionChange) => void\n }) => Promise<void>,\n options: {\n throttle: () => number\n onComplete?: (value: T, error?: RunlaneError) => void\n onConnectionChange?: (change: RealtimeConnectionChange) => void\n },\n) {\n const serverState: ReaderState<T> = { value: initial, error: undefined, isConnected: false }\n let state = serverState\n let stopReader: (() => void) | undefined\n\n return {\n getSnapshot: () => state,\n getServerSnapshot: () => serverState,\n stop: () => stopReader?.(),\n subscribe: (notify: () => void) => {\n const controller = new AbortController()\n const { signal } = controller\n let pending = serverState\n let timer: ReturnType<typeof setTimeout> | undefined\n let completed = false\n state = serverState\n const flush = () => {\n clearTimeout(timer)\n timer = undefined\n if (signal.aborted || state === pending) return\n state = pending\n notify()\n }\n const schedule = () => {\n timer ??= setTimeout(flush, options.throttle())\n }\n const complete = (error?: RunlaneError) => {\n if (signal.aborted || completed) return\n completed = true\n flush()\n options.onComplete?.(pending.value, error)\n }\n const stop = () => {\n if (signal.aborted) return\n pending = { ...pending, isConnected: false }\n flush()\n controller.abort()\n }\n stopReader = stop\n void read({\n signal,\n flush,\n complete,\n update: (reduce) => {\n if (!signal.aborted) {\n const value = reduce(pending.value)\n if (!Object.is(value, pending.value)) {\n pending = { ...pending, value }\n schedule()\n }\n }\n return pending.value\n },\n onConnectionChange: (change) => {\n if (signal.aborted) return\n pending = { ...pending, isConnected: change.state === RealtimeConnectionState.Open }\n if (change.state === RealtimeConnectionState.Closed) flush()\n else schedule()\n options.onConnectionChange?.(change)\n },\n })\n .then(() => {\n if (signal.aborted) return\n if (pending.isConnected) pending = { ...pending, isConnected: false }\n flush()\n })\n .catch((cause: unknown) => {\n if (signal.aborted) return\n pending = {\n ...pending,\n isConnected: false,\n error: readerError(cause),\n }\n flush()\n try {\n complete(pending.error)\n } catch (cause) {\n pending = { ...pending, error: readerError(cause) }\n flush()\n }\n controller.abort()\n })\n return stop\n },\n }\n}\n\nexport function useReader<T>(store: ReturnType<typeof createReaderStore<T>>) {\n const latest = useLatest(store)\n const stop = useCallback(() => latest.current.stop(), [latest])\n return { ...useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot), stop }\n}\n\nfunction readerError(cause: unknown): RunlaneError {\n return cause instanceof RunlaneError\n ? cause\n : new RunlaneError({\n code: ErrorCode.InternalError,\n message: 'Run reader failed.',\n cause,\n })\n}\n","import {\n RunSubscriptionEventType,\n type RunMeta,\n type RunOutput,\n type RunRecord,\n type RunSubscriptionEvent,\n} from '@runlane/contracts/realtime'\n\n/** Read-only live projection. Only fields maintained by snapshot/deltas are exposed. */\nexport interface RunRealtimeState<TTask = undefined> {\n /** Public run identifier. */\n readonly id: RunRecord['id']\n /** Environment that owns the run. */\n readonly environment: RunRecord['environment']\n /** Registered task identifier. */\n readonly taskId: RunRecord['taskId']\n /** Latest delivered lifecycle status; terminal task failure is data. */\n readonly status: RunRecord['status']\n /** Number of started attempts, from the snapshot counters or status delta. */\n readonly attempts: RunRecord['counters']['attempts']\n /** Last delivered status or metadata event sequence, independent of stream positions. */\n readonly eventSequence: RunRecord['eventSequence']\n /** Starting code identity when permitted and available. */\n readonly version: RunRecord['version']\n /** Stored handler output (schema input) when permitted and available; independent of streamed chunks. */\n readonly output: RunOutput<TTask> | undefined\n /** Latest permitted task failure summary, cleared by a status delta without failure. */\n readonly failure: RunRecord['failure']\n /** Permitted metadata after applying top-level patches, including explicit null values. */\n readonly meta: RunMeta<TTask> | undefined\n}\n\nexport function reduceRun<TTask>(\n state: RunRealtimeState<TTask> | undefined,\n event: RunSubscriptionEvent<TTask>,\n): RunRealtimeState<TTask> | undefined\nexport function reduceRun(\n state: RunRealtimeState | undefined,\n event: RunSubscriptionEvent,\n): RunRealtimeState | undefined {\n if (event.type === RunSubscriptionEventType.Snapshot) {\n const { run } = event\n return {\n id: run.id,\n environment: run.environment,\n taskId: run.taskId,\n status: run.status,\n attempts: run.counters.attempts,\n eventSequence: run.eventSequence,\n version: run.version,\n output: run.output,\n failure: run.failure,\n meta: run.meta,\n }\n }\n if (state === undefined) return state\n switch (event.type) {\n case RunSubscriptionEventType.Status:\n return {\n ...state,\n status: event.status,\n attempts: event.attempts,\n eventSequence: event.eventSequence,\n version: event.version,\n output: event.output,\n failure: event.failure,\n }\n case RunSubscriptionEventType.Meta:\n return { ...state, eventSequence: event.eventSequence, meta: { ...state.meta, ...event.patch } }\n case RunSubscriptionEventType.Stream:\n return state\n }\n}\n","import { RunStreamRecordType, type RunStreamCloseReason, type RunStreamRecord } from '@runlane/contracts/realtime'\n\n/** Whether a named reader retains the latest attempt or all attempts. */\nexport enum RunStreamMode {\n Latest = 'latest',\n All = 'all',\n}\n\n/** One retained attempt. Parts are already validated by the task on the server. */\nexport interface RunStreamAttempt<TPart> {\n readonly attempt: number\n readonly parts: readonly TPart[]\n readonly closeReason?: RunStreamCloseReason\n}\n\n/** Retained parts and sticky eviction state for one reader. */\nexport interface StreamState<TPart> {\n readonly attempts: readonly RunStreamAttempt<TPart>[]\n readonly truncated: boolean\n}\n\nexport function reduceStream<TPart>(\n state: StreamState<TPart>,\n record: RunStreamRecord<TPart>,\n mode: RunStreamMode,\n maxParts: number,\n): StreamState<TPart> {\n const attempts =\n mode === RunStreamMode.Latest && record.type === RunStreamRecordType.AttemptStarted ? [] : [...state.attempts]\n const previous = attempts.at(-1)\n const current = previous?.attempt === record.attempt ? previous : { attempt: record.attempt, parts: [] }\n if (current === previous) attempts.pop()\n switch (record.type) {\n case RunStreamRecordType.AttemptStarted:\n attempts.push(current)\n break\n case RunStreamRecordType.Chunk:\n attempts.push({ ...current, parts: [...current.parts, record.value] })\n break\n case RunStreamRecordType.AttemptClosed:\n attempts.push({ ...current, closeReason: record.reason })\n break\n }\n const evicted = evictParts(attempts, maxParts)\n return { attempts, truncated: state.truncated || evicted }\n}\n\nfunction evictParts<TPart>(attempts: RunStreamAttempt<TPart>[], maxParts: number): boolean {\n const excessAttempts = Math.max(0, attempts.length - maxParts)\n attempts.splice(0, excessAttempts)\n let excess = attempts.reduce((total, attempt) => total + attempt.parts.length, 0) - maxParts\n const evicted = excessAttempts > 0 || excess > 0\n while (excess > 0) {\n const oldest = attempts[0]\n if (oldest === undefined) break\n if (oldest.parts.length <= excess) {\n attempts.shift()\n excess -= oldest.parts.length\n } else {\n attempts[0] = { ...oldest, parts: oldest.parts.slice(excess) }\n excess = 0\n }\n }\n return evicted\n}\n","'use client'\n\nimport { useMemo } from 'react'\n\nimport {\n contractDefaults,\n createDurationSchema,\n ErrorCode,\n RunlaneError,\n runStatusValues,\n RunStreamRecordType,\n type DurationString,\n type RealtimeConnectionChange,\n type RunlaneIdInput,\n type RunStreamName,\n type RunStreamPart,\n} from '@runlane/contracts/realtime'\nimport { type RunlaneClient } from '@runlane/realtime/client'\n\nimport { useLatest } from './latest.js'\nimport { useClient } from './provider.js'\nimport { createReaderStore, useReader } from './reader-store.js'\nimport { reduceRun, type RunRealtimeState } from './run-state.js'\nimport { reduceStream, RunStreamMode, type RunStreamAttempt, type StreamState } from './stream-state.js'\n\nexport { RunStreamMode, type RunStreamAttempt } from './stream-state.js'\n\nexport { RunlaneProvider, type RunlaneProviderProps } from './provider.js'\n\nexport type { RunRealtimeState } from './run-state.js'\n\n/** One caller-owned client; disabling a hook opens no reader and clears its state. */\ninterface ReaderOptions {\n readonly client?: RunlaneClient\n readonly accessToken?: string\n readonly enabled?: boolean\n readonly throttle?: DurationString\n readonly onConnectionChange?: (change: RealtimeConnectionChange) => void\n}\n\n/** Run reader options. Callback, token, and throttle changes keep the reader open. */\nexport interface UseRunOptions<TTask = undefined> extends ReaderOptions {\n readonly onComplete?: (run: RunRealtimeState<TTask> | undefined, error?: RunlaneError) => void\n}\n\n/** Live run projection and transport state for this hook instance. */\nexport interface UseRunResult<TTask = undefined> {\n readonly stop: () => void\n readonly run: RunRealtimeState<TTask> | undefined\n readonly error: RunlaneError | undefined\n /** True only after the client's Open notification, until another connection state. */\n readonly isConnected: boolean\n}\n\n/** Subscribe to a snapshot and apply status, metadata, and stream deltas in delivery order. */\nexport function useRun<TTask = undefined>(\n runId: RunlaneIdInput | undefined,\n {\n client: supplied,\n enabled = true,\n accessToken,\n onComplete,\n onConnectionChange,\n throttle = contractDefaults.realtime.renderThrottle,\n }: UseRunOptions<TTask> = {},\n): UseRunResult<TTask> {\n const client = useClient(supplied)\n const latest = useReaderOptions({ accessToken, throttle, onComplete, onConnectionChange })\n const store = useMemo(\n () =>\n createReaderStore<RunRealtimeState<TTask> | undefined>(\n undefined,\n async (options) => {\n if (!enabled || runId === undefined) return\n for await (const event of client.subscribe<TTask>(runId, {\n streams: false,\n accessToken: latest.current.accessToken,\n signal: options.signal,\n onConnectionChange: options.onConnectionChange,\n })) {\n const run = options.update((state) => reduceRun(state, event))\n if (run !== undefined && runStatusValues.isTerminal(run.status)) options.complete()\n }\n },\n {\n throttle: () => latest.current.throttleMs,\n onComplete: (run, error) => latest.current.onComplete?.(run, error),\n onConnectionChange: (change) => latest.current.onConnectionChange?.(change),\n },\n ),\n [runId, client, enabled],\n )\n const { value: run, error, isConnected, stop } = useReader(store)\n return { run, error, isConnected, stop }\n}\n\n/** Named reader policy. Identity changes clear retained parts and attempt history. */\nexport interface UseRunStreamOptions<TPart> extends ReaderOptions {\n readonly onData?: (part: TPart) => void\n readonly mode?: RunStreamMode\n /** Total retained parts across attempts; positive and at most clientMaxPartsLimit. */\n readonly maxParts?: number\n}\n\n/** Bounded attempt history and reader state for this hook instance. */\nexport interface UseRunStreamResult<TPart> {\n readonly stop: () => void\n readonly parts: readonly TPart[]\n readonly attempts: readonly RunStreamAttempt<TPart>[]\n readonly error: RunlaneError | undefined\n readonly isConnected: boolean\n /** Sticky after any part eviction in this reader. */\n readonly truncated: boolean\n}\n\n/** Read a task-declared stream. The server validates parts when writing them. */\nexport function useRunStream<TTask = undefined, TName extends RunStreamName<TTask> = RunStreamName<TTask>>(\n runId: RunlaneIdInput | undefined,\n name: TName,\n {\n client: supplied,\n accessToken,\n onData,\n onConnectionChange,\n throttle = contractDefaults.realtime.renderThrottle,\n enabled = true,\n mode = RunStreamMode.Latest,\n maxParts = contractDefaults.realtime.clientMaxParts,\n }: UseRunStreamOptions<RunStreamPart<TTask, TName>> = {},\n): UseRunStreamResult<RunStreamPart<TTask, TName>> {\n const client = useClient(supplied)\n const latest = useReaderOptions({ accessToken, onData, onConnectionChange, throttle })\n validatePartLimit(maxParts)\n const store = useMemo(\n () =>\n createReaderStore<StreamState<RunStreamPart<TTask, TName>>>(\n { attempts: [], truncated: false },\n async (options) => {\n if (!enabled || runId === undefined) return\n for await (const record of client.readStream<TTask, TName>(runId, name, {\n accessToken: latest.current.accessToken,\n signal: options.signal,\n onConnectionChange: options.onConnectionChange,\n })) {\n if (options.signal.aborted) return\n options.update((state) => reduceStream(state, record, mode, maxParts))\n if (record.type === RunStreamRecordType.Chunk) latest.current.onData?.(record.value)\n if (record.type === RunStreamRecordType.AttemptClosed) options.flush()\n }\n },\n {\n throttle: () => latest.current.throttleMs,\n onConnectionChange: (change) => latest.current.onConnectionChange?.(change),\n },\n ),\n [runId, name, client, enabled, mode, maxParts],\n )\n const { value, error, isConnected, stop } = useReader(store)\n return { ...value, parts: value.attempts.at(-1)?.parts ?? [], error, isConnected, stop }\n}\n\nexport type {\n RunTypes,\n RunOutput,\n RunMeta,\n RunStreams,\n RunStreamName,\n RunStreamPart,\n} from '@runlane/contracts/realtime'\n\nconst throttleSchema = createDurationSchema(\n 'throttle must be a positive DurationString that resolves to whole milliseconds.',\n)\n\nfunction useReaderOptions<T extends { readonly throttle: DurationString }>(options: T) {\n const result = throttleSchema.safeParse(options.throttle)\n if (!result.success)\n throw new RunlaneError({\n code: ErrorCode.ConfigurationInvalid,\n message: 'Invalid render throttle.',\n cause: result.error,\n })\n return useLatest({ ...options, throttleMs: result.data.milliseconds })\n}\n\nfunction validatePartLimit(maxParts: number): void {\n if (!Number.isSafeInteger(maxParts) || maxParts < 1 || maxParts > contractDefaults.realtime.clientMaxPartsLimit)\n throw new RunlaneError({\n code: ErrorCode.ConfigurationInvalid,\n message: 'maxParts must be a positive safe integer no greater than realtime.clientMaxPartsLimit.',\n })\n}\n"],"mappings":";;;;;;AAGA,SAAgB,UAAa,OAAU;CACrC,MAAM,OAAA,GAAMA,MAAAA,OAAAA,CAAO,KAAK;CACxB,CAAA,GAAA,MAAA,gBAAA,OAAsB;EACpB,IAAI,UAAU;CAChB,CAAC;CACD,OAAO;AACT;;ACGA,MAAM,iBAAA,GAAgBC,MAAAA,cAAAA,CAAyC,KAAA,CAAS;AAExE,SAAgB,UAAU,QAAkD;CAC1E,MAAM,YAAA,GAAWC,MAAAA,WAAAA,CAAW,aAAa;CACzC,MAAM,WAAW,UAAU;CAC3B,IAAI,aAAa,KAAA,GACf,MAAM,IAAIC,4BAAAA,aAAa;EACrB,MAAMC,4BAAAA,UAAU;EAChB,SAAS;CACX,CAAC;CACH,OAAO;AACT;;AAQA,SAAgB,gBAAgB,EAAE,UAAU,GAAG,WAAiC;CAC9E,MAAM,SAAS,UAAU,OAAO;CAChC,MAAM,EAAE,SAAS,UAAU;CAC3B,MAAM,UAAA,GAASC,MAAAA,QAAAA,OAAc;EAC3B,IAAI;EACJ,MAAM,WAAoE,YAAY;GACpF,MAAM,WAAW,OAAO,QAAQ;GAChC,IAAI,aAAa,KAAA,GACf,MAAM,IAAIF,4BAAAA,aAAa;IAAE,MAAMC,4BAAAA,UAAU;IAAc,SAAS;GAA2C,CAAC;GAC9G,OAAO,SAAS,OAAO;EACzB;EAGA,SAAS,YAA2B;GAClC,IAAI,UAAU,KAAA,GAAW,OAAO;GAChC,IAAI;GACJ,IAAI;IACF,MAAM,IAAI,IAAI,SAAS,OAAO,aAAa,cAAc,KAAA,IAAY,SAAS,IAAI;GACpF,SAAS,OAAO;IACd,MAAM,IAAID,4BAAAA,aAAa;KACrB,MAAMC,4BA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