@xsai/stream-object 0.2.0-beta.1 → 0.2.0-beta.3

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 (3) hide show
  1. package/dist/index.d.ts +783 -1
  2. package/dist/index.js +237 -258
  3. package/package.json +3 -3
package/dist/index.d.ts CHANGED
@@ -1,7 +1,789 @@
1
1
  import { StreamTextOptions, StreamTextResult } from '@xsai/stream-text';
2
- import { PartialDeep } from 'type-fest';
3
2
  import { Schema, Infer } from 'xsschema';
4
3
 
4
+ /**
5
+ Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
6
+
7
+ @category Type
8
+ */
9
+ type Primitive =
10
+ | null
11
+ | undefined
12
+ | string
13
+ | number
14
+ | boolean
15
+ | symbol
16
+ | bigint;
17
+
18
+ declare global {
19
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- It has to be an `interface` so that it can be merged.
20
+ interface SymbolConstructor {
21
+ readonly observable: symbol;
22
+ }
23
+ }
24
+
25
+ /**
26
+ Convert a union type to an intersection type using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
27
+
28
+ Inspired by [this Stack Overflow answer](https://stackoverflow.com/a/50375286/2172153).
29
+
30
+ @example
31
+ ```
32
+ import type {UnionToIntersection} from 'type-fest';
33
+
34
+ type Union = {the(): void} | {great(arg: string): void} | {escape: boolean};
35
+
36
+ type Intersection = UnionToIntersection<Union>;
37
+ //=> {the(): void; great(arg: string): void; escape: boolean};
38
+ ```
39
+
40
+ A more applicable example which could make its way into your library code follows.
41
+
42
+ @example
43
+ ```
44
+ import type {UnionToIntersection} from 'type-fest';
45
+
46
+ class CommandOne {
47
+ commands: {
48
+ a1: () => undefined,
49
+ b1: () => undefined,
50
+ }
51
+ }
52
+
53
+ class CommandTwo {
54
+ commands: {
55
+ a2: (argA: string) => undefined,
56
+ b2: (argB: string) => undefined,
57
+ }
58
+ }
59
+
60
+ const union = [new CommandOne(), new CommandTwo()].map(instance => instance.commands);
61
+ type Union = typeof union;
62
+ //=> {a1(): void; b1(): void} | {a2(argA: string): void; b2(argB: string): void}
63
+
64
+ type Intersection = UnionToIntersection<Union>;
65
+ //=> {a1(): void; b1(): void; a2(argA: string): void; b2(argB: string): void}
66
+ ```
67
+
68
+ @category Type
69
+ */
70
+ type UnionToIntersection<Union> = (
71
+ // `extends unknown` is always going to be the case and is used to convert the
72
+ // `Union` into a [distributive conditional
73
+ // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
74
+ Union extends unknown
75
+ // The union type is used as the only argument to a function since the union
76
+ // of function arguments is an intersection.
77
+ ? (distributedUnion: Union) => void
78
+ // This won't happen.
79
+ : never
80
+ // Infer the `Intersection` type since TypeScript represents the positional
81
+ // arguments of unions of functions as an intersection of the union.
82
+ ) extends ((mergedIntersection: infer Intersection) => void)
83
+ // The `& Union` is to allow indexing by the resulting type
84
+ ? Intersection & Union
85
+ : never;
86
+
87
+ /**
88
+ Create a union of all keys from a given type, even those exclusive to specific union members.
89
+
90
+ Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member.
91
+
92
+ @link https://stackoverflow.com/a/49402091
93
+
94
+ @example
95
+ ```
96
+ import type {KeysOfUnion} from 'type-fest';
97
+
98
+ type A = {
99
+ common: string;
100
+ a: number;
101
+ };
102
+
103
+ type B = {
104
+ common: string;
105
+ b: string;
106
+ };
107
+
108
+ type C = {
109
+ common: string;
110
+ c: boolean;
111
+ };
112
+
113
+ type Union = A | B | C;
114
+
115
+ type CommonKeys = keyof Union;
116
+ //=> 'common'
117
+
118
+ type AllKeys = KeysOfUnion<Union>;
119
+ //=> 'common' | 'a' | 'b' | 'c'
120
+ ```
121
+
122
+ @category Object
123
+ */
124
+ type KeysOfUnion<ObjectType> =
125
+ // Hack to fix https://github.com/sindresorhus/type-fest/issues/1008
126
+ keyof UnionToIntersection<ObjectType extends unknown ? Record<keyof ObjectType, never> : never>;
127
+
128
+ /**
129
+ Extract all optional keys from the given type.
130
+
131
+ This is useful when you want to create a new type that contains different type values for the optional keys only.
132
+
133
+ @example
134
+ ```
135
+ import type {OptionalKeysOf, Except} from 'type-fest';
136
+
137
+ interface User {
138
+ name: string;
139
+ surname: string;
140
+
141
+ luckyNumber?: number;
142
+ }
143
+
144
+ const REMOVE_FIELD = Symbol('remove field symbol');
145
+ type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
146
+ [Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
147
+ };
148
+
149
+ const update1: UpdateOperation<User> = {
150
+ name: 'Alice'
151
+ };
152
+
153
+ const update2: UpdateOperation<User> = {
154
+ name: 'Bob',
155
+ luckyNumber: REMOVE_FIELD
156
+ };
157
+ ```
158
+
159
+ @category Utilities
160
+ */
161
+ type OptionalKeysOf<BaseType extends object> = KeysOfUnion<{
162
+ [Key in keyof BaseType as BaseType extends Record<Key, BaseType[Key]> ? never : Key]: never
163
+ }>;
164
+
165
+ /**
166
+ Extract all required keys from the given type.
167
+
168
+ This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc...
169
+
170
+ @example
171
+ ```
172
+ import type {RequiredKeysOf} from 'type-fest';
173
+
174
+ declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn;
175
+
176
+ interface User {
177
+ name: string;
178
+ surname: string;
179
+
180
+ luckyNumber?: number;
181
+ }
182
+
183
+ const validator1 = createValidation<User>('name', value => value.length < 25);
184
+ const validator2 = createValidation<User>('surname', value => value.length < 25);
185
+ ```
186
+
187
+ @category Utilities
188
+ */
189
+ type RequiredKeysOf<BaseType extends object> =
190
+ BaseType extends unknown // For distributing `BaseType`
191
+ ? Exclude<keyof BaseType, OptionalKeysOf<BaseType>>
192
+ : never; // Should never happen
193
+
194
+ /**
195
+ Returns a boolean for whether the given type is `never`.
196
+
197
+ @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
198
+ @link https://stackoverflow.com/a/53984913/10292952
199
+ @link https://www.zhenghao.io/posts/ts-never
200
+
201
+ Useful in type utilities, such as checking if something does not occur.
202
+
203
+ @example
204
+ ```
205
+ import type {IsNever, And} from 'type-fest';
206
+
207
+ // https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts
208
+ type AreStringsEqual<A extends string, B extends string> =
209
+ And<
210
+ IsNever<Exclude<A, B>> extends true ? true : false,
211
+ IsNever<Exclude<B, A>> extends true ? true : false
212
+ >;
213
+
214
+ type EndIfEqual<I extends string, O extends string> =
215
+ AreStringsEqual<I, O> extends true
216
+ ? never
217
+ : void;
218
+
219
+ function endIfEqual<I extends string, O extends string>(input: I, output: O): EndIfEqual<I, O> {
220
+ if (input === output) {
221
+ process.exit(0);
222
+ }
223
+ }
224
+
225
+ endIfEqual('abc', 'abc');
226
+ //=> never
227
+
228
+ endIfEqual('abc', '123');
229
+ //=> void
230
+ ```
231
+
232
+ @category Type Guard
233
+ @category Utilities
234
+ */
235
+ type IsNever<T> = [T] extends [never] ? true : false;
236
+
237
+ /**
238
+ An if-else-like type that resolves depending on whether the given type is `never`.
239
+
240
+ @see {@link IsNever}
241
+
242
+ @example
243
+ ```
244
+ import type {IfNever} from 'type-fest';
245
+
246
+ type ShouldBeTrue = IfNever<never>;
247
+ //=> true
248
+
249
+ type ShouldBeBar = IfNever<'not never', 'foo', 'bar'>;
250
+ //=> 'bar'
251
+ ```
252
+
253
+ @category Type Guard
254
+ @category Utilities
255
+ */
256
+ type IfNever<T, TypeIfNever = true, TypeIfNotNever = false> = (
257
+ IsNever<T> extends true ? TypeIfNever : TypeIfNotNever
258
+ );
259
+
260
+ // Can eventually be replaced with the built-in once this library supports
261
+ // TS5.4+ only. Tracked in https://github.com/sindresorhus/type-fest/issues/848
262
+ type NoInfer<T> = T extends infer U ? U : never;
263
+
264
+ /**
265
+ Returns a boolean for whether the given type is `any`.
266
+
267
+ @link https://stackoverflow.com/a/49928360/1490091
268
+
269
+ Useful in type utilities, such as disallowing `any`s to be passed to a function.
270
+
271
+ @example
272
+ ```
273
+ import type {IsAny} from 'type-fest';
274
+
275
+ const typedObject = {a: 1, b: 2} as const;
276
+ const anyObject: any = {a: 1, b: 2};
277
+
278
+ function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(obj: O, key: K) {
279
+ return obj[key];
280
+ }
281
+
282
+ const typedA = get(typedObject, 'a');
283
+ //=> 1
284
+
285
+ const anyA = get(anyObject, 'a');
286
+ //=> any
287
+ ```
288
+
289
+ @category Type Guard
290
+ @category Utilities
291
+ */
292
+ type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
293
+
294
+ /**
295
+ Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
296
+
297
+ @example
298
+ ```
299
+ import type {Simplify} from 'type-fest';
300
+
301
+ type PositionProps = {
302
+ top: number;
303
+ left: number;
304
+ };
305
+
306
+ type SizeProps = {
307
+ width: number;
308
+ height: number;
309
+ };
310
+
311
+ // In your editor, hovering over `Props` will show a flattened object with all the properties.
312
+ type Props = Simplify<PositionProps & SizeProps>;
313
+ ```
314
+
315
+ Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface.
316
+
317
+ If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`.
318
+
319
+ @example
320
+ ```
321
+ import type {Simplify} from 'type-fest';
322
+
323
+ interface SomeInterface {
324
+ foo: number;
325
+ bar?: string;
326
+ baz: number | undefined;
327
+ }
328
+
329
+ type SomeType = {
330
+ foo: number;
331
+ bar?: string;
332
+ baz: number | undefined;
333
+ };
334
+
335
+ const literal = {foo: 123, bar: 'hello', baz: 456};
336
+ const someType: SomeType = literal;
337
+ const someInterface: SomeInterface = literal;
338
+
339
+ function fn(object: Record<string, unknown>): void {}
340
+
341
+ fn(literal); // Good: literal object type is sealed
342
+ fn(someType); // Good: type is sealed
343
+ fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
344
+ fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
345
+ ```
346
+
347
+ @link https://github.com/microsoft/TypeScript/issues/15300
348
+ @see SimplifyDeep
349
+ @category Object
350
+ */
351
+ type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
352
+
353
+ /**
354
+ Omit any index signatures from the given object type, leaving only explicitly defined properties.
355
+
356
+ This is the counterpart of `PickIndexSignature`.
357
+
358
+ Use-cases:
359
+ - Remove overly permissive signatures from third-party types.
360
+
361
+ This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
362
+
363
+ It relies on the fact that an empty object (`{}`) is assignable to an object with just an index signature, like `Record<string, unknown>`, but not to an object with explicitly defined keys, like `Record<'foo' | 'bar', unknown>`.
364
+
365
+ (The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
366
+
367
+ ```
368
+ const indexed: Record<string, unknown> = {}; // Allowed
369
+
370
+ const keyed: Record<'foo', unknown> = {}; // Error
371
+ // => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
372
+ ```
373
+
374
+ Instead of causing a type error like the above, you can also use a [conditional type](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html) to test whether a type is assignable to another:
375
+
376
+ ```
377
+ type Indexed = {} extends Record<string, unknown>
378
+ ? '✅ `{}` is assignable to `Record<string, unknown>`'
379
+ : '❌ `{}` is NOT assignable to `Record<string, unknown>`';
380
+ // => '✅ `{}` is assignable to `Record<string, unknown>`'
381
+
382
+ type Keyed = {} extends Record<'foo' | 'bar', unknown>
383
+ ? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`"
384
+ : "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`";
385
+ // => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"
386
+ ```
387
+
388
+ Using a [mapped type](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#further-exploration), you can then check for each `KeyType` of `ObjectType`...
389
+
390
+ ```
391
+ import type {OmitIndexSignature} from 'type-fest';
392
+
393
+ type OmitIndexSignature<ObjectType> = {
394
+ [KeyType in keyof ObjectType // Map each key of `ObjectType`...
395
+ ]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
396
+ };
397
+ ```
398
+
399
+ ...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
400
+
401
+ ```
402
+ import type {OmitIndexSignature} from 'type-fest';
403
+
404
+ type OmitIndexSignature<ObjectType> = {
405
+ [KeyType in keyof ObjectType
406
+ // Is `{}` assignable to `Record<KeyType, unknown>`?
407
+ as {} extends Record<KeyType, unknown>
408
+ ? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>`
409
+ : ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
410
+ ]: ObjectType[KeyType];
411
+ };
412
+ ```
413
+
414
+ If `{}` is assignable, it means that `KeyType` is an index signature and we want to remove it. If it is not assignable, `KeyType` is a "real" key and we want to keep it.
415
+
416
+ @example
417
+ ```
418
+ import type {OmitIndexSignature} from 'type-fest';
419
+
420
+ interface Example {
421
+ // These index signatures will be removed.
422
+ [x: string]: any
423
+ [x: number]: any
424
+ [x: symbol]: any
425
+ [x: `head-${string}`]: string
426
+ [x: `${string}-tail`]: string
427
+ [x: `head-${string}-tail`]: string
428
+ [x: `${bigint}`]: string
429
+ [x: `embedded-${number}`]: string
430
+
431
+ // These explicitly defined keys will remain.
432
+ foo: 'bar';
433
+ qux?: 'baz';
434
+ }
435
+
436
+ type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
437
+ // => { foo: 'bar'; qux?: 'baz' | undefined; }
438
+ ```
439
+
440
+ @see PickIndexSignature
441
+ @category Object
442
+ */
443
+ type OmitIndexSignature<ObjectType> = {
444
+ [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
445
+ ? never
446
+ : KeyType]: ObjectType[KeyType];
447
+ };
448
+
449
+ /**
450
+ Pick only index signatures from the given object type, leaving out all explicitly defined properties.
451
+
452
+ This is the counterpart of `OmitIndexSignature`.
453
+
454
+ @example
455
+ ```
456
+ import type {PickIndexSignature} from 'type-fest';
457
+
458
+ declare const symbolKey: unique symbol;
459
+
460
+ type Example = {
461
+ // These index signatures will remain.
462
+ [x: string]: unknown;
463
+ [x: number]: unknown;
464
+ [x: symbol]: unknown;
465
+ [x: `head-${string}`]: string;
466
+ [x: `${string}-tail`]: string;
467
+ [x: `head-${string}-tail`]: string;
468
+ [x: `${bigint}`]: string;
469
+ [x: `embedded-${number}`]: string;
470
+
471
+ // These explicitly defined keys will be removed.
472
+ ['kebab-case-key']: string;
473
+ [symbolKey]: string;
474
+ foo: 'bar';
475
+ qux?: 'baz';
476
+ };
477
+
478
+ type ExampleIndexSignature = PickIndexSignature<Example>;
479
+ // {
480
+ // [x: string]: unknown;
481
+ // [x: number]: unknown;
482
+ // [x: symbol]: unknown;
483
+ // [x: `head-${string}`]: string;
484
+ // [x: `${string}-tail`]: string;
485
+ // [x: `head-${string}-tail`]: string;
486
+ // [x: `${bigint}`]: string;
487
+ // [x: `embedded-${number}`]: string;
488
+ // }
489
+ ```
490
+
491
+ @see OmitIndexSignature
492
+ @category Object
493
+ */
494
+ type PickIndexSignature<ObjectType> = {
495
+ [KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
496
+ ? KeyType
497
+ : never]: ObjectType[KeyType];
498
+ };
499
+
500
+ // Merges two objects without worrying about index signatures.
501
+ type SimpleMerge<Destination, Source> = {
502
+ [Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
503
+ } & Source;
504
+
505
+ /**
506
+ Merge two types into a new type. Keys of the second type overrides keys of the first type.
507
+
508
+ @example
509
+ ```
510
+ import type {Merge} from 'type-fest';
511
+
512
+ interface Foo {
513
+ [x: string]: unknown;
514
+ [x: number]: unknown;
515
+ foo: string;
516
+ bar: symbol;
517
+ }
518
+
519
+ type Bar = {
520
+ [x: number]: number;
521
+ [x: symbol]: unknown;
522
+ bar: Date;
523
+ baz: boolean;
524
+ };
525
+
526
+ export type FooBar = Merge<Foo, Bar>;
527
+ // => {
528
+ // [x: string]: unknown;
529
+ // [x: number]: number;
530
+ // [x: symbol]: unknown;
531
+ // foo: string;
532
+ // bar: Date;
533
+ // baz: boolean;
534
+ // }
535
+ ```
536
+
537
+ @category Object
538
+ */
539
+ type Merge<Destination, Source> =
540
+ Simplify<
541
+ SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
542
+ & SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
543
+ >;
544
+
545
+ /**
546
+ An if-else-like type that resolves depending on whether the given type is `any`.
547
+
548
+ @see {@link IsAny}
549
+
550
+ @example
551
+ ```
552
+ import type {IfAny} from 'type-fest';
553
+
554
+ type ShouldBeTrue = IfAny<any>;
555
+ //=> true
556
+
557
+ type ShouldBeBar = IfAny<'not any', 'foo', 'bar'>;
558
+ //=> 'bar'
559
+ ```
560
+
561
+ @category Type Guard
562
+ @category Utilities
563
+ */
564
+ type IfAny<T, TypeIfAny = true, TypeIfNotAny = false> = (
565
+ IsAny<T> extends true ? TypeIfAny : TypeIfNotAny
566
+ );
567
+
568
+ /**
569
+ Matches any primitive, `void`, `Date`, or `RegExp` value.
570
+ */
571
+ type BuiltIns = Primitive | void | Date | RegExp;
572
+
573
+ /**
574
+ Merges user specified options with default options.
575
+
576
+ @example
577
+ ```
578
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
579
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
580
+ type SpecifiedOptions = {leavesOnly: true};
581
+
582
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
583
+ //=> {maxRecursionDepth: 10; leavesOnly: true}
584
+ ```
585
+
586
+ @example
587
+ ```
588
+ // Complains if default values are not provided for optional options
589
+
590
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
591
+ type DefaultPathsOptions = {maxRecursionDepth: 10};
592
+ type SpecifiedOptions = {};
593
+
594
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
595
+ // ~~~~~~~~~~~~~~~~~~~
596
+ // Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
597
+ ```
598
+
599
+ @example
600
+ ```
601
+ // Complains if an option's default type does not conform to the expected type
602
+
603
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
604
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
605
+ type SpecifiedOptions = {};
606
+
607
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
608
+ // ~~~~~~~~~~~~~~~~~~~
609
+ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
610
+ ```
611
+
612
+ @example
613
+ ```
614
+ // Complains if an option's specified type does not conform to the expected type
615
+
616
+ type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
617
+ type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
618
+ type SpecifiedOptions = {leavesOnly: 'yes'};
619
+
620
+ type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
621
+ // ~~~~~~~~~~~~~~~~
622
+ // Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
623
+ ```
624
+ */
625
+ type ApplyDefaultOptions<
626
+ Options extends object,
627
+ Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>,
628
+ SpecifiedOptions extends Options,
629
+ > =
630
+ IfAny<SpecifiedOptions, Defaults,
631
+ IfNever<SpecifiedOptions, Defaults,
632
+ Simplify<Merge<Defaults, {
633
+ [Key in keyof SpecifiedOptions
634
+ as Key extends OptionalKeysOf<Options>
635
+ ? Extract<SpecifiedOptions[Key], undefined> extends never
636
+ ? Key
637
+ : never
638
+ : Key
639
+ ]: SpecifiedOptions[Key]
640
+ }> & Required<Options>> // `& Required<Options>` ensures that `ApplyDefaultOptions<SomeOption, ...>` is always assignable to `Required<SomeOption>`
641
+ >>;
642
+
643
+ /**
644
+ @see {@link PartialDeep}
645
+ */
646
+ type PartialDeepOptions = {
647
+ /**
648
+ Whether to affect the individual elements of arrays and tuples.
649
+
650
+ @default false
651
+ */
652
+ readonly recurseIntoArrays?: boolean;
653
+
654
+ /**
655
+ Allows `undefined` values in non-tuple arrays.
656
+
657
+ - When set to `true`, elements of non-tuple arrays can be `undefined`.
658
+ - When set to `false`, only explicitly defined elements are allowed in non-tuple arrays, ensuring stricter type checking.
659
+
660
+ @default true
661
+
662
+ @example
663
+ You can prevent `undefined` values in non-tuple arrays by passing `{recurseIntoArrays: true; allowUndefinedInNonTupleArrays: false}` as the second type argument:
664
+
665
+ ```
666
+ import type {PartialDeep} from 'type-fest';
667
+
668
+ type Settings = {
669
+ languages: string[];
670
+ };
671
+
672
+ declare const partialSettings: PartialDeep<Settings, {recurseIntoArrays: true; allowUndefinedInNonTupleArrays: false}>;
673
+
674
+ partialSettings.languages = [undefined]; // Error
675
+ partialSettings.languages = []; // Ok
676
+ ```
677
+ */
678
+ readonly allowUndefinedInNonTupleArrays?: boolean;
679
+ };
680
+
681
+ type DefaultPartialDeepOptions = {
682
+ recurseIntoArrays: false;
683
+ allowUndefinedInNonTupleArrays: true;
684
+ };
685
+
686
+ /**
687
+ Create a type from another type with all keys and nested keys set to optional.
688
+
689
+ Use-cases:
690
+ - Merging a default settings/config object with another object, the second object would be a deep partial of the default object.
691
+ - Mocking and testing complex entities, where populating an entire object with its keys would be redundant in terms of the mock or test.
692
+
693
+ @example
694
+ ```
695
+ import type {PartialDeep} from 'type-fest';
696
+
697
+ const settings: Settings = {
698
+ textEditor: {
699
+ fontSize: 14,
700
+ fontColor: '#000000',
701
+ fontWeight: 400
702
+ },
703
+ autocomplete: false,
704
+ autosave: true
705
+ };
706
+
707
+ const applySavedSettings = (savedSettings: PartialDeep<Settings>) => {
708
+ return {...settings, ...savedSettings};
709
+ }
710
+
711
+ settings = applySavedSettings({textEditor: {fontWeight: 500}});
712
+ ```
713
+
714
+ By default, this does not affect elements in array and tuple types. You can change this by passing `{recurseIntoArrays: true}` as the second type argument:
715
+
716
+ ```
717
+ import type {PartialDeep} from 'type-fest';
718
+
719
+ type Settings = {
720
+ languages: string[];
721
+ }
722
+
723
+ const partialSettings: PartialDeep<Settings, {recurseIntoArrays: true}> = {
724
+ languages: [undefined]
725
+ };
726
+ ```
727
+
728
+ @see {@link PartialDeepOptions}
729
+
730
+ @category Object
731
+ @category Array
732
+ @category Set
733
+ @category Map
734
+ */
735
+ type PartialDeep<T, Options extends PartialDeepOptions = {}> =
736
+ _PartialDeep<T, ApplyDefaultOptions<PartialDeepOptions, DefaultPartialDeepOptions, Options>>;
737
+
738
+ type _PartialDeep<T, Options extends Required<PartialDeepOptions>> = T extends BuiltIns | (((...arguments_: any[]) => unknown)) | (new (...arguments_: any[]) => unknown)
739
+ ? T
740
+ : T extends Map<infer KeyType, infer ValueType>
741
+ ? PartialMapDeep<KeyType, ValueType, Options>
742
+ : T extends Set<infer ItemType>
743
+ ? PartialSetDeep<ItemType, Options>
744
+ : T extends ReadonlyMap<infer KeyType, infer ValueType>
745
+ ? PartialReadonlyMapDeep<KeyType, ValueType, Options>
746
+ : T extends ReadonlySet<infer ItemType>
747
+ ? PartialReadonlySetDeep<ItemType, Options>
748
+ : T extends object
749
+ ? T extends ReadonlyArray<infer ItemType> // Test for arrays/tuples, per https://github.com/microsoft/TypeScript/issues/35156
750
+ ? Options['recurseIntoArrays'] extends true
751
+ ? ItemType[] extends T // Test for arrays (non-tuples) specifically
752
+ ? readonly ItemType[] extends T // Differentiate readonly and mutable arrays
753
+ ? ReadonlyArray<_PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
754
+ : Array<_PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
755
+ : PartialObjectDeep<T, Options> // Tuples behave properly
756
+ : T // If they don't opt into array testing, just use the original type
757
+ : PartialObjectDeep<T, Options>
758
+ : unknown;
759
+
760
+ /**
761
+ Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`.
762
+ */
763
+ type PartialMapDeep<KeyType, ValueType, Options extends Required<PartialDeepOptions>> = {} & Map<_PartialDeep<KeyType, Options>, _PartialDeep<ValueType, Options>>;
764
+
765
+ /**
766
+ Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`.
767
+ */
768
+ type PartialSetDeep<T, Options extends Required<PartialDeepOptions>> = {} & Set<_PartialDeep<T, Options>>;
769
+
770
+ /**
771
+ Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`.
772
+ */
773
+ type PartialReadonlyMapDeep<KeyType, ValueType, Options extends Required<PartialDeepOptions>> = {} & ReadonlyMap<_PartialDeep<KeyType, Options>, _PartialDeep<ValueType, Options>>;
774
+
775
+ /**
776
+ Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`.
777
+ */
778
+ type PartialReadonlySetDeep<T, Options extends Required<PartialDeepOptions>> = {} & ReadonlySet<_PartialDeep<T, Options>>;
779
+
780
+ /**
781
+ Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`.
782
+ */
783
+ type PartialObjectDeep<ObjectType extends object, Options extends Required<PartialDeepOptions>> = {
784
+ [KeyType in keyof ObjectType]?: _PartialDeep<ObjectType[KeyType], Options>
785
+ };
786
+
5
787
  interface StreamObjectOnFinishResult<T extends Schema> {
6
788
  object?: Infer<T>;
7
789
  }
package/dist/index.js CHANGED
@@ -1,257 +1,237 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
1
+ import { streamText } from '@xsai/stream-text';
2
+ import { toJsonSchema } from 'xsschema';
26
3
 
27
- // ../../node_modules/.pnpm/best-effort-json-parser@1.1.3/node_modules/best-effort-json-parser/dist/parse.js
28
- var require_parse = __commonJS({
29
- "../../node_modules/.pnpm/best-effort-json-parser@1.1.3/node_modules/best-effort-json-parser/dist/parse.js"(exports) {
30
- "use strict";
31
- Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.parse = void 0;
33
- function parse2(s) {
34
- if (s === void 0) {
35
- return void 0;
36
- }
37
- if (s === null) {
38
- return null;
39
- }
40
- if (s === "") {
41
- return "";
42
- }
43
- s = s.replace(/\\+$/, (match) => match.length % 2 === 0 ? match : match.slice(0, -1));
44
- try {
45
- return JSON.parse(s);
46
- } catch (e) {
47
- const [data, reminding] = s.trimLeft()[0] === ":" ? parseAny(s, e) : parseAny(s, e, parseStringWithoutQuote);
48
- parse2.lastParseReminding = reminding;
49
- if (parse2.onExtraToken && reminding.length > 0) {
50
- const trimmedReminding = reminding.trimRight();
51
- parse2.lastParseReminding = trimmedReminding;
52
- if (trimmedReminding.length > 0) {
53
- parse2.onExtraToken(s, data, trimmedReminding);
54
- }
55
- }
56
- return data;
57
- }
58
- }
59
- exports.parse = parse2;
60
- (function(parse3) {
61
- parse3.onExtraToken = (text, data, reminding) => {
62
- console.error("parsed json with extra tokens:", {
63
- text,
64
- data,
65
- reminding
66
- });
67
- };
68
- })(parse2 = exports.parse || (exports.parse = {}));
69
- function parseAny(s, e, fallback) {
70
- const parser = parsers[s[0]] || fallback;
71
- if (!parser) {
72
- console.error(`no parser registered for ${JSON.stringify(s[0])}:`, { s });
73
- throw e;
74
- }
75
- return parser(s, e);
76
- }
77
- function parseStringCasual(s, e, delimiters) {
78
- if (s[0] === '"') {
79
- return parseString(s);
80
- }
81
- if (s[0] === "'") {
82
- return parseSingleQuoteString(s);
83
- }
84
- return parseStringWithoutQuote(s, e, delimiters);
85
- }
86
- var parsers = {};
87
- function skipSpace(s) {
88
- return s.trimLeft();
89
- }
90
- parsers[" "] = parseSpace;
91
- parsers["\r"] = parseSpace;
92
- parsers["\n"] = parseSpace;
93
- parsers[" "] = parseSpace;
94
- function parseSpace(s, e) {
95
- s = skipSpace(s);
96
- return parseAny(s, e);
97
- }
98
- parsers["["] = parseArray;
99
- function parseArray(s, e) {
100
- s = s.substr(1);
101
- const acc = [];
102
- s = skipSpace(s);
103
- for (; s.length > 0; ) {
104
- if (s[0] === "]") {
105
- s = s.substr(1);
106
- break;
107
- }
108
- const res = parseAny(s, e, (s2, e2) => parseStringWithoutQuote(s2, e2, [",", "]"]));
109
- acc.push(res[0]);
110
- s = res[1];
111
- s = skipSpace(s);
112
- if (s[0] === ",") {
113
- s = s.substring(1);
114
- s = skipSpace(s);
115
- }
116
- }
117
- return [acc, s];
118
- }
119
- for (const c of "0123456789.-".slice()) {
120
- parsers[c] = parseNumber;
121
- }
122
- function parseNumber(s) {
123
- for (let i = 0; i < s.length; i++) {
124
- const c = s[i];
125
- if (parsers[c] === parseNumber) {
126
- continue;
127
- }
128
- const num = s.substring(0, i);
129
- s = s.substring(i);
130
- return [numToStr(num), s];
131
- }
132
- return [numToStr(s), ""];
133
- }
134
- function numToStr(s) {
135
- if (s === "-") {
136
- return -0;
137
- }
138
- const num = +s;
139
- if (Number.isNaN(num)) {
140
- return s;
141
- }
142
- return num;
143
- }
144
- parsers['"'] = parseString;
145
- function parseString(s) {
146
- for (let i = 1; i < s.length; i++) {
147
- const c = s[i];
148
- if (c === "\\") {
149
- i++;
150
- continue;
151
- }
152
- if (c === '"') {
153
- const str = fixEscapedCharacters(s.substring(0, i + 1));
154
- s = s.substring(i + 1);
155
- return [JSON.parse(str), s];
156
- }
157
- }
158
- return [JSON.parse(fixEscapedCharacters(s) + '"'), ""];
159
- }
160
- function fixEscapedCharacters(s) {
161
- return s.replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
162
- }
163
- parsers["'"] = parseSingleQuoteString;
164
- function parseSingleQuoteString(s) {
165
- for (let i = 1; i < s.length; i++) {
166
- const c = s[i];
167
- if (c === "\\") {
168
- i++;
169
- continue;
170
- }
171
- if (c === "'") {
172
- const str = fixEscapedCharacters(s.substring(0, i + 1));
173
- s = s.substring(i + 1);
174
- return [JSON.parse('"' + str.slice(1, -1) + '"'), s];
175
- }
176
- }
177
- return [JSON.parse('"' + fixEscapedCharacters(s.slice(1)) + '"'), ""];
178
- }
179
- function parseStringWithoutQuote(s, e, delimiters = [" "]) {
180
- const index = Math.min(...delimiters.map((delimiter) => {
181
- const index2 = s.indexOf(delimiter);
182
- return index2 === -1 ? s.length : index2;
183
- }));
184
- const value = s.substring(0, index).trim();
185
- const rest = s.substring(index);
186
- return [value, rest];
187
- }
188
- parsers["{"] = parseObject;
189
- function parseObject(s, e) {
190
- s = s.substr(1);
191
- const acc = {};
192
- s = skipSpace(s);
193
- for (; s.length > 0; ) {
194
- if (s[0] === "}") {
195
- s = s.substr(1);
196
- break;
197
- }
198
- const keyRes = parseStringCasual(s, e, [":", "}"]);
199
- const key = keyRes[0];
200
- s = keyRes[1];
201
- s = skipSpace(s);
202
- if (s[0] !== ":") {
203
- acc[key] = void 0;
204
- break;
205
- }
206
- s = s.substr(1);
207
- s = skipSpace(s);
208
- if (s.length === 0) {
209
- acc[key] = void 0;
210
- break;
211
- }
212
- const valueRes = parseAny(s, e);
213
- acc[key] = valueRes[0];
214
- s = valueRes[1];
215
- s = skipSpace(s);
216
- if (s[0] === ",") {
217
- s = s.substr(1);
218
- s = skipSpace(s);
219
- }
220
- }
221
- return [acc, s];
222
- }
223
- parsers["t"] = parseTrue;
224
- function parseTrue(s, e) {
225
- return parseToken(s, `true`, true, e);
226
- }
227
- parsers["f"] = parseFalse;
228
- function parseFalse(s, e) {
229
- return parseToken(s, `false`, false, e);
230
- }
231
- parsers["n"] = parseNull;
232
- function parseNull(s, e) {
233
- return parseToken(s, `null`, null, e);
234
- }
235
- function parseToken(s, tokenStr, tokenVal, e) {
236
- for (let i = tokenStr.length; i >= 1; i--) {
237
- if (s.startsWith(tokenStr.slice(0, i))) {
238
- return [tokenVal, s.slice(i)];
239
- }
240
- }
241
- {
242
- const prefix = JSON.stringify(s.slice(0, tokenStr.length));
243
- console.error(`unknown token starting with ${prefix}:`, { s });
244
- throw e;
245
- }
246
- }
247
- }
248
- });
4
+ var parse = {};
5
+
6
+ var hasRequiredParse;
7
+
8
+ function requireParse () {
9
+ if (hasRequiredParse) return parse;
10
+ hasRequiredParse = 1;
11
+ (function (exports) {
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.parse = void 0;
14
+ function parse(s) {
15
+ if (s === void 0) {
16
+ return void 0;
17
+ }
18
+ if (s === null) {
19
+ return null;
20
+ }
21
+ if (s === "") {
22
+ return "";
23
+ }
24
+ s = s.replace(/\\+$/, (match) => match.length % 2 === 0 ? match : match.slice(0, -1));
25
+ try {
26
+ return JSON.parse(s);
27
+ } catch (e) {
28
+ const [data, reminding] = s.trimLeft()[0] === ":" ? parseAny(s, e) : parseAny(s, e, parseStringWithoutQuote);
29
+ parse.lastParseReminding = reminding;
30
+ if (parse.onExtraToken && reminding.length > 0) {
31
+ const trimmedReminding = reminding.trimRight();
32
+ parse.lastParseReminding = trimmedReminding;
33
+ if (trimmedReminding.length > 0) {
34
+ parse.onExtraToken(s, data, trimmedReminding);
35
+ }
36
+ }
37
+ return data;
38
+ }
39
+ }
40
+ exports.parse = parse;
41
+ (function(parse2) {
42
+ parse2.onExtraToken = (text, data, reminding) => {
43
+ console.error("parsed json with extra tokens:", {
44
+ text,
45
+ data,
46
+ reminding
47
+ });
48
+ };
49
+ })(parse = exports.parse || (exports.parse = {}));
50
+ function parseAny(s, e, fallback) {
51
+ const parser = parsers[s[0]] || fallback;
52
+ if (!parser) {
53
+ console.error(`no parser registered for ${JSON.stringify(s[0])}:`, { s });
54
+ throw e;
55
+ }
56
+ return parser(s, e);
57
+ }
58
+ function parseStringCasual(s, e, delimiters) {
59
+ if (s[0] === '"') {
60
+ return parseString(s);
61
+ }
62
+ if (s[0] === "'") {
63
+ return parseSingleQuoteString(s);
64
+ }
65
+ return parseStringWithoutQuote(s, e, delimiters);
66
+ }
67
+ const parsers = {};
68
+ function skipSpace(s) {
69
+ return s.trimLeft();
70
+ }
71
+ parsers[" "] = parseSpace;
72
+ parsers["\r"] = parseSpace;
73
+ parsers["\n"] = parseSpace;
74
+ parsers[" "] = parseSpace;
75
+ function parseSpace(s, e) {
76
+ s = skipSpace(s);
77
+ return parseAny(s, e);
78
+ }
79
+ parsers["["] = parseArray;
80
+ function parseArray(s, e) {
81
+ s = s.substr(1);
82
+ const acc = [];
83
+ s = skipSpace(s);
84
+ for (; s.length > 0; ) {
85
+ if (s[0] === "]") {
86
+ s = s.substr(1);
87
+ break;
88
+ }
89
+ const res = parseAny(s, e, (s2, e2) => parseStringWithoutQuote(s2, e2, [",", "]"]));
90
+ acc.push(res[0]);
91
+ s = res[1];
92
+ s = skipSpace(s);
93
+ if (s[0] === ",") {
94
+ s = s.substring(1);
95
+ s = skipSpace(s);
96
+ }
97
+ }
98
+ return [acc, s];
99
+ }
100
+ for (const c of "0123456789.-".slice()) {
101
+ parsers[c] = parseNumber;
102
+ }
103
+ function parseNumber(s) {
104
+ for (let i = 0; i < s.length; i++) {
105
+ const c = s[i];
106
+ if (parsers[c] === parseNumber) {
107
+ continue;
108
+ }
109
+ const num = s.substring(0, i);
110
+ s = s.substring(i);
111
+ return [numToStr(num), s];
112
+ }
113
+ return [numToStr(s), ""];
114
+ }
115
+ function numToStr(s) {
116
+ if (s === "-") {
117
+ return -0;
118
+ }
119
+ const num = +s;
120
+ if (Number.isNaN(num)) {
121
+ return s;
122
+ }
123
+ return num;
124
+ }
125
+ parsers['"'] = parseString;
126
+ function parseString(s) {
127
+ for (let i = 1; i < s.length; i++) {
128
+ const c = s[i];
129
+ if (c === "\\") {
130
+ i++;
131
+ continue;
132
+ }
133
+ if (c === '"') {
134
+ const str = fixEscapedCharacters(s.substring(0, i + 1));
135
+ s = s.substring(i + 1);
136
+ return [JSON.parse(str), s];
137
+ }
138
+ }
139
+ return [JSON.parse(fixEscapedCharacters(s) + '"'), ""];
140
+ }
141
+ function fixEscapedCharacters(s) {
142
+ return s.replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
143
+ }
144
+ parsers["'"] = parseSingleQuoteString;
145
+ function parseSingleQuoteString(s) {
146
+ for (let i = 1; i < s.length; i++) {
147
+ const c = s[i];
148
+ if (c === "\\") {
149
+ i++;
150
+ continue;
151
+ }
152
+ if (c === "'") {
153
+ const str = fixEscapedCharacters(s.substring(0, i + 1));
154
+ s = s.substring(i + 1);
155
+ return [JSON.parse('"' + str.slice(1, -1) + '"'), s];
156
+ }
157
+ }
158
+ return [JSON.parse('"' + fixEscapedCharacters(s.slice(1)) + '"'), ""];
159
+ }
160
+ function parseStringWithoutQuote(s, e, delimiters = [" "]) {
161
+ const index = Math.min(...delimiters.map((delimiter) => {
162
+ const index2 = s.indexOf(delimiter);
163
+ return index2 === -1 ? s.length : index2;
164
+ }));
165
+ const value = s.substring(0, index).trim();
166
+ const rest = s.substring(index);
167
+ return [value, rest];
168
+ }
169
+ parsers["{"] = parseObject;
170
+ function parseObject(s, e) {
171
+ s = s.substr(1);
172
+ const acc = {};
173
+ s = skipSpace(s);
174
+ for (; s.length > 0; ) {
175
+ if (s[0] === "}") {
176
+ s = s.substr(1);
177
+ break;
178
+ }
179
+ const keyRes = parseStringCasual(s, e, [":", "}"]);
180
+ const key = keyRes[0];
181
+ s = keyRes[1];
182
+ s = skipSpace(s);
183
+ if (s[0] !== ":") {
184
+ acc[key] = void 0;
185
+ break;
186
+ }
187
+ s = s.substr(1);
188
+ s = skipSpace(s);
189
+ if (s.length === 0) {
190
+ acc[key] = void 0;
191
+ break;
192
+ }
193
+ const valueRes = parseAny(s, e);
194
+ acc[key] = valueRes[0];
195
+ s = valueRes[1];
196
+ s = skipSpace(s);
197
+ if (s[0] === ",") {
198
+ s = s.substr(1);
199
+ s = skipSpace(s);
200
+ }
201
+ }
202
+ return [acc, s];
203
+ }
204
+ parsers["t"] = parseTrue;
205
+ function parseTrue(s, e) {
206
+ return parseToken(s, `true`, true, e);
207
+ }
208
+ parsers["f"] = parseFalse;
209
+ function parseFalse(s, e) {
210
+ return parseToken(s, `false`, false, e);
211
+ }
212
+ parsers["n"] = parseNull;
213
+ function parseNull(s, e) {
214
+ return parseToken(s, `null`, null, e);
215
+ }
216
+ function parseToken(s, tokenStr, tokenVal, e) {
217
+ for (let i = tokenStr.length; i >= 1; i--) {
218
+ if (s.startsWith(tokenStr.slice(0, i))) {
219
+ return [tokenVal, s.slice(i)];
220
+ }
221
+ }
222
+ {
223
+ const prefix = JSON.stringify(s.slice(0, tokenStr.length));
224
+ console.error(`unknown token starting with ${prefix}:`, { s });
225
+ throw e;
226
+ }
227
+ }
228
+ } (parse));
229
+ return parse;
230
+ }
249
231
 
250
- // src/index.ts
251
- var import_best_effort_json_parser = __toESM(require_parse(), 1);
252
- import { streamText } from "@xsai/stream-text";
253
- import { toJsonSchema } from "xsschema";
254
- var wrap = (schema) => {
232
+ var parseExports = requireParse();
233
+
234
+ const wrap = (schema) => {
255
235
  return {
256
236
  properties: {
257
237
  elements: {
@@ -292,14 +272,14 @@ async function streamObject(options) {
292
272
  let partialData = "";
293
273
  elementStream = rawElementStream.pipeThrough(new TransformStream({
294
274
  flush: (controller) => {
295
- const data = (0, import_best_effort_json_parser.parse)(partialData);
275
+ const data = parseExports.parse(partialData);
296
276
  controller.enqueue(data.elements.at(-1));
297
277
  options.onFinish?.({ object: data.elements });
298
278
  },
299
279
  transform: (chunk, controller) => {
300
280
  partialData += chunk;
301
281
  try {
302
- const data = (0, import_best_effort_json_parser.parse)(partialData);
282
+ const data = parseExports.parse(partialData);
303
283
  if (Array.isArray(Object.getOwnPropertyDescriptor(data, "elements")?.value) && data.elements.length > index + 1) {
304
284
  controller.enqueue(data.elements[index++]);
305
285
  }
@@ -316,7 +296,7 @@ async function streamObject(options) {
316
296
  transform: (chunk, controller) => {
317
297
  partialObjectData += chunk;
318
298
  try {
319
- const data = (0, import_best_effort_json_parser.parse)(partialObjectData);
299
+ const data = parseExports.parse(partialObjectData);
320
300
  if (JSON.stringify(partialObjectSnapshot) !== JSON.stringify(data)) {
321
301
  partialObjectSnapshot = data;
322
302
  controller.enqueue(data);
@@ -335,6 +315,5 @@ async function streamObject(options) {
335
315
  };
336
316
  });
337
317
  }
338
- export {
339
- streamObject
340
- };
318
+
319
+ export { streamObject };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xsai/stream-object",
3
3
  "type": "module",
4
- "version": "0.2.0-beta.1",
4
+ "version": "0.2.0-beta.3",
5
5
  "description": "extra-small AI SDK for Browser, Node.js, Deno, Bun or Edge Runtime.",
6
6
  "author": "Moeru AI",
7
7
  "license": "MIT",
@@ -35,11 +35,11 @@
35
35
  "devDependencies": {
36
36
  "@valibot/to-json-schema": "^1.0.0",
37
37
  "best-effort-json-parser": "^1.1.3",
38
- "type-fest": "^4.35.0",
38
+ "type-fest": "^4.39.0",
39
39
  "valibot": "^1.0.0"
40
40
  },
41
41
  "scripts": {
42
- "build": "tsup",
42
+ "build": "pkgroll",
43
43
  "test": "vitest run",
44
44
  "test:watch": "vitest"
45
45
  },