modelfusion 0.130.1 → 0.131.1
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/CHANGELOG.md +64 -0
- package/README.md +22 -21
- package/core/api/postToApi.cjs +1 -1
- package/core/api/postToApi.js +1 -1
- package/core/schema/JsonSchemaProducer.d.ts +1 -1
- package/core/schema/Schema.d.ts +7 -7
- package/core/schema/TypeValidationError.cjs +5 -5
- package/core/schema/TypeValidationError.d.ts +4 -4
- package/core/schema/TypeValidationError.js +5 -5
- package/core/schema/UncheckedSchema.cjs +2 -2
- package/core/schema/UncheckedSchema.d.ts +5 -5
- package/core/schema/UncheckedSchema.js +2 -2
- package/core/schema/ZodSchema.cjs +5 -2
- package/core/schema/ZodSchema.d.ts +9 -9
- package/core/schema/ZodSchema.js +5 -2
- package/core/schema/parseJSON.cjs +6 -6
- package/core/schema/parseJSON.d.ts +3 -3
- package/core/schema/parseJSON.js +6 -6
- package/core/schema/validateTypes.cjs +13 -13
- package/core/schema/validateTypes.d.ts +9 -9
- package/core/schema/validateTypes.js +13 -13
- package/model-function/ModelCallEvent.d.ts +4 -4
- package/model-function/PromptTemplate.d.ts +2 -2
- package/model-function/{generate-structure/StructureFromTextGenerationModel.cjs → generate-object/ObjectFromTextGenerationModel.cjs} +8 -8
- package/model-function/{generate-structure/StructureFromTextGenerationModel.d.ts → generate-object/ObjectFromTextGenerationModel.d.ts} +6 -6
- package/model-function/{generate-structure/StructureFromTextGenerationModel.js → generate-object/ObjectFromTextGenerationModel.js} +6 -6
- package/model-function/{generate-structure/StructureFromTextPromptTemplate.d.ts → generate-object/ObjectFromTextPromptTemplate.d.ts} +4 -4
- package/model-function/{generate-structure/StructureFromTextStreamingModel.cjs → generate-object/ObjectFromTextStreamingModel.cjs} +10 -10
- package/model-function/generate-object/ObjectFromTextStreamingModel.d.ts +19 -0
- package/model-function/{generate-structure/StructureFromTextStreamingModel.js → generate-object/ObjectFromTextStreamingModel.js} +8 -8
- package/model-function/{generate-structure/StructureGenerationEvent.d.ts → generate-object/ObjectGenerationEvent.d.ts} +6 -6
- package/model-function/generate-object/ObjectGenerationModel.d.ts +24 -0
- package/model-function/{generate-structure/StructureParseError.cjs → generate-object/ObjectParseError.cjs} +5 -5
- package/model-function/{generate-structure/StructureParseError.d.ts → generate-object/ObjectParseError.d.ts} +1 -1
- package/model-function/{generate-structure/StructureParseError.js → generate-object/ObjectParseError.js} +3 -3
- package/model-function/generate-object/ObjectStream.cjs +57 -0
- package/model-function/generate-object/ObjectStream.d.ts +32 -0
- package/model-function/generate-object/ObjectStream.js +52 -0
- package/model-function/generate-object/ObjectStreamingEvent.d.ts +7 -0
- package/model-function/{generate-structure/StructureValidationError.cjs → generate-object/ObjectValidationError.cjs} +5 -5
- package/model-function/{generate-structure/StructureValidationError.d.ts → generate-object/ObjectValidationError.d.ts} +1 -1
- package/model-function/{generate-structure/StructureValidationError.js → generate-object/ObjectValidationError.js} +3 -3
- package/model-function/{generate-structure/generateStructure.cjs → generate-object/generateObject.cjs} +11 -12
- package/model-function/generate-object/generateObject.d.ts +56 -0
- package/model-function/{generate-structure/generateStructure.js → generate-object/generateObject.js} +9 -10
- package/model-function/{generate-structure → generate-object}/index.cjs +12 -11
- package/model-function/generate-object/index.d.ts +12 -0
- package/model-function/generate-object/index.js +12 -0
- package/model-function/{generate-structure/jsonStructurePrompt.cjs → generate-object/jsonObjectPrompt.cjs} +6 -6
- package/model-function/{generate-structure/jsonStructurePrompt.d.ts → generate-object/jsonObjectPrompt.d.ts} +6 -6
- package/model-function/{generate-structure/jsonStructurePrompt.js → generate-object/jsonObjectPrompt.js} +5 -5
- package/model-function/generate-object/streamObject.cjs +80 -0
- package/model-function/generate-object/streamObject.d.ts +57 -0
- package/model-function/generate-object/streamObject.js +76 -0
- package/model-function/generate-text/PromptTemplateTextGenerationModel.cjs +3 -3
- package/model-function/generate-text/PromptTemplateTextGenerationModel.d.ts +3 -3
- package/model-function/generate-text/PromptTemplateTextGenerationModel.js +3 -3
- package/model-function/generate-text/PromptTemplateTextStreamingModel.cjs +3 -3
- package/model-function/generate-text/PromptTemplateTextStreamingModel.d.ts +3 -3
- package/model-function/generate-text/PromptTemplateTextStreamingModel.js +3 -3
- package/model-function/generate-text/TextGenerationPromptTemplate.d.ts +1 -1
- package/model-function/index.cjs +1 -1
- package/model-function/index.d.ts +1 -1
- package/model-function/index.js +1 -1
- package/model-provider/cohere/CohereTextGenerationModel.cjs +1 -1
- package/model-provider/cohere/CohereTextGenerationModel.js +1 -1
- package/model-provider/elevenlabs/ElevenLabsSpeechModel.cjs +1 -1
- package/model-provider/elevenlabs/ElevenLabsSpeechModel.js +1 -1
- package/model-provider/huggingface/HuggingFaceTextGenerationModel.cjs +1 -1
- package/model-provider/huggingface/HuggingFaceTextGenerationModel.js +1 -1
- package/model-provider/llamacpp/LlamaCppBakLLaVA1PromptTemplate.cjs +1 -1
- package/model-provider/llamacpp/LlamaCppBakLLaVA1PromptTemplate.d.ts +1 -1
- package/model-provider/llamacpp/LlamaCppBakLLaVA1PromptTemplate.js +1 -1
- package/model-provider/llamacpp/LlamaCppCompletionModel.cjs +5 -5
- package/model-provider/llamacpp/LlamaCppCompletionModel.d.ts +3 -3
- package/model-provider/llamacpp/LlamaCppCompletionModel.js +5 -5
- package/model-provider/mistral/MistralChatModel.cjs +1 -1
- package/model-provider/mistral/MistralChatModel.js +1 -1
- package/model-provider/ollama/OllamaChatModel.cjs +7 -7
- package/model-provider/ollama/OllamaChatModel.d.ts +3 -3
- package/model-provider/ollama/OllamaChatModel.js +7 -7
- package/model-provider/ollama/OllamaCompletionModel.cjs +7 -7
- package/model-provider/ollama/OllamaCompletionModel.d.ts +3 -3
- package/model-provider/ollama/OllamaCompletionModel.js +7 -7
- package/model-provider/ollama/OllamaCompletionModel.test.cjs +8 -6
- package/model-provider/ollama/OllamaCompletionModel.test.js +8 -6
- package/model-provider/openai/AbstractOpenAIChatModel.cjs +1 -1
- package/model-provider/openai/AbstractOpenAIChatModel.js +1 -1
- package/model-provider/openai/AbstractOpenAICompletionModel.cjs +1 -1
- package/model-provider/openai/AbstractOpenAICompletionModel.js +1 -1
- package/model-provider/openai/{OpenAIChatFunctionCallStructureGenerationModel.cjs → OpenAIChatFunctionCallObjectGenerationModel.cjs} +12 -12
- package/model-provider/openai/{OpenAIChatFunctionCallStructureGenerationModel.d.ts → OpenAIChatFunctionCallObjectGenerationModel.d.ts} +10 -10
- package/model-provider/openai/{OpenAIChatFunctionCallStructureGenerationModel.js → OpenAIChatFunctionCallObjectGenerationModel.js} +10 -10
- package/model-provider/openai/OpenAIChatModel.cjs +7 -7
- package/model-provider/openai/OpenAIChatModel.d.ts +6 -6
- package/model-provider/openai/OpenAIChatModel.js +7 -7
- package/model-provider/openai/OpenAIChatModel.test.cjs +7 -5
- package/model-provider/openai/OpenAIChatModel.test.js +7 -5
- package/model-provider/openai-compatible/OpenAICompatibleChatModel.cjs +4 -4
- package/model-provider/openai-compatible/OpenAICompatibleChatModel.d.ts +3 -3
- package/model-provider/openai-compatible/OpenAICompatibleChatModel.js +4 -4
- package/model-provider/whispercpp/WhisperCppTranscriptionModel.cjs +3 -3
- package/model-provider/whispercpp/WhisperCppTranscriptionModel.js +3 -3
- package/package.json +3 -3
- package/tool/WebSearchTool.cjs +1 -1
- package/tool/WebSearchTool.js +1 -1
- package/tool/generate-tool-call/generateToolCall.cjs +1 -1
- package/tool/generate-tool-call/generateToolCall.js +1 -1
- package/tool/generate-tool-calls/generateToolCalls.cjs +1 -1
- package/tool/generate-tool-calls/generateToolCalls.js +1 -1
- package/{model-function/generate-structure → util}/fixJson.test.cjs +1 -1
- package/{model-function/generate-structure → util}/fixJson.test.js +1 -1
- package/util/isDeepEqualData.cjs +1 -1
- package/util/isDeepEqualData.d.ts +1 -1
- package/util/isDeepEqualData.js +1 -1
- package/util/streaming/parseEventSourceStreamAsAsyncIterable.cjs +1 -1
- package/util/streaming/parseEventSourceStreamAsAsyncIterable.js +1 -1
- package/vector-index/memory/MemoryVectorIndex.cjs +1 -1
- package/vector-index/memory/MemoryVectorIndex.js +1 -1
- package/model-function/generate-structure/StructureFromTextStreamingModel.d.ts +0 -19
- package/model-function/generate-structure/StructureGenerationModel.d.ts +0 -24
- package/model-function/generate-structure/StructureStreamingEvent.d.ts +0 -7
- package/model-function/generate-structure/generateStructure.d.ts +0 -56
- package/model-function/generate-structure/index.d.ts +0 -11
- package/model-function/generate-structure/index.js +0 -11
- package/model-function/generate-structure/streamStructure.cjs +0 -61
- package/model-function/generate-structure/streamStructure.d.ts +0 -67
- package/model-function/generate-structure/streamStructure.js +0 -57
- /package/model-function/{generate-structure/StructureFromTextPromptTemplate.cjs → generate-object/ObjectFromTextPromptTemplate.cjs} +0 -0
- /package/model-function/{generate-structure/StructureFromTextPromptTemplate.js → generate-object/ObjectFromTextPromptTemplate.js} +0 -0
- /package/model-function/{generate-structure/StructureGenerationEvent.cjs → generate-object/ObjectGenerationEvent.cjs} +0 -0
- /package/model-function/{generate-structure/StructureGenerationEvent.js → generate-object/ObjectGenerationEvent.js} +0 -0
- /package/model-function/{generate-structure/StructureGenerationModel.cjs → generate-object/ObjectGenerationModel.cjs} +0 -0
- /package/model-function/{generate-structure/StructureGenerationModel.js → generate-object/ObjectGenerationModel.js} +0 -0
- /package/model-function/{generate-structure/StructureStreamingEvent.cjs → generate-object/ObjectStreamingEvent.cjs} +0 -0
- /package/model-function/{generate-structure/StructureStreamingEvent.js → generate-object/ObjectStreamingEvent.js} +0 -0
- /package/{model-function/generate-structure → util}/fixJson.cjs +0 -0
- /package/{model-function/generate-structure → util}/fixJson.d.ts +0 -0
- /package/{model-function/generate-structure → util}/fixJson.js +0 -0
- /package/{model-function/generate-structure → util}/fixJson.test.d.ts +0 -0
- /package/{model-function/generate-structure → util}/parsePartialJson.cjs +0 -0
- /package/{model-function/generate-structure → util}/parsePartialJson.d.ts +0 -0
- /package/{model-function/generate-structure → util}/parsePartialJson.js +0 -0
package/CHANGELOG.md
CHANGED
@@ -1,5 +1,69 @@
|
|
1
1
|
# Changelog
|
2
2
|
|
3
|
+
## v0.131.1 - 2024-01-25
|
4
|
+
|
5
|
+
### Fixed
|
6
|
+
|
7
|
+
- Add `type-fest` as dependency to fix type inference errors.
|
8
|
+
|
9
|
+
## v0.131.0 - 2024-01-23
|
10
|
+
|
11
|
+
### Added
|
12
|
+
|
13
|
+
- `ObjectStreamResponse` and `ObjectStreamFromResponse` serialization functions for using server-generated object streams in web applications.
|
14
|
+
|
15
|
+
Server example:
|
16
|
+
|
17
|
+
```ts
|
18
|
+
export async function POST(req: Request) {
|
19
|
+
const { myArgs } = await req.json();
|
20
|
+
|
21
|
+
const objectStream = await streamObject({
|
22
|
+
// ...
|
23
|
+
});
|
24
|
+
|
25
|
+
// serialize the object stream to a response:
|
26
|
+
return new ObjectStreamResponse(objectStream);
|
27
|
+
}
|
28
|
+
```
|
29
|
+
|
30
|
+
Client example:
|
31
|
+
|
32
|
+
```ts
|
33
|
+
const response = await fetch("/api/stream-object-openai", {
|
34
|
+
method: "POST",
|
35
|
+
body: JSON.stringify({ myArgs }),
|
36
|
+
});
|
37
|
+
|
38
|
+
// deserialize (result object is simpler than the full response)
|
39
|
+
const stream = ObjectStreamFromResponse({
|
40
|
+
schema: itinerarySchema,
|
41
|
+
response,
|
42
|
+
});
|
43
|
+
|
44
|
+
for await (const { partialObject } of stream) {
|
45
|
+
// do something, e.g. setting a React state
|
46
|
+
}
|
47
|
+
```
|
48
|
+
|
49
|
+
### Changed
|
50
|
+
|
51
|
+
- **breaking change**: rename `generateStructure` to `generateObject` and `streamStructure` to `streamObject`. Related names have been changed accordingly.
|
52
|
+
- **breaking change**: the `streamObject` result stream contains additional data. You need to use `stream.partialObject` or destructuring to access it:
|
53
|
+
|
54
|
+
```ts
|
55
|
+
const objectStream = await streamObject({
|
56
|
+
// ...
|
57
|
+
});
|
58
|
+
|
59
|
+
for await (const { partialObject } of objectStream) {
|
60
|
+
console.clear();
|
61
|
+
console.log(partialObject);
|
62
|
+
}
|
63
|
+
```
|
64
|
+
|
65
|
+
- **breaking change**: the result from successful `Schema` validations is stored in the `value` property (before: `data`).
|
66
|
+
|
3
67
|
## v0.130.1 - 2024-01-22
|
4
68
|
|
5
69
|
### Fixed
|
package/README.md
CHANGED
@@ -7,12 +7,13 @@
|
|
7
7
|
[](https://modelfusion.dev)
|
8
8
|
[](https://discord.gg/GqCwYZATem)
|
9
9
|
[](https://twitter.com/lgrammel)
|
10
|
+
[](https://twitter.com/modelfusionjs)
|
10
11
|
|
11
12
|
[Introduction](#introduction) | [Quick Install](#quick-install) | [Usage](#usage-examples) | [Documentation](#documentation) | [Examples](#more-examples) | [Contributing](#contributing) | [modelfusion.dev](https://modelfusion.dev)
|
12
13
|
|
13
14
|
## Introduction
|
14
15
|
|
15
|
-
**ModelFusion** is an abstraction layer for integrating AI models into JavaScript and TypeScript applications, unifying the API for common operations such as **text streaming**, **
|
16
|
+
**ModelFusion** is an abstraction layer for integrating AI models into JavaScript and TypeScript applications, unifying the API for common operations such as **text streaming**, **object generation**, and **tool usage**. It provides features to support production environments, including observability hooks, logging, and automatic retries. You can use ModelFusion to build AI applications, chatbots, and agents.
|
16
17
|
|
17
18
|
- **Vendor-neutral**: ModelFusion is a non-commercial open source project that is community-driven. You can use it with any supported provider.
|
18
19
|
- **Multi-modal**: ModelFusion supports a wide range of models including text generation, image generation, vision, text-to-speech, speech-to-text, and embedding models.
|
@@ -30,7 +31,7 @@
|
|
30
31
|
npm install modelfusion
|
31
32
|
```
|
32
33
|
|
33
|
-
Or use a
|
34
|
+
Or use a starter template:
|
34
35
|
|
35
36
|
- [ModelFusion terminal app starter](https://github.com/lgrammel/modelfusion-terminal-app-starter)
|
36
37
|
- [Next.js, Vercel AI SDK, Llama.cpp & ModelFusion starter](https://github.com/lgrammel/modelfusion-llamacpp-nextjs-starter)
|
@@ -108,30 +109,30 @@ for await (const textPart of textStream) {
|
|
108
109
|
|
109
110
|
Providers: [OpenAI](https://modelfusion.dev/integration/model-provider/openai), [OpenAI compatible](https://modelfusion.dev/integration/model-provider/openaicompatible), [Llama.cpp](https://modelfusion.dev/integration/model-provider/llamacpp), [Ollama](https://modelfusion.dev/integration/model-provider/ollama)
|
110
111
|
|
111
|
-
### [Generate
|
112
|
+
### [Generate Object](https://modelfusion.dev/guide/function/generate-object)
|
112
113
|
|
113
114
|
Generate typed objects using a language model and a schema.
|
114
115
|
|
115
|
-
####
|
116
|
+
#### generateObject
|
116
117
|
|
117
|
-
Generate
|
118
|
+
Generate an object that matches a schema.
|
118
119
|
|
119
120
|
```ts
|
120
121
|
import {
|
121
122
|
ollama,
|
122
123
|
zodSchema,
|
123
|
-
|
124
|
-
|
124
|
+
generateObject,
|
125
|
+
jsonObjectPrompt,
|
125
126
|
} from "modelfusion";
|
126
127
|
|
127
|
-
const sentiment = await
|
128
|
+
const sentiment = await generateObject({
|
128
129
|
model: ollama
|
129
130
|
.ChatTextGenerator({
|
130
131
|
model: "openhermes2.5-mistral",
|
131
132
|
maxGenerationTokens: 1024,
|
132
133
|
temperature: 0,
|
133
134
|
})
|
134
|
-
.
|
135
|
+
.asObjectGenerationModel(jsonObjectPrompt.instruction()),
|
135
136
|
|
136
137
|
schema: zodSchema(
|
137
138
|
z.object({
|
@@ -154,17 +155,17 @@ const sentiment = await generateStructure({
|
|
154
155
|
|
155
156
|
Providers: [OpenAI](https://modelfusion.dev/integration/model-provider/openai), [Ollama](https://modelfusion.dev//integration/model-provider/ollama), [Llama.cpp](https://modelfusion.dev//integration/model-provider/llama.cpp)
|
156
157
|
|
157
|
-
####
|
158
|
+
#### streamObject
|
158
159
|
|
159
|
-
Stream a
|
160
|
+
Stream a object that matches a schema. Partial objects before the final part are untyped JSON.
|
160
161
|
|
161
162
|
```ts
|
162
|
-
import { zodSchema, openai,
|
163
|
+
import { zodSchema, openai, streamObject } from "modelfusion";
|
163
164
|
|
164
|
-
const
|
165
|
+
const objectStream = await streamObject({
|
165
166
|
model: openai
|
166
167
|
.ChatTextGenerator(/* ... */)
|
167
|
-
.
|
168
|
+
.asFunctionCallObjectGenerationModel({
|
168
169
|
fnName: "generateCharacter",
|
169
170
|
fnDescription: "Generate character descriptions.",
|
170
171
|
})
|
@@ -187,9 +188,9 @@ const structureStream = await streamStructure({
|
|
187
188
|
prompt: "Generate 3 character descriptions for a fantasy role playing game.",
|
188
189
|
});
|
189
190
|
|
190
|
-
for await (const
|
191
|
+
for await (const { partialObject } of objectStream) {
|
191
192
|
console.clear();
|
192
|
-
console.log(
|
193
|
+
console.log(partialObject);
|
193
194
|
}
|
194
195
|
```
|
195
196
|
|
@@ -575,10 +576,10 @@ const text = await generateText({
|
|
575
576
|
|
576
577
|
- [Model Functions](https://modelfusion.dev/guide/function/)
|
577
578
|
- [Generate text](https://modelfusion.dev/guide/function/generate-text)
|
578
|
-
- [Generate
|
579
|
+
- [Generate object](https://modelfusion.dev/guide/function/generate-object)
|
579
580
|
- [Generate image](https://modelfusion.dev/guide/function/generate-image)
|
580
581
|
- [Generate speech](https://modelfusion.dev/guide/function/generate-speech)
|
581
|
-
- [Generate transcription](https://modelfusion.dev/guide/function/
|
582
|
+
- [Generate transcription](https://modelfusion.dev/guide/function/generate-transcription)
|
582
583
|
- [Tokenize Text](https://modelfusion.dev/guide/function/tokenize-text)
|
583
584
|
- [Embed Value](https://modelfusion.dev/guide/function/embed)
|
584
585
|
- [Classify Value](https://modelfusion.dev/guide/function/classify)
|
@@ -627,7 +628,7 @@ Examples for almost all of the individual functions and objects. Highly recommen
|
|
627
628
|
|
628
629
|
### [StoryTeller](https://github.com/lgrammel/storyteller)
|
629
630
|
|
630
|
-
> _multi-modal_,
|
631
|
+
> _multi-modal_, _object streaming_, _image generation_, _text to speech_, _speech to text_, _text generation_, _object generation_, _embeddings_
|
631
632
|
|
632
633
|
StoryTeller is an exploratory web application that creates short audio stories for pre-school kids.
|
633
634
|
|
@@ -645,13 +646,13 @@ Ask questions about a PDF document and get answers from the document.
|
|
645
646
|
|
646
647
|
### [Next.js / ModelFusion Demos](https://github.com/lgrammel/modelfusion/tree/main/examples/nextjs)
|
647
648
|
|
648
|
-
> _Next.js app_, _image generation_, _transcription_,
|
649
|
+
> _Next.js app_, _image generation_, _transcription_, _object streaming_, _OpenAI_, _Stability AI_, _Ollama_
|
649
650
|
|
650
651
|
Examples of using ModelFusion with Next.js 14 (App Router):
|
651
652
|
|
652
653
|
- image generation
|
653
654
|
- voice recording & transcription
|
654
|
-
-
|
655
|
+
- object streaming
|
655
656
|
|
656
657
|
### [Duplex Speech Streaming (using Vite/React & ModelFusion Server/Fastify)](https://github.com/lgrammel/modelfusion/tree/main/examples/speech-streaming-vite-react-fastify)
|
657
658
|
|
package/core/api/postToApi.cjs
CHANGED
@@ -73,7 +73,7 @@ const createJsonResponseHandler = (responseSchema) => async ({ response, url, re
|
|
73
73
|
requestBodyValues,
|
74
74
|
});
|
75
75
|
}
|
76
|
-
return parsedResult.
|
76
|
+
return parsedResult.value;
|
77
77
|
};
|
78
78
|
exports.createJsonResponseHandler = createJsonResponseHandler;
|
79
79
|
const createTextResponseHandler = () => async ({ response }) => response.text();
|
package/core/api/postToApi.js
CHANGED
@@ -68,7 +68,7 @@ export const createJsonResponseHandler = (responseSchema) => async ({ response,
|
|
68
68
|
requestBodyValues,
|
69
69
|
});
|
70
70
|
}
|
71
|
-
return parsedResult.
|
71
|
+
return parsedResult.value;
|
72
72
|
};
|
73
73
|
export const createTextResponseHandler = () => async ({ response }) => response.text();
|
74
74
|
export const createAudioMpegResponseHandler = () => async ({ response, url, requestBodyValues }) => {
|
package/core/schema/Schema.d.ts
CHANGED
@@ -1,14 +1,14 @@
|
|
1
1
|
/**
|
2
|
-
* Validates that the structure of
|
2
|
+
* Validates that the structure of a value matches this schema.
|
3
3
|
*/
|
4
|
-
export interface Schema<
|
4
|
+
export interface Schema<OBJECT> {
|
5
5
|
/**
|
6
|
-
* Validates that the structure of
|
7
|
-
* and returns a typed version of
|
6
|
+
* Validates that the structure of a value matches this schema,
|
7
|
+
* and returns a typed version of the value if it does.
|
8
8
|
*/
|
9
|
-
validate(
|
9
|
+
validate(value: unknown): {
|
10
10
|
success: true;
|
11
|
-
|
11
|
+
value: OBJECT;
|
12
12
|
} | {
|
13
13
|
success: false;
|
14
14
|
error: unknown;
|
@@ -16,5 +16,5 @@ export interface Schema<STRUCTURE> {
|
|
16
16
|
/**
|
17
17
|
* Only used for type inference.
|
18
18
|
*/
|
19
|
-
readonly _type:
|
19
|
+
readonly _type: OBJECT;
|
20
20
|
}
|
@@ -3,11 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.TypeValidationError = void 0;
|
4
4
|
const getErrorMessage_js_1 = require("../../util/getErrorMessage.cjs");
|
5
5
|
class TypeValidationError extends Error {
|
6
|
-
constructor({
|
6
|
+
constructor({ value, cause }) {
|
7
7
|
super(`Type validation failed: ` +
|
8
|
-
`
|
8
|
+
`Value: ${JSON.stringify(value)}.\n` +
|
9
9
|
`Error message: ${(0, getErrorMessage_js_1.getErrorMessage)(cause)}`);
|
10
|
-
Object.defineProperty(this, "
|
10
|
+
Object.defineProperty(this, "value", {
|
11
11
|
enumerable: true,
|
12
12
|
configurable: true,
|
13
13
|
writable: true,
|
@@ -21,7 +21,7 @@ class TypeValidationError extends Error {
|
|
21
21
|
});
|
22
22
|
this.name = "TypeValidationError";
|
23
23
|
this.cause = cause;
|
24
|
-
this.
|
24
|
+
this.value = value;
|
25
25
|
}
|
26
26
|
toJSON() {
|
27
27
|
return {
|
@@ -29,7 +29,7 @@ class TypeValidationError extends Error {
|
|
29
29
|
message: this.message,
|
30
30
|
cause: this.cause,
|
31
31
|
stack: this.stack,
|
32
|
-
|
32
|
+
value: this.value,
|
33
33
|
};
|
34
34
|
}
|
35
35
|
}
|
@@ -1,8 +1,8 @@
|
|
1
1
|
export declare class TypeValidationError extends Error {
|
2
|
-
readonly
|
2
|
+
readonly value: unknown;
|
3
3
|
readonly cause: unknown;
|
4
|
-
constructor({
|
5
|
-
|
4
|
+
constructor({ value, cause }: {
|
5
|
+
value: unknown;
|
6
6
|
cause: unknown;
|
7
7
|
});
|
8
8
|
toJSON(): {
|
@@ -10,6 +10,6 @@ export declare class TypeValidationError extends Error {
|
|
10
10
|
message: string;
|
11
11
|
cause: unknown;
|
12
12
|
stack: string | undefined;
|
13
|
-
|
13
|
+
value: unknown;
|
14
14
|
};
|
15
15
|
}
|
@@ -1,10 +1,10 @@
|
|
1
1
|
import { getErrorMessage } from "../../util/getErrorMessage.js";
|
2
2
|
export class TypeValidationError extends Error {
|
3
|
-
constructor({
|
3
|
+
constructor({ value, cause }) {
|
4
4
|
super(`Type validation failed: ` +
|
5
|
-
`
|
5
|
+
`Value: ${JSON.stringify(value)}.\n` +
|
6
6
|
`Error message: ${getErrorMessage(cause)}`);
|
7
|
-
Object.defineProperty(this, "
|
7
|
+
Object.defineProperty(this, "value", {
|
8
8
|
enumerable: true,
|
9
9
|
configurable: true,
|
10
10
|
writable: true,
|
@@ -18,7 +18,7 @@ export class TypeValidationError extends Error {
|
|
18
18
|
});
|
19
19
|
this.name = "TypeValidationError";
|
20
20
|
this.cause = cause;
|
21
|
-
this.
|
21
|
+
this.value = value;
|
22
22
|
}
|
23
23
|
toJSON() {
|
24
24
|
return {
|
@@ -26,7 +26,7 @@ export class TypeValidationError extends Error {
|
|
26
26
|
message: this.message,
|
27
27
|
cause: this.cause,
|
28
28
|
stack: this.stack,
|
29
|
-
|
29
|
+
value: this.value,
|
30
30
|
};
|
31
31
|
}
|
32
32
|
}
|
@@ -1,16 +1,16 @@
|
|
1
1
|
import { JsonSchemaProducer } from "./JsonSchemaProducer.js";
|
2
2
|
import { Schema } from "./Schema.js";
|
3
|
-
export declare function uncheckedSchema<
|
4
|
-
export declare class UncheckedSchema<
|
3
|
+
export declare function uncheckedSchema<OBJECT>(jsonSchema?: unknown): UncheckedSchema<OBJECT>;
|
4
|
+
export declare class UncheckedSchema<OBJECT> implements Schema<OBJECT>, JsonSchemaProducer {
|
5
5
|
private readonly jsonSchema?;
|
6
6
|
constructor(jsonSchema?: unknown);
|
7
|
-
validate(
|
7
|
+
validate(value: unknown): {
|
8
8
|
success: true;
|
9
|
-
|
9
|
+
value: OBJECT;
|
10
10
|
} | {
|
11
11
|
success: false;
|
12
12
|
error: unknown;
|
13
13
|
};
|
14
14
|
getJsonSchema(): unknown;
|
15
|
-
readonly _type:
|
15
|
+
readonly _type: OBJECT;
|
16
16
|
}
|
@@ -34,8 +34,11 @@ class ZodSchema {
|
|
34
34
|
});
|
35
35
|
this.zodSchema = zodSchema;
|
36
36
|
}
|
37
|
-
validate(
|
38
|
-
|
37
|
+
validate(value) {
|
38
|
+
const result = this.zodSchema.safeParse(value);
|
39
|
+
return result.success
|
40
|
+
? { success: true, value: result.data }
|
41
|
+
: { success: false, error: result.error };
|
39
42
|
}
|
40
43
|
getJsonSchema() {
|
41
44
|
return (0, zod_to_json_schema_1.zodToJsonSchema)(this.zodSchema);
|
@@ -1,14 +1,14 @@
|
|
1
|
+
import { PartialDeep } from "type-fest";
|
1
2
|
import { z } from "zod";
|
2
3
|
import { JsonSchemaProducer } from "./JsonSchemaProducer.js";
|
3
4
|
import { Schema } from "./Schema.js";
|
4
|
-
|
5
|
-
export declare
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
validate(data: unknown): {
|
5
|
+
export declare function zodSchema<OBJECT>(zodSchema: z.Schema<OBJECT>): ZodSchema<OBJECT>;
|
6
|
+
export declare class ZodSchema<OBJECT> implements Schema<OBJECT>, JsonSchemaProducer {
|
7
|
+
readonly zodSchema: z.Schema<OBJECT>;
|
8
|
+
constructor(zodSchema: z.Schema<OBJECT>);
|
9
|
+
validate(value: unknown): {
|
10
10
|
success: true;
|
11
|
-
|
11
|
+
value: OBJECT;
|
12
12
|
} | {
|
13
13
|
success: false;
|
14
14
|
error: unknown;
|
@@ -17,11 +17,11 @@ export declare class ZodSchema<STRUCTURE> implements Schema<STRUCTURE>, JsonSche
|
|
17
17
|
/**
|
18
18
|
* Use only for typing purposes. The value is always `undefined`.
|
19
19
|
*/
|
20
|
-
readonly _type:
|
20
|
+
readonly _type: OBJECT;
|
21
21
|
/**
|
22
22
|
* Use only for typing purposes. The value is always `undefined`.
|
23
23
|
*/
|
24
|
-
readonly _partialType: PartialDeep<
|
24
|
+
readonly _partialType: PartialDeep<OBJECT, {
|
25
25
|
recurseIntoArrays: true;
|
26
26
|
}>;
|
27
27
|
}
|
package/core/schema/ZodSchema.js
CHANGED
@@ -30,8 +30,11 @@ export class ZodSchema {
|
|
30
30
|
});
|
31
31
|
this.zodSchema = zodSchema;
|
32
32
|
}
|
33
|
-
validate(
|
34
|
-
|
33
|
+
validate(value) {
|
34
|
+
const result = this.zodSchema.safeParse(value);
|
35
|
+
return result.success
|
36
|
+
? { success: true, value: result.data }
|
37
|
+
: { success: false, error: result.error };
|
35
38
|
}
|
36
39
|
getJsonSchema() {
|
37
40
|
return zodToJsonSchema(this.zodSchema);
|
@@ -10,11 +10,11 @@ const validateTypes_js_1 = require("./validateTypes.cjs");
|
|
10
10
|
const TypeValidationError_js_1 = require("./TypeValidationError.cjs");
|
11
11
|
function parseJSON({ text, schema, }) {
|
12
12
|
try {
|
13
|
-
const
|
13
|
+
const value = secure_json_parse_1.default.parse(text);
|
14
14
|
if (schema == null) {
|
15
|
-
return
|
15
|
+
return value;
|
16
16
|
}
|
17
|
-
return (0, validateTypes_js_1.validateTypes)({
|
17
|
+
return (0, validateTypes_js_1.validateTypes)({ value, schema });
|
18
18
|
}
|
19
19
|
catch (error) {
|
20
20
|
if (error instanceof JSONParseError_js_1.JSONParseError ||
|
@@ -27,14 +27,14 @@ function parseJSON({ text, schema, }) {
|
|
27
27
|
exports.parseJSON = parseJSON;
|
28
28
|
function safeParseJSON({ text, schema, }) {
|
29
29
|
try {
|
30
|
-
const
|
30
|
+
const value = secure_json_parse_1.default.parse(text);
|
31
31
|
if (schema == null) {
|
32
32
|
return {
|
33
33
|
success: true,
|
34
|
-
|
34
|
+
value: value,
|
35
35
|
};
|
36
36
|
}
|
37
|
-
return (0, validateTypes_js_1.safeValidateTypes)({
|
37
|
+
return (0, validateTypes_js_1.safeValidateTypes)({ value, schema });
|
38
38
|
}
|
39
39
|
catch (error) {
|
40
40
|
return {
|
@@ -32,13 +32,13 @@ export declare function safeParseJSON({ text, }: {
|
|
32
32
|
text: string;
|
33
33
|
}): {
|
34
34
|
success: true;
|
35
|
-
|
35
|
+
value: unknown;
|
36
36
|
} | {
|
37
37
|
success: false;
|
38
38
|
error: JSONParseError | TypeValidationError;
|
39
39
|
};
|
40
40
|
/**
|
41
|
-
* Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the
|
41
|
+
* Safely parses a JSON string into a strongly-typed object, using a provided schema to validate the object.
|
42
42
|
*
|
43
43
|
* @template T - The type of the object to parse the JSON into.
|
44
44
|
* @param {string} text - The JSON string to parse.
|
@@ -50,7 +50,7 @@ export declare function safeParseJSON<T>({ text, schema, }: {
|
|
50
50
|
schema: Schema<T>;
|
51
51
|
}): {
|
52
52
|
success: true;
|
53
|
-
|
53
|
+
value: T;
|
54
54
|
} | {
|
55
55
|
success: false;
|
56
56
|
error: JSONParseError | TypeValidationError;
|
package/core/schema/parseJSON.js
CHANGED
@@ -4,11 +4,11 @@ import { safeValidateTypes, validateTypes } from "./validateTypes.js";
|
|
4
4
|
import { TypeValidationError } from "./TypeValidationError.js";
|
5
5
|
export function parseJSON({ text, schema, }) {
|
6
6
|
try {
|
7
|
-
const
|
7
|
+
const value = SecureJSON.parse(text);
|
8
8
|
if (schema == null) {
|
9
|
-
return
|
9
|
+
return value;
|
10
10
|
}
|
11
|
-
return validateTypes({
|
11
|
+
return validateTypes({ value, schema });
|
12
12
|
}
|
13
13
|
catch (error) {
|
14
14
|
if (error instanceof JSONParseError ||
|
@@ -20,14 +20,14 @@ export function parseJSON({ text, schema, }) {
|
|
20
20
|
}
|
21
21
|
export function safeParseJSON({ text, schema, }) {
|
22
22
|
try {
|
23
|
-
const
|
23
|
+
const value = SecureJSON.parse(text);
|
24
24
|
if (schema == null) {
|
25
25
|
return {
|
26
26
|
success: true,
|
27
|
-
|
27
|
+
value: value,
|
28
28
|
};
|
29
29
|
}
|
30
|
-
return safeValidateTypes({
|
30
|
+
return safeValidateTypes({ value, schema });
|
31
31
|
}
|
32
32
|
catch (error) {
|
33
33
|
return {
|
@@ -7,26 +7,26 @@ const TypeValidationError_js_1 = require("./TypeValidationError.cjs");
|
|
7
7
|
* return a strongly-typed object.
|
8
8
|
*
|
9
9
|
* @template T - The type of the object to validate.
|
10
|
-
* @param {string}
|
11
|
-
* @param {Schema<T>} schema - The schema to use for validating the JSON.
|
10
|
+
* @param {string} options.value - The object to validate.
|
11
|
+
* @param {Schema<T>} options.schema - The schema to use for validating the JSON.
|
12
12
|
* @returns {T} - The typed object.
|
13
13
|
*/
|
14
|
-
function validateTypes({
|
14
|
+
function validateTypes({ value, schema, }) {
|
15
15
|
try {
|
16
|
-
const validationResult = schema.validate(
|
16
|
+
const validationResult = schema.validate(value);
|
17
17
|
if (!validationResult.success) {
|
18
18
|
throw new TypeValidationError_js_1.TypeValidationError({
|
19
|
-
|
19
|
+
value,
|
20
20
|
cause: validationResult.error,
|
21
21
|
});
|
22
22
|
}
|
23
|
-
return validationResult.
|
23
|
+
return validationResult.value;
|
24
24
|
}
|
25
25
|
catch (error) {
|
26
26
|
if (error instanceof TypeValidationError_js_1.TypeValidationError) {
|
27
27
|
throw error;
|
28
28
|
}
|
29
|
-
throw new TypeValidationError_js_1.TypeValidationError({
|
29
|
+
throw new TypeValidationError_js_1.TypeValidationError({ value, cause: error });
|
30
30
|
}
|
31
31
|
}
|
32
32
|
exports.validateTypes = validateTypes;
|
@@ -35,20 +35,20 @@ exports.validateTypes = validateTypes;
|
|
35
35
|
* return a strongly-typed object.
|
36
36
|
*
|
37
37
|
* @template T - The type of the object to validate.
|
38
|
-
* @param {string}
|
39
|
-
* @param {Schema<T>} schema - The schema to use for validating the JSON.
|
38
|
+
* @param {string} options.value - The JSON object to validate.
|
39
|
+
* @param {Schema<T>} options.schema - The schema to use for validating the JSON.
|
40
40
|
* @returns An object with either a `success` flag and the parsed and typed data, or a `success` flag and an error object.
|
41
41
|
*/
|
42
|
-
function safeValidateTypes({
|
42
|
+
function safeValidateTypes({ value, schema, }) {
|
43
43
|
try {
|
44
|
-
const validationResult = schema.validate(
|
44
|
+
const validationResult = schema.validate(value);
|
45
45
|
if (validationResult.success) {
|
46
46
|
return validationResult;
|
47
47
|
}
|
48
48
|
return {
|
49
49
|
success: false,
|
50
50
|
error: new TypeValidationError_js_1.TypeValidationError({
|
51
|
-
|
51
|
+
value,
|
52
52
|
cause: validationResult.error,
|
53
53
|
}),
|
54
54
|
};
|
@@ -58,7 +58,7 @@ function safeValidateTypes({ structure, schema, }) {
|
|
58
58
|
success: false,
|
59
59
|
error: error instanceof TypeValidationError_js_1.TypeValidationError
|
60
60
|
? error
|
61
|
-
: new TypeValidationError_js_1.TypeValidationError({
|
61
|
+
: new TypeValidationError_js_1.TypeValidationError({ value, cause: error }),
|
62
62
|
};
|
63
63
|
}
|
64
64
|
}
|