@xsai/stream-object 0.1.3 → 0.2.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +679 -1
- package/dist/index.js +238 -259
- package/package.json +5 -5
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,685 @@
|
|
|
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
|
+
Extract all required keys from the given type.
|
|
27
|
+
|
|
28
|
+
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...
|
|
29
|
+
|
|
30
|
+
@example
|
|
31
|
+
```
|
|
32
|
+
import type {RequiredKeysOf} from 'type-fest';
|
|
33
|
+
|
|
34
|
+
declare function createValidation<Entity extends object, Key extends RequiredKeysOf<Entity> = RequiredKeysOf<Entity>>(field: Key, validator: (value: Entity[Key]) => boolean): ValidatorFn;
|
|
35
|
+
|
|
36
|
+
interface User {
|
|
37
|
+
name: string;
|
|
38
|
+
surname: string;
|
|
39
|
+
|
|
40
|
+
luckyNumber?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const validator1 = createValidation<User>('name', value => value.length < 25);
|
|
44
|
+
const validator2 = createValidation<User>('surname', value => value.length < 25);
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
@category Utilities
|
|
48
|
+
*/
|
|
49
|
+
type RequiredKeysOf<BaseType extends object> = Exclude<{
|
|
50
|
+
[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
|
|
51
|
+
? Key
|
|
52
|
+
: never
|
|
53
|
+
}[keyof BaseType], undefined>;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
Returns a boolean for whether the given type is `never`.
|
|
57
|
+
|
|
58
|
+
@link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
|
|
59
|
+
@link https://stackoverflow.com/a/53984913/10292952
|
|
60
|
+
@link https://www.zhenghao.io/posts/ts-never
|
|
61
|
+
|
|
62
|
+
Useful in type utilities, such as checking if something does not occur.
|
|
63
|
+
|
|
64
|
+
@example
|
|
65
|
+
```
|
|
66
|
+
import type {IsNever, And} from 'type-fest';
|
|
67
|
+
|
|
68
|
+
// https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts
|
|
69
|
+
type AreStringsEqual<A extends string, B extends string> =
|
|
70
|
+
And<
|
|
71
|
+
IsNever<Exclude<A, B>> extends true ? true : false,
|
|
72
|
+
IsNever<Exclude<B, A>> extends true ? true : false
|
|
73
|
+
>;
|
|
74
|
+
|
|
75
|
+
type EndIfEqual<I extends string, O extends string> =
|
|
76
|
+
AreStringsEqual<I, O> extends true
|
|
77
|
+
? never
|
|
78
|
+
: void;
|
|
79
|
+
|
|
80
|
+
function endIfEqual<I extends string, O extends string>(input: I, output: O): EndIfEqual<I, O> {
|
|
81
|
+
if (input === output) {
|
|
82
|
+
process.exit(0);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
endIfEqual('abc', 'abc');
|
|
87
|
+
//=> never
|
|
88
|
+
|
|
89
|
+
endIfEqual('abc', '123');
|
|
90
|
+
//=> void
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
@category Type Guard
|
|
94
|
+
@category Utilities
|
|
95
|
+
*/
|
|
96
|
+
type IsNever<T> = [T] extends [never] ? true : false;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
An if-else-like type that resolves depending on whether the given type is `never`.
|
|
100
|
+
|
|
101
|
+
@see {@link IsNever}
|
|
102
|
+
|
|
103
|
+
@example
|
|
104
|
+
```
|
|
105
|
+
import type {IfNever} from 'type-fest';
|
|
106
|
+
|
|
107
|
+
type ShouldBeTrue = IfNever<never>;
|
|
108
|
+
//=> true
|
|
109
|
+
|
|
110
|
+
type ShouldBeBar = IfNever<'not never', 'foo', 'bar'>;
|
|
111
|
+
//=> 'bar'
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
@category Type Guard
|
|
115
|
+
@category Utilities
|
|
116
|
+
*/
|
|
117
|
+
type IfNever<T, TypeIfNever = true, TypeIfNotNever = false> = (
|
|
118
|
+
IsNever<T> extends true ? TypeIfNever : TypeIfNotNever
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
// Can eventually be replaced with the built-in once this library supports
|
|
122
|
+
// TS5.4+ only. Tracked in https://github.com/sindresorhus/type-fest/issues/848
|
|
123
|
+
type NoInfer<T> = T extends infer U ? U : never;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
Returns a boolean for whether the given type is `any`.
|
|
127
|
+
|
|
128
|
+
@link https://stackoverflow.com/a/49928360/1490091
|
|
129
|
+
|
|
130
|
+
Useful in type utilities, such as disallowing `any`s to be passed to a function.
|
|
131
|
+
|
|
132
|
+
@example
|
|
133
|
+
```
|
|
134
|
+
import type {IsAny} from 'type-fest';
|
|
135
|
+
|
|
136
|
+
const typedObject = {a: 1, b: 2} as const;
|
|
137
|
+
const anyObject: any = {a: 1, b: 2};
|
|
138
|
+
|
|
139
|
+
function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(obj: O, key: K) {
|
|
140
|
+
return obj[key];
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const typedA = get(typedObject, 'a');
|
|
144
|
+
//=> 1
|
|
145
|
+
|
|
146
|
+
const anyA = get(anyObject, 'a');
|
|
147
|
+
//=> any
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
@category Type Guard
|
|
151
|
+
@category Utilities
|
|
152
|
+
*/
|
|
153
|
+
type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
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.
|
|
157
|
+
|
|
158
|
+
@example
|
|
159
|
+
```
|
|
160
|
+
import type {Simplify} from 'type-fest';
|
|
161
|
+
|
|
162
|
+
type PositionProps = {
|
|
163
|
+
top: number;
|
|
164
|
+
left: number;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
type SizeProps = {
|
|
168
|
+
width: number;
|
|
169
|
+
height: number;
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// In your editor, hovering over `Props` will show a flattened object with all the properties.
|
|
173
|
+
type Props = Simplify<PositionProps & SizeProps>;
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
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.
|
|
177
|
+
|
|
178
|
+
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`.
|
|
179
|
+
|
|
180
|
+
@example
|
|
181
|
+
```
|
|
182
|
+
import type {Simplify} from 'type-fest';
|
|
183
|
+
|
|
184
|
+
interface SomeInterface {
|
|
185
|
+
foo: number;
|
|
186
|
+
bar?: string;
|
|
187
|
+
baz: number | undefined;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
type SomeType = {
|
|
191
|
+
foo: number;
|
|
192
|
+
bar?: string;
|
|
193
|
+
baz: number | undefined;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const literal = {foo: 123, bar: 'hello', baz: 456};
|
|
197
|
+
const someType: SomeType = literal;
|
|
198
|
+
const someInterface: SomeInterface = literal;
|
|
199
|
+
|
|
200
|
+
function fn(object: Record<string, unknown>): void {}
|
|
201
|
+
|
|
202
|
+
fn(literal); // Good: literal object type is sealed
|
|
203
|
+
fn(someType); // Good: type is sealed
|
|
204
|
+
fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
|
|
205
|
+
fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
@link https://github.com/microsoft/TypeScript/issues/15300
|
|
209
|
+
@see SimplifyDeep
|
|
210
|
+
@category Object
|
|
211
|
+
*/
|
|
212
|
+
type Simplify<T> = {[KeyType in keyof T]: T[KeyType]} & {};
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
Omit any index signatures from the given object type, leaving only explicitly defined properties.
|
|
216
|
+
|
|
217
|
+
This is the counterpart of `PickIndexSignature`.
|
|
218
|
+
|
|
219
|
+
Use-cases:
|
|
220
|
+
- Remove overly permissive signatures from third-party types.
|
|
221
|
+
|
|
222
|
+
This type was taken from this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747).
|
|
223
|
+
|
|
224
|
+
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>`.
|
|
225
|
+
|
|
226
|
+
(The actual value type, `unknown`, is irrelevant and could be any type. Only the key type matters.)
|
|
227
|
+
|
|
228
|
+
```
|
|
229
|
+
const indexed: Record<string, unknown> = {}; // Allowed
|
|
230
|
+
|
|
231
|
+
const keyed: Record<'foo', unknown> = {}; // Error
|
|
232
|
+
// => TS2739: Type '{}' is missing the following properties from type 'Record<"foo" | "bar", unknown>': foo, bar
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
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:
|
|
236
|
+
|
|
237
|
+
```
|
|
238
|
+
type Indexed = {} extends Record<string, unknown>
|
|
239
|
+
? '✅ `{}` is assignable to `Record<string, unknown>`'
|
|
240
|
+
: '❌ `{}` is NOT assignable to `Record<string, unknown>`';
|
|
241
|
+
// => '✅ `{}` is assignable to `Record<string, unknown>`'
|
|
242
|
+
|
|
243
|
+
type Keyed = {} extends Record<'foo' | 'bar', unknown>
|
|
244
|
+
? "✅ `{}` is assignable to `Record<'foo' | 'bar', unknown>`"
|
|
245
|
+
: "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`";
|
|
246
|
+
// => "❌ `{}` is NOT assignable to `Record<'foo' | 'bar', unknown>`"
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
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`...
|
|
250
|
+
|
|
251
|
+
```
|
|
252
|
+
import type {OmitIndexSignature} from 'type-fest';
|
|
253
|
+
|
|
254
|
+
type OmitIndexSignature<ObjectType> = {
|
|
255
|
+
[KeyType in keyof ObjectType // Map each key of `ObjectType`...
|
|
256
|
+
]: ObjectType[KeyType]; // ...to its original value, i.e. `OmitIndexSignature<Foo> == Foo`.
|
|
257
|
+
};
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
...whether an empty object (`{}`) would be assignable to an object with that `KeyType` (`Record<KeyType, unknown>`)...
|
|
261
|
+
|
|
262
|
+
```
|
|
263
|
+
import type {OmitIndexSignature} from 'type-fest';
|
|
264
|
+
|
|
265
|
+
type OmitIndexSignature<ObjectType> = {
|
|
266
|
+
[KeyType in keyof ObjectType
|
|
267
|
+
// Is `{}` assignable to `Record<KeyType, unknown>`?
|
|
268
|
+
as {} extends Record<KeyType, unknown>
|
|
269
|
+
? ... // ✅ `{}` is assignable to `Record<KeyType, unknown>`
|
|
270
|
+
: ... // ❌ `{}` is NOT assignable to `Record<KeyType, unknown>`
|
|
271
|
+
]: ObjectType[KeyType];
|
|
272
|
+
};
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
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.
|
|
276
|
+
|
|
277
|
+
@example
|
|
278
|
+
```
|
|
279
|
+
import type {OmitIndexSignature} from 'type-fest';
|
|
280
|
+
|
|
281
|
+
interface Example {
|
|
282
|
+
// These index signatures will be removed.
|
|
283
|
+
[x: string]: any
|
|
284
|
+
[x: number]: any
|
|
285
|
+
[x: symbol]: any
|
|
286
|
+
[x: `head-${string}`]: string
|
|
287
|
+
[x: `${string}-tail`]: string
|
|
288
|
+
[x: `head-${string}-tail`]: string
|
|
289
|
+
[x: `${bigint}`]: string
|
|
290
|
+
[x: `embedded-${number}`]: string
|
|
291
|
+
|
|
292
|
+
// These explicitly defined keys will remain.
|
|
293
|
+
foo: 'bar';
|
|
294
|
+
qux?: 'baz';
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
|
|
298
|
+
// => { foo: 'bar'; qux?: 'baz' | undefined; }
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
@see PickIndexSignature
|
|
302
|
+
@category Object
|
|
303
|
+
*/
|
|
304
|
+
type OmitIndexSignature<ObjectType> = {
|
|
305
|
+
[KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
|
|
306
|
+
? never
|
|
307
|
+
: KeyType]: ObjectType[KeyType];
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
Pick only index signatures from the given object type, leaving out all explicitly defined properties.
|
|
312
|
+
|
|
313
|
+
This is the counterpart of `OmitIndexSignature`.
|
|
314
|
+
|
|
315
|
+
@example
|
|
316
|
+
```
|
|
317
|
+
import type {PickIndexSignature} from 'type-fest';
|
|
318
|
+
|
|
319
|
+
declare const symbolKey: unique symbol;
|
|
320
|
+
|
|
321
|
+
type Example = {
|
|
322
|
+
// These index signatures will remain.
|
|
323
|
+
[x: string]: unknown;
|
|
324
|
+
[x: number]: unknown;
|
|
325
|
+
[x: symbol]: unknown;
|
|
326
|
+
[x: `head-${string}`]: string;
|
|
327
|
+
[x: `${string}-tail`]: string;
|
|
328
|
+
[x: `head-${string}-tail`]: string;
|
|
329
|
+
[x: `${bigint}`]: string;
|
|
330
|
+
[x: `embedded-${number}`]: string;
|
|
331
|
+
|
|
332
|
+
// These explicitly defined keys will be removed.
|
|
333
|
+
['kebab-case-key']: string;
|
|
334
|
+
[symbolKey]: string;
|
|
335
|
+
foo: 'bar';
|
|
336
|
+
qux?: 'baz';
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
type ExampleIndexSignature = PickIndexSignature<Example>;
|
|
340
|
+
// {
|
|
341
|
+
// [x: string]: unknown;
|
|
342
|
+
// [x: number]: unknown;
|
|
343
|
+
// [x: symbol]: unknown;
|
|
344
|
+
// [x: `head-${string}`]: string;
|
|
345
|
+
// [x: `${string}-tail`]: string;
|
|
346
|
+
// [x: `head-${string}-tail`]: string;
|
|
347
|
+
// [x: `${bigint}`]: string;
|
|
348
|
+
// [x: `embedded-${number}`]: string;
|
|
349
|
+
// }
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
@see OmitIndexSignature
|
|
353
|
+
@category Object
|
|
354
|
+
*/
|
|
355
|
+
type PickIndexSignature<ObjectType> = {
|
|
356
|
+
[KeyType in keyof ObjectType as {} extends Record<KeyType, unknown>
|
|
357
|
+
? KeyType
|
|
358
|
+
: never]: ObjectType[KeyType];
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
// Merges two objects without worrying about index signatures.
|
|
362
|
+
type SimpleMerge<Destination, Source> = {
|
|
363
|
+
[Key in keyof Destination as Key extends keyof Source ? never : Key]: Destination[Key];
|
|
364
|
+
} & Source;
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
Merge two types into a new type. Keys of the second type overrides keys of the first type.
|
|
368
|
+
|
|
369
|
+
@example
|
|
370
|
+
```
|
|
371
|
+
import type {Merge} from 'type-fest';
|
|
372
|
+
|
|
373
|
+
interface Foo {
|
|
374
|
+
[x: string]: unknown;
|
|
375
|
+
[x: number]: unknown;
|
|
376
|
+
foo: string;
|
|
377
|
+
bar: symbol;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
type Bar = {
|
|
381
|
+
[x: number]: number;
|
|
382
|
+
[x: symbol]: unknown;
|
|
383
|
+
bar: Date;
|
|
384
|
+
baz: boolean;
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
export type FooBar = Merge<Foo, Bar>;
|
|
388
|
+
// => {
|
|
389
|
+
// [x: string]: unknown;
|
|
390
|
+
// [x: number]: number;
|
|
391
|
+
// [x: symbol]: unknown;
|
|
392
|
+
// foo: string;
|
|
393
|
+
// bar: Date;
|
|
394
|
+
// baz: boolean;
|
|
395
|
+
// }
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
@category Object
|
|
399
|
+
*/
|
|
400
|
+
type Merge<Destination, Source> =
|
|
401
|
+
Simplify<
|
|
402
|
+
SimpleMerge<PickIndexSignature<Destination>, PickIndexSignature<Source>>
|
|
403
|
+
& SimpleMerge<OmitIndexSignature<Destination>, OmitIndexSignature<Source>>
|
|
404
|
+
>;
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
An if-else-like type that resolves depending on whether the given type is `any`.
|
|
408
|
+
|
|
409
|
+
@see {@link IsAny}
|
|
410
|
+
|
|
411
|
+
@example
|
|
412
|
+
```
|
|
413
|
+
import type {IfAny} from 'type-fest';
|
|
414
|
+
|
|
415
|
+
type ShouldBeTrue = IfAny<any>;
|
|
416
|
+
//=> true
|
|
417
|
+
|
|
418
|
+
type ShouldBeBar = IfAny<'not any', 'foo', 'bar'>;
|
|
419
|
+
//=> 'bar'
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
@category Type Guard
|
|
423
|
+
@category Utilities
|
|
424
|
+
*/
|
|
425
|
+
type IfAny<T, TypeIfAny = true, TypeIfNotAny = false> = (
|
|
426
|
+
IsAny<T> extends true ? TypeIfAny : TypeIfNotAny
|
|
427
|
+
);
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
Extract all optional keys from the given type.
|
|
431
|
+
|
|
432
|
+
This is useful when you want to create a new type that contains different type values for the optional keys only.
|
|
433
|
+
|
|
434
|
+
@example
|
|
435
|
+
```
|
|
436
|
+
import type {OptionalKeysOf, Except} from 'type-fest';
|
|
437
|
+
|
|
438
|
+
interface User {
|
|
439
|
+
name: string;
|
|
440
|
+
surname: string;
|
|
441
|
+
|
|
442
|
+
luckyNumber?: number;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
const REMOVE_FIELD = Symbol('remove field symbol');
|
|
446
|
+
type UpdateOperation<Entity extends object> = Except<Partial<Entity>, OptionalKeysOf<Entity>> & {
|
|
447
|
+
[Key in OptionalKeysOf<Entity>]?: Entity[Key] | typeof REMOVE_FIELD;
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const update1: UpdateOperation<User> = {
|
|
451
|
+
name: 'Alice'
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
const update2: UpdateOperation<User> = {
|
|
455
|
+
name: 'Bob',
|
|
456
|
+
luckyNumber: REMOVE_FIELD
|
|
457
|
+
};
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
@category Utilities
|
|
461
|
+
*/
|
|
462
|
+
type OptionalKeysOf<BaseType extends object> = Exclude<{
|
|
463
|
+
[Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>
|
|
464
|
+
? never
|
|
465
|
+
: Key
|
|
466
|
+
}[keyof BaseType], undefined>;
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
Matches any primitive, `void`, `Date`, or `RegExp` value.
|
|
470
|
+
*/
|
|
471
|
+
type BuiltIns = Primitive | void | Date | RegExp;
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
Merges user specified options with default options.
|
|
475
|
+
|
|
476
|
+
@example
|
|
477
|
+
```
|
|
478
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
479
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
|
|
480
|
+
type SpecifiedOptions = {leavesOnly: true};
|
|
481
|
+
|
|
482
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
483
|
+
//=> {maxRecursionDepth: 10; leavesOnly: true}
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
@example
|
|
487
|
+
```
|
|
488
|
+
// Complains if default values are not provided for optional options
|
|
489
|
+
|
|
490
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
491
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10};
|
|
492
|
+
type SpecifiedOptions = {};
|
|
493
|
+
|
|
494
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
495
|
+
// ~~~~~~~~~~~~~~~~~~~
|
|
496
|
+
// Property 'leavesOnly' is missing in type 'DefaultPathsOptions' but required in type '{ maxRecursionDepth: number; leavesOnly: boolean; }'.
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
@example
|
|
500
|
+
```
|
|
501
|
+
// Complains if an option's default type does not conform to the expected type
|
|
502
|
+
|
|
503
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
504
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: 'no'};
|
|
505
|
+
type SpecifiedOptions = {};
|
|
506
|
+
|
|
507
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
508
|
+
// ~~~~~~~~~~~~~~~~~~~
|
|
509
|
+
// Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
@example
|
|
513
|
+
```
|
|
514
|
+
// Complains if an option's specified type does not conform to the expected type
|
|
515
|
+
|
|
516
|
+
type PathsOptions = {maxRecursionDepth?: number; leavesOnly?: boolean};
|
|
517
|
+
type DefaultPathsOptions = {maxRecursionDepth: 10; leavesOnly: false};
|
|
518
|
+
type SpecifiedOptions = {leavesOnly: 'yes'};
|
|
519
|
+
|
|
520
|
+
type Result = ApplyDefaultOptions<PathsOptions, DefaultPathsOptions, SpecifiedOptions>;
|
|
521
|
+
// ~~~~~~~~~~~~~~~~
|
|
522
|
+
// Types of property 'leavesOnly' are incompatible. Type 'string' is not assignable to type 'boolean'.
|
|
523
|
+
```
|
|
524
|
+
*/
|
|
525
|
+
type ApplyDefaultOptions<
|
|
526
|
+
Options extends object,
|
|
527
|
+
Defaults extends Simplify<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>,
|
|
528
|
+
SpecifiedOptions extends Options,
|
|
529
|
+
> =
|
|
530
|
+
IfAny<SpecifiedOptions, Defaults,
|
|
531
|
+
IfNever<SpecifiedOptions, Defaults,
|
|
532
|
+
Simplify<Merge<Defaults, {
|
|
533
|
+
[Key in keyof SpecifiedOptions
|
|
534
|
+
as Key extends OptionalKeysOf<Options> ? undefined extends SpecifiedOptions[Key] ? never : Key : Key
|
|
535
|
+
]: SpecifiedOptions[Key]
|
|
536
|
+
}> & Required<Options>> // `& Required<Options>` ensures that `ApplyDefaultOptions<SomeOption, ...>` is always assignable to `Required<SomeOption>`
|
|
537
|
+
>>;
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
@see {@link PartialDeep}
|
|
541
|
+
*/
|
|
542
|
+
type PartialDeepOptions = {
|
|
543
|
+
/**
|
|
544
|
+
Whether to affect the individual elements of arrays and tuples.
|
|
545
|
+
|
|
546
|
+
@default false
|
|
547
|
+
*/
|
|
548
|
+
readonly recurseIntoArrays?: boolean;
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
Allows `undefined` values in non-tuple arrays.
|
|
552
|
+
|
|
553
|
+
- When set to `true`, elements of non-tuple arrays can be `undefined`.
|
|
554
|
+
- When set to `false`, only explicitly defined elements are allowed in non-tuple arrays, ensuring stricter type checking.
|
|
555
|
+
|
|
556
|
+
@default true
|
|
557
|
+
|
|
558
|
+
@example
|
|
559
|
+
You can prevent `undefined` values in non-tuple arrays by passing `{recurseIntoArrays: true; allowUndefinedInNonTupleArrays: false}` as the second type argument:
|
|
560
|
+
|
|
561
|
+
```
|
|
562
|
+
import type {PartialDeep} from 'type-fest';
|
|
563
|
+
|
|
564
|
+
type Settings = {
|
|
565
|
+
languages: string[];
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
declare const partialSettings: PartialDeep<Settings, {recurseIntoArrays: true; allowUndefinedInNonTupleArrays: false}>;
|
|
569
|
+
|
|
570
|
+
partialSettings.languages = [undefined]; // Error
|
|
571
|
+
partialSettings.languages = []; // Ok
|
|
572
|
+
```
|
|
573
|
+
*/
|
|
574
|
+
readonly allowUndefinedInNonTupleArrays?: boolean;
|
|
575
|
+
};
|
|
576
|
+
|
|
577
|
+
type DefaultPartialDeepOptions = {
|
|
578
|
+
recurseIntoArrays: false;
|
|
579
|
+
allowUndefinedInNonTupleArrays: true;
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
Create a type from another type with all keys and nested keys set to optional.
|
|
584
|
+
|
|
585
|
+
Use-cases:
|
|
586
|
+
- Merging a default settings/config object with another object, the second object would be a deep partial of the default object.
|
|
587
|
+
- Mocking and testing complex entities, where populating an entire object with its keys would be redundant in terms of the mock or test.
|
|
588
|
+
|
|
589
|
+
@example
|
|
590
|
+
```
|
|
591
|
+
import type {PartialDeep} from 'type-fest';
|
|
592
|
+
|
|
593
|
+
const settings: Settings = {
|
|
594
|
+
textEditor: {
|
|
595
|
+
fontSize: 14,
|
|
596
|
+
fontColor: '#000000',
|
|
597
|
+
fontWeight: 400
|
|
598
|
+
},
|
|
599
|
+
autocomplete: false,
|
|
600
|
+
autosave: true
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
const applySavedSettings = (savedSettings: PartialDeep<Settings>) => {
|
|
604
|
+
return {...settings, ...savedSettings};
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
settings = applySavedSettings({textEditor: {fontWeight: 500}});
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
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:
|
|
611
|
+
|
|
612
|
+
```
|
|
613
|
+
import type {PartialDeep} from 'type-fest';
|
|
614
|
+
|
|
615
|
+
type Settings = {
|
|
616
|
+
languages: string[];
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const partialSettings: PartialDeep<Settings, {recurseIntoArrays: true}> = {
|
|
620
|
+
languages: [undefined]
|
|
621
|
+
};
|
|
622
|
+
```
|
|
623
|
+
|
|
624
|
+
@see {@link PartialDeepOptions}
|
|
625
|
+
|
|
626
|
+
@category Object
|
|
627
|
+
@category Array
|
|
628
|
+
@category Set
|
|
629
|
+
@category Map
|
|
630
|
+
*/
|
|
631
|
+
type PartialDeep<T, Options extends PartialDeepOptions = {}> =
|
|
632
|
+
_PartialDeep<T, ApplyDefaultOptions<PartialDeepOptions, DefaultPartialDeepOptions, Options>>;
|
|
633
|
+
|
|
634
|
+
type _PartialDeep<T, Options extends Required<PartialDeepOptions>> = T extends BuiltIns | (((...arguments_: any[]) => unknown)) | (new (...arguments_: any[]) => unknown)
|
|
635
|
+
? T
|
|
636
|
+
: T extends Map<infer KeyType, infer ValueType>
|
|
637
|
+
? PartialMapDeep<KeyType, ValueType, Options>
|
|
638
|
+
: T extends Set<infer ItemType>
|
|
639
|
+
? PartialSetDeep<ItemType, Options>
|
|
640
|
+
: T extends ReadonlyMap<infer KeyType, infer ValueType>
|
|
641
|
+
? PartialReadonlyMapDeep<KeyType, ValueType, Options>
|
|
642
|
+
: T extends ReadonlySet<infer ItemType>
|
|
643
|
+
? PartialReadonlySetDeep<ItemType, Options>
|
|
644
|
+
: T extends object
|
|
645
|
+
? T extends ReadonlyArray<infer ItemType> // Test for arrays/tuples, per https://github.com/microsoft/TypeScript/issues/35156
|
|
646
|
+
? Options['recurseIntoArrays'] extends true
|
|
647
|
+
? ItemType[] extends T // Test for arrays (non-tuples) specifically
|
|
648
|
+
? readonly ItemType[] extends T // Differentiate readonly and mutable arrays
|
|
649
|
+
? ReadonlyArray<_PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
|
|
650
|
+
: Array<_PartialDeep<Options['allowUndefinedInNonTupleArrays'] extends false ? ItemType : ItemType | undefined, Options>>
|
|
651
|
+
: PartialObjectDeep<T, Options> // Tuples behave properly
|
|
652
|
+
: T // If they don't opt into array testing, just use the original type
|
|
653
|
+
: PartialObjectDeep<T, Options>
|
|
654
|
+
: unknown;
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`.
|
|
658
|
+
*/
|
|
659
|
+
type PartialMapDeep<KeyType, ValueType, Options extends Required<PartialDeepOptions>> = {} & Map<_PartialDeep<KeyType, Options>, _PartialDeep<ValueType, Options>>;
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`.
|
|
663
|
+
*/
|
|
664
|
+
type PartialSetDeep<T, Options extends Required<PartialDeepOptions>> = {} & Set<_PartialDeep<T, Options>>;
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`.
|
|
668
|
+
*/
|
|
669
|
+
type PartialReadonlyMapDeep<KeyType, ValueType, Options extends Required<PartialDeepOptions>> = {} & ReadonlyMap<_PartialDeep<KeyType, Options>, _PartialDeep<ValueType, Options>>;
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`.
|
|
673
|
+
*/
|
|
674
|
+
type PartialReadonlySetDeep<T, Options extends Required<PartialDeepOptions>> = {} & ReadonlySet<_PartialDeep<T, Options>>;
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`.
|
|
678
|
+
*/
|
|
679
|
+
type PartialObjectDeep<ObjectType extends object, Options extends Required<PartialDeepOptions>> = {
|
|
680
|
+
[KeyType in keyof ObjectType]?: _PartialDeep<ObjectType[KeyType], Options>
|
|
681
|
+
};
|
|
682
|
+
|
|
5
683
|
interface StreamObjectOnFinishResult<T extends Schema> {
|
|
6
684
|
object?: Infer<T>;
|
|
7
685
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,257 +1,237 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
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
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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: {
|
|
@@ -265,7 +245,7 @@ var wrap = (schema) => {
|
|
|
265
245
|
};
|
|
266
246
|
async function streamObject(options) {
|
|
267
247
|
const { schema: schemaValidator } = options;
|
|
268
|
-
let schema = await
|
|
248
|
+
let schema = await toJsonSchema(schemaValidator);
|
|
269
249
|
if (options.output === "array")
|
|
270
250
|
schema = wrap(schema);
|
|
271
251
|
return streamText({
|
|
@@ -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 =
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
339
|
-
|
|
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.
|
|
4
|
+
"version": "0.2.0-beta.2",
|
|
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",
|
|
@@ -33,13 +33,13 @@
|
|
|
33
33
|
"xsschema": ""
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
|
-
"@valibot/to-json-schema": "^1.0.0
|
|
36
|
+
"@valibot/to-json-schema": "^1.0.0",
|
|
37
37
|
"best-effort-json-parser": "^1.1.3",
|
|
38
|
-
"type-fest": "^4.
|
|
39
|
-
"valibot": "^1.0.0
|
|
38
|
+
"type-fest": "^4.38.0",
|
|
39
|
+
"valibot": "^1.0.0"
|
|
40
40
|
},
|
|
41
41
|
"scripts": {
|
|
42
|
-
"build": "
|
|
42
|
+
"build": "pkgroll",
|
|
43
43
|
"test": "vitest run",
|
|
44
44
|
"test:watch": "vitest"
|
|
45
45
|
},
|