@wabot-dev/framework 0.1.0-beta.13 → 0.1.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/src/ai/claude/ClaudeChatBotAdapter.js +1 -3
  2. package/package.json +1 -1
  3. package/dist/src/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.js +0 -221
  4. package/dist/src/node_modules/@anthropic-ai/sdk/client.js +0 -540
  5. package/dist/src/node_modules/@anthropic-ai/sdk/core/api-promise.js +0 -74
  6. package/dist/src/node_modules/@anthropic-ai/sdk/core/error.js +0 -100
  7. package/dist/src/node_modules/@anthropic-ai/sdk/core/pagination.js +0 -119
  8. package/dist/src/node_modules/@anthropic-ai/sdk/core/resource.js +0 -8
  9. package/dist/src/node_modules/@anthropic-ai/sdk/core/streaming.js +0 -283
  10. package/dist/src/node_modules/@anthropic-ai/sdk/internal/constants.js +0 -16
  11. package/dist/src/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.js +0 -37
  12. package/dist/src/node_modules/@anthropic-ai/sdk/internal/decoders/line.js +0 -110
  13. package/dist/src/node_modules/@anthropic-ai/sdk/internal/detect-platform.js +0 -159
  14. package/dist/src/node_modules/@anthropic-ai/sdk/internal/errors.js +0 -37
  15. package/dist/src/node_modules/@anthropic-ai/sdk/internal/headers.js +0 -71
  16. package/dist/src/node_modules/@anthropic-ai/sdk/internal/parse.js +0 -53
  17. package/dist/src/node_modules/@anthropic-ai/sdk/internal/request-options.js +0 -11
  18. package/dist/src/node_modules/@anthropic-ai/sdk/internal/shims.js +0 -86
  19. package/dist/src/node_modules/@anthropic-ai/sdk/internal/to-file.js +0 -94
  20. package/dist/src/node_modules/@anthropic-ai/sdk/internal/tslib.js +0 -14
  21. package/dist/src/node_modules/@anthropic-ai/sdk/internal/uploads.js +0 -113
  22. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/bytes.js +0 -27
  23. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/env.js +0 -19
  24. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/log.js +0 -82
  25. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/path.js +0 -76
  26. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/sleep.js +0 -4
  27. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/uuid.js +0 -16
  28. package/dist/src/node_modules/@anthropic-ai/sdk/internal/utils/values.js +0 -48
  29. package/dist/src/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.js +0 -588
  30. package/dist/src/node_modules/@anthropic-ai/sdk/lib/MessageStream.js +0 -582
  31. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/beta.js +0 -19
  32. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/files.js +0 -120
  33. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.js +0 -202
  34. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.js +0 -85
  35. package/dist/src/node_modules/@anthropic-ai/sdk/resources/beta/models.js +0 -58
  36. package/dist/src/node_modules/@anthropic-ai/sdk/resources/completions.js +0 -21
  37. package/dist/src/node_modules/@anthropic-ai/sdk/resources/messages/batches.js +0 -151
  38. package/dist/src/node_modules/@anthropic-ai/sdk/resources/messages/messages.js +0 -71
  39. package/dist/src/node_modules/@anthropic-ai/sdk/resources/models.js +0 -43
  40. package/dist/src/node_modules/@anthropic-ai/sdk/version.js +0 -3
@@ -1,100 +0,0 @@
1
- import { castToError } from '../internal/errors.js';
2
-
3
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
4
- class AnthropicError extends Error {
5
- }
6
- class APIError extends AnthropicError {
7
- constructor(status, error, message, headers) {
8
- super(`${APIError.makeMessage(status, error, message)}`);
9
- this.status = status;
10
- this.headers = headers;
11
- this.requestID = headers?.get('request-id');
12
- this.error = error;
13
- }
14
- static makeMessage(status, error, message) {
15
- const msg = error?.message ?
16
- typeof error.message === 'string' ?
17
- error.message
18
- : JSON.stringify(error.message)
19
- : error ? JSON.stringify(error)
20
- : message;
21
- if (status && msg) {
22
- return `${status} ${msg}`;
23
- }
24
- if (status) {
25
- return `${status} status code (no body)`;
26
- }
27
- if (msg) {
28
- return msg;
29
- }
30
- return '(no status code or body)';
31
- }
32
- static generate(status, errorResponse, message, headers) {
33
- if (!status || !headers) {
34
- return new APIConnectionError({ message, cause: castToError(errorResponse) });
35
- }
36
- const error = errorResponse;
37
- if (status === 400) {
38
- return new BadRequestError(status, error, message, headers);
39
- }
40
- if (status === 401) {
41
- return new AuthenticationError(status, error, message, headers);
42
- }
43
- if (status === 403) {
44
- return new PermissionDeniedError(status, error, message, headers);
45
- }
46
- if (status === 404) {
47
- return new NotFoundError(status, error, message, headers);
48
- }
49
- if (status === 409) {
50
- return new ConflictError(status, error, message, headers);
51
- }
52
- if (status === 422) {
53
- return new UnprocessableEntityError(status, error, message, headers);
54
- }
55
- if (status === 429) {
56
- return new RateLimitError(status, error, message, headers);
57
- }
58
- if (status >= 500) {
59
- return new InternalServerError(status, error, message, headers);
60
- }
61
- return new APIError(status, error, message, headers);
62
- }
63
- }
64
- class APIUserAbortError extends APIError {
65
- constructor({ message } = {}) {
66
- super(undefined, undefined, message || 'Request was aborted.', undefined);
67
- }
68
- }
69
- class APIConnectionError extends APIError {
70
- constructor({ message, cause }) {
71
- super(undefined, undefined, message || 'Connection error.', undefined);
72
- // in some environments the 'cause' property is already declared
73
- // @ts-ignore
74
- if (cause)
75
- this.cause = cause;
76
- }
77
- }
78
- class APIConnectionTimeoutError extends APIConnectionError {
79
- constructor({ message } = {}) {
80
- super({ message: message ?? 'Request timed out.' });
81
- }
82
- }
83
- class BadRequestError extends APIError {
84
- }
85
- class AuthenticationError extends APIError {
86
- }
87
- class PermissionDeniedError extends APIError {
88
- }
89
- class NotFoundError extends APIError {
90
- }
91
- class ConflictError extends APIError {
92
- }
93
- class UnprocessableEntityError extends APIError {
94
- }
95
- class RateLimitError extends APIError {
96
- }
97
- class InternalServerError extends APIError {
98
- }
99
-
100
- export { APIConnectionError, APIConnectionTimeoutError, APIError, APIUserAbortError, AnthropicError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, PermissionDeniedError, RateLimitError, UnprocessableEntityError };
@@ -1,119 +0,0 @@
1
- import { __classPrivateFieldSet, __classPrivateFieldGet } from '../internal/tslib.js';
2
- import { AnthropicError } from './error.js';
3
- import { defaultParseResponse } from '../internal/parse.js';
4
- import { APIPromise } from './api-promise.js';
5
- import { maybeObj } from '../internal/utils/values.js';
6
-
7
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8
- var _AbstractPage_client;
9
- class AbstractPage {
10
- constructor(client, response, body, options) {
11
- _AbstractPage_client.set(this, void 0);
12
- __classPrivateFieldSet(this, _AbstractPage_client, client);
13
- this.options = options;
14
- this.response = response;
15
- this.body = body;
16
- }
17
- hasNextPage() {
18
- const items = this.getPaginatedItems();
19
- if (!items.length)
20
- return false;
21
- return this.nextPageRequestOptions() != null;
22
- }
23
- async getNextPage() {
24
- const nextOptions = this.nextPageRequestOptions();
25
- if (!nextOptions) {
26
- throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
27
- }
28
- return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
29
- }
30
- async *iterPages() {
31
- let page = this;
32
- yield page;
33
- while (page.hasNextPage()) {
34
- page = await page.getNextPage();
35
- yield page;
36
- }
37
- }
38
- async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
39
- for await (const page of this.iterPages()) {
40
- for (const item of page.getPaginatedItems()) {
41
- yield item;
42
- }
43
- }
44
- }
45
- }
46
- /**
47
- * This subclass of Promise will resolve to an instantiated Page once the request completes.
48
- *
49
- * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
50
- *
51
- * for await (const item of client.items.list()) {
52
- * console.log(item)
53
- * }
54
- */
55
- class PagePromise extends APIPromise {
56
- constructor(client, request, Page) {
57
- super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options));
58
- }
59
- /**
60
- * Allow auto-paginating iteration on an unawaited list call, eg:
61
- *
62
- * for await (const item of client.items.list()) {
63
- * console.log(item)
64
- * }
65
- */
66
- async *[Symbol.asyncIterator]() {
67
- const page = await this;
68
- for await (const item of page) {
69
- yield item;
70
- }
71
- }
72
- }
73
- class Page extends AbstractPage {
74
- constructor(client, response, body, options) {
75
- super(client, response, body, options);
76
- this.data = body.data || [];
77
- this.has_more = body.has_more || false;
78
- this.first_id = body.first_id || null;
79
- this.last_id = body.last_id || null;
80
- }
81
- getPaginatedItems() {
82
- return this.data ?? [];
83
- }
84
- hasNextPage() {
85
- if (this.has_more === false) {
86
- return false;
87
- }
88
- return super.hasNextPage();
89
- }
90
- nextPageRequestOptions() {
91
- if (this.options.query?.['before_id']) {
92
- // in reverse
93
- const first_id = this.first_id;
94
- if (!first_id) {
95
- return null;
96
- }
97
- return {
98
- ...this.options,
99
- query: {
100
- ...maybeObj(this.options.query),
101
- before_id: first_id,
102
- },
103
- };
104
- }
105
- const cursor = this.last_id;
106
- if (!cursor) {
107
- return null;
108
- }
109
- return {
110
- ...this.options,
111
- query: {
112
- ...maybeObj(this.options.query),
113
- after_id: cursor,
114
- },
115
- };
116
- }
117
- }
118
-
119
- export { AbstractPage, Page, PagePromise };
@@ -1,8 +0,0 @@
1
- // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
- class APIResource {
3
- constructor(client) {
4
- this._client = client;
5
- }
6
- }
7
-
8
- export { APIResource };
@@ -1,283 +0,0 @@
1
- import { __classPrivateFieldSet, __classPrivateFieldGet } from '../internal/tslib.js';
2
- import { APIError, AnthropicError } from './error.js';
3
- import { makeReadableStream, ReadableStreamToAsyncIterable } from '../internal/shims.js';
4
- import { LineDecoder, findDoubleNewlineIndex } from '../internal/decoders/line.js';
5
- import { isAbortError } from '../internal/errors.js';
6
- import { safeJSON } from '../internal/utils/values.js';
7
- import { encodeUTF8 } from '../internal/utils/bytes.js';
8
- import { loggerFor } from '../internal/utils/log.js';
9
-
10
- var _Stream_client;
11
- class Stream {
12
- constructor(iterator, controller, client) {
13
- this.iterator = iterator;
14
- _Stream_client.set(this, void 0);
15
- this.controller = controller;
16
- __classPrivateFieldSet(this, _Stream_client, client);
17
- }
18
- static fromSSEResponse(response, controller, client) {
19
- let consumed = false;
20
- const logger = client ? loggerFor(client) : console;
21
- async function* iterator() {
22
- if (consumed) {
23
- throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
24
- }
25
- consumed = true;
26
- let done = false;
27
- try {
28
- for await (const sse of _iterSSEMessages(response, controller)) {
29
- if (sse.event === 'completion') {
30
- try {
31
- yield JSON.parse(sse.data);
32
- }
33
- catch (e) {
34
- logger.error(`Could not parse message into JSON:`, sse.data);
35
- logger.error(`From chunk:`, sse.raw);
36
- throw e;
37
- }
38
- }
39
- if (sse.event === 'message_start' ||
40
- sse.event === 'message_delta' ||
41
- sse.event === 'message_stop' ||
42
- sse.event === 'content_block_start' ||
43
- sse.event === 'content_block_delta' ||
44
- sse.event === 'content_block_stop') {
45
- try {
46
- yield JSON.parse(sse.data);
47
- }
48
- catch (e) {
49
- logger.error(`Could not parse message into JSON:`, sse.data);
50
- logger.error(`From chunk:`, sse.raw);
51
- throw e;
52
- }
53
- }
54
- if (sse.event === 'ping') {
55
- continue;
56
- }
57
- if (sse.event === 'error') {
58
- throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers);
59
- }
60
- }
61
- done = true;
62
- }
63
- catch (e) {
64
- // If the user calls `stream.controller.abort()`, we should exit without throwing.
65
- if (isAbortError(e))
66
- return;
67
- throw e;
68
- }
69
- finally {
70
- // If the user `break`s, abort the ongoing request.
71
- if (!done)
72
- controller.abort();
73
- }
74
- }
75
- return new Stream(iterator, controller, client);
76
- }
77
- /**
78
- * Generates a Stream from a newline-separated ReadableStream
79
- * where each item is a JSON value.
80
- */
81
- static fromReadableStream(readableStream, controller, client) {
82
- let consumed = false;
83
- async function* iterLines() {
84
- const lineDecoder = new LineDecoder();
85
- const iter = ReadableStreamToAsyncIterable(readableStream);
86
- for await (const chunk of iter) {
87
- for (const line of lineDecoder.decode(chunk)) {
88
- yield line;
89
- }
90
- }
91
- for (const line of lineDecoder.flush()) {
92
- yield line;
93
- }
94
- }
95
- async function* iterator() {
96
- if (consumed) {
97
- throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
98
- }
99
- consumed = true;
100
- let done = false;
101
- try {
102
- for await (const line of iterLines()) {
103
- if (done)
104
- continue;
105
- if (line)
106
- yield JSON.parse(line);
107
- }
108
- done = true;
109
- }
110
- catch (e) {
111
- // If the user calls `stream.controller.abort()`, we should exit without throwing.
112
- if (isAbortError(e))
113
- return;
114
- throw e;
115
- }
116
- finally {
117
- // If the user `break`s, abort the ongoing request.
118
- if (!done)
119
- controller.abort();
120
- }
121
- }
122
- return new Stream(iterator, controller, client);
123
- }
124
- [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
125
- return this.iterator();
126
- }
127
- /**
128
- * Splits the stream into two streams which can be
129
- * independently read from at different speeds.
130
- */
131
- tee() {
132
- const left = [];
133
- const right = [];
134
- const iterator = this.iterator();
135
- const teeIterator = (queue) => {
136
- return {
137
- next: () => {
138
- if (queue.length === 0) {
139
- const result = iterator.next();
140
- left.push(result);
141
- right.push(result);
142
- }
143
- return queue.shift();
144
- },
145
- };
146
- };
147
- return [
148
- new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
149
- new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
150
- ];
151
- }
152
- /**
153
- * Converts this stream to a newline-separated ReadableStream of
154
- * JSON stringified values in the stream
155
- * which can be turned back into a Stream with `Stream.fromReadableStream()`.
156
- */
157
- toReadableStream() {
158
- const self = this;
159
- let iter;
160
- return makeReadableStream({
161
- async start() {
162
- iter = self[Symbol.asyncIterator]();
163
- },
164
- async pull(ctrl) {
165
- try {
166
- const { value, done } = await iter.next();
167
- if (done)
168
- return ctrl.close();
169
- const bytes = encodeUTF8(JSON.stringify(value) + '\n');
170
- ctrl.enqueue(bytes);
171
- }
172
- catch (err) {
173
- ctrl.error(err);
174
- }
175
- },
176
- async cancel() {
177
- await iter.return?.();
178
- },
179
- });
180
- }
181
- }
182
- async function* _iterSSEMessages(response, controller) {
183
- if (!response.body) {
184
- controller.abort();
185
- if (typeof globalThis.navigator !== 'undefined' &&
186
- globalThis.navigator.product === 'ReactNative') {
187
- throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
188
- }
189
- throw new AnthropicError(`Attempted to iterate over a response with no body`);
190
- }
191
- const sseDecoder = new SSEDecoder();
192
- const lineDecoder = new LineDecoder();
193
- const iter = ReadableStreamToAsyncIterable(response.body);
194
- for await (const sseChunk of iterSSEChunks(iter)) {
195
- for (const line of lineDecoder.decode(sseChunk)) {
196
- const sse = sseDecoder.decode(line);
197
- if (sse)
198
- yield sse;
199
- }
200
- }
201
- for (const line of lineDecoder.flush()) {
202
- const sse = sseDecoder.decode(line);
203
- if (sse)
204
- yield sse;
205
- }
206
- }
207
- /**
208
- * Given an async iterable iterator, iterates over it and yields full
209
- * SSE chunks, i.e. yields when a double new-line is encountered.
210
- */
211
- async function* iterSSEChunks(iterator) {
212
- let data = new Uint8Array();
213
- for await (const chunk of iterator) {
214
- if (chunk == null) {
215
- continue;
216
- }
217
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
218
- : typeof chunk === 'string' ? encodeUTF8(chunk)
219
- : chunk;
220
- let newData = new Uint8Array(data.length + binaryChunk.length);
221
- newData.set(data);
222
- newData.set(binaryChunk, data.length);
223
- data = newData;
224
- let patternIndex;
225
- while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
226
- yield data.slice(0, patternIndex);
227
- data = data.slice(patternIndex);
228
- }
229
- }
230
- if (data.length > 0) {
231
- yield data;
232
- }
233
- }
234
- class SSEDecoder {
235
- constructor() {
236
- this.event = null;
237
- this.data = [];
238
- this.chunks = [];
239
- }
240
- decode(line) {
241
- if (line.endsWith('\r')) {
242
- line = line.substring(0, line.length - 1);
243
- }
244
- if (!line) {
245
- // empty line and we didn't previously encounter any messages
246
- if (!this.event && !this.data.length)
247
- return null;
248
- const sse = {
249
- event: this.event,
250
- data: this.data.join('\n'),
251
- raw: this.chunks,
252
- };
253
- this.event = null;
254
- this.data = [];
255
- this.chunks = [];
256
- return sse;
257
- }
258
- this.chunks.push(line);
259
- if (line.startsWith(':')) {
260
- return null;
261
- }
262
- let [fieldname, _, value] = partition(line, ':');
263
- if (value.startsWith(' ')) {
264
- value = value.substring(1);
265
- }
266
- if (fieldname === 'event') {
267
- this.event = value;
268
- }
269
- else if (fieldname === 'data') {
270
- this.data.push(value);
271
- }
272
- return null;
273
- }
274
- }
275
- function partition(str, delimiter) {
276
- const index = str.indexOf(delimiter);
277
- if (index !== -1) {
278
- return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
279
- }
280
- return [str, '', ''];
281
- }
282
-
283
- export { Stream, _iterSSEMessages };
@@ -1,16 +0,0 @@
1
- // File containing shared constants
2
- /**
3
- * Model-specific timeout constraints for non-streaming requests
4
- */
5
- const MODEL_NONSTREAMING_TOKENS = {
6
- 'claude-opus-4-20250514': 8192,
7
- 'claude-opus-4-0': 8192,
8
- 'claude-4-opus-20250514': 8192,
9
- 'anthropic.claude-opus-4-20250514-v1:0': 8192,
10
- 'claude-opus-4@20250514': 8192,
11
- 'claude-opus-4-1-20250805': 8192,
12
- 'anthropic.claude-opus-4-1-20250805-v1:0': 8192,
13
- 'claude-opus-4-1@20250805': 8192,
14
- };
15
-
16
- export { MODEL_NONSTREAMING_TOKENS };
@@ -1,37 +0,0 @@
1
- import { AnthropicError } from '../../core/error.js';
2
- import { ReadableStreamToAsyncIterable } from '../shims.js';
3
- import { LineDecoder } from './line.js';
4
-
5
- class JSONLDecoder {
6
- constructor(iterator, controller) {
7
- this.iterator = iterator;
8
- this.controller = controller;
9
- }
10
- async *decoder() {
11
- const lineDecoder = new LineDecoder();
12
- for await (const chunk of this.iterator) {
13
- for (const line of lineDecoder.decode(chunk)) {
14
- yield JSON.parse(line);
15
- }
16
- }
17
- for (const line of lineDecoder.flush()) {
18
- yield JSON.parse(line);
19
- }
20
- }
21
- [Symbol.asyncIterator]() {
22
- return this.decoder();
23
- }
24
- static fromResponse(response, controller) {
25
- if (!response.body) {
26
- controller.abort();
27
- if (typeof globalThis.navigator !== 'undefined' &&
28
- globalThis.navigator.product === 'ReactNative') {
29
- throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
30
- }
31
- throw new AnthropicError(`Attempted to iterate over a response with no body`);
32
- }
33
- return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller);
34
- }
35
- }
36
-
37
- export { JSONLDecoder };
@@ -1,110 +0,0 @@
1
- import { __classPrivateFieldSet, __classPrivateFieldGet } from '../tslib.js';
2
- import { encodeUTF8, concatBytes, decodeUTF8 } from '../utils/bytes.js';
3
-
4
- var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex;
5
- /**
6
- * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
7
- * reading lines from text.
8
- *
9
- * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
10
- */
11
- class LineDecoder {
12
- constructor() {
13
- _LineDecoder_buffer.set(this, void 0);
14
- _LineDecoder_carriageReturnIndex.set(this, void 0);
15
- __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array());
16
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null);
17
- }
18
- decode(chunk) {
19
- if (chunk == null) {
20
- return [];
21
- }
22
- const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
23
- : typeof chunk === 'string' ? encodeUTF8(chunk)
24
- : chunk;
25
- __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]));
26
- const lines = [];
27
- let patternIndex;
28
- while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
29
- if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) {
30
- // skip until we either get a corresponding `\n`, a new `\r` or nothing
31
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index);
32
- continue;
33
- }
34
- // we got double \r or \rtext\n
35
- if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null &&
36
- (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
37
- lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
38
- __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")));
39
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null);
40
- continue;
41
- }
42
- const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
43
- const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex));
44
- lines.push(line);
45
- __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index));
46
- __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null);
47
- }
48
- return lines;
49
- }
50
- flush() {
51
- if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
52
- return [];
53
- }
54
- return this.decode('\n');
55
- }
56
- }
57
- _LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap();
58
- // prettier-ignore
59
- LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
60
- LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
61
- /**
62
- * This function searches the buffer for the end patterns, (\r or \n)
63
- * and returns an object with the index preceding the matched newline and the
64
- * index after the newline char. `null` is returned if no new line is found.
65
- *
66
- * ```ts
67
- * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
68
- * ```
69
- */
70
- function findNewlineIndex(buffer, startIndex) {
71
- const newline = 0x0a; // \n
72
- const carriage = 0x0d; // \r
73
- for (let i = startIndex ?? 0; i < buffer.length; i++) {
74
- if (buffer[i] === newline) {
75
- return { preceding: i, index: i + 1, carriage: false };
76
- }
77
- if (buffer[i] === carriage) {
78
- return { preceding: i, index: i + 1, carriage: true };
79
- }
80
- }
81
- return null;
82
- }
83
- function findDoubleNewlineIndex(buffer) {
84
- // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
85
- // and returns the index right after the first occurrence of any pattern,
86
- // or -1 if none of the patterns are found.
87
- const newline = 0x0a; // \n
88
- const carriage = 0x0d; // \r
89
- for (let i = 0; i < buffer.length - 1; i++) {
90
- if (buffer[i] === newline && buffer[i + 1] === newline) {
91
- // \n\n
92
- return i + 2;
93
- }
94
- if (buffer[i] === carriage && buffer[i + 1] === carriage) {
95
- // \r\r
96
- return i + 2;
97
- }
98
- if (buffer[i] === carriage &&
99
- buffer[i + 1] === newline &&
100
- i + 3 < buffer.length &&
101
- buffer[i + 2] === carriage &&
102
- buffer[i + 3] === newline) {
103
- // \r\n\r\n
104
- return i + 4;
105
- }
106
- }
107
- return -1;
108
- }
109
-
110
- export { LineDecoder, findDoubleNewlineIndex };