@cadenya/widgets 1.0.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/README.md +133 -0
- package/api.md +66 -0
- package/dist/client.d.ts +33 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +49 -0
- package/dist/client.js.map +1 -0
- package/dist/core/error.d.ts +39 -0
- package/dist/core/error.d.ts.map +1 -0
- package/dist/core/error.js +56 -0
- package/dist/core/error.js.map +1 -0
- package/dist/core/http.d.ts +140 -0
- package/dist/core/http.d.ts.map +1 -0
- package/dist/core/http.js +525 -0
- package/dist/core/http.js.map +1 -0
- package/dist/core/pagination.d.ts +12 -0
- package/dist/core/pagination.d.ts.map +1 -0
- package/dist/core/pagination.js +29 -0
- package/dist/core/pagination.js.map +1 -0
- package/dist/core/sse.d.ts +44 -0
- package/dist/core/sse.d.ts.map +1 -0
- package/dist/core/sse.js +350 -0
- package/dist/core/sse.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/resources/config.d.ts +16 -0
- package/dist/resources/config.d.ts.map +1 -0
- package/dist/resources/config.js +21 -0
- package/dist/resources/config.js.map +1 -0
- package/dist/resources/conversations.d.ts +173 -0
- package/dist/resources/conversations.d.ts.map +1 -0
- package/dist/resources/conversations.js +150 -0
- package/dist/resources/conversations.js.map +1 -0
- package/dist/types.d.ts +461 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +29 -0
- package/src/client.ts +87 -0
- package/src/core/error.ts +69 -0
- package/src/core/http.ts +639 -0
- package/src/core/pagination.ts +27 -0
- package/src/core/sse.ts +338 -0
- package/src/index.ts +13 -0
- package/src/resources/config.ts +22 -0
- package/src/resources/conversations.ts +232 -0
- package/src/types.ts +512 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pagination.js","sourceRoot":"","sources":["../../src/core/pagination.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAE1E,MAAM,OAAO,IAAI;IAEJ;IACA;IACQ;IAHnB,YACW,KAAU,EACV,UAA8B,EACtB,SAA+C;QAFvD,UAAK,GAAL,KAAK,CAAK;QACV,eAAU,GAAV,UAAU,CAAoB;QACtB,cAAS,GAAT,SAAS,CAAsC;IAC/D,CAAC;IAEJ,WAAW;QACT,OAAO,IAAI,CAAC,UAAU,KAAK,SAAS,IAAI,IAAI,CAAC,UAAU,KAAK,EAAE,CAAC;IACjE,CAAC;IAED,KAAK,CAAC,WAAW;QACf,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YAAE,OAAO,IAAI,CAAC;QACrC,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,UAAoB,CAAC,CAAC;IACnD,CAAC;IAED,yDAAyD;IACzD,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC;QAC3B,IAAI,IAAI,GAAmB,IAAI,CAAC;QAChC,OAAO,IAAI,EAAE,CAAC;YACZ,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK;gBAAE,MAAM,IAAI,CAAC;YAC1C,IAAI,GAAG,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC;QAClC,CAAC;IACH,CAAC;CACF","sourcesContent":["/** Cursor pagination. Pages are async-iterable across page boundaries. */\n\nexport class Page<T> implements AsyncIterable<T> {\n constructor(\n readonly items: T[],\n readonly nextCursor: string | undefined,\n private readonly fetchPage: (cursor: string) => Promise<Page<T>>,\n ) {}\n\n hasNextPage(): boolean {\n return this.nextCursor !== undefined && this.nextCursor !== '';\n }\n\n async getNextPage(): Promise<Page<T> | null> {\n if (!this.hasNextPage()) return null;\n return this.fetchPage(this.nextCursor as string);\n }\n\n /** Iterate every item on every page, fetching lazily. */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n let page: Page<T> | null = this;\n while (page) {\n for (const item of page.items) yield item;\n page = await page.getNextPage();\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-sent events over fetch. Parses the wire format incrementally from a
|
|
3
|
+
* ReadableStream — multi-line data, event names, comments, CRLF — with no
|
|
4
|
+
* dependencies. Each event's `data` is JSON-decoded to `T`.
|
|
5
|
+
*/
|
|
6
|
+
export interface ServerSentEvent<T> {
|
|
7
|
+
event: string | undefined;
|
|
8
|
+
data: T;
|
|
9
|
+
id: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
export declare class Stream<T> implements AsyncIterable<T> {
|
|
12
|
+
private response;
|
|
13
|
+
private readonly signal?;
|
|
14
|
+
private readonly skipEvents;
|
|
15
|
+
private readonly reconnect?;
|
|
16
|
+
/**
|
|
17
|
+
* The resume checkpoint: seeded from the id this stream was resumed with,
|
|
18
|
+
* then updated by `id:` fields (persistent across events per the SSE
|
|
19
|
+
* spec). Pass it as `options.lastEventId` to resume after a disconnect.
|
|
20
|
+
*/
|
|
21
|
+
lastEventId: string | undefined;
|
|
22
|
+
private releaseDeadline;
|
|
23
|
+
/** Server `retry:` hint (ms), used as the reconnection delay when set. */
|
|
24
|
+
private retryHintMs;
|
|
25
|
+
/** Stream-owned cancellation: close() trips it so backoff sleeps and
|
|
26
|
+
* in-flight reconnect handshakes settle immediately. */
|
|
27
|
+
private readonly closer;
|
|
28
|
+
private closed;
|
|
29
|
+
private consumed;
|
|
30
|
+
private activeReader;
|
|
31
|
+
constructor(response: Response, signal?: AbortSignal | undefined, resumedFrom?: string, skipEvents?: readonly string[], reconnect?: ((lastEventId: string | undefined, signal: AbortSignal) => Promise<Response>) | undefined);
|
|
32
|
+
/**
|
|
33
|
+
* Idempotent explicit close: cancels the underlying response body exactly
|
|
34
|
+
* once and detaches deadline state. Safe before iteration (an opened but
|
|
35
|
+
* never-iterated stream would otherwise hold its connection), during
|
|
36
|
+
* iteration from another control path, and after EOF.
|
|
37
|
+
*/
|
|
38
|
+
close(): Promise<void>;
|
|
39
|
+
/** Iterate decoded event payloads. */
|
|
40
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
41
|
+
/** Iterate full events (name + id + decoded data). */
|
|
42
|
+
events(): AsyncGenerator<ServerSentEvent<T>>;
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=sse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/core/sse.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAKH,MAAM,WAAW,eAAe,CAAC,CAAC;IAChC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,IAAI,EAAE,CAAC,CAAC;IACR,EAAE,EAAE,MAAM,GAAG,SAAS,CAAC;CACxB;AAED,qBAAa,MAAM,CAAC,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;IAmB9C,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;IAIxB,OAAO,CAAC,QAAQ,CAAC,UAAU;IAM3B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC;IA7B7B;;;;OAIG;IACH,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAEhC,OAAO,CAAC,eAAe,CAA2B;IAClD,0EAA0E;IAC1E,OAAO,CAAC,WAAW,CAAqB;IACxC;4DACwD;IACxD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAyB;IAChD,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,YAAY,CAAsD;gBAGhE,QAAQ,EAAE,QAAQ,EACT,MAAM,CAAC,EAAE,WAAW,YAAA,EACrC,WAAW,CAAC,EAAE,MAAM,EAGH,UAAU,GAAE,SAAS,MAAM,EAAO,EAMlC,SAAS,CAAC,GAAE,CAC3B,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,MAAM,EAAE,WAAW,KAChB,OAAO,CAAC,QAAQ,CAAC,aAAA;IAMxB;;;;;OAKG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyB5B,sCAAsC;IAC/B,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC;IAMjD,sDAAsD;IAC/C,MAAM,IAAI,cAAc,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;CAoPpD"}
|
package/dist/core/sse.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-sent events over fetch. Parses the wire format incrementally from a
|
|
3
|
+
* ReadableStream — multi-line data, event names, comments, CRLF — with no
|
|
4
|
+
* dependencies. Each event's `data` is JSON-decoded to `T`.
|
|
5
|
+
*/
|
|
6
|
+
import { APIConnectionError, APIResponseError, APIUserAbortError } from './error.js';
|
|
7
|
+
import { takeStreamCleanup } from './http.js';
|
|
8
|
+
export class Stream {
|
|
9
|
+
response;
|
|
10
|
+
signal;
|
|
11
|
+
skipEvents;
|
|
12
|
+
reconnect;
|
|
13
|
+
/**
|
|
14
|
+
* The resume checkpoint: seeded from the id this stream was resumed with,
|
|
15
|
+
* then updated by `id:` fields (persistent across events per the SSE
|
|
16
|
+
* spec). Pass it as `options.lastEventId` to resume after a disconnect.
|
|
17
|
+
*/
|
|
18
|
+
lastEventId;
|
|
19
|
+
releaseDeadline;
|
|
20
|
+
/** Server `retry:` hint (ms), used as the reconnection delay when set. */
|
|
21
|
+
retryHintMs;
|
|
22
|
+
/** Stream-owned cancellation: close() trips it so backoff sleeps and
|
|
23
|
+
* in-flight reconnect handshakes settle immediately. */
|
|
24
|
+
closer = new AbortController();
|
|
25
|
+
closed = false;
|
|
26
|
+
consumed = false;
|
|
27
|
+
activeReader;
|
|
28
|
+
constructor(response, signal, resumedFrom,
|
|
29
|
+
// Transport-housekeeping event names (`event:` field) skipped without
|
|
30
|
+
// decoding; their `id:` fields still advance the resume checkpoint.
|
|
31
|
+
skipEvents = [],
|
|
32
|
+
// Re-issues the request with the current resume checkpoint. When set,
|
|
33
|
+
// a MID-STREAM transport drop reconnects automatically (like the
|
|
34
|
+
// platform's EventSource): bounded attempts, backoff honoring the
|
|
35
|
+
// server's `retry:` hint, counter reset once events flow again. A clean
|
|
36
|
+
// EOF, an explicit close(), and a caller abort NEVER reconnect.
|
|
37
|
+
reconnect) {
|
|
38
|
+
this.response = response;
|
|
39
|
+
this.signal = signal;
|
|
40
|
+
this.skipEvents = skipEvents;
|
|
41
|
+
this.reconnect = reconnect;
|
|
42
|
+
this.lastEventId = resumedFrom;
|
|
43
|
+
this.releaseDeadline = takeStreamCleanup(response);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Idempotent explicit close: cancels the underlying response body exactly
|
|
47
|
+
* once and detaches deadline state. Safe before iteration (an opened but
|
|
48
|
+
* never-iterated stream would otherwise hold its connection), during
|
|
49
|
+
* iteration from another control path, and after EOF.
|
|
50
|
+
*/
|
|
51
|
+
async close() {
|
|
52
|
+
if (this.closed)
|
|
53
|
+
return;
|
|
54
|
+
this.closed = true;
|
|
55
|
+
this.closer.abort();
|
|
56
|
+
if (this.activeReader) {
|
|
57
|
+
// The body is LOCKED to the active reader: body.cancel() would
|
|
58
|
+
// reject, silently doing nothing. Cancel the reader itself — the
|
|
59
|
+
// pending read() settles, the generator's finally runs the terminal
|
|
60
|
+
// cleanup (deadline release included), and the consumer unblocks.
|
|
61
|
+
try {
|
|
62
|
+
await this.activeReader.cancel();
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Reader already errored/released; the generator finally cleans up.
|
|
66
|
+
}
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
// Pre-iteration close: no reader owns the body yet.
|
|
70
|
+
this.releaseDeadline?.();
|
|
71
|
+
try {
|
|
72
|
+
await this.response.body?.cancel();
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// Already closed.
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Iterate decoded event payloads. */
|
|
79
|
+
async *[Symbol.asyncIterator]() {
|
|
80
|
+
for await (const event of this.events()) {
|
|
81
|
+
yield event.data;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Iterate full events (name + id + decoded data). */
|
|
85
|
+
async *events() {
|
|
86
|
+
// One Stream wraps exactly one response body. The consumed transition
|
|
87
|
+
// is synchronous (before any await/getReader), so a competing second
|
|
88
|
+
// iterator — concurrent or after EOF/error — deterministically gets the
|
|
89
|
+
// stable SDK error instead of a raw locked-stream TypeError or a silent
|
|
90
|
+
// empty sequence. A closed-but-never-consumed stream still ends empty.
|
|
91
|
+
if (this.closed && !this.consumed)
|
|
92
|
+
return;
|
|
93
|
+
if (this.consumed) {
|
|
94
|
+
throw new Error('stream already consumed — reconnect with a new call passing { lastEventId: stream.lastEventId }');
|
|
95
|
+
}
|
|
96
|
+
this.consumed = true;
|
|
97
|
+
const firstBody = this.response.body;
|
|
98
|
+
if (!firstBody)
|
|
99
|
+
throw new Error('SSE response has no body');
|
|
100
|
+
// Connection-local: a reconnect swaps in a FRESH decoder, so a partial
|
|
101
|
+
// UTF-8 code point from the dead connection cannot corrupt the first
|
|
102
|
+
// resumed event.
|
|
103
|
+
let decoder = new TextDecoder();
|
|
104
|
+
let reader = firstBody.getReader();
|
|
105
|
+
this.activeReader = reader;
|
|
106
|
+
let buffer = '';
|
|
107
|
+
let dataLines = [];
|
|
108
|
+
let eventName;
|
|
109
|
+
// Consecutive failed reconnects; reset whenever a chunk arrives.
|
|
110
|
+
let reconnectAttempts = 0;
|
|
111
|
+
const MAX_RECONNECTS = 5;
|
|
112
|
+
// A mid-stream transport drop swaps in a fresh connection resumed from
|
|
113
|
+
// the checkpoint. Partial buffered lines from the dead connection are
|
|
114
|
+
// DISCARDED — the server re-sends everything after Last-Event-ID.
|
|
115
|
+
const tryReconnect = async () => {
|
|
116
|
+
while (this.reconnect && !this.closed && !this.signal?.aborted && reconnectAttempts < MAX_RECONNECTS) {
|
|
117
|
+
const delay = this.retryHintMs ?? Math.min(500 * 2 ** reconnectAttempts, 10_000);
|
|
118
|
+
reconnectAttempts++;
|
|
119
|
+
// Abortable sleep: BOTH the caller's signal and the stream's own
|
|
120
|
+
// closer wake it, and listeners are removed on every exit path so a
|
|
121
|
+
// long-lived flapping stream cannot accumulate them.
|
|
122
|
+
await new Promise((resolve) => {
|
|
123
|
+
const finish = () => {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
this.signal?.removeEventListener('abort', finish);
|
|
126
|
+
this.closer.signal.removeEventListener('abort', finish);
|
|
127
|
+
resolve();
|
|
128
|
+
};
|
|
129
|
+
const timer = setTimeout(finish, delay);
|
|
130
|
+
this.signal?.addEventListener('abort', finish);
|
|
131
|
+
this.closer.signal.addEventListener('abort', finish);
|
|
132
|
+
});
|
|
133
|
+
if (this.closed || this.signal?.aborted)
|
|
134
|
+
return false;
|
|
135
|
+
let next;
|
|
136
|
+
try {
|
|
137
|
+
next = await this.reconnect(this.lastEventId, this.closer.signal);
|
|
138
|
+
}
|
|
139
|
+
catch (err) {
|
|
140
|
+
if (this.closed)
|
|
141
|
+
return false;
|
|
142
|
+
// A TRANSPORT handshake failure (server restarting, connection
|
|
143
|
+
// refused) consumes budget and retries; an HTTP-level failure
|
|
144
|
+
// (e.g. expired credentials -> APIError) propagates immediately —
|
|
145
|
+
// reconnecting cannot fix it and must not mask it.
|
|
146
|
+
if (err instanceof APIConnectionError)
|
|
147
|
+
continue;
|
|
148
|
+
throw err;
|
|
149
|
+
}
|
|
150
|
+
if (this.closed) {
|
|
151
|
+
void next.body?.cancel().catch(() => { });
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
// Release the SUPERSEDED connection completely: cancel its reader
|
|
155
|
+
// (unlocking the old body) and its deadline cleanup, exactly once.
|
|
156
|
+
try {
|
|
157
|
+
await reader.cancel();
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// Dead reader.
|
|
161
|
+
}
|
|
162
|
+
reader.releaseLock();
|
|
163
|
+
this.releaseDeadline?.();
|
|
164
|
+
this.response = next;
|
|
165
|
+
this.releaseDeadline = takeStreamCleanup(next);
|
|
166
|
+
const nextBody = next.body;
|
|
167
|
+
if (!nextBody)
|
|
168
|
+
throw new Error('SSE response has no body');
|
|
169
|
+
reader = nextBody.getReader();
|
|
170
|
+
this.activeReader = reader;
|
|
171
|
+
buffer = '';
|
|
172
|
+
dataLines = [];
|
|
173
|
+
eventName = undefined;
|
|
174
|
+
decoder = new TextDecoder();
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
return false;
|
|
178
|
+
};
|
|
179
|
+
const flush = () => {
|
|
180
|
+
if (dataLines.length === 0)
|
|
181
|
+
return undefined;
|
|
182
|
+
const raw = dataLines.join('\n');
|
|
183
|
+
dataLines = [];
|
|
184
|
+
const name = eventName;
|
|
185
|
+
eventName = undefined;
|
|
186
|
+
// Housekeeping frames (e.g. ping/open) never reach the consumer and
|
|
187
|
+
// never JSON-decode - but their id: has already advanced the resume
|
|
188
|
+
// checkpoint above.
|
|
189
|
+
if (name !== undefined && this.skipEvents.includes(name))
|
|
190
|
+
return undefined;
|
|
191
|
+
let data;
|
|
192
|
+
try {
|
|
193
|
+
data = JSON.parse(raw);
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
// Malformed event JSON is a PROTOCOL error, distinct from transport
|
|
197
|
+
// failure.
|
|
198
|
+
throw new APIResponseError(this.response.status, 'SSE event data is not valid JSON', err);
|
|
199
|
+
}
|
|
200
|
+
// Per the SSE spec the last-event-ID buffer persists across events
|
|
201
|
+
// until another `id:` field changes it (an empty one resets it).
|
|
202
|
+
return { event: name, data, id: this.lastEventId };
|
|
203
|
+
};
|
|
204
|
+
// WHATWG event streams terminate lines with LF, CRLF, OR bare CR; a CR
|
|
205
|
+
// at a chunk boundary must wait for the next chunk to see whether an LF
|
|
206
|
+
// follows (CRLF is one terminator, never two).
|
|
207
|
+
const nextLine = (atEof) => {
|
|
208
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
209
|
+
const ch = buffer[i];
|
|
210
|
+
if (ch === '\n') {
|
|
211
|
+
const line = buffer.slice(0, i);
|
|
212
|
+
buffer = buffer.slice(i + 1);
|
|
213
|
+
return line;
|
|
214
|
+
}
|
|
215
|
+
if (ch === '\r') {
|
|
216
|
+
if (i + 1 < buffer.length) {
|
|
217
|
+
const line = buffer.slice(0, i);
|
|
218
|
+
buffer = buffer.slice(buffer[i + 1] === '\n' ? i + 2 : i + 1);
|
|
219
|
+
return line;
|
|
220
|
+
}
|
|
221
|
+
if (atEof) {
|
|
222
|
+
const line = buffer.slice(0, i);
|
|
223
|
+
buffer = '';
|
|
224
|
+
return line;
|
|
225
|
+
}
|
|
226
|
+
return null; // possible CRLF split across chunks
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
};
|
|
231
|
+
const processLine = (line) => {
|
|
232
|
+
if (line === '')
|
|
233
|
+
return flush();
|
|
234
|
+
if (line.startsWith(':'))
|
|
235
|
+
return undefined; // comment / keep-alive
|
|
236
|
+
const colonAt = line.indexOf(':');
|
|
237
|
+
const field = colonAt === -1 ? line : line.slice(0, colonAt);
|
|
238
|
+
let value = colonAt === -1 ? '' : line.slice(colonAt + 1);
|
|
239
|
+
if (value.startsWith(' '))
|
|
240
|
+
value = value.slice(1);
|
|
241
|
+
switch (field) {
|
|
242
|
+
case 'data':
|
|
243
|
+
dataLines.push(value);
|
|
244
|
+
break;
|
|
245
|
+
case 'event':
|
|
246
|
+
eventName = value;
|
|
247
|
+
break;
|
|
248
|
+
case 'id':
|
|
249
|
+
// Per the event-stream algorithm, ids containing U+0000 are
|
|
250
|
+
// ignored entirely; an empty id resets the buffer.
|
|
251
|
+
if (!value.includes('\0')) {
|
|
252
|
+
this.lastEventId = value === '' ? undefined : value;
|
|
253
|
+
}
|
|
254
|
+
break;
|
|
255
|
+
case 'retry':
|
|
256
|
+
// Reconnection-delay hint; honored when auto-reconnect is active.
|
|
257
|
+
if (/^[0-9]+$/.test(value))
|
|
258
|
+
this.retryHintMs = Math.min(Number(value), 60_000);
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
return undefined;
|
|
262
|
+
};
|
|
263
|
+
try {
|
|
264
|
+
while (true) {
|
|
265
|
+
if (this.signal?.aborted)
|
|
266
|
+
throw new APIUserAbortError();
|
|
267
|
+
let done;
|
|
268
|
+
let value;
|
|
269
|
+
try {
|
|
270
|
+
({ done, value } = await reader.read());
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
// A user abort mid-read surfaces as a raw AbortError DOMException;
|
|
274
|
+
// the public contract is APIUserAbortError regardless of when the
|
|
275
|
+
// abort lands. Partial buffered events are NOT flushed. Any other
|
|
276
|
+
// read failure is a transport failure — auto-reconnect resumes
|
|
277
|
+
// from the checkpoint when configured; otherwise the public
|
|
278
|
+
// contract is APIConnectionError before AND after response
|
|
279
|
+
// headers, never a runtime-specific error shape.
|
|
280
|
+
if (this.signal?.aborted)
|
|
281
|
+
throw new APIUserAbortError();
|
|
282
|
+
if (this.closed)
|
|
283
|
+
break;
|
|
284
|
+
if (await tryReconnect())
|
|
285
|
+
continue;
|
|
286
|
+
if (this.closed || this.signal?.aborted)
|
|
287
|
+
break;
|
|
288
|
+
throw new APIConnectionError(err);
|
|
289
|
+
}
|
|
290
|
+
// Re-check AFTER every awaited read: a chunk that arrives
|
|
291
|
+
// concurrently with close() must not be processed.
|
|
292
|
+
if (this.closed)
|
|
293
|
+
break;
|
|
294
|
+
if (done)
|
|
295
|
+
break;
|
|
296
|
+
// Bytes flowing again: the reconnect budget is per-outage.
|
|
297
|
+
reconnectAttempts = 0;
|
|
298
|
+
buffer += decoder.decode(value, { stream: true });
|
|
299
|
+
let line;
|
|
300
|
+
while ((line = nextLine(false)) !== null) {
|
|
301
|
+
const event = processLine(line);
|
|
302
|
+
if (event)
|
|
303
|
+
yield event;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
// The stream may end without a trailing newline: the leftover buffer
|
|
307
|
+
// is still line data and must be parsed, not dropped.
|
|
308
|
+
buffer += decoder.decode();
|
|
309
|
+
let tail;
|
|
310
|
+
while ((tail = nextLine(true)) !== null) {
|
|
311
|
+
const event = processLine(tail);
|
|
312
|
+
if (event)
|
|
313
|
+
yield event;
|
|
314
|
+
}
|
|
315
|
+
if (buffer !== '') {
|
|
316
|
+
const event = processLine(buffer);
|
|
317
|
+
if (event)
|
|
318
|
+
yield event;
|
|
319
|
+
}
|
|
320
|
+
// Spec-compliant servers end with a blank line, but flush a trailing
|
|
321
|
+
// event if the stream closed without one.
|
|
322
|
+
const last = flush();
|
|
323
|
+
if (last)
|
|
324
|
+
yield last;
|
|
325
|
+
}
|
|
326
|
+
finally {
|
|
327
|
+
// EVERY terminal path — EOF, decode error, transport error, caller
|
|
328
|
+
// abort, explicit close, early consumer return — releases the
|
|
329
|
+
// deadline listener and the body exactly once.
|
|
330
|
+
this.closed = true;
|
|
331
|
+
this.activeReader = undefined;
|
|
332
|
+
this.releaseDeadline?.();
|
|
333
|
+
try {
|
|
334
|
+
await reader.cancel();
|
|
335
|
+
}
|
|
336
|
+
catch {
|
|
337
|
+
// Already cancelled/errored.
|
|
338
|
+
}
|
|
339
|
+
reader.releaseLock();
|
|
340
|
+
try {
|
|
341
|
+
// The CURRENT connection's body (reconnects swap this.response).
|
|
342
|
+
await this.response.body?.cancel();
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
// Already closed.
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
//# sourceMappingURL=sse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../src/core/sse.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACrF,OAAO,EAAE,iBAA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,CAAC;gBAClB,MAAM,KAAK,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;gBAClC,IAAI,KAAK;oBAAE,MAAM,KAAK,CAAC;YACzB,CAAC;YACD,qEAAqE;YACrE,0CAA0C;YAC1C,MAAM,IAAI,GAAG,KAAK,EAAE,CAAC;YACrB,IAAI,IAAI;gBAAE,MAAM,IAAI,CAAC;QACvB,CAAC;gBAAS,CAAC;YACT,mEAAmE;YACnE,8DAA8D;YAC9D,+CAA+C;YAC/C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;YACnB,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;YAC9B,IAAI,CAAC,eAAe,EAAE,EAAE,CAAC;YACzB,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;YACxB,CAAC;YAAC,MAAM,CAAC;gBACP,6BAA6B;YAC/B,CAAC;YACD,MAAM,CAAC,WAAW,EAAE,CAAC;YACrB,IAAI,CAAC;gBACH,iEAAiE;gBACjE,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;YACrC,CAAC;YAAC,MAAM,CAAC;gBACP,kBAAkB;YACpB,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Server-sent events over fetch. Parses the wire format incrementally from a\n * ReadableStream — multi-line data, event names, comments, CRLF — with no\n * dependencies. Each event's `data` is JSON-decoded to `T`.\n */\n\nimport { APIConnectionError, APIResponseError, APIUserAbortError } from './error.js';\nimport { takeStreamCleanup } from './http.js';\n\nexport interface ServerSentEvent<T> {\n event: string | undefined;\n data: T;\n id: string | undefined;\n}\n\nexport class Stream<T> implements AsyncIterable<T> {\n /**\n * The resume checkpoint: seeded from the id this stream was resumed with,\n * then updated by `id:` fields (persistent across events per the SSE\n * spec). Pass it as `options.lastEventId` to resume after a disconnect.\n */\n lastEventId: string | undefined;\n\n private releaseDeadline: (() => void) | undefined;\n /** Server `retry:` hint (ms), used as the reconnection delay when set. */\n private retryHintMs: number | undefined;\n /** Stream-owned cancellation: close() trips it so backoff sleeps and\n * in-flight reconnect handshakes settle immediately. */\n private readonly closer = new AbortController();\n private closed = false;\n private consumed = false;\n private activeReader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n constructor(\n private response: Response,\n private readonly signal?: AbortSignal,\n resumedFrom?: string,\n // Transport-housekeeping event names (`event:` field) skipped without\n // decoding; their `id:` fields still advance the resume checkpoint.\n private readonly skipEvents: readonly string[] = [],\n // Re-issues the request with the current resume checkpoint. When set,\n // a MID-STREAM transport drop reconnects automatically (like the\n // platform's EventSource): bounded attempts, backoff honoring the\n // server's `retry:` hint, counter reset once events flow again. A clean\n // EOF, an explicit close(), and a caller abort NEVER reconnect.\n private readonly reconnect?: (\n lastEventId: string | undefined,\n signal: AbortSignal,\n ) => Promise<Response>,\n ) {\n this.lastEventId = resumedFrom;\n this.releaseDeadline = takeStreamCleanup(response);\n }\n\n /**\n * Idempotent explicit close: cancels the underlying response body exactly\n * once and detaches deadline state. Safe before iteration (an opened but\n * never-iterated stream would otherwise hold its connection), during\n * iteration from another control path, and after EOF.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n this.closer.abort();\n if (this.activeReader) {\n // The body is LOCKED to the active reader: body.cancel() would\n // reject, silently doing nothing. Cancel the reader itself — the\n // pending read() settles, the generator's finally runs the terminal\n // cleanup (deadline release included), and the consumer unblocks.\n try {\n await this.activeReader.cancel();\n } catch {\n // Reader already errored/released; the generator finally cleans up.\n }\n return;\n }\n // Pre-iteration close: no reader owns the body yet.\n this.releaseDeadline?.();\n try {\n await this.response.body?.cancel();\n } catch {\n // Already closed.\n }\n }\n\n /** Iterate decoded event payloads. */\n async *[Symbol.asyncIterator](): AsyncIterator<T> {\n for await (const event of this.events()) {\n yield event.data;\n }\n }\n\n /** Iterate full events (name + id + decoded data). */\n async *events(): AsyncGenerator<ServerSentEvent<T>> {\n // One Stream wraps exactly one response body. The consumed transition\n // is synchronous (before any await/getReader), so a competing second\n // iterator — concurrent or after EOF/error — deterministically gets the\n // stable SDK error instead of a raw locked-stream TypeError or a silent\n // empty sequence. A closed-but-never-consumed stream still ends empty.\n if (this.closed && !this.consumed) return;\n if (this.consumed) {\n throw new Error(\n 'stream already consumed — reconnect with a new call passing { lastEventId: stream.lastEventId }',\n );\n }\n this.consumed = true;\n const firstBody = this.response.body;\n if (!firstBody) throw new Error('SSE response has no body');\n // Connection-local: a reconnect swaps in a FRESH decoder, so a partial\n // UTF-8 code point from the dead connection cannot corrupt the first\n // resumed event.\n let decoder = new TextDecoder();\n let reader = firstBody.getReader();\n this.activeReader = reader;\n let buffer = '';\n let dataLines: string[] = [];\n let eventName: string | undefined;\n // Consecutive failed reconnects; reset whenever a chunk arrives.\n let reconnectAttempts = 0;\n const MAX_RECONNECTS = 5;\n\n // A mid-stream transport drop swaps in a fresh connection resumed from\n // the checkpoint. Partial buffered lines from the dead connection are\n // DISCARDED — the server re-sends everything after Last-Event-ID.\n const tryReconnect = async (): Promise<boolean> => {\n while (this.reconnect && !this.closed && !this.signal?.aborted && reconnectAttempts < MAX_RECONNECTS) {\n const delay = this.retryHintMs ?? Math.min(500 * 2 ** reconnectAttempts, 10_000);\n reconnectAttempts++;\n // Abortable sleep: BOTH the caller's signal and the stream's own\n // closer wake it, and listeners are removed on every exit path so a\n // long-lived flapping stream cannot accumulate them.\n await new Promise<void>((resolve) => {\n const finish = () => {\n clearTimeout(timer);\n this.signal?.removeEventListener('abort', finish);\n this.closer.signal.removeEventListener('abort', finish);\n resolve();\n };\n const timer = setTimeout(finish, delay);\n this.signal?.addEventListener('abort', finish);\n this.closer.signal.addEventListener('abort', finish);\n });\n if (this.closed || this.signal?.aborted) return false;\n let next: Response;\n try {\n next = await this.reconnect(this.lastEventId, this.closer.signal);\n } catch (err) {\n if (this.closed) return false;\n // A TRANSPORT handshake failure (server restarting, connection\n // refused) consumes budget and retries; an HTTP-level failure\n // (e.g. expired credentials -> APIError) propagates immediately —\n // reconnecting cannot fix it and must not mask it.\n if (err instanceof APIConnectionError) continue;\n throw err;\n }\n if (this.closed) {\n void next.body?.cancel().catch(() => {});\n return false;\n }\n // Release the SUPERSEDED connection completely: cancel its reader\n // (unlocking the old body) and its deadline cleanup, exactly once.\n try {\n await reader.cancel();\n } catch {\n // Dead reader.\n }\n reader.releaseLock();\n this.releaseDeadline?.();\n this.response = next;\n this.releaseDeadline = takeStreamCleanup(next);\n const nextBody = next.body;\n if (!nextBody) throw new Error('SSE response has no body');\n reader = nextBody.getReader();\n this.activeReader = reader;\n buffer = '';\n dataLines = [];\n eventName = undefined;\n decoder = new TextDecoder();\n return true;\n }\n return false;\n };\n\n const flush = (): ServerSentEvent<T> | undefined => {\n if (dataLines.length === 0) return undefined;\n const raw = dataLines.join('\\n');\n dataLines = [];\n const name = eventName;\n eventName = undefined;\n // Housekeeping frames (e.g. ping/open) never reach the consumer and\n // never JSON-decode - but their id: has already advanced the resume\n // checkpoint above.\n if (name !== undefined && this.skipEvents.includes(name)) return undefined;\n let data: T;\n try {\n data = JSON.parse(raw) as T;\n } catch (err) {\n // Malformed event JSON is a PROTOCOL error, distinct from transport\n // failure.\n throw new APIResponseError(this.response.status, 'SSE event data is not valid JSON', err);\n }\n // Per the SSE spec the last-event-ID buffer persists across events\n // until another `id:` field changes it (an empty one resets it).\n return { event: name, data, id: this.lastEventId };\n };\n\n // WHATWG event streams terminate lines with LF, CRLF, OR bare CR; a CR\n // at a chunk boundary must wait for the next chunk to see whether an LF\n // follows (CRLF is one terminator, never two).\n const nextLine = (atEof: boolean): string | null => {\n for (let i = 0; i < buffer.length; i++) {\n const ch = buffer[i];\n if (ch === '\\n') {\n const line = buffer.slice(0, i);\n buffer = buffer.slice(i + 1);\n return line;\n }\n if (ch === '\\r') {\n if (i + 1 < buffer.length) {\n const line = buffer.slice(0, i);\n buffer = buffer.slice(buffer[i + 1] === '\\n' ? i + 2 : i + 1);\n return line;\n }\n if (atEof) {\n const line = buffer.slice(0, i);\n buffer = '';\n return line;\n }\n return null; // possible CRLF split across chunks\n }\n }\n return null;\n };\n\n const processLine = (line: string): ServerSentEvent<T> | undefined => {\n if (line === '') return flush();\n if (line.startsWith(':')) return undefined; // comment / keep-alive\n\n const colonAt = line.indexOf(':');\n const field = colonAt === -1 ? line : line.slice(0, colonAt);\n let value = colonAt === -1 ? '' : line.slice(colonAt + 1);\n if (value.startsWith(' ')) value = value.slice(1);\n\n switch (field) {\n case 'data':\n dataLines.push(value);\n break;\n case 'event':\n eventName = value;\n break;\n case 'id':\n // Per the event-stream algorithm, ids containing U+0000 are\n // ignored entirely; an empty id resets the buffer.\n if (!value.includes('\\0')) {\n this.lastEventId = value === '' ? undefined : value;\n }\n break;\n case 'retry':\n // Reconnection-delay hint; honored when auto-reconnect is active.\n if (/^[0-9]+$/.test(value)) this.retryHintMs = Math.min(Number(value), 60_000);\n break;\n }\n return undefined;\n };\n\n try {\n while (true) {\n if (this.signal?.aborted) throw new APIUserAbortError();\n let done: boolean;\n let value: Uint8Array | undefined;\n try {\n ({ done, value } = await reader.read());\n } catch (err) {\n // A user abort mid-read surfaces as a raw AbortError DOMException;\n // the public contract is APIUserAbortError regardless of when the\n // abort lands. Partial buffered events are NOT flushed. Any other\n // read failure is a transport failure — auto-reconnect resumes\n // from the checkpoint when configured; otherwise the public\n // contract is APIConnectionError before AND after response\n // headers, never a runtime-specific error shape.\n if (this.signal?.aborted) throw new APIUserAbortError();\n if (this.closed) break;\n if (await tryReconnect()) continue;\n if (this.closed || this.signal?.aborted) break;\n throw new APIConnectionError(err);\n }\n // Re-check AFTER every awaited read: a chunk that arrives\n // concurrently with close() must not be processed.\n if (this.closed) break;\n if (done) break;\n // Bytes flowing again: the reconnect budget is per-outage.\n reconnectAttempts = 0;\n buffer += decoder.decode(value, { stream: true });\n\n let line: string | null;\n while ((line = nextLine(false)) !== null) {\n const event = processLine(line);\n if (event) yield event;\n }\n }\n // The stream may end without a trailing newline: the leftover buffer\n // is still line data and must be parsed, not dropped.\n buffer += decoder.decode();\n let tail: string | null;\n while ((tail = nextLine(true)) !== null) {\n const event = processLine(tail);\n if (event) yield event;\n }\n if (buffer !== '') {\n const event = processLine(buffer);\n if (event) yield event;\n }\n // Spec-compliant servers end with a blank line, but flush a trailing\n // event if the stream closed without one.\n const last = flush();\n if (last) yield last;\n } finally {\n // EVERY terminal path — EOF, decode error, transport error, caller\n // abort, explicit close, early consumer return — releases the\n // deadline listener and the body exactly once.\n this.closed = true;\n this.activeReader = undefined;\n this.releaseDeadline?.();\n try {\n await reader.cancel();\n } catch {\n // Already cancelled/errored.\n }\n reader.releaseLock();\n try {\n // The CURRENT connection's body (reconnects swap this.response).\n await this.response.body?.cancel();\n } catch {\n // Already closed.\n }\n }\n }\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { CadenyaWidgets, CadenyaWidgets as default } from './client.js';
|
|
2
|
+
export type { ClientOptions } from './client.js';
|
|
3
|
+
export { APIError, APIConnectionError, APIUserAbortError, APIRequestError, APIResponseError, APITimeoutError } from './core/error.js';
|
|
4
|
+
export type { RequestOptions } from './core/http.js';
|
|
5
|
+
export { APIPromise } from './core/http.js';
|
|
6
|
+
export { Page } from './core/pagination.js';
|
|
7
|
+
export { Stream } from './core/sse.js';
|
|
8
|
+
export type { ServerSentEvent } from './core/sse.js';
|
|
9
|
+
export * from './types.js';
|
|
10
|
+
export * from './resources/config.js';
|
|
11
|
+
export * from './resources/conversations.js';
|
|
12
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,cAAc,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AACxE,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACtI,YAAY,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACvC,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,cAAc,YAAY,CAAC;AAC3B,cAAc,uBAAuB,CAAC;AACtC,cAAc,8BAA8B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Generated by redwood. Do not edit by hand.
|
|
2
|
+
export { CadenyaWidgets, CadenyaWidgets as default } from './client.js';
|
|
3
|
+
export { APIError, APIConnectionError, APIUserAbortError, APIRequestError, APIResponseError, APITimeoutError } from './core/error.js';
|
|
4
|
+
export { APIPromise } from './core/http.js';
|
|
5
|
+
export { Page } from './core/pagination.js';
|
|
6
|
+
export { Stream } from './core/sse.js';
|
|
7
|
+
export * from './types.js';
|
|
8
|
+
export * from './resources/config.js';
|
|
9
|
+
export * from './resources/conversations.js';
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAE7C,OAAO,EAAE,cAAc,EAAE,cAAc,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAExE,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEtI,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEvC,cAAc,YAAY,CAAC;AAC3B,cAAc,uBAAuB,CAAC;AACtC,cAAc,8BAA8B,CAAC","sourcesContent":["// Generated by redwood. Do not edit by hand.\n\nexport { CadenyaWidgets, CadenyaWidgets as default } from './client.js';\nexport type { ClientOptions } from './client.js';\nexport { APIError, APIConnectionError, APIUserAbortError, APIRequestError, APIResponseError, APITimeoutError } from './core/error.js';\nexport type { RequestOptions } from './core/http.js';\nexport { APIPromise } from './core/http.js';\nexport { Page } from './core/pagination.js';\nexport { Stream } from './core/sse.js';\nexport type { ServerSentEvent } from './core/sse.js';\nexport * from './types.js';\nexport * from './resources/config.js';\nexport * from './resources/conversations.js';\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { HttpClient, RequestOptions, APIPromise } from '../core/http.js';
|
|
2
|
+
import type { WidgetConfig } from '../types.js';
|
|
3
|
+
export declare class Config {
|
|
4
|
+
private readonly _client;
|
|
5
|
+
constructor(_client: HttpClient);
|
|
6
|
+
/**
|
|
7
|
+
* Get widget config
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* const widgetConfig = await client.config.retrieveWidget();
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
retrieveWidget(options?: RequestOptions): APIPromise<WidgetConfig>;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=config.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/resources/config.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,qBAAa,MAAM;IACL,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,UAAU;IAEhD;;;;;;;OAOG;IACH,cAAc,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,UAAU,CAAC,YAAY,CAAC;CAKnE"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Generated by redwood. Do not edit by hand.
|
|
2
|
+
export class Config {
|
|
3
|
+
_client;
|
|
4
|
+
constructor(_client) {
|
|
5
|
+
this._client = _client;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Get widget config
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* const widgetConfig = await client.config.retrieveWidget();
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
retrieveWidget(options) {
|
|
16
|
+
return this._client.requestAPI(() => {
|
|
17
|
+
return { method: 'GET', path: `/v1/config` };
|
|
18
|
+
}, options);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/resources/config.ts"],"names":[],"mappings":"AAAA,6CAA6C;AAK7C,MAAM,OAAO,MAAM;IACY;IAA7B,YAA6B,OAAmB;QAAnB,YAAO,GAAP,OAAO,CAAY;IAAG,CAAC;IAEpD;;;;;;;OAOG;IACH,cAAc,CAAC,OAAwB;QACrC,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,CAAe,GAAG,EAAE;YAChD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;QAC/C,CAAC,EAAE,OAAO,CAAC,CAAC;IACd,CAAC;CACF","sourcesContent":["// Generated by redwood. Do not edit by hand.\n\nimport { HttpClient, RequestOptions, APIPromise } from '../core/http.js';\nimport type { WidgetConfig } from '../types.js';\n\nexport class Config {\n constructor(private readonly _client: HttpClient) {}\n\n /**\n * Get widget config\n * \n * @example\n * ```ts\n * const widgetConfig = await client.config.retrieveWidget();\n * ```\n */\n retrieveWidget(options?: RequestOptions): APIPromise<WidgetConfig> {\n return this._client.requestAPI<WidgetConfig>(() => {\n return { method: 'GET', path: `/v1/config` };\n }, options);\n }\n}\n"]}
|