@sidekickdb/resumable-stream 0.0.0 → 2.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.
@@ -0,0 +1,353 @@
1
+ import { beforeAll, beforeEach, describe, expect, it } from 'vitest';
2
+ import {
3
+ createResumableStreamContext,
4
+ type ResumableStreamContext,
5
+ } from '../../src/index.js';
6
+ import { createTestingStream, streamToBuffer } from './testing-stream.js';
7
+
8
+ type EphemeralApp = {
9
+ appId: string;
10
+ adminToken: string;
11
+ apiURI: string;
12
+ };
13
+
14
+ // SidekickDB: networked suite. It runs only against the backend named by
15
+ // SIDEKICK_E2E_API_URI and is skipped when that is unset; there is no default.
16
+ const e2eApiURI = process.env.SIDEKICK_E2E_API_URI
17
+ ? new URL(process.env.SIDEKICK_E2E_API_URI).href.replace(/\/+$/, '')
18
+ : undefined;
19
+ if (!e2eApiURI) {
20
+ console.warn(
21
+ '[sidekick] Skipping resumable stream tests: set SIDEKICK_E2E_API_URI to a SidekickDB server URL to run them.',
22
+ );
23
+ }
24
+
25
+ async function createEphemeralAppForTests(): Promise<EphemeralApp> {
26
+ const apiURI = e2eApiURI!;
27
+ const response = await fetch(`${apiURI}/dash/apps/ephemeral`, {
28
+ method: 'POST',
29
+ headers: {
30
+ 'Content-Type': 'application/json',
31
+ },
32
+ body: JSON.stringify({
33
+ title: `resumable-stream-tests-${Date.now()}`,
34
+ }),
35
+ });
36
+
37
+ if (!response.ok) {
38
+ const body = await response.text();
39
+ throw new Error(
40
+ `Failed to create ephemeral app (${response.status}): ${body}`,
41
+ );
42
+ }
43
+
44
+ const json = (await response.json()) as any;
45
+ const appId = json?.app?.id ?? json?.appId;
46
+ const adminToken =
47
+ json?.app?.['admin-token'] ??
48
+ json?.app?.adminToken ??
49
+ json?.app?.admin_token ??
50
+ json?.adminToken;
51
+
52
+ if (!appId || !adminToken) {
53
+ throw new Error(
54
+ `Unexpected ephemeral app response: ${JSON.stringify(json)}`,
55
+ );
56
+ }
57
+
58
+ return {
59
+ appId,
60
+ adminToken,
61
+ apiURI,
62
+ };
63
+ }
64
+
65
+ function withScopedStreamIds(
66
+ context: ResumableStreamContext,
67
+ scope: string,
68
+ ): ResumableStreamContext {
69
+ const scopedId = (streamId: string) => `${scope}:${streamId}`;
70
+ return {
71
+ resumableStream: (streamId, makeStream, skipCharacters) =>
72
+ context.resumableStream(scopedId(streamId), makeStream, skipCharacters),
73
+ resumeExistingStream: (streamId, skipCharacters) =>
74
+ context.resumeExistingStream(scopedId(streamId), skipCharacters),
75
+ createNewResumableStream: (streamId, makeStream, skipCharacters) =>
76
+ context.createNewResumableStream(
77
+ scopedId(streamId),
78
+ makeStream,
79
+ skipCharacters,
80
+ ),
81
+ hasExistingStream: (streamId) =>
82
+ context.hasExistingStream(scopedId(streamId)),
83
+ };
84
+ }
85
+
86
+ describe.skipIf(!e2eApiURI)('resumable stream', () => {
87
+ let app: EphemeralApp;
88
+ let resume: ResumableStreamContext;
89
+ let waitUntilPromises: Promise<any>[] = [];
90
+
91
+ beforeAll(async () => {
92
+ app = await createEphemeralAppForTests();
93
+ }, 60000);
94
+
95
+ beforeEach(() => {
96
+ waitUntilPromises = [];
97
+ const baseContext = createResumableStreamContext({
98
+ waitUntil: (p) => waitUntilPromises.push(p),
99
+ appId: app.appId,
100
+ adminToken: app.adminToken,
101
+ apiURI: app.apiURI,
102
+ });
103
+ resume = withScopedStreamIds(baseContext, crypto.randomUUID());
104
+ });
105
+
106
+ it('should act like a normal stream', async () => {
107
+ const { readable, writer } = createTestingStream();
108
+ const stream = await resume.resumableStream('test', () => readable);
109
+ writer.write('1\n');
110
+ writer.write('2\n');
111
+ writer.write('3\n');
112
+ writer.close();
113
+ const result2 = await streamToBuffer(stream);
114
+ expect(result2).toEqual('1\n2\n3\n');
115
+ });
116
+
117
+ it('should resume a done stream', async () => {
118
+ const { readable, writer } = createTestingStream();
119
+ const stream = await resume.resumableStream('test', () => readable);
120
+ const stream2 = await resume.resumableStream('test', () => readable);
121
+ writer.write('1\n');
122
+ writer.write('2\n');
123
+ writer.close();
124
+ const result = await streamToBuffer(stream);
125
+ const result2 = await streamToBuffer(stream2);
126
+ expect(result).toEqual('1\n2\n');
127
+ expect(result2).toEqual('1\n2\n');
128
+ });
129
+
130
+ it('hasExistingStream', async () => {
131
+ const { readable, writer } = createTestingStream();
132
+ expect(await resume.hasExistingStream('test')).toBe(null);
133
+ const stream = await resume.resumableStream('test', () => readable);
134
+ expect(await resume.hasExistingStream('test')).toBe(true);
135
+ expect(await resume.hasExistingStream('test2')).toBe(null);
136
+ const stream2 = await resume.resumableStream('test', () => readable);
137
+ expect(await resume.hasExistingStream('test')).toBe(true);
138
+ writer.write('1\n');
139
+ writer.write('2\n');
140
+ writer.close();
141
+
142
+ const result = await streamToBuffer(stream);
143
+ const result2 = await streamToBuffer(stream2);
144
+ expect(result).toEqual('1\n2\n');
145
+ expect(result2).toEqual('1\n2\n');
146
+ await Promise.all(waitUntilPromises);
147
+ expect(await resume.hasExistingStream('test')).toBe('DONE');
148
+ });
149
+
150
+ it('should resume a done stream reverse read', async () => {
151
+ const { readable, writer } = createTestingStream();
152
+ const stream = await resume.resumableStream('test', () => readable);
153
+ const stream2 = await resume.resumableStream('test', () => readable);
154
+ writer.write('1\n');
155
+ writer.write('2\n');
156
+ writer.close();
157
+ const result2 = await streamToBuffer(stream2);
158
+ const result = await streamToBuffer(stream);
159
+
160
+ expect(result).toEqual('1\n2\n');
161
+ expect(result2).toEqual('1\n2\n');
162
+ });
163
+
164
+ it('should resume an in-progress stream', async () => {
165
+ const { readable, writer } = createTestingStream();
166
+ const stream = await resume.resumableStream('test', () => readable);
167
+ writer.write('1\n');
168
+ const stream2 = await resume.resumableStream('test', () => readable);
169
+ writer.write('2\n');
170
+ writer.close();
171
+ const result = await streamToBuffer(stream);
172
+ const result2 = await streamToBuffer(stream2);
173
+ expect(result).toEqual('1\n2\n');
174
+ expect(result2).toEqual('1\n2\n');
175
+ });
176
+
177
+ it('should actually stream', async () => {
178
+ const { readable, writer } = createTestingStream();
179
+ const stream = await resume.resumableStream('test', () => readable);
180
+ writer.write('1\n');
181
+ const stream2 = await resume.resumableStream('test', () => readable);
182
+ const result = await streamToBuffer(stream, 1);
183
+ const result2 = await streamToBuffer(stream2, 1);
184
+ expect(result).toEqual('1\n');
185
+ expect(result2).toEqual('1\n');
186
+ writer.write('2\n');
187
+ writer.close();
188
+ const step1 = await streamToBuffer(stream);
189
+ const step2 = await streamToBuffer(stream2);
190
+ expect(step1).toEqual('2\n');
191
+ expect(step2).toEqual('2\n');
192
+ });
193
+
194
+ it('should actually stream producer first', async () => {
195
+ const { readable, writer } = createTestingStream();
196
+ const stream = await resume.resumableStream('test', () => readable);
197
+ writer.write('1\n');
198
+ const stream2 = await resume.resumableStream('test', () => readable);
199
+ const result = await streamToBuffer(stream, 1);
200
+ expect(result).toEqual('1\n');
201
+ writer.write('2\n');
202
+ writer.close();
203
+ const step1 = await streamToBuffer(stream);
204
+ const step2 = await streamToBuffer(stream2);
205
+ expect(step1).toEqual('2\n');
206
+ expect(step2).toEqual('1\n2\n');
207
+ });
208
+
209
+ it('should actually stream consumer first', async () => {
210
+ const { readable, writer } = createTestingStream();
211
+ const stream = await resume.resumableStream('test', () => readable);
212
+ writer.write('1\n');
213
+ const stream2 = await resume.resumableStream('test', () => readable);
214
+ const result2 = await streamToBuffer(stream2, 1);
215
+ expect(result2).toEqual('1\n');
216
+ writer.write('2\n');
217
+ writer.close();
218
+ const step1 = await streamToBuffer(stream);
219
+ const step2 = await streamToBuffer(stream2);
220
+ expect(step1).toEqual('1\n2\n');
221
+ expect(step2).toEqual('2\n');
222
+ });
223
+
224
+ it('should resume multiple streams', async () => {
225
+ const { readable, writer } = createTestingStream();
226
+ const stream = await resume.resumableStream('test', () => readable);
227
+ writer.write('1\n');
228
+ const stream2 = await resume.resumableStream('test', () => readable);
229
+ writer.write('2\n');
230
+ const stream3 = await resume.resumableStream('test', () => readable);
231
+ writer.close();
232
+ const result = await streamToBuffer(stream);
233
+ const result2 = await streamToBuffer(stream2);
234
+ const result3 = await streamToBuffer(stream3);
235
+ expect(result).toEqual('1\n2\n');
236
+ expect(result2).toEqual('1\n2\n');
237
+ expect(result3).toEqual('1\n2\n');
238
+ });
239
+
240
+ it('should differentiate between streams', async () => {
241
+ const { readable, writer } = createTestingStream();
242
+ const { readable: readable2, writer: writer2 } = createTestingStream();
243
+ const stream1 = await resume.resumableStream('test', () => readable);
244
+ const stream2 = await resume.resumableStream('test2', () => readable2);
245
+ const stream12 = await resume.resumableStream('test', () => readable);
246
+ const stream22 = await resume.resumableStream('test2', () => readable2);
247
+ writer.write('1\n');
248
+ writer.write('2\n');
249
+ writer.close();
250
+ writer2.write('writer2\n');
251
+ writer2.close();
252
+ const result1 = await streamToBuffer(stream1);
253
+ const result2 = await streamToBuffer(stream2);
254
+ const result12 = await streamToBuffer(stream12);
255
+ const result22 = await streamToBuffer(stream22);
256
+ expect(result1).toEqual('1\n2\n');
257
+ expect(result2).toEqual('writer2\n');
258
+ expect(result12).toEqual('1\n2\n');
259
+ expect(result22).toEqual('writer2\n');
260
+ });
261
+
262
+ it('should respect skipCharacters', async () => {
263
+ const { readable, writer } = createTestingStream();
264
+ const stream = await resume.resumableStream('test', () => readable);
265
+ writer.write('1\n');
266
+ writer.write('2\n');
267
+ const stream2 = await resume.resumableStream('test', () => readable, 2);
268
+ writer.close();
269
+ const result = await streamToBuffer(stream);
270
+ const result2 = await streamToBuffer(stream2);
271
+ expect(result).toEqual('1\n2\n');
272
+ expect(result2).toEqual('2\n');
273
+ });
274
+
275
+ it('should respect skipCharacters 2', async () => {
276
+ const { readable, writer } = createTestingStream();
277
+ const stream = await resume.resumableStream('test', () => readable);
278
+ writer.write('1\n');
279
+ writer.write('2\n');
280
+ const stream2 = await resume.resumableStream('test', () => readable, 4);
281
+ writer.close();
282
+ const result = await streamToBuffer(stream);
283
+ const result2 = await streamToBuffer(stream2);
284
+ expect(result).toEqual('1\n2\n');
285
+ expect(result2).toEqual('');
286
+ });
287
+
288
+ it('should respect skipCharacters 0', async () => {
289
+ const { readable, writer } = createTestingStream();
290
+ const stream = await resume.resumableStream('test', () => readable);
291
+ writer.write('1\n');
292
+ writer.write('2\n');
293
+ const stream2 = await resume.resumableStream('test', () => readable, 0);
294
+ writer.close();
295
+ const result = await streamToBuffer(stream);
296
+ const result2 = await streamToBuffer(stream2);
297
+ expect(result).toEqual('1\n2\n');
298
+ expect(result2).toEqual('1\n2\n');
299
+ });
300
+
301
+ // We return the stream because we can afford to hold on to the old streams
302
+ // Leaving this as a skipped test in case we want to offer a compat mode that
303
+ // returns null
304
+ it.skip('should return null if stream is done', async () => {
305
+ const { readable, writer } = createTestingStream();
306
+ const stream = await resume.resumableStream('test', () => readable);
307
+ writer.write('1\n');
308
+ writer.write('2\n');
309
+ writer.close();
310
+
311
+ const result = await streamToBuffer(stream);
312
+ expect(
313
+ await resume.resumableStream('test', () => {
314
+ throw new Error('Should never be called');
315
+ }),
316
+ ).toBeNull();
317
+ expect(result).toEqual('1\n2\n');
318
+ });
319
+
320
+ it('should support the deconstructed APIs', async () => {
321
+ const { readable, writer } = createTestingStream();
322
+ const stream = await resume.createNewResumableStream(
323
+ 'test',
324
+ () => readable,
325
+ );
326
+ const stream2 = await resume.resumeExistingStream('test');
327
+ writer.write('1\n');
328
+ writer.write('2\n');
329
+ writer.close();
330
+ const result = await streamToBuffer(stream);
331
+ const result2 = await streamToBuffer(stream2);
332
+ expect(result).toEqual('1\n2\n');
333
+ expect(result2).toEqual('1\n2\n');
334
+ });
335
+
336
+ // We return the stream because we can afford to hold on to the old streams
337
+ // Leaving this as a skipped test in case we want to offer a compat mode that
338
+ // returns null
339
+ it.skip('should return null if stream is done explicit APIs', async () => {
340
+ const { readable, writer } = createTestingStream();
341
+ const stream = await resume.createNewResumableStream(
342
+ 'test',
343
+ () => readable,
344
+ );
345
+ writer.write('1\n');
346
+ writer.write('2\n');
347
+ writer.close();
348
+
349
+ const result = await streamToBuffer(stream);
350
+ expect(await resume.resumeExistingStream('test')).toBeNull();
351
+ expect(result).toEqual('1\n2\n');
352
+ });
353
+ });
@@ -0,0 +1,87 @@
1
+ export function createTestingStream() {
2
+ let controller: ReadableStreamDefaultController<string> | undefined =
3
+ undefined;
4
+ const buffer: string[] = [];
5
+ const readable = new ReadableStream<string>({
6
+ start(c) {
7
+ controller = c;
8
+ if (buffer.length > 0) {
9
+ for (const chunk of buffer) {
10
+ controller.enqueue(chunk);
11
+ }
12
+ }
13
+ },
14
+ });
15
+
16
+ const writable = new WritableStream<string>({
17
+ write(chunk) {
18
+ if (controller) {
19
+ controller.enqueue(chunk);
20
+ }
21
+ buffer.push(chunk);
22
+ },
23
+ close() {
24
+ controller?.close();
25
+ },
26
+ abort(reason) {
27
+ controller?.error(reason);
28
+ },
29
+ });
30
+
31
+ return {
32
+ readable,
33
+ writer: writable.getWriter(),
34
+ buffer,
35
+ };
36
+ }
37
+
38
+ const readers = new WeakMap<
39
+ ReadableStream<string>,
40
+ ReadableStreamDefaultReader<string>
41
+ >();
42
+
43
+ export async function streamToBuffer(
44
+ stream: ReadableStream<string> | null | undefined,
45
+ maxNReads?: number,
46
+ ) {
47
+ if (stream === null) {
48
+ throw new Error('Stream should not be null');
49
+ }
50
+ if (stream === undefined) {
51
+ throw new Error('Stream should not be undefined');
52
+ }
53
+
54
+ const reader = (
55
+ readers.has(stream) ? readers.get(stream) : stream.getReader()
56
+ ) as ReadableStreamDefaultReader<string>;
57
+ readers.set(stream, reader);
58
+
59
+ const buffer: string[] = [];
60
+ function timeout(ms: number) {
61
+ return new Promise((_, reject) =>
62
+ setTimeout(
63
+ () =>
64
+ reject(new Error(`Timeout with buffer ${JSON.stringify(buffer)}`)),
65
+ ms,
66
+ ),
67
+ );
68
+ }
69
+
70
+ let i = 0;
71
+ while (true) {
72
+ const { done, value } = await (Promise.race([
73
+ reader.read(),
74
+ timeout(2000),
75
+ ]) as Promise<{ done: boolean; value: string }>);
76
+ if (!done) {
77
+ buffer.push(value);
78
+ }
79
+ if (maxNReads && ++i === maxNReads) {
80
+ break;
81
+ }
82
+ if (done) {
83
+ break;
84
+ }
85
+ }
86
+ return buffer.join('');
87
+ }
@@ -0,0 +1,71 @@
1
+ export interface CreateResumableStreamContextOptions {
2
+ /**
3
+ * A function that takes a promise and ensures that the current program stays alive
4
+ * until the promise is resolved.
5
+ *
6
+ * If you are deploying to a server environment, where you don't have to worry about
7
+ * the function getting suspended, pass in null.
8
+ */
9
+ waitUntil: ((promise: Promise<unknown>) => void) | null;
10
+ /**
11
+ * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable
12
+ * (or their older names, INSTANT_APP_ID and NEXT_PUBLIC_INSTANT_APP_ID).
13
+ */
14
+ appId?: string;
15
+ /**
16
+ * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable
17
+ * (or its older name, INSTANT_APP_ADMIN_TOKEN).
18
+ */
19
+ adminToken?: string;
20
+ /**
21
+ * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI
22
+ * environment variable (or its older name, INSTANT_API_URI); one of the two
23
+ * is required.
24
+ */
25
+ apiURI?: string;
26
+ /**
27
+ * Enable verbose logging from the underlying instant connection
28
+ */
29
+ verbose?: boolean;
30
+ }
31
+ export interface ResumableStreamContext {
32
+ /**
33
+ * Creates or resumes a resumable stream.
34
+ *
35
+ * Does not throw if the underlying stream is already done. The output can always be read from the
36
+ * stream and does not have to be saved to a separate table after streaming is completed.
37
+ *
38
+ * By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.
39
+ *
40
+ * @param streamId - The ID of the stream. Must be unique for each stream.
41
+ * @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.
42
+ * @param skipCharacters - Number of characters to skip
43
+ * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
44
+ */
45
+ resumableStream: (streamId: string, makeStream: () => ReadableStream<string>, skipCharacters?: number) => Promise<ReadableStream<string> | null>;
46
+ /**
47
+ * Resumes a stream that was previously created by `createNewResumableStream`.
48
+ *
49
+ * @param streamId - The ID of the stream. Must be unique for each stream.
50
+ * @param skipCharacters - Number of characters to skip
51
+ * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
52
+ */
53
+ resumeExistingStream: (streamId: string, skipCharacters?: number) => Promise<ReadableStream<string> | null | undefined>;
54
+ /**
55
+ * Creates a new resumable stream.
56
+ *
57
+ * @param streamId - The ID of the stream. Must be unique for each stream.
58
+ * @param makeStream - A function that returns a stream of strings.
59
+ * @param skipCharacters - Number of characters to skip
60
+ * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
61
+ */
62
+ createNewResumableStream: (streamId: string, makeStream: () => ReadableStream<string>, skipCharacters?: number) => Promise<ReadableStream<string> | null>;
63
+ /**
64
+ * Checks if a stream with the given streamId exists.
65
+ * @param streamId - The ID of the stream.
66
+ * @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. "DONE" if the stream is fully done.
67
+ */
68
+ hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;
69
+ }
70
+ export declare function createResumableStreamContext(options: CreateResumableStreamContextOptions): ResumableStreamContext;
71
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,mCAAmC;IAClD;;;;;;OAMG;IACH,SAAS,EAAE,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC;IACxD;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,sBAAsB;IACrC;;;;;;;;;;;;OAYG;IACH,eAAe,EAAE,CACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,cAAc,CAAC,MAAM,CAAC,EACxC,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IAC5C;;;;;;OAMG;IACH,oBAAoB,EAAE,CACpB,QAAQ,EAAE,MAAM,EAChB,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;IACxD;;;;;;;OAOG;IACH,wBAAwB,EAAE,CACxB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,cAAc,CAAC,MAAM,CAAC,EACxC,cAAc,CAAC,EAAE,MAAM,KACpB,OAAO,CAAC,cAAc,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,MAAM,CAAC,CAAC;CACxE;AAiCD,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,mCAAmC,GAC3C,sBAAsB,CAgIxB"}
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createResumableStreamContext = createResumableStreamContext;
4
+ const admin_1 = require("@sidekickdb/admin");
5
+ function skipCharactersTransformer(skipCharacters) {
6
+ let skipLeft = skipCharacters;
7
+ return new TransformStream({
8
+ transform(chunk, controller) {
9
+ if (!skipLeft) {
10
+ controller.enqueue(chunk);
11
+ return;
12
+ }
13
+ if (skipLeft > chunk.length) {
14
+ skipLeft -= chunk.length;
15
+ return;
16
+ }
17
+ const remaining = chunk.slice(skipLeft);
18
+ skipLeft = 0;
19
+ controller.enqueue(remaining);
20
+ },
21
+ });
22
+ }
23
+ /**
24
+ * Reads an environment variable that can be set under its SidekickDB name
25
+ * (`SIDEKICK_APP_ID`) or its older name (`INSTANT_APP_ID`). The SidekickDB name
26
+ * wins; a blank value counts as unset.
27
+ */
28
+ function readEnv(sidekickName) {
29
+ return [
30
+ process.env[sidekickName],
31
+ process.env[sidekickName.replace('SIDEKICK_', 'INSTANT_')],
32
+ ].find((v) => v?.trim());
33
+ }
34
+ function createResumableStreamContext(options) {
35
+ const appId = options.appId ||
36
+ readEnv('SIDEKICK_APP_ID') ||
37
+ readEnv('NEXT_PUBLIC_SIDEKICK_APP_ID');
38
+ if (!appId) {
39
+ throw new Error('Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.');
40
+ }
41
+ const adminToken = options.adminToken || readEnv('SIDEKICK_APP_ADMIN_TOKEN');
42
+ if (!adminToken) {
43
+ throw new Error('Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.');
44
+ }
45
+ const apiURI = (0, admin_1.requireApiURI)(options.apiURI || readEnv('SIDEKICK_API_URI'), {
46
+ target: 'createResumableStreamContext()',
47
+ envVar: 'SIDEKICK_API_URI',
48
+ });
49
+ const config = { appId, adminToken, apiURI };
50
+ if (options.verbose) {
51
+ config.verbose = options.verbose;
52
+ }
53
+ const db = (0, admin_1.init)(config);
54
+ async function resumableStream(streamId, makeStream, skipCharacters) {
55
+ const writeStream = db.streams.createWriteStream({
56
+ clientId: streamId,
57
+ waitUntil: options.waitUntil ?? undefined,
58
+ });
59
+ try {
60
+ const s = await writeStream.streamId();
61
+ const inputStream = makeStream();
62
+ inputStream.pipeTo(writeStream);
63
+ const readStream = db.streams.createReadStream({ streamId: s });
64
+ if (skipCharacters) {
65
+ return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
66
+ }
67
+ return readStream;
68
+ }
69
+ catch (e) {
70
+ const readStream = db.streams.createReadStream({ clientId: streamId });
71
+ if (skipCharacters) {
72
+ return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
73
+ }
74
+ return readStream;
75
+ }
76
+ }
77
+ async function resumeExistingStream(streamId, skipCharacters) {
78
+ const readStream = db.streams.createReadStream({ clientId: streamId });
79
+ try {
80
+ await readStream.streamId();
81
+ }
82
+ catch (e) {
83
+ if (e instanceof admin_1.InstantError &&
84
+ e.hint?.errors?.[0]?.message === 'Stream is missing.') {
85
+ return undefined;
86
+ }
87
+ throw e;
88
+ }
89
+ if (skipCharacters) {
90
+ return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
91
+ }
92
+ return readStream;
93
+ }
94
+ async function createNewResumableStream(streamId, makeStream, skipCharacters) {
95
+ const inputStream = makeStream();
96
+ const writeStream = db.streams.createWriteStream({
97
+ clientId: streamId,
98
+ waitUntil: options.waitUntil ?? undefined,
99
+ });
100
+ // Wait for stream to be acknowledged by the server
101
+ await writeStream.streamId();
102
+ inputStream.pipeTo(writeStream);
103
+ const readStream = db.streams.createReadStream({ clientId: streamId });
104
+ if (skipCharacters) {
105
+ return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
106
+ }
107
+ return readStream;
108
+ }
109
+ async function hasExistingStream(streamId) {
110
+ const data = await db.query({
111
+ $streams: { $: { where: { clientId: streamId } } },
112
+ });
113
+ const stream = data?.$streams?.[0];
114
+ if (stream?.done) {
115
+ return 'DONE';
116
+ }
117
+ if (stream) {
118
+ return true;
119
+ }
120
+ return null;
121
+ }
122
+ return {
123
+ resumableStream,
124
+ resumeExistingStream,
125
+ createNewResumableStream,
126
+ hasExistingStream,
127
+ };
128
+ }
129
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;AAoHA,oEAkIC;AAtPD,6CAA8E;AAqF9E,SAAS,yBAAyB,CAAC,cAAsB;IACvD,IAAI,QAAQ,GAAG,cAAc,CAAC;IAC9B,OAAO,IA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AAW,CAAC,yBAAyB,CAAC,cAAc,CAAC,CAAC,CAAC;QAC3E,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,KAAK,UAAU,iBAAiB,CAC9B,QAAgB;QAEhB,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC;YAC1B,QAAQ,EAAE,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,EAAE;SACnD,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,MAAM,EAAE,IAAI,EAAE,CAAC;YACjB,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,eAAe;QACf,oBAAoB;QACpB,wBAAwB;QACxB,iBAAiB;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import { Config, init, InstantError, requireApiURI } from '@sidekickdb/admin';\n\nexport interface CreateResumableStreamContextOptions {\n /**\n * A function that takes a promise and ensures that the current program stays alive\n * until the promise is resolved.\n *\n * If you are deploying to a server environment, where you don't have to worry about\n * the function getting suspended, pass in null.\n */\n waitUntil: ((promise: Promise<unknown>) => void) | null;\n /**\n * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable\n * (or their older names, INSTANT_APP_ID and NEXT_PUBLIC_INSTANT_APP_ID).\n */\n appId?: string;\n /**\n * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable\n * (or its older name, INSTANT_APP_ADMIN_TOKEN).\n */\n adminToken?: string;\n /**\n * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI\n * environment variable (or its older name, INSTANT_API_URI); one of the two\n * is required.\n */\n apiURI?: string;\n /**\n * Enable verbose logging from the underlying instant connection\n */\n verbose?: boolean;\n}\n\nexport interface ResumableStreamContext {\n /**\n * Creates or resumes a resumable stream.\n *\n * Does not throw if the underlying stream is already done. The output can always be read from the\n * stream and does not have to be saved to a separate table after streaming is completed.\n *\n * By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n /**\n * Resumes a stream that was previously created by `createNewResumableStream`.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n resumeExistingStream: (\n streamId: string,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null | undefined>;\n /**\n * Creates a new resumable stream.\n *\n * @param streamId - The ID of the stream. Must be unique for each stream.\n * @param makeStream - A function that returns a stream of strings.\n * @param skipCharacters - Number of characters to skip\n * @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)\n */\n createNewResumableStream: (\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ) => Promise<ReadableStream<string> | null>;\n\n /**\n * Checks if a stream with the given streamId exists.\n * @param streamId - The ID of the stream.\n * @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. \"DONE\" if the stream is fully done.\n */\n hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;\n}\n\nfunction skipCharactersTransformer(skipCharacters: number) {\n let skipLeft = skipCharacters;\n return new TransformStream<string>({\n transform(chunk, controller) {\n if (!skipLeft) {\n controller.enqueue(chunk);\n return;\n }\n if (skipLeft > chunk.length) {\n skipLeft -= chunk.length;\n return;\n }\n const remaining = chunk.slice(skipLeft);\n skipLeft = 0;\n controller.enqueue(remaining);\n },\n });\n}\n\n/**\n * Reads an environment variable that can be set under its SidekickDB name\n * (`SIDEKICK_APP_ID`) or its older name (`INSTANT_APP_ID`). The SidekickDB name\n * wins; a blank value counts as unset.\n */\nfunction readEnv(sidekickName: string): string | undefined {\n return [\n process.env[sidekickName],\n process.env[sidekickName.replace('SIDEKICK_', 'INSTANT_')],\n ].find((v) => v?.trim());\n}\n\nexport function createResumableStreamContext(\n options: CreateResumableStreamContextOptions,\n): ResumableStreamContext {\n const appId =\n options.appId ||\n readEnv('SIDEKICK_APP_ID') ||\n readEnv('NEXT_PUBLIC_SIDEKICK_APP_ID');\n if (!appId) {\n throw new Error(\n 'Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.',\n );\n }\n const adminToken = options.adminToken || readEnv('SIDEKICK_APP_ADMIN_TOKEN');\n if (!adminToken) {\n throw new Error(\n 'Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.',\n );\n }\n\n const apiURI = requireApiURI(options.apiURI || readEnv('SIDEKICK_API_URI'), {\n target: 'createResumableStreamContext()',\n envVar: 'SIDEKICK_API_URI',\n });\n\n const config: Config = { appId, adminToken, apiURI };\n\n if (options.verbose) {\n config.verbose = options.verbose;\n }\n\n const db = init(config);\n\n async function resumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n try {\n const s = await writeStream.streamId();\n const inputStream = makeStream();\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ streamId: s });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n } catch (e) {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(\n skipCharactersTransformer(skipCharacters),\n );\n }\n return readStream;\n }\n }\n\n async function resumeExistingStream(\n streamId: string,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null | undefined> {\n const readStream = db.streams.createReadStream({ clientId: streamId });\n try {\n await readStream.streamId();\n } catch (e) {\n if (\n e instanceof InstantError &&\n (e.hint as any)?.errors?.[0]?.message === 'Stream is missing.'\n ) {\n return undefined;\n }\n throw e;\n }\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function createNewResumableStream(\n streamId: string,\n makeStream: () => ReadableStream<string>,\n skipCharacters?: number,\n ): Promise<ReadableStream<string> | null> {\n const inputStream = makeStream();\n const writeStream = db.streams.createWriteStream({\n clientId: streamId,\n waitUntil: options.waitUntil ?? undefined,\n });\n\n // Wait for stream to be acknowledged by the server\n await writeStream.streamId();\n\n inputStream.pipeTo(writeStream);\n const readStream = db.streams.createReadStream({ clientId: streamId });\n if (skipCharacters) {\n return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));\n }\n return readStream;\n }\n\n async function hasExistingStream(\n streamId: string,\n ): Promise<null | true | 'DONE'> {\n const data = await db.query({\n $streams: { $: { where: { clientId: streamId } } },\n });\n\n const stream = data?.$streams?.[0];\n if (stream?.done) {\n return 'DONE';\n }\n if (stream) {\n return true;\n }\n return null;\n }\n\n return {\n resumableStream,\n resumeExistingStream,\n createNewResumableStream,\n hasExistingStream,\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }