wellcrafted 0.33.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/error/index.d.ts +34 -17
- package/dist/error/index.d.ts.map +1 -1
- package/dist/error/index.js +32 -4
- package/dist/error/index.js.map +1 -1
- package/dist/{index-Cd0uJHqj.d.ts → index-8WW9UMob.d.ts} +2 -2
- package/dist/{index-Cd0uJHqj.d.ts.map → index-8WW9UMob.d.ts.map} +1 -1
- package/dist/json.d.ts +25 -0
- package/dist/json.d.ts.map +1 -0
- package/dist/json.js +0 -0
- package/dist/query/index.d.ts +2 -3
- package/dist/query/index.d.ts.map +1 -1
- package/dist/query/index.js.map +1 -1
- package/dist/result/index.d.ts +3 -3
- package/dist/{result-DolxQXIZ.d.ts → result-BgPMmUXd.d.ts} +2 -26
- package/dist/result-BgPMmUXd.d.ts.map +1 -0
- package/dist/result-DnOm5ds5.js.map +1 -1
- package/dist/standard-schema/index.d.ts +1 -7
- package/dist/standard-schema/index.d.ts.map +1 -1
- package/dist/standard-schema/index.js.map +1 -1
- package/package.json +5 -1
- package/dist/result-DolxQXIZ.d.ts.map +0 -1
package/dist/error/index.d.ts
CHANGED
|
@@ -1,18 +1,7 @@
|
|
|
1
|
-
import { Err } from "../result-
|
|
1
|
+
import { Err } from "../result-BgPMmUXd.js";
|
|
2
2
|
|
|
3
3
|
//#region src/error/types.d.ts
|
|
4
4
|
|
|
5
|
-
/**
|
|
6
|
-
* JSON-serializable value types for error context.
|
|
7
|
-
* Ensures all error data can be safely serialized via JSON.stringify.
|
|
8
|
-
*/
|
|
9
|
-
type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
10
|
-
[key: string]: JsonValue;
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* JSON-serializable object type for error context.
|
|
14
|
-
*/
|
|
15
|
-
type JsonObject = Record<string, JsonValue>;
|
|
16
5
|
/**
|
|
17
6
|
* Base type for any tagged error, used as a minimum constraint.
|
|
18
7
|
*/
|
|
@@ -63,12 +52,16 @@ type InferErrors<T> = { [K in keyof T]: T[K] extends ((...args: any[]) => Err<in
|
|
|
63
52
|
* @example
|
|
64
53
|
* ```ts
|
|
65
54
|
* const HttpError = defineErrors({
|
|
66
|
-
* Connection: ({ cause }: { cause:
|
|
67
|
-
* message: `Failed to connect: ${cause}`,
|
|
55
|
+
* Connection: ({ cause }: { cause: unknown }) => ({
|
|
56
|
+
* message: `Failed to connect: ${extractErrorMessage(cause)}`,
|
|
68
57
|
* cause,
|
|
69
58
|
* }),
|
|
70
|
-
*
|
|
71
|
-
* message: `
|
|
59
|
+
* Response: ({ status }: { status: number; bodyMessage?: string }) => ({
|
|
60
|
+
* message: `HTTP ${status}`,
|
|
61
|
+
* status,
|
|
62
|
+
* }),
|
|
63
|
+
* Parse: ({ cause }: { cause: unknown }) => ({
|
|
64
|
+
* message: `Failed to parse response body: ${extractErrorMessage(cause)}`,
|
|
72
65
|
* cause,
|
|
73
66
|
* }),
|
|
74
67
|
* });
|
|
@@ -77,6 +70,30 @@ type InferErrors<T> = { [K in keyof T]: T[K] extends ((...args: any[]) => Err<in
|
|
|
77
70
|
*
|
|
78
71
|
* const result = HttpError.Connection({ cause: 'timeout' }); // Err<...>
|
|
79
72
|
* ```
|
|
73
|
+
*
|
|
74
|
+
* Inspired by Rust's {@link https://docs.rs/thiserror | thiserror} crate. The
|
|
75
|
+
* mapping is nearly 1:1:
|
|
76
|
+
*
|
|
77
|
+
* - `enum HttpError` → `const HttpError = defineErrors(...)`
|
|
78
|
+
* - Variant `Connection { cause: String }` → key `Connection: ({ cause }: { cause: unknown }) => (...)`
|
|
79
|
+
* - `#[error("Failed: {cause}")]` → `` message: `Failed: ${extractErrorMessage(cause)}` ``
|
|
80
|
+
* - `HttpError::Connection { ... }` → `HttpError.Connection({ ... })`
|
|
81
|
+
* - `match error { Connection { .. } => }` → `switch (error.name) { case 'Connection': }`
|
|
82
|
+
*
|
|
83
|
+
* The equivalent Rust `thiserror` enum:
|
|
84
|
+
* ```rust
|
|
85
|
+
* #[derive(Error, Debug)]
|
|
86
|
+
* enum HttpError {
|
|
87
|
+
* #[error("Failed to connect: {cause}")]
|
|
88
|
+
* Connection { cause: String },
|
|
89
|
+
*
|
|
90
|
+
* #[error("HTTP {status}")]
|
|
91
|
+
* Response { status: u16, body_message: Option<String> },
|
|
92
|
+
*
|
|
93
|
+
* #[error("Failed to parse response body: {cause}")]
|
|
94
|
+
* Parse { cause: String },
|
|
95
|
+
* }
|
|
96
|
+
* ```
|
|
80
97
|
*/
|
|
81
98
|
declare function defineErrors<const TConfig extends ErrorsConfig>(config: TConfig & ValidatedConfig<TConfig>): DefineErrorsReturn<TConfig>;
|
|
82
99
|
//# sourceMappingURL=defineErrors.d.ts.map
|
|
@@ -92,5 +109,5 @@ declare function extractErrorMessage(error: unknown): string;
|
|
|
92
109
|
//# sourceMappingURL=extractErrorMessage.d.ts.map
|
|
93
110
|
|
|
94
111
|
//#endregion
|
|
95
|
-
export { AnyTaggedError, DefineErrorsReturn, ErrorBody, ErrorsConfig, InferError, InferErrors,
|
|
112
|
+
export { AnyTaggedError, DefineErrorsReturn, ErrorBody, ErrorsConfig, InferError, InferErrors, ValidatedConfig, defineErrors, extractErrorMessage };
|
|
96
113
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/error/types.ts","../../src/error/defineErrors.ts","../../src/error/extractErrorMessage.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/error/types.ts","../../src/error/defineErrors.ts","../../src/error/extractErrorMessage.ts"],"sourcesContent":[],"mappings":";;;;;;AAKA;AAWY,KAXA,cAAA,GAWS;EAMhB,IAAA,EAAA,MAAA;EAOO,OAAA,EAAA,MAAY;CAAA;;;AAAS;AAGjC;;AAAsC,KAhB1B,SAAA,GAgB0B;EAAY,OA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UJ,CAVI,EAUD,OAVC,CAUO,CAVP,CAAA,CAAA,EAAC,CAAA,MAW1C,OARP,GAAA,MAAA,CAAA,CAAA;AAAC;AAIQ,KAQA,UARA,CAAA,CAAA,CAAkB,GAU7B,CAV6B,UAAA,CAAA,GAAA,IAAA,EAAA,GAAA,EAAA,EAAA,GAUC,GAVD,CAAA,KAAA,EAAA,CAAA,IAUgB,CAVhB,GAAA,KAAA;;AAAiB,KAanC,WAbmC,CAAA,CAAA,CAAA,GAAA,QAGhC,MAYF,CAZE,GAYE,CAZF,CAYI,CAZJ,CAAA,UAAA,CAAA,GAAA,IAAA,EAAA,GAAA,EAAA,EAAA,GAYmC,GAZnC,CAAA,KAAA,EAAA,CAAA,IAYkD,CAZlD,GAAA,KAAA,EAAO,CAAA,MAad,CAbuC,CAAA;;;;;AAxD/C;AAWA;AAA4C;AAa5C;;;;AAAiC;AAGjC;;;;;;;;;;;;AAIO;AACL;;;;;;;;;;;AAUO;AAAA;;;;;AAOL;AAIJ;;;;;;;;;;AACoB;AAOpB;AAAsB,iBCNN,YDMM,CAAA,sBCN6B,YDM7B,CAAA,CAAA,MAAA,ECLb,ODKa,GCLH,eDKG,CCLa,ODKb,CAAA,CAAA,ECJnB,kBDImB,CCJA,ODIA,CAAA;;;;;;;AA7DtB;AAWA;AAA4C;AAahC,iBEvBI,mBAAA,CFuBQ,KAAA,EAAA,OAAA,CAAA,EAAA,MAAA"}
|
package/dist/error/index.js
CHANGED
|
@@ -11,12 +11,16 @@ import { Err } from "../result-DnOm5ds5.js";
|
|
|
11
11
|
* @example
|
|
12
12
|
* ```ts
|
|
13
13
|
* const HttpError = defineErrors({
|
|
14
|
-
* Connection: ({ cause }: { cause:
|
|
15
|
-
* message: `Failed to connect: ${cause}`,
|
|
14
|
+
* Connection: ({ cause }: { cause: unknown }) => ({
|
|
15
|
+
* message: `Failed to connect: ${extractErrorMessage(cause)}`,
|
|
16
16
|
* cause,
|
|
17
17
|
* }),
|
|
18
|
-
*
|
|
19
|
-
* message: `
|
|
18
|
+
* Response: ({ status }: { status: number; bodyMessage?: string }) => ({
|
|
19
|
+
* message: `HTTP ${status}`,
|
|
20
|
+
* status,
|
|
21
|
+
* }),
|
|
22
|
+
* Parse: ({ cause }: { cause: unknown }) => ({
|
|
23
|
+
* message: `Failed to parse response body: ${extractErrorMessage(cause)}`,
|
|
20
24
|
* cause,
|
|
21
25
|
* }),
|
|
22
26
|
* });
|
|
@@ -25,6 +29,30 @@ import { Err } from "../result-DnOm5ds5.js";
|
|
|
25
29
|
*
|
|
26
30
|
* const result = HttpError.Connection({ cause: 'timeout' }); // Err<...>
|
|
27
31
|
* ```
|
|
32
|
+
*
|
|
33
|
+
* Inspired by Rust's {@link https://docs.rs/thiserror | thiserror} crate. The
|
|
34
|
+
* mapping is nearly 1:1:
|
|
35
|
+
*
|
|
36
|
+
* - `enum HttpError` → `const HttpError = defineErrors(...)`
|
|
37
|
+
* - Variant `Connection { cause: String }` → key `Connection: ({ cause }: { cause: unknown }) => (...)`
|
|
38
|
+
* - `#[error("Failed: {cause}")]` → `` message: `Failed: ${extractErrorMessage(cause)}` ``
|
|
39
|
+
* - `HttpError::Connection { ... }` → `HttpError.Connection({ ... })`
|
|
40
|
+
* - `match error { Connection { .. } => }` → `switch (error.name) { case 'Connection': }`
|
|
41
|
+
*
|
|
42
|
+
* The equivalent Rust `thiserror` enum:
|
|
43
|
+
* ```rust
|
|
44
|
+
* #[derive(Error, Debug)]
|
|
45
|
+
* enum HttpError {
|
|
46
|
+
* #[error("Failed to connect: {cause}")]
|
|
47
|
+
* Connection { cause: String },
|
|
48
|
+
*
|
|
49
|
+
* #[error("HTTP {status}")]
|
|
50
|
+
* Response { status: u16, body_message: Option<String> },
|
|
51
|
+
*
|
|
52
|
+
* #[error("Failed to parse response body: {cause}")]
|
|
53
|
+
* Parse { cause: String },
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
28
56
|
*/
|
|
29
57
|
function defineErrors(config) {
|
|
30
58
|
const result = {};
|
package/dist/error/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["config: TConfig & ValidatedConfig<TConfig>","result: Record<string, unknown>","error: unknown"],"sources":["../../src/error/defineErrors.ts","../../src/error/extractErrorMessage.ts"],"sourcesContent":["import { Err } from \"../result/result.js\";\nimport type {\n\tDefineErrorsReturn,\n\tErrorsConfig,\n\tValidatedConfig,\n} from \"./types.js\";\n\n/**\n * Defines a set of typed error factories using Rust-style namespaced variants.\n *\n * Each key is a short variant name (the namespace provides context). Every\n * factory returns `Err<...>` directly — ready for `trySync`/`tryAsync` catch\n * handlers. The variant name is stamped as `name` on the error object.\n *\n * @example\n * ```ts\n * const HttpError = defineErrors({\n * Connection: ({ cause }: { cause:
|
|
1
|
+
{"version":3,"file":"index.js","names":["config: TConfig & ValidatedConfig<TConfig>","result: Record<string, unknown>","error: unknown"],"sources":["../../src/error/defineErrors.ts","../../src/error/extractErrorMessage.ts"],"sourcesContent":["import { Err } from \"../result/result.js\";\nimport type {\n\tDefineErrorsReturn,\n\tErrorsConfig,\n\tValidatedConfig,\n} from \"./types.js\";\n\n/**\n * Defines a set of typed error factories using Rust-style namespaced variants.\n *\n * Each key is a short variant name (the namespace provides context). Every\n * factory returns `Err<...>` directly — ready for `trySync`/`tryAsync` catch\n * handlers. The variant name is stamped as `name` on the error object.\n *\n * @example\n * ```ts\n * const HttpError = defineErrors({\n * Connection: ({ cause }: { cause: unknown }) => ({\n * message: `Failed to connect: ${extractErrorMessage(cause)}`,\n * cause,\n * }),\n * Response: ({ status }: { status: number; bodyMessage?: string }) => ({\n * message: `HTTP ${status}`,\n * status,\n * }),\n * Parse: ({ cause }: { cause: unknown }) => ({\n * message: `Failed to parse response body: ${extractErrorMessage(cause)}`,\n * cause,\n * }),\n * });\n *\n * type HttpError = InferErrors<typeof HttpError>;\n *\n * const result = HttpError.Connection({ cause: 'timeout' }); // Err<...>\n * ```\n *\n * Inspired by Rust's {@link https://docs.rs/thiserror | thiserror} crate. The\n * mapping is nearly 1:1:\n *\n * - `enum HttpError` → `const HttpError = defineErrors(...)`\n * - Variant `Connection { cause: String }` → key `Connection: ({ cause }: { cause: unknown }) => (...)`\n * - `#[error(\"Failed: {cause}\")]` → `` message: `Failed: ${extractErrorMessage(cause)}` ``\n * - `HttpError::Connection { ... }` → `HttpError.Connection({ ... })`\n * - `match error { Connection { .. } => }` → `switch (error.name) { case 'Connection': }`\n *\n * The equivalent Rust `thiserror` enum:\n * ```rust\n * #[derive(Error, Debug)]\n * enum HttpError {\n * #[error(\"Failed to connect: {cause}\")]\n * Connection { cause: String },\n *\n * #[error(\"HTTP {status}\")]\n * Response { status: u16, body_message: Option<String> },\n *\n * #[error(\"Failed to parse response body: {cause}\")]\n * Parse { cause: String },\n * }\n * ```\n */\nexport function defineErrors<const TConfig extends ErrorsConfig>(\n\tconfig: TConfig & ValidatedConfig<TConfig>,\n): DefineErrorsReturn<TConfig> {\n\tconst result: Record<string, unknown> = {};\n\n\tfor (const [name, ctor] of Object.entries(config)) {\n\t\tresult[name] = (...args: unknown[]) => {\n\t\t\tconst body = (ctor as (...a: unknown[]) => Record<string, unknown>)(\n\t\t\t\t...args,\n\t\t\t);\n\t\t\treturn Err(Object.freeze({ ...body, name }));\n\t\t};\n\t}\n\n\treturn result as DefineErrorsReturn<TConfig>;\n}\n","/**\n * Extracts a readable error message from an unknown error value\n *\n * @param error - The unknown error to extract a message from\n * @returns A string representation of the error\n */\nexport function extractErrorMessage(error: unknown): string {\n\t// Handle Error instances\n\tif (error instanceof Error) {\n\t\treturn error.message;\n\t}\n\n\t// Handle primitives\n\tif (typeof error === \"string\") return error;\n\tif (\n\t\ttypeof error === \"number\" ||\n\t\ttypeof error === \"boolean\" ||\n\t\ttypeof error === \"bigint\"\n\t)\n\t\treturn String(error);\n\tif (typeof error === \"symbol\") return error.toString();\n\tif (error === null) return \"null\";\n\tif (error === undefined) return \"undefined\";\n\n\t// Handle arrays\n\tif (Array.isArray(error)) return JSON.stringify(error);\n\n\t// Handle plain objects\n\tif (typeof error === \"object\") {\n\t\tconst errorObj = error as Record<string, unknown>;\n\n\t\t// Check common error properties\n\t\tconst messageProps = [\n\t\t\t\"message\",\n\t\t\t\"error\",\n\t\t\t\"description\",\n\t\t\t\"title\",\n\t\t\t\"reason\",\n\t\t\t\"details\",\n\t\t] as const;\n\t\tfor (const prop of messageProps) {\n\t\t\tif (prop in errorObj && typeof errorObj[prop] === \"string\") {\n\t\t\t\treturn errorObj[prop];\n\t\t\t}\n\t\t}\n\n\t\t// Fallback to JSON stringification\n\t\ttry {\n\t\t\treturn JSON.stringify(error);\n\t\t} catch {\n\t\t\treturn String(error);\n\t\t}\n\t}\n\n\t// Final fallback\n\treturn String(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,SAAgB,aACfA,QAC8B;CAC9B,MAAMC,SAAkC,CAAE;AAE1C,MAAK,MAAM,CAAC,MAAM,KAAK,IAAI,OAAO,QAAQ,OAAO,CAChD,QAAO,QAAQ,CAAC,GAAG,SAAoB;EACtC,MAAM,OAAO,AAAC,KACb,GAAG,KACH;AACD,SAAO,IAAI,OAAO,OAAO;GAAE,GAAG;GAAM;EAAM,EAAC,CAAC;CAC5C;AAGF,QAAO;AACP;;;;;;;;;;ACrED,SAAgB,oBAAoBC,OAAwB;AAE3D,KAAI,iBAAiB,MACpB,QAAO,MAAM;AAId,YAAW,UAAU,SAAU,QAAO;AACtC,YACQ,UAAU,mBACV,UAAU,oBACV,UAAU,SAEjB,QAAO,OAAO,MAAM;AACrB,YAAW,UAAU,SAAU,QAAO,MAAM,UAAU;AACtD,KAAI,UAAU,KAAM,QAAO;AAC3B,KAAI,iBAAqB,QAAO;AAGhC,KAAI,MAAM,QAAQ,MAAM,CAAE,QAAO,KAAK,UAAU,MAAM;AAGtD,YAAW,UAAU,UAAU;EAC9B,MAAM,WAAW;EAGjB,MAAM,eAAe;GACpB;GACA;GACA;GACA;GACA;GACA;EACA;AACD,OAAK,MAAM,QAAQ,aAClB,KAAI,QAAQ,mBAAmB,SAAS,UAAU,SACjD,QAAO,SAAS;AAKlB,MAAI;AACH,UAAO,KAAK,UAAU,MAAM;EAC5B,QAAO;AACP,UAAO,OAAO,MAAM;EACpB;CACD;AAGD,QAAO,OAAO,MAAM;AACpB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Err, Ok, Result } from "./result-
|
|
1
|
+
import { Err, Ok, Result } from "./result-BgPMmUXd.js";
|
|
2
2
|
|
|
3
3
|
//#region src/result/utils.d.ts
|
|
4
4
|
|
|
@@ -25,4 +25,4 @@ declare function partitionResults<T, E>(results: Result<T, E>[]): {
|
|
|
25
25
|
//# sourceMappingURL=utils.d.ts.map
|
|
26
26
|
//#endregion
|
|
27
27
|
export { partitionResults };
|
|
28
|
-
//# sourceMappingURL=index-
|
|
28
|
+
//# sourceMappingURL=index-8WW9UMob.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index-
|
|
1
|
+
{"version":3,"file":"index-8WW9UMob.d.ts","names":[],"sources":["../src/result/utils.ts"],"sourcesContent":[],"mappings":";;;;;;AAmBA;;;;;;;;;AAK+B;;;;;iBALf,gCAAgC,OAAO,GAAG;OAK7C,GAAG;QAAY,IAAI"}
|
package/dist/json.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/json.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* JSON-serializable value types.
|
|
4
|
+
* Ensures data can be safely serialized via JSON.stringify.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```typescript
|
|
8
|
+
* import type { JsonValue, JsonObject } from "wellcrafted/json";
|
|
9
|
+
*
|
|
10
|
+
* const value: JsonValue = { key: [1, "two", true, null] };
|
|
11
|
+
* const obj: JsonObject = { name: "Alice", age: 30 };
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
type JsonValue = string | number | boolean | null | JsonValue[] | {
|
|
15
|
+
[key: string]: JsonValue;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* JSON-serializable object type.
|
|
19
|
+
* A record where every value is a {@link JsonValue}.
|
|
20
|
+
*/
|
|
21
|
+
type JsonObject = Record<string, JsonValue>;
|
|
22
|
+
//# sourceMappingURL=json.d.ts.map
|
|
23
|
+
//#endregion
|
|
24
|
+
export { JsonObject, JsonValue };
|
|
25
|
+
//# sourceMappingURL=json.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json.d.ts","names":[],"sources":["../src/json.ts"],"sourcesContent":[],"mappings":";;AAYA;;;;AAM6B;AAM7B;;;;AAA+B;;KAZnB,SAAA,sCAKT;iBACiB;;;;;;KAMR,UAAA,GAAa,eAAe"}
|
package/dist/json.js
ADDED
|
File without changes
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Result } from "../result-
|
|
2
|
-
import "../index-
|
|
1
|
+
import { Result } from "../result-BgPMmUXd.js";
|
|
2
|
+
import "../index-8WW9UMob.js";
|
|
3
3
|
import { DefaultError, MutationFunction, MutationKey, MutationOptions, QueryClient, QueryFunction, QueryKey, QueryObserverOptions } from "@tanstack/query-core";
|
|
4
4
|
|
|
5
5
|
//#region src/query/utils.d.ts
|
|
@@ -155,7 +155,6 @@ declare function createQueryFactories(queryClient: QueryClient): {
|
|
|
155
155
|
defineQuery: <TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = readonly unknown[]>(options: DefineQueryInput<TQueryFnData, TError, TData, TQueryData, TQueryKey>) => DefineQueryOutput<TQueryFnData, TError, TData, TQueryData, TQueryKey>;
|
|
156
156
|
defineMutation: <TData, TError, TVariables = void, TContext = unknown>(options: DefineMutationInput<TData, TError, TVariables, TContext>) => DefineMutationOutput<TData, TError, TVariables, TContext>;
|
|
157
157
|
};
|
|
158
|
-
//# sourceMappingURL=utils.d.ts.map
|
|
159
158
|
//#endregion
|
|
160
159
|
export { createQueryFactories };
|
|
161
160
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/query/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/query/utils.ts"],"sourcesContent":[],"mappings":";;;;;;;;;AAUmE;;;;;;;;;KAc9D,gBAOuC,CAAA,eAAA,OAAA,EAAA,SALlC,YAKkC,EAAA,QAJnC,YAImC,EAAA,aAH9B,YAG8B,EAAA,kBAFzB,QAEyB,GAFd,QAEc,CAAA,GADxC,IACwC,CAA3C,oBAA2C,CAAtB,YAAsB,EAAR,MAAQ,EAAA,KAAA,EAAO,UAAP,EAAmB,SAAnB,CAAA,EAAA,SAAA,CAAA,GAAA;EAAK,QAAE,EAGxC,SAHwC;EAAU,OAAE,EAIrD,aAJqD,CAIvC,MAJuC,CAIhC,YAJgC,EAIlB,MAJkB,CAAA,EAIT,SAJS,CAAA;CAAS;;;;;;;;AAIjD;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;AAmDD,KAfjB,iBAeiB,CAAA,eAAA,OAAA,EAAA,SAbZ,YAaY,EAAA,QAZb,YAYa,EAAA,aAXR,YAWQ,EAAA,kBAVH,QAUG,GAVQ,QAUR,CAAA,GAAA,CAAA,GAAA,GATX,OASW,CATH,MASG,CATI,UASJ,EATgB,MAShB,CAAA,CAAA,CAAA,GAAA;EAejB,OAAA,EAvBK,oBAuBc,CAtBtB,YAsBsB,EArBtB,MAqBsB,EApBtB,KAoBsB,EAnBtB,UAmBsB,EAlBtB,SAkBsB,CAAA;EAAA,KAAA,EAAA,GAAA,GAhBV,OAgBU,CAhBF,MAgBE,CAhBK,UAgBL,EAhBiB,MAgBjB,CAAA,CAAA;EAAA,MAKC,EAAA,GAAA,GApBV,OAoB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"index.js","names":["queryClient: QueryClient","options: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>","options: DefineMutationInput<TData, TError, TVariables, TContext>","variables: TVariables","options: MutationOptions<TData, TError, TVariables, TContext>"],"sources":["../../src/query/utils.ts"],"sourcesContent":["import type {\n\tDefaultError,\n\tMutationFunction,\n\tMutationKey,\n\tMutationOptions,\n\tQueryClient,\n\tQueryFunction,\n\tQueryKey,\n\tQueryObserverOptions,\n} from \"@tanstack/query-core\";\nimport { Err, Ok, type Result, resolve } from \"../result/index.js\";\n\n/**\n * Input options for defining a query.\n *\n * Extends TanStack Query's QueryObserverOptions but expects queryFn to return a Result type.\n * This type represents the configuration for creating a query definition with both\n * reactive and imperative interfaces for data fetching.\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\nexport type DefineQueryInput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = Omit<\n\tQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n\t\"queryFn\"\n> & {\n\tqueryKey: TQueryKey;\n\tqueryFn: QueryFunction<Result<TQueryFnData, TError>, TQueryKey>;\n};\n\n/**\n * Output of defineQuery function.\n *\n * The query definition is directly callable and defaults to `ensure()` behavior,\n * which is recommended for most imperative use cases like preloaders.\n *\n * Provides both reactive and imperative interfaces for data fetching:\n * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n * - `options`: Returns config for use with useQuery() or createQuery()\n * - `fetch()`: Always attempts to fetch data (from cache if fresh, network if stale)\n * - `ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n *\n * @example\n * ```typescript\n * const userQuery = defineQuery({...});\n *\n * // Directly callable (same as .ensure())\n * const { data, error } = await userQuery();\n *\n * // Or use explicit methods\n * const { data, error } = await userQuery.ensure();\n * const { data, error } = await userQuery.fetch();\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n * ```\n */\nexport type DefineQueryOutput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = (() => Promise<Result<TQueryData, TError>>) & {\n\toptions: QueryObserverOptions<\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData,\n\t\tTQueryData,\n\t\tTQueryKey\n\t>;\n\tfetch: () => Promise<Result<TQueryData, TError>>;\n\tensure: () => Promise<Result<TQueryData, TError>>;\n};\n\n/**\n * Input options for defining a mutation.\n *\n * Extends TanStack Query's MutationOptions but expects mutationFn to return a Result type.\n * This type represents the configuration for creating a mutation definition with both\n * reactive and imperative interfaces for data mutations.\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\nexport type DefineMutationInput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = Omit<MutationOptions<TData, TError, TVariables, TContext>, \"mutationFn\"> & {\n\tmutationKey: MutationKey;\n\tmutationFn: MutationFunction<Result<TData, TError>, TVariables>;\n};\n\n/**\n * Output of defineMutation function.\n *\n * The mutation definition is directly callable, which executes the mutation\n * and returns a Result. This is equivalent to calling `.execute()`.\n *\n * Provides both reactive and imperative interfaces for data mutations:\n * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n * - `options`: Returns config for use with useMutation() or createMutation()\n * - `execute(variables)`: Directly executes the mutation and returns a Result\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n *\n * @example\n * ```typescript\n * const createUser = defineMutation({...});\n *\n * // Directly callable (same as .execute())\n * const { data, error } = await createUser({ name: 'John' });\n *\n * // Or use explicit method\n * const { data, error } = await createUser.execute({ name: 'John' });\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const mutation = createMutation(() => createUser.options); // Svelte 5\n * const mutation = useMutation(createUser.options); // React\n * ```\n */\nexport type DefineMutationOutput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = ((variables: TVariables) => Promise<Result<TData, TError>>) & {\n\toptions: MutationOptions<TData, TError, TVariables, TContext>;\n\texecute: (variables: TVariables) => Promise<Result<TData, TError>>;\n};\n\n/**\n * Creates factory functions for defining queries and mutations bound to a specific QueryClient.\n *\n * This factory pattern allows you to create isolated query/mutation definitions that are\n * bound to a specific QueryClient instance, enabling:\n * - Multiple query clients in the same application\n * - Testing with isolated query clients\n * - Framework-agnostic query definitions\n * - Proper separation of concerns between query logic and client instances\n *\n * The returned functions handle Result types automatically, unwrapping them for TanStack Query\n * while maintaining type safety throughout your application.\n *\n * @param queryClient - The QueryClient instance to bind the factories to\n * @returns An object containing defineQuery and defineMutation functions bound to the provided client\n *\n * @example\n * ```typescript\n * // Create your query client\n * const queryClient = new QueryClient({\n * defaultOptions: {\n * queries: { staleTime: 5 * 60 * 1000 }\n * }\n * });\n *\n * // Create the factory functions\n * const { defineQuery, defineMutation } = createQueryFactories(queryClient);\n *\n * // Now use defineQuery and defineMutation as before\n * const userQuery = defineQuery({\n * queryKey: ['user', userId],\n * queryFn: () => services.getUser(userId)\n * });\n *\n * // Use in components (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n *\n * // Or imperatively\n * const { data, error } = await userQuery.fetch();\n * ```\n */\nexport function createQueryFactories(queryClient: QueryClient) {\n\t/**\n\t * Creates a query definition that bridges the gap between pure service functions and reactive UI components.\n\t *\n\t * This factory function is the cornerstone of our data fetching architecture. It wraps service calls\n\t * with TanStack Query superpowers while maintaining type safety through Result types.\n\t *\n\t * The returned query definition is **directly callable** and defaults to `ensure()` behavior,\n\t * which is recommended for most imperative use cases like preloaders.\n\t *\n\t * ## Why use defineQuery?\n\t *\n\t * 1. **Callable**: Call directly like `userQuery()` for imperative data fetching\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.fetch()`, `.ensure()`) APIs\n\t * 3. **Automatic Error Handling**: Service functions return `Result<T, E>` types which are automatically\n\t * unwrapped by TanStack Query, giving you proper error states in your components\n\t * 4. **Type Safety**: Full TypeScript support with proper inference for data and error types\n\t * 5. **Consistency**: Every query in the app follows the same pattern, making it easy to understand\n\t *\n\t * @template TQueryFnData - The type of data returned by the query function\n\t * @template TError - The type of error that can be thrown\n\t * @template TData - The type of data returned by the query (after select transform)\n\t * @template TQueryKey - The type of the query key\n\t *\n\t * @param options - Query configuration object\n\t * @param options.queryKey - Unique key for this query (used for caching and refetching)\n\t * @param options.queryFn - Function that fetches data and returns a Result type\n\t * @param options.* - Any other TanStack Query options (staleTime, refetchInterval, etc.)\n\t *\n\t * @returns Callable query definition with:\n\t * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n\t * - `.options`: Config for use with useQuery() or createQuery()\n\t * - `.fetch()`: Always attempts to fetch (from cache if fresh, network if stale)\n\t * - `.ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your query in the query layer\n\t * const userQuery = defineQuery({\n\t * queryKey: ['users', userId],\n\t * queryFn: () => services.getUser(userId), // Returns Result<User, ApiError>\n\t * staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const query = createQuery(() => userQuery.options);\n\t * // query.data is User | undefined\n\t * // query.error is ApiError | null\n\t *\n\t * // Step 2b: Call directly in preloaders (recommended)\n\t * export const load = async () => {\n\t * const { data, error } = await userQuery(); // Same as userQuery.ensure()\n\t * if (error) throw error;\n\t * return { user: data };\n\t * };\n\t *\n\t * // Step 2c: Use explicit methods when needed\n\t * async function refreshUser() {\n\t * const { data, error } = await userQuery.fetch(); // Force fresh fetch\n\t * if (error) {\n\t * console.error('Failed to fetch user:', error);\n\t * }\n\t * }\n\t * ```\n\t */\n\tconst defineQuery = <\n\t\tTQueryFnData = unknown,\n\t\tTError = DefaultError,\n\t\tTData = TQueryFnData,\n\t\tTQueryData = TQueryFnData,\n\t\tTQueryKey extends QueryKey = QueryKey,\n\t>(\n\t\toptions: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>,\n\t): DefineQueryOutput<TQueryFnData, TError, TData, TQueryData, TQueryKey> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tqueryFn: async (context) => {\n\t\t\t\tlet result = options.queryFn(context);\n\t\t\t\tif (result instanceof Promise) result = await result;\n\t\t\t\treturn resolve(result);\n\t\t\t},\n\t\t} satisfies QueryObserverOptions<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>;\n\n\t\t/**\n\t\t * Fetches data for this query using queryClient.fetchQuery().\n\t\t *\n\t\t * This method ALWAYS evaluates freshness and will refetch if data is stale.\n\t\t * It wraps TanStack Query's fetchQuery method, which returns cached data if fresh\n\t\t * or makes a network request if the data is stale or missing.\n\t\t *\n\t\t * **When to use fetch():**\n\t\t * - When you explicitly want to check data freshness\n\t\t * - For user-triggered refresh actions\n\t\t * - When you need the most up-to-date data\n\t\t *\n\t\t * **For preloaders, use ensure() instead** - it's more efficient for initial data loading.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Good for user-triggered refresh\n\t\t * const { data, error } = await userQuery.fetch();\n\t\t * if (error) {\n\t\t * console.error('Failed to load user:', error);\n\t\t * }\n\t\t */\n\t\tasync function fetch(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.fetchQuery<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Ensures data is available for this query using queryClient.ensureQueryData().\n\t\t *\n\t\t * This method PRIORITIZES cached data and only calls fetchQuery internally if no cached\n\t\t * data exists. It wraps TanStack Query's ensureQueryData method, which is perfect for\n\t\t * guaranteeing data availability with minimal network requests.\n\t\t *\n\t\t * **This is the RECOMMENDED method for preloaders** because:\n\t\t * - It returns cached data immediately if available\n\t\t * - It updates the query client cache properly\n\t\t * - It minimizes network requests during navigation\n\t\t * - It ensures components have data ready when they mount\n\t\t *\n\t\t * **When to use ensure():**\n\t\t * - Route preloaders and data loading functions\n\t\t * - Initial component data requirements\n\t\t * - When cached data is acceptable for immediate display\n\t\t *\n\t\t * This is also the default behavior when calling the query directly.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Perfect for preloaders\n\t\t * export const load = async () => {\n\t\t * const { data, error } = await userQuery.ensure();\n\t\t * // Or simply: await userQuery();\n\t\t * if (error) {\n\t\t * throw error;\n\t\t * }\n\t\t * return { user: data };\n\t\t * };\n\t\t */\n\t\tasync function ensure(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.ensureQueryData<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that defaults to ensure() behavior\n\t\t// and attach options, fetch, and ensure as properties\n\t\treturn Object.assign(ensure, {\n\t\t\toptions: newOptions,\n\t\t\tfetch,\n\t\t\tensure,\n\t\t});\n\t};\n\n\t/**\n\t * Creates a mutation definition for operations that modify data (create, update, delete).\n\t *\n\t * This factory function is the mutation counterpart to defineQuery. It provides a clean way to\n\t * wrap service functions that perform side effects, while maintaining the same dual interface\n\t * pattern for maximum flexibility.\n\t *\n\t * The returned mutation definition is **directly callable**, which executes the mutation\n\t * and returns a Result. This is equivalent to calling `.execute()`.\n\t *\n\t * ## Why use defineMutation?\n\t *\n\t * 1. **Callable**: Call directly like `createUser({ name: 'John' })` for imperative execution\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.execute()`) APIs\n\t * 3. **Consistent Error Handling**: Service functions return `Result<T, E>` types, ensuring\n\t * errors are handled consistently throughout the app\n\t * 4. **Cache Management**: Mutations often update the cache after success (see examples)\n\t *\n\t * @template TData - The type of data returned by the mutation\n\t * @template TError - The type of error that can be thrown\n\t * @template TVariables - The type of variables passed to the mutation\n\t * @template TContext - The type of context data for optimistic updates\n\t *\n\t * @param options - Mutation configuration object\n\t * @param options.mutationKey - Unique key for this mutation (used for tracking in-flight state)\n\t * @param options.mutationFn - Function that performs the mutation and returns a Result type\n\t * @param options.* - Any other TanStack Mutation options (onSuccess, onError, etc.)\n\t *\n\t * @returns Callable mutation definition with:\n\t * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n\t * - `.options`: Config for use with useMutation() or createMutation()\n\t * - `.execute(variables)`: Directly executes the mutation and returns a Result\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your mutation with cache updates\n\t * const createRecording = defineMutation({\n\t * mutationKey: ['recordings', 'create'],\n\t * mutationFn: async (recording: Recording) => {\n\t * // Call the service\n\t * const result = await services.db.createRecording(recording);\n\t * if (result.error) return Err(result.error);\n\t *\n\t * // Update cache on success\n\t * queryClient.setQueryData(['recordings'], (old) =>\n\t * [...(old || []), recording]\n\t * );\n\t *\n\t * return Ok(result.data);\n\t * }\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const mutation = createMutation(() => createRecording.options);\n\t * // Call with: mutation.mutate(recordingData)\n\t *\n\t * // Step 2b: Call directly in an action (recommended)\n\t * async function saveRecording(data: Recording) {\n\t * const { error } = await createRecording(data); // Same as createRecording.execute(data)\n\t * if (error) {\n\t * notify.error({ title: 'Failed to save', description: error.message });\n\t * } else {\n\t * notify.success({ title: 'Recording saved!' });\n\t * }\n\t * }\n\t * ```\n\t *\n\t * @tip Calling directly is especially useful for:\n\t * - Event handlers that need to await the result\n\t * - Sequential operations that depend on each other\n\t * - Non-component code that needs to trigger mutations\n\t */\n\tconst defineMutation = <TData, TError, TVariables = void, TContext = unknown>(\n\t\toptions: DefineMutationInput<TData, TError, TVariables, TContext>,\n\t): DefineMutationOutput<TData, TError, TVariables, TContext> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tmutationFn: async (variables: TVariables) => {\n\t\t\t\treturn resolve(await options.mutationFn(variables));\n\t\t\t},\n\t\t} satisfies MutationOptions<TData, TError, TVariables, TContext>;\n\n\t\t/**\n\t\t * Executes the mutation imperatively and returns a Result.\n\t\t *\n\t\t * This is the recommended way to trigger mutations from:\n\t\t * - Button click handlers\n\t\t * - Form submissions\n\t\t * - Keyboard shortcuts\n\t\t * - Any non-component code\n\t\t *\n\t\t * The method automatically wraps the result in a Result type, so you always\n\t\t * get back `{ data, error }` for consistent error handling.\n\t\t *\n\t\t * This is also the default behavior when calling the mutation directly.\n\t\t *\n\t\t * @param variables - The variables to pass to the mutation function\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // In an event handler\n\t\t * async function handleSubmit(formData: FormData) {\n\t\t * const { data, error } = await createUser.execute(formData);\n\t\t * // Or simply: await createUser(formData);\n\t\t * if (error) {\n\t\t * notify.error({ title: 'Failed to create user', description: error.message });\n\t\t * return;\n\t\t * }\n\t\t * goto(`/users/${data.id}`);\n\t\t * }\n\t\t */\n\t\tasync function execute(variables: TVariables) {\n\t\t\ttry {\n\t\t\t\treturn Ok(await runMutation(queryClient, newOptions, variables));\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that executes the mutation\n\t\t// and attach options and execute as properties\n\t\treturn Object.assign(execute, {\n\t\t\toptions: newOptions,\n\t\t\texecute,\n\t\t});\n\t};\n\n\treturn {\n\t\tdefineQuery,\n\t\tdefineMutation,\n\t};\n}\n\n/**\n * Internal helper that executes a mutation directly using the query client's mutation cache.\n *\n * This is what powers the callable behavior and `.execute()` method on mutations.\n * It bypasses the reactive mutation hooks and runs the mutation imperatively,\n * which is perfect for event handlers and other imperative code.\n *\n * @internal\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data\n * @param queryClient - The query client instance to use\n * @param options - The mutation options including mutationFn and mutationKey\n * @param variables - The variables to pass to the mutation function\n * @returns Promise that resolves with the mutation result\n */\nfunction runMutation<TData, TError, TVariables, TContext>(\n\tqueryClient: QueryClient,\n\toptions: MutationOptions<TData, TError, TVariables, TContext>,\n\tvariables: TVariables,\n) {\n\tconst mutation = queryClient.getMutationCache().build(queryClient, options);\n\treturn mutation.execute(variables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AAU,CAAC;GAChE,SAAQ,OAAO;AACf,WAAO,IAAI,MAAgB;GAC3B;EACD;AAID,SAAO,OAAO,OAAO,SAAS;GAC7B,SAAS;GACT;EACA,EAAC;CACF;AAED,QAAO;EACN;EACA;CACA;AACD;;;;;;;;;;;;;;;;;;AAmBD,SAAS,YACRH,aACAI,SACAD,WACC;CACD,MAAM,WAAW,YAAY,kBAAkB,CAAC,MAAM,aAAa,QAAQ;AAC3E,QAAO,SAAS,QAAQ,UAAU;AAClC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["queryClient: QueryClient","options: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>","options: DefineMutationInput<TData, TError, TVariables, TContext>","variables: TVariables","options: MutationOptions<TData, TError, TVariables, TContext>"],"sources":["../../src/query/utils.ts"],"sourcesContent":["import type {\n\tDefaultError,\n\tMutationFunction,\n\tMutationKey,\n\tMutationOptions,\n\tQueryClient,\n\tQueryFunction,\n\tQueryKey,\n\tQueryObserverOptions,\n} from \"@tanstack/query-core\";\nimport { Err, Ok, type Result, resolve } from \"../result/index.js\";\n\n/**\n * Input options for defining a query.\n *\n * Extends TanStack Query's QueryObserverOptions but expects queryFn to return a Result type.\n * This type represents the configuration for creating a query definition with both\n * reactive and imperative interfaces for data fetching.\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n */\ntype DefineQueryInput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = Omit<\n\tQueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n\t\"queryFn\"\n> & {\n\tqueryKey: TQueryKey;\n\tqueryFn: QueryFunction<Result<TQueryFnData, TError>, TQueryKey>;\n};\n\n/**\n * Output of defineQuery function.\n *\n * The query definition is directly callable and defaults to `ensure()` behavior,\n * which is recommended for most imperative use cases like preloaders.\n *\n * Provides both reactive and imperative interfaces for data fetching:\n * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n * - `options`: Returns config for use with useQuery() or createQuery()\n * - `fetch()`: Always attempts to fetch data (from cache if fresh, network if stale)\n * - `ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n *\n * @template TQueryFnData - The type of data returned by the query function\n * @template TError - The type of error that can be thrown\n * @template TData - The type of data returned by the query (after select transform)\n * @template TQueryKey - The type of the query key\n *\n * @example\n * ```typescript\n * const userQuery = defineQuery({...});\n *\n * // Directly callable (same as .ensure())\n * const { data, error } = await userQuery();\n *\n * // Or use explicit methods\n * const { data, error } = await userQuery.ensure();\n * const { data, error } = await userQuery.fetch();\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n * ```\n */\ntype DefineQueryOutput<\n\tTQueryFnData = unknown,\n\tTError = DefaultError,\n\tTData = TQueryFnData,\n\tTQueryData = TQueryFnData,\n\tTQueryKey extends QueryKey = QueryKey,\n> = (() => Promise<Result<TQueryData, TError>>) & {\n\toptions: QueryObserverOptions<\n\t\tTQueryFnData,\n\t\tTError,\n\t\tTData,\n\t\tTQueryData,\n\t\tTQueryKey\n\t>;\n\tfetch: () => Promise<Result<TQueryData, TError>>;\n\tensure: () => Promise<Result<TQueryData, TError>>;\n};\n\n/**\n * Input options for defining a mutation.\n *\n * Extends TanStack Query's MutationOptions but expects mutationFn to return a Result type.\n * This type represents the configuration for creating a mutation definition with both\n * reactive and imperative interfaces for data mutations.\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n */\ntype DefineMutationInput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = Omit<MutationOptions<TData, TError, TVariables, TContext>, \"mutationFn\"> & {\n\tmutationKey: MutationKey;\n\tmutationFn: MutationFunction<Result<TData, TError>, TVariables>;\n};\n\n/**\n * Output of defineMutation function.\n *\n * The mutation definition is directly callable, which executes the mutation\n * and returns a Result. This is equivalent to calling `.execute()`.\n *\n * Provides both reactive and imperative interfaces for data mutations:\n * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n * - `options`: Returns config for use with useMutation() or createMutation()\n * - `execute(variables)`: Directly executes the mutation and returns a Result\n *\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data for optimistic updates\n *\n * @example\n * ```typescript\n * const createUser = defineMutation({...});\n *\n * // Directly callable (same as .execute())\n * const { data, error } = await createUser({ name: 'John' });\n *\n * // Or use explicit method\n * const { data, error } = await createUser.execute({ name: 'John' });\n *\n * // For reactive usage (Svelte 5 requires accessor wrapper)\n * const mutation = createMutation(() => createUser.options); // Svelte 5\n * const mutation = useMutation(createUser.options); // React\n * ```\n */\ntype DefineMutationOutput<\n\tTData,\n\tTError,\n\tTVariables = void,\n\tTContext = unknown,\n> = ((variables: TVariables) => Promise<Result<TData, TError>>) & {\n\toptions: MutationOptions<TData, TError, TVariables, TContext>;\n\texecute: (variables: TVariables) => Promise<Result<TData, TError>>;\n};\n\n/**\n * Creates factory functions for defining queries and mutations bound to a specific QueryClient.\n *\n * This factory pattern allows you to create isolated query/mutation definitions that are\n * bound to a specific QueryClient instance, enabling:\n * - Multiple query clients in the same application\n * - Testing with isolated query clients\n * - Framework-agnostic query definitions\n * - Proper separation of concerns between query logic and client instances\n *\n * The returned functions handle Result types automatically, unwrapping them for TanStack Query\n * while maintaining type safety throughout your application.\n *\n * @param queryClient - The QueryClient instance to bind the factories to\n * @returns An object containing defineQuery and defineMutation functions bound to the provided client\n *\n * @example\n * ```typescript\n * // Create your query client\n * const queryClient = new QueryClient({\n * defaultOptions: {\n * queries: { staleTime: 5 * 60 * 1000 }\n * }\n * });\n *\n * // Create the factory functions\n * const { defineQuery, defineMutation } = createQueryFactories(queryClient);\n *\n * // Now use defineQuery and defineMutation as before\n * const userQuery = defineQuery({\n * queryKey: ['user', userId],\n * queryFn: () => services.getUser(userId)\n * });\n *\n * // Use in components (Svelte 5 requires accessor wrapper)\n * const query = createQuery(() => userQuery.options); // Svelte 5\n * const query = useQuery(userQuery.options); // React\n *\n * // Or imperatively\n * const { data, error } = await userQuery.fetch();\n * ```\n */\nexport function createQueryFactories(queryClient: QueryClient) {\n\t/**\n\t * Creates a query definition that bridges the gap between pure service functions and reactive UI components.\n\t *\n\t * This factory function is the cornerstone of our data fetching architecture. It wraps service calls\n\t * with TanStack Query superpowers while maintaining type safety through Result types.\n\t *\n\t * The returned query definition is **directly callable** and defaults to `ensure()` behavior,\n\t * which is recommended for most imperative use cases like preloaders.\n\t *\n\t * ## Why use defineQuery?\n\t *\n\t * 1. **Callable**: Call directly like `userQuery()` for imperative data fetching\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.fetch()`, `.ensure()`) APIs\n\t * 3. **Automatic Error Handling**: Service functions return `Result<T, E>` types which are automatically\n\t * unwrapped by TanStack Query, giving you proper error states in your components\n\t * 4. **Type Safety**: Full TypeScript support with proper inference for data and error types\n\t * 5. **Consistency**: Every query in the app follows the same pattern, making it easy to understand\n\t *\n\t * @template TQueryFnData - The type of data returned by the query function\n\t * @template TError - The type of error that can be thrown\n\t * @template TData - The type of data returned by the query (after select transform)\n\t * @template TQueryKey - The type of the query key\n\t *\n\t * @param options - Query configuration object\n\t * @param options.queryKey - Unique key for this query (used for caching and refetching)\n\t * @param options.queryFn - Function that fetches data and returns a Result type\n\t * @param options.* - Any other TanStack Query options (staleTime, refetchInterval, etc.)\n\t *\n\t * @returns Callable query definition with:\n\t * - `()` (callable): Same as `ensure()` - returns cached data if available, fetches if not\n\t * - `.options`: Config for use with useQuery() or createQuery()\n\t * - `.fetch()`: Always attempts to fetch (from cache if fresh, network if stale)\n\t * - `.ensure()`: Guarantees data availability, preferring cached data (recommended for preloaders)\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your query in the query layer\n\t * const userQuery = defineQuery({\n\t * queryKey: ['users', userId],\n\t * queryFn: () => services.getUser(userId), // Returns Result<User, ApiError>\n\t * staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const query = createQuery(() => userQuery.options);\n\t * // query.data is User | undefined\n\t * // query.error is ApiError | null\n\t *\n\t * // Step 2b: Call directly in preloaders (recommended)\n\t * export const load = async () => {\n\t * const { data, error } = await userQuery(); // Same as userQuery.ensure()\n\t * if (error) throw error;\n\t * return { user: data };\n\t * };\n\t *\n\t * // Step 2c: Use explicit methods when needed\n\t * async function refreshUser() {\n\t * const { data, error } = await userQuery.fetch(); // Force fresh fetch\n\t * if (error) {\n\t * console.error('Failed to fetch user:', error);\n\t * }\n\t * }\n\t * ```\n\t */\n\tconst defineQuery = <\n\t\tTQueryFnData = unknown,\n\t\tTError = DefaultError,\n\t\tTData = TQueryFnData,\n\t\tTQueryData = TQueryFnData,\n\t\tTQueryKey extends QueryKey = QueryKey,\n\t>(\n\t\toptions: DefineQueryInput<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>,\n\t): DefineQueryOutput<TQueryFnData, TError, TData, TQueryData, TQueryKey> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tqueryFn: async (context) => {\n\t\t\t\tlet result = options.queryFn(context);\n\t\t\t\tif (result instanceof Promise) result = await result;\n\t\t\t\treturn resolve(result);\n\t\t\t},\n\t\t} satisfies QueryObserverOptions<\n\t\t\tTQueryFnData,\n\t\t\tTError,\n\t\t\tTData,\n\t\t\tTQueryData,\n\t\t\tTQueryKey\n\t\t>;\n\n\t\t/**\n\t\t * Fetches data for this query using queryClient.fetchQuery().\n\t\t *\n\t\t * This method ALWAYS evaluates freshness and will refetch if data is stale.\n\t\t * It wraps TanStack Query's fetchQuery method, which returns cached data if fresh\n\t\t * or makes a network request if the data is stale or missing.\n\t\t *\n\t\t * **When to use fetch():**\n\t\t * - When you explicitly want to check data freshness\n\t\t * - For user-triggered refresh actions\n\t\t * - When you need the most up-to-date data\n\t\t *\n\t\t * **For preloaders, use ensure() instead** - it's more efficient for initial data loading.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Good for user-triggered refresh\n\t\t * const { data, error } = await userQuery.fetch();\n\t\t * if (error) {\n\t\t * console.error('Failed to load user:', error);\n\t\t * }\n\t\t */\n\t\tasync function fetch(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.fetchQuery<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Ensures data is available for this query using queryClient.ensureQueryData().\n\t\t *\n\t\t * This method PRIORITIZES cached data and only calls fetchQuery internally if no cached\n\t\t * data exists. It wraps TanStack Query's ensureQueryData method, which is perfect for\n\t\t * guaranteeing data availability with minimal network requests.\n\t\t *\n\t\t * **This is the RECOMMENDED method for preloaders** because:\n\t\t * - It returns cached data immediately if available\n\t\t * - It updates the query client cache properly\n\t\t * - It minimizes network requests during navigation\n\t\t * - It ensures components have data ready when they mount\n\t\t *\n\t\t * **When to use ensure():**\n\t\t * - Route preloaders and data loading functions\n\t\t * - Initial component data requirements\n\t\t * - When cached data is acceptable for immediate display\n\t\t *\n\t\t * This is also the default behavior when calling the query directly.\n\t\t *\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // Perfect for preloaders\n\t\t * export const load = async () => {\n\t\t * const { data, error } = await userQuery.ensure();\n\t\t * // Or simply: await userQuery();\n\t\t * if (error) {\n\t\t * throw error;\n\t\t * }\n\t\t * return { user: data };\n\t\t * };\n\t\t */\n\t\tasync function ensure(): Promise<Result<TQueryData, TError>> {\n\t\t\ttry {\n\t\t\t\treturn Ok(\n\t\t\t\t\tawait queryClient.ensureQueryData<\n\t\t\t\t\t\tTQueryFnData,\n\t\t\t\t\t\tTError,\n\t\t\t\t\t\tTQueryData,\n\t\t\t\t\t\tTQueryKey\n\t\t\t\t\t>({\n\t\t\t\t\t\tqueryKey: newOptions.queryKey,\n\t\t\t\t\t\tqueryFn: newOptions.queryFn,\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that defaults to ensure() behavior\n\t\t// and attach options, fetch, and ensure as properties\n\t\treturn Object.assign(ensure, {\n\t\t\toptions: newOptions,\n\t\t\tfetch,\n\t\t\tensure,\n\t\t});\n\t};\n\n\t/**\n\t * Creates a mutation definition for operations that modify data (create, update, delete).\n\t *\n\t * This factory function is the mutation counterpart to defineQuery. It provides a clean way to\n\t * wrap service functions that perform side effects, while maintaining the same dual interface\n\t * pattern for maximum flexibility.\n\t *\n\t * The returned mutation definition is **directly callable**, which executes the mutation\n\t * and returns a Result. This is equivalent to calling `.execute()`.\n\t *\n\t * ## Why use defineMutation?\n\t *\n\t * 1. **Callable**: Call directly like `createUser({ name: 'John' })` for imperative execution\n\t * 2. **Dual Interface**: Also provides reactive (`.options`) and explicit imperative (`.execute()`) APIs\n\t * 3. **Consistent Error Handling**: Service functions return `Result<T, E>` types, ensuring\n\t * errors are handled consistently throughout the app\n\t * 4. **Cache Management**: Mutations often update the cache after success (see examples)\n\t *\n\t * @template TData - The type of data returned by the mutation\n\t * @template TError - The type of error that can be thrown\n\t * @template TVariables - The type of variables passed to the mutation\n\t * @template TContext - The type of context data for optimistic updates\n\t *\n\t * @param options - Mutation configuration object\n\t * @param options.mutationKey - Unique key for this mutation (used for tracking in-flight state)\n\t * @param options.mutationFn - Function that performs the mutation and returns a Result type\n\t * @param options.* - Any other TanStack Mutation options (onSuccess, onError, etc.)\n\t *\n\t * @returns Callable mutation definition with:\n\t * - `(variables)` (callable): Same as `execute()` - directly executes the mutation\n\t * - `.options`: Config for use with useMutation() or createMutation()\n\t * - `.execute(variables)`: Directly executes the mutation and returns a Result\n\t *\n\t * @example\n\t * ```typescript\n\t * // Step 1: Define your mutation with cache updates\n\t * const createRecording = defineMutation({\n\t * mutationKey: ['recordings', 'create'],\n\t * mutationFn: async (recording: Recording) => {\n\t * // Call the service\n\t * const result = await services.db.createRecording(recording);\n\t * if (result.error) return Err(result.error);\n\t *\n\t * // Update cache on success\n\t * queryClient.setQueryData(['recordings'], (old) =>\n\t * [...(old || []), recording]\n\t * );\n\t *\n\t * return Ok(result.data);\n\t * }\n\t * });\n\t *\n\t * // Step 2a: Use reactively in a Svelte 5 component (accessor wrapper required)\n\t * const mutation = createMutation(() => createRecording.options);\n\t * // Call with: mutation.mutate(recordingData)\n\t *\n\t * // Step 2b: Call directly in an action (recommended)\n\t * async function saveRecording(data: Recording) {\n\t * const { error } = await createRecording(data); // Same as createRecording.execute(data)\n\t * if (error) {\n\t * notify.error({ title: 'Failed to save', description: error.message });\n\t * } else {\n\t * notify.success({ title: 'Recording saved!' });\n\t * }\n\t * }\n\t * ```\n\t *\n\t * @tip Calling directly is especially useful for:\n\t * - Event handlers that need to await the result\n\t * - Sequential operations that depend on each other\n\t * - Non-component code that needs to trigger mutations\n\t */\n\tconst defineMutation = <TData, TError, TVariables = void, TContext = unknown>(\n\t\toptions: DefineMutationInput<TData, TError, TVariables, TContext>,\n\t): DefineMutationOutput<TData, TError, TVariables, TContext> => {\n\t\tconst newOptions = {\n\t\t\t...options,\n\t\t\tmutationFn: async (variables: TVariables) => {\n\t\t\t\treturn resolve(await options.mutationFn(variables));\n\t\t\t},\n\t\t} satisfies MutationOptions<TData, TError, TVariables, TContext>;\n\n\t\t/**\n\t\t * Executes the mutation imperatively and returns a Result.\n\t\t *\n\t\t * This is the recommended way to trigger mutations from:\n\t\t * - Button click handlers\n\t\t * - Form submissions\n\t\t * - Keyboard shortcuts\n\t\t * - Any non-component code\n\t\t *\n\t\t * The method automatically wraps the result in a Result type, so you always\n\t\t * get back `{ data, error }` for consistent error handling.\n\t\t *\n\t\t * This is also the default behavior when calling the mutation directly.\n\t\t *\n\t\t * @param variables - The variables to pass to the mutation function\n\t\t * @returns Promise that resolves with a Result containing either the data or an error\n\t\t *\n\t\t * @example\n\t\t * // In an event handler\n\t\t * async function handleSubmit(formData: FormData) {\n\t\t * const { data, error } = await createUser.execute(formData);\n\t\t * // Or simply: await createUser(formData);\n\t\t * if (error) {\n\t\t * notify.error({ title: 'Failed to create user', description: error.message });\n\t\t * return;\n\t\t * }\n\t\t * goto(`/users/${data.id}`);\n\t\t * }\n\t\t */\n\t\tasync function execute(variables: TVariables) {\n\t\t\ttry {\n\t\t\t\treturn Ok(await runMutation(queryClient, newOptions, variables));\n\t\t\t} catch (error) {\n\t\t\t\treturn Err(error as TError);\n\t\t\t}\n\t\t}\n\n\t\t// Create a callable function that executes the mutation\n\t\t// and attach options and execute as properties\n\t\treturn Object.assign(execute, {\n\t\t\toptions: newOptions,\n\t\t\texecute,\n\t\t});\n\t};\n\n\treturn {\n\t\tdefineQuery,\n\t\tdefineMutation,\n\t};\n}\n\n/**\n * Internal helper that executes a mutation directly using the query client's mutation cache.\n *\n * This is what powers the callable behavior and `.execute()` method on mutations.\n * It bypasses the reactive mutation hooks and runs the mutation imperatively,\n * which is perfect for event handlers and other imperative code.\n *\n * @internal\n * @template TData - The type of data returned by the mutation\n * @template TError - The type of error that can be thrown\n * @template TVariables - The type of variables passed to the mutation\n * @template TContext - The type of context data\n * @param queryClient - The query client instance to use\n * @param options - The mutation options including mutationFn and mutationKey\n * @param variables - The variables to pass to the mutation function\n * @returns Promise that resolves with the mutation result\n */\nfunction runMutation<TData, TError, TVariables, TContext>(\n\tqueryClient: QueryClient,\n\toptions: MutationOptions<TData, TError, TVariables, TContext>,\n\tvariables: TVariables,\n) {\n\tconst mutation = queryClient.getMutationCache().build(queryClient, options);\n\treturn mutation.execute(variables);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkMA,SAAgB,qBAAqBA,aAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiE9D,MAAM,cAAc,CAOnBC,YAO2E;EAC3E,MAAM,aAAa;GAClB,GAAG;GACH,SAAS,OAAO,YAAY;IAC3B,IAAI,SAAS,QAAQ,QAAQ,QAAQ;AACrC,QAAI,kBAAkB,QAAS,UAAS,MAAM;AAC9C,WAAO,QAAQ,OAAO;GACtB;EACD;;;;;;;;;;;;;;;;;;;;;;;;EA+BD,eAAe,QAA6C;AAC3D,OAAI;AACH,WAAO,GACN,MAAM,YAAY,WAKhB;KACD,UAAU,WAAW;KACrB,SAAS,WAAW;IACpB,EAAC,CACF;GACD,SAAQ,OAAO;AACf,WAAO,IAAI,MAAgB;GAC3B;EACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmCD,eAAe,SAA8C;AAC5D,OAAI;AACH,WAAO,GACN,MAAM,YAAY,gBAKhB;KACD,UAAU,WAAW;KACrB,SAAS,WAAW;IACpB,EAAC,CACF;GACD,SAAQ,OAAO;AACf,WAAO,IAAI,MAAgB;GAC3B;EACD;AAID,SAAO,OAAO,OAAO,QAAQ;GAC5B,SAAS;GACT;GACA;EACA,EAAC;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0ED,MAAM,iBAAiB,CACtBC,YAC+D;EAC/D,MAAM,aAAa;GAClB,GAAG;GACH,YAAY,OAAOC,cAA0B;AAC5C,WAAO,QAAQ,MAAM,QAAQ,WAAW,UAAU,CAAC;GACnD;EACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+BD,eAAe,QAAQA,WAAuB;AAC7C,OAAI;AACH,WAAO,GAAG,MAAM,YAAY,aAAa,YAAY,UAAU,CAAC;GAChE,SAAQ,OAAO;AACf,WAAO,IAAI,MAAgB;GAC3B;EACD;AAID,SAAO,OAAO,OAAO,SAAS;GAC7B,SAAS;GACT;EACA,EAAC;CACF;AAED,QAAO;EACN;EACA;CACA;AACD;;;;;;;;;;;;;;;;;;AAmBD,SAAS,YACRH,aACAI,SACAD,WACC;CACD,MAAM,WAAW,YAAY,kBAAkB,CAAC,MAAM,aAAa,QAAQ;AAC3E,QAAO,SAAS,QAAQ,UAAU;AAClC"}
|
package/dist/result/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { Err,
|
|
2
|
-
import { partitionResults } from "../index-
|
|
3
|
-
export { Err,
|
|
1
|
+
import { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap } from "../result-BgPMmUXd.js";
|
|
2
|
+
import { partitionResults } from "../index-8WW9UMob.js";
|
|
3
|
+
export { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, partitionResults, resolve, tryAsync, trySync, unwrap };
|
|
@@ -97,30 +97,6 @@ declare const Ok: <T>(data: T) => Ok<T>;
|
|
|
97
97
|
* ```
|
|
98
98
|
*/
|
|
99
99
|
declare const Err: <E>(error: E) => Err<E>;
|
|
100
|
-
/**
|
|
101
|
-
* Utility type to extract the `Ok<T>` variant from a `Result<T, E>` union type.
|
|
102
|
-
*
|
|
103
|
-
* If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve
|
|
104
|
-
* to `Ok<string>`. This can be useful in generic contexts or for type narrowing.
|
|
105
|
-
*
|
|
106
|
-
* @template R - The `Result<T, E>` union type from which to extract the `Ok<T>` variant.
|
|
107
|
-
* Must extend `Result<unknown, unknown>`.
|
|
108
|
-
*/
|
|
109
|
-
type ExtractOkFromResult<R extends Result<unknown, unknown>> = Extract<R, {
|
|
110
|
-
error: null;
|
|
111
|
-
}>;
|
|
112
|
-
/**
|
|
113
|
-
* Utility type to extract the `Err<E>` variant from a `Result<T, E>` union type.
|
|
114
|
-
*
|
|
115
|
-
* If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve
|
|
116
|
-
* to `Err<Error>`. This can be useful in generic contexts or for type narrowing.
|
|
117
|
-
*
|
|
118
|
-
* @template R - The `Result<T, E>` union type from which to extract the `Err<E>` variant.
|
|
119
|
-
* Must extend `Result<unknown, unknown>`.
|
|
120
|
-
*/
|
|
121
|
-
type ExtractErrFromResult<R extends Result<unknown, unknown>> = Extract<R, {
|
|
122
|
-
data: null;
|
|
123
|
-
}>;
|
|
124
100
|
/**
|
|
125
101
|
* Utility type to extract the success value's type `T` from a `Result<T, E>` type.
|
|
126
102
|
*
|
|
@@ -447,5 +423,5 @@ declare function unwrap<T, E>(result: Result<T, E>): T;
|
|
|
447
423
|
declare function resolve<T, E>(value: T | Result<T, E>): T;
|
|
448
424
|
//# sourceMappingURL=result.d.ts.map
|
|
449
425
|
//#endregion
|
|
450
|
-
export { Err,
|
|
451
|
-
//# sourceMappingURL=result-
|
|
426
|
+
export { Err, Ok, Result, UnwrapErr, UnwrapOk, isErr, isOk, isResult, resolve, tryAsync, trySync, unwrap };
|
|
427
|
+
//# sourceMappingURL=result-BgPMmUXd.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"result-BgPMmUXd.d.ts","names":[],"sources":["../src/result/result.ts"],"sourcesContent":[],"mappings":";;AAWA;AAaA;AAqCA;;;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;;;;;;;;;;iBAyB/C,oBAAoB,OAAO,GAAG,eAAe,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgDjD;aACJ;6BACgB,GAAG;IAC3B,GAAG;iBAES;aACJ;6BACgB,IAAI;IAC5B,OAAO,GAAG;iBAEE;aACJ;6BACgB,GAAG,KAAK,IAAI;IACpC,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiEQ;aACV,QAAQ;6BACQ,GAAG;IAC3B,QAAQ,GAAG;iBAEO;aACV,QAAQ;6BACQ,IAAI;IAC5B,QAAQ,OAAO,GAAG;iBAEA;aACV,QAAQ;6BACQ,GAAG,KAAK,IAAI;IACpC,QAAQ,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+GN,qBAAqB,OAAO,GAAG,KAAK;iBAOpC,qBAAqB,IAAI,OAAO,GAAG,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"result-DnOm5ds5.js","names":["data: T","error: E","value: unknown","result: Result<T, E>","value: T | Result<T, E>"],"sources":["../src/result/result.ts"],"sourcesContent":["/**\n * Represents the successful outcome of an operation, encapsulating the success value.\n *\n * This is the 'Ok' variant of the `Result` type. It holds a `data` property\n * of type `T` (the success value) and an `error` property explicitly set to `null`,\n * signifying no error occurred.\n *\n * Use this type in conjunction with `Err<E>` and `Result<T, E>`.\n *\n * @template T - The type of the success value contained within.\n */\nexport type Ok<T> = { data: T; error: null };\n\n/**\n * Represents the failure outcome of an operation, encapsulating the error value.\n *\n * This is the 'Err' variant of the `Result` type. It holds an `error` property\n * of type `E` (the error value) and a `data` property explicitly set to `null`,\n * signifying that no success value is present due to the failure.\n *\n * Use this type in conjunction with `Ok<T>` and `Result<T, E>`.\n *\n * @template E - The type of the error value contained within.\n */\nexport type Err<E> = { error: E; data: null };\n\n/**\n * A type that represents the outcome of an operation that can either succeed or fail.\n *\n * `Result<T, E>` is a discriminated union type with two possible variants:\n * - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.\n * In this case, the `error` field is `null`.\n * - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.\n * In this case, the `data` field is `null`.\n *\n * This type promotes explicit error handling by requiring developers to check\n * the variant of the `Result` before accessing its potential value or error.\n * It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).\n *\n * @template T - The type of the success value if the operation is successful (held in `Ok<T>`).\n * @template E - The type of the error value if the operation fails (held in `Err<E>`).\n * @example\n * ```ts\n * function divide(numerator: number, denominator: number): Result<number, string> {\n * if (denominator === 0) {\n * return Err(\"Cannot divide by zero\");\n * }\n * return Ok(numerator / denominator);\n * }\n *\n * const result1 = divide(10, 2);\n * if (isOk(result1)) {\n * console.log(\"Success:\", result1.data); // Output: Success: 5\n * }\n *\n * const result2 = divide(10, 0);\n * if (isErr(result2)) {\n * console.error(\"Failure:\", result2.error); // Output: Failure: Cannot divide by zero\n * }\n * ```\n */\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Constructs an `Ok<T>` variant, representing a successful outcome.\n *\n * This factory function creates the success variant of a `Result`.\n * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.\n *\n * @template T - The type of the success value.\n * @param data - The success value to be wrapped in the `Ok` variant.\n * @returns An `Ok<T>` object with the provided data and `error` set to `null`.\n * @example\n * ```ts\n * const successfulResult = Ok(\"Operation completed successfully\");\n * // successfulResult is { data: \"Operation completed successfully\", error: null }\n * ```\n */\nexport const Ok = <T>(data: T): Ok<T> => ({ data, error: null });\n\n/**\n * Constructs an `Err<E>` variant, representing a failure outcome.\n *\n * This factory function creates the error variant of a `Result`.\n * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.\n *\n * @template E - The type of the error value.\n * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.\n * @returns An `Err<E>` object with the provided error and `data` set to `null`.\n * @example\n * ```ts\n * const failedResult = Err(new TypeError(\"Invalid input\"));\n * // failedResult is { error: TypeError(\"Invalid input\"), data: null }\n * ```\n */\nexport const Err = <E>(error: E): Err<E> => ({ error, data: null });\n\n/**\n * Utility type to extract the `Ok<T>` variant from a `Result<T, E>` union type.\n *\n * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve\n * to `Ok<string>`. This can be useful in generic contexts or for type narrowing.\n *\n * @template R - The `Result<T, E>` union type from which to extract the `Ok<T>` variant.\n * Must extend `Result<unknown, unknown>`.\n */\nexport type ExtractOkFromResult<R extends Result<unknown, unknown>> = Extract<\n\tR,\n\t{ error: null }\n>;\n\n/**\n * Utility type to extract the `Err<E>` variant from a `Result<T, E>` union type.\n *\n * If `R` is a `Result` type (e.g., `Result<string, Error>`), this type will resolve\n * to `Err<Error>`. This can be useful in generic contexts or for type narrowing.\n *\n * @template R - The `Result<T, E>` union type from which to extract the `Err<E>` variant.\n * Must extend `Result<unknown, unknown>`.\n */\nexport type ExtractErrFromResult<R extends Result<unknown, unknown>> = Extract<\n\tR,\n\t{ data: null }\n>;\n\n/**\n * Utility type to extract the success value's type `T` from a `Result<T, E>` type.\n *\n * If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),\n * this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `data` field when you know you have a success.\n *\n * @template R - The `Result<T, E>` type from which to extract the success value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number\n *\n * type MyErrorResult = Err<string>;\n * type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never\n * ```\n */\nexport type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>\n\t? U\n\t: never;\n\n/**\n * Utility type to extract the error value's type `E` from a `Result<T, E>` type.\n *\n * If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),\n * this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `error` field when you know you have a failure.\n *\n * @template R - The `Result<T, E>` type from which to extract the error value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string\n *\n * type MySuccessResult = Ok<number>;\n * type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never\n * ```\n */\nexport type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<\n\tinfer E\n>\n\t? E\n\t: never;\n\n/**\n * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.\n *\n * A value is considered a valid `Result` if:\n * 1. It is a non-null object.\n * 2. It has both `data` and `error` properties.\n * 3. At least one of the `data` or `error` channels is `null`. Both being `null` represents `Ok(null)`.\n *\n * This function does not validate the types of `data` or `error` beyond `null` checks.\n *\n * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).\n * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).\n * @param value - The value to check.\n * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.\n * @example\n * ```ts\n * declare const someValue: unknown;\n *\n * if (isResult<string, Error>(someValue)) {\n * // someValue is now typed as Result<string, Error>\n * if (isOk(someValue)) {\n * console.log(someValue.data); // string\n * } else {\n * console.error(someValue.error); // Error\n * }\n * }\n * ```\n */\nexport function isResult<T = unknown, E = unknown>(\n\tvalue: unknown,\n): value is Result<T, E> {\n\tconst isNonNullObject = typeof value === \"object\" && value !== null;\n\tif (!isNonNullObject) return false;\n\n\tconst hasDataProperty = \"data\" in value;\n\tconst hasErrorProperty = \"error\" in value;\n\tif (!hasDataProperty || !hasErrorProperty) return false;\n\n\treturn true;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.\n *\n * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.\n * An `Ok<T>` variant is identified by its `error` property being `null`.\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isOk(myResult)) {\n * // myResult is now typed as Ok<number>\n * console.log(\"Success value:\", myResult.data); // myResult.data is number\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.error === null;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.\n *\n * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.\n * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isErr(myResult)) {\n * // myResult is now typed as Err<string>\n * console.error(\"Error value:\", myResult.error); // myResult.error is string\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.error !== null; // Equivalent to result.data === null\n}\n\n/**\n * Executes a synchronous operation and wraps its outcome in a Result type.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation completes successfully, its return value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation throws an exception, the caught exception (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically narrowed based on what your catch function returns:\n * - If catch always returns `Ok<T>`, the function returns `Ok<T>` (guaranteed success)\n * - If catch always returns `Err<E>`, the function returns `Result<T, E>` (may succeed or fail)\n * - If catch can return either `Ok<T>` or `Err<E>`, the function returns `Result<T, E>` (conditional recovery)\n *\n * @template T - The success value type\n * @template E - The error value type (when catch can return errors)\n * @param options - Configuration object\n * @param options.try - The operation to execute\n * @param options.catch - Error handler that transforms caught exceptions into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Ok<T>` if catch always returns Ok (recovery), otherwise `Result<T, E>` (propagation or conditional recovery)\n *\n * @example\n * ```ts\n * // Returns Ok<string> - guaranteed success since catch always returns Ok\n * const alwaysOk = trySync({\n * try: () => JSON.parse(input),\n * catch: () => Ok(\"fallback\") // Always Ok<T>\n * });\n *\n * // Returns Result<object, string> - may fail since catch always returns Err\n * const mayFail = trySync({\n * try: () => JSON.parse(input),\n * catch: (err) => Err(\"Parse failed\") // Returns Err<E>\n * });\n *\n * // Returns Result<void, MyError> - conditional recovery based on error type\n * const conditional = trySync({\n * try: () => riskyOperation(),\n * catch: (err) => {\n * if (isRecoverable(err)) return Ok(undefined);\n * return MyErr({ message: \"Unrecoverable\" });\n * }\n * });\n * ```\n */\nexport function trySync<T>(options: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Ok<T>;\n}): Ok<T>;\n\nexport function trySync<T, E>(options: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Err<E>;\n}): Result<T, E>;\n\nexport function trySync<T, E>(options: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Result<T, E>;\n\nexport function trySync<T, E>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Ok<T> | Result<T, E> {\n\ttry {\n\t\tconst data = operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Executes an asynchronous operation and wraps its outcome in a Promise<Result>.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation rejects or throws an exception, the caught error (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically narrowed based on what your catch function returns:\n * - If catch always returns `Ok<T>`, the function returns `Promise<Ok<T>>` (guaranteed success)\n * - If catch always returns `Err<E>`, the function returns `Promise<Result<T, E>>` (may succeed or fail)\n * - If catch can return either `Ok<T>` or `Err<E>`, the function returns `Promise<Result<T, E>>` (conditional recovery)\n *\n * @template T - The success value type\n * @template E - The error value type (when catch can return errors)\n * @param options - Configuration object\n * @param options.try - The async operation to execute\n * @param options.catch - Error handler that transforms caught exceptions/rejections into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Promise<Ok<T>>` if catch always returns Ok (recovery), otherwise `Promise<Result<T, E>>` (propagation or conditional recovery)\n *\n * @example\n * ```ts\n * // Returns Promise<Ok<Response>> - guaranteed success since catch always returns Ok\n * const alwaysOk = tryAsync({\n * try: async () => fetch(url),\n * catch: () => Ok(new Response()) // Always Ok<T>\n * });\n *\n * // Returns Promise<Result<Response, Error>> - may fail since catch always returns Err\n * const mayFail = tryAsync({\n * try: async () => fetch(url),\n * catch: (err) => Err(new Error(\"Fetch failed\")) // Returns Err<E>\n * });\n *\n * // Returns Promise<Result<void, BlobError>> - conditional recovery based on error type\n * const conditional = await tryAsync({\n * try: async () => {\n * await deleteFile(filename);\n * },\n * catch: (err) => {\n * if ((err as { name?: string }).name === 'NotFoundError') {\n * return Ok(undefined); // Already deleted, that's fine\n * }\n * return BlobErr({ message: \"Delete failed\" });\n * }\n * });\n * ```\n */\nexport async function tryAsync<T>(options: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Ok<T>;\n}): Promise<Ok<T>>;\n\nexport async function tryAsync<T, E>(options: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Err<E>;\n}): Promise<Result<T, E>>;\n\nexport async function tryAsync<T, E>(options: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Promise<Result<T, E>>;\n\nexport async function tryAsync<T, E>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Promise<Ok<T> | Result<T, E>> {\n\ttry {\n\t\tconst data = await operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.\n *\n * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:\n * - If `value` is an `Ok<T>` variant, returns the contained success value.\n * - If `value` is an `Err<E>` variant, throws the contained error value.\n * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),\n * returns it as-is.\n *\n * This is useful when working with APIs that might return either direct values or Results,\n * allowing you to normalize them to the actual value or propagate errors via throwing.\n *\n * Use `resolve` when the input might or might not be a Result.\n * Use `unwrap` when you know the input is definitely a Result.\n *\n * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.\n * @template E - The type of the error value (if `value` is `Err<E>`).\n * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.\n * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.\n * @throws The error value `E` if `value` is an `Err<E>` variant.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const resolved = resolve(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"failure\"));\n * try {\n * resolve(errResult);\n * } catch (e) {\n * console.error(e.message); // \"failure\"\n * }\n *\n * // Example with a plain value\n * const plainValue = \"plain data\";\n * const resolved = resolve(plainValue); // \"plain data\"\n *\n * // Example with a function that might return Result or plain value\n * declare function mightReturnResult(): string | Result<string, Error>;\n * const outcome = mightReturnResult();\n * try {\n * const finalValue = resolve(outcome); // handles both cases\n * console.log(\"Final value:\", finalValue);\n * } catch (e) {\n * console.error(\"Operation failed:\", e);\n * }\n * ```\n */\n/**\n * Unwraps a `Result<T, E>`, returning the success value or throwing the error.\n *\n * This function extracts the data from a `Result`:\n * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.\n * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.\n *\n * Unlike `resolve`, this function expects the input to always be a `Result` type,\n * making it more direct for cases where you know you're working with a `Result`.\n *\n * @template T - The type of the success value contained in the `Ok<T>` variant.\n * @template E - The type of the error value contained in the `Err<E>` variant.\n * @param result - The `Result<T, E>` to unwrap.\n * @returns The success value of type `T` if the `Result` is `Ok<T>`.\n * @throws The error value of type `E` if the `Result` is `Err<E>`.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const value = unwrap(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"something went wrong\"));\n * try {\n * unwrap(errResult);\n * } catch (error) {\n * console.error(error.message); // \"something went wrong\"\n * }\n *\n * // Usage in a function that returns Result\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return Err(\"Division by zero\");\n * return Ok(a / b);\n * }\n *\n * try {\n * const result = unwrap(divide(10, 2)); // 5\n * console.log(\"Result:\", result);\n * } catch (error) {\n * console.error(\"Division failed:\", error);\n * }\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n\tif (isOk(result)) {\n\t\treturn result.data;\n\t}\n\tthrow result.error;\n}\n\nexport function resolve<T, E>(value: T | Result<T, E>): T {\n\tif (isResult<T, E>(value)) {\n\t\tif (isOk(value)) {\n\t\t\treturn value.data;\n\t\t}\n\t\t// If it's a Result and not Ok, it must be Err.\n\t\t// The type guard isResult<T,E>(value) and isOk(value) already refine the type.\n\t\t// So, 'value' here is known to be Err<E>.\n\t\tthrow value.error;\n\t}\n\n\t// If it's not a Result type, return the value as-is.\n\t// 'value' here is known to be of type T.\n\treturn value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8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|
+
{"version":3,"file":"result-DnOm5ds5.js","names":["data: T","error: E","value: unknown","result: Result<T, E>","value: T | Result<T, E>"],"sources":["../src/result/result.ts"],"sourcesContent":["/**\n * Represents the successful outcome of an operation, encapsulating the success value.\n *\n * This is the 'Ok' variant of the `Result` type. It holds a `data` property\n * of type `T` (the success value) and an `error` property explicitly set to `null`,\n * signifying no error occurred.\n *\n * Use this type in conjunction with `Err<E>` and `Result<T, E>`.\n *\n * @template T - The type of the success value contained within.\n */\nexport type Ok<T> = { data: T; error: null };\n\n/**\n * Represents the failure outcome of an operation, encapsulating the error value.\n *\n * This is the 'Err' variant of the `Result` type. It holds an `error` property\n * of type `E` (the error value) and a `data` property explicitly set to `null`,\n * signifying that no success value is present due to the failure.\n *\n * Use this type in conjunction with `Ok<T>` and `Result<T, E>`.\n *\n * @template E - The type of the error value contained within.\n */\nexport type Err<E> = { error: E; data: null };\n\n/**\n * A type that represents the outcome of an operation that can either succeed or fail.\n *\n * `Result<T, E>` is a discriminated union type with two possible variants:\n * - `Ok<T>`: Represents a successful outcome, containing a `data` field with the success value of type `T`.\n * In this case, the `error` field is `null`.\n * - `Err<E>`: Represents a failure outcome, containing an `error` field with the error value of type `E`.\n * In this case, the `data` field is `null`.\n *\n * This type promotes explicit error handling by requiring developers to check\n * the variant of the `Result` before accessing its potential value or error.\n * It helps avoid runtime errors often associated with implicit error handling (e.g., relying on `try-catch` for all errors).\n *\n * @template T - The type of the success value if the operation is successful (held in `Ok<T>`).\n * @template E - The type of the error value if the operation fails (held in `Err<E>`).\n * @example\n * ```ts\n * function divide(numerator: number, denominator: number): Result<number, string> {\n * if (denominator === 0) {\n * return Err(\"Cannot divide by zero\");\n * }\n * return Ok(numerator / denominator);\n * }\n *\n * const result1 = divide(10, 2);\n * if (isOk(result1)) {\n * console.log(\"Success:\", result1.data); // Output: Success: 5\n * }\n *\n * const result2 = divide(10, 0);\n * if (isErr(result2)) {\n * console.error(\"Failure:\", result2.error); // Output: Failure: Cannot divide by zero\n * }\n * ```\n */\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n/**\n * Constructs an `Ok<T>` variant, representing a successful outcome.\n *\n * This factory function creates the success variant of a `Result`.\n * It wraps the provided `data` (the success value) and ensures the `error` property is `null`.\n *\n * @template T - The type of the success value.\n * @param data - The success value to be wrapped in the `Ok` variant.\n * @returns An `Ok<T>` object with the provided data and `error` set to `null`.\n * @example\n * ```ts\n * const successfulResult = Ok(\"Operation completed successfully\");\n * // successfulResult is { data: \"Operation completed successfully\", error: null }\n * ```\n */\nexport const Ok = <T>(data: T): Ok<T> => ({ data, error: null });\n\n/**\n * Constructs an `Err<E>` variant, representing a failure outcome.\n *\n * This factory function creates the error variant of a `Result`.\n * It wraps the provided `error` (the error value) and ensures the `data` property is `null`.\n *\n * @template E - The type of the error value.\n * @param error - The error value to be wrapped in the `Err` variant. This value represents the specific error that occurred.\n * @returns An `Err<E>` object with the provided error and `data` set to `null`.\n * @example\n * ```ts\n * const failedResult = Err(new TypeError(\"Invalid input\"));\n * // failedResult is { error: TypeError(\"Invalid input\"), data: null }\n * ```\n */\nexport const Err = <E>(error: E): Err<E> => ({ error, data: null });\n\n/**\n * Utility type to extract the success value's type `T` from a `Result<T, E>` type.\n *\n * If `R` is an `Ok<T>` variant (or a `Result<T, E>` that could be an `Ok<T>`),\n * this type resolves to `T`. If `R` can only be an `Err<E>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `data` field when you know you have a success.\n *\n * @template R - The `Result<T, E>` type from which to extract the success value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type SuccessValueType = UnwrapOk<MyResult>; // SuccessValueType is number\n *\n * type MyErrorResult = Err<string>;\n * type ErrorValueType = UnwrapOk<MyErrorResult>; // ErrorValueType is never\n * ```\n */\nexport type UnwrapOk<R extends Result<unknown, unknown>> = R extends Ok<infer U>\n\t? U\n\t: never;\n\n/**\n * Utility type to extract the error value's type `E` from a `Result<T, E>` type.\n *\n * If `R` is an `Err<E>` variant (or a `Result<T, E>` that could be an `Err<E>`),\n * this type resolves to `E`. If `R` can only be an `Ok<T>` variant, it resolves to `never`.\n * This is useful for obtaining the type of the `error` field when you know you have a failure.\n *\n * @template R - The `Result<T, E>` type from which to extract the error value's type.\n * Must extend `Result<unknown, unknown>`.\n * @example\n * ```ts\n * type MyResult = Result<number, string>;\n * type ErrorValueType = UnwrapErr<MyResult>; // ErrorValueType is string\n *\n * type MySuccessResult = Ok<number>;\n * type SuccessValueType = UnwrapErr<MySuccessResult>; // SuccessValueType is never\n * ```\n */\nexport type UnwrapErr<R extends Result<unknown, unknown>> = R extends Err<\n\tinfer E\n>\n\t? E\n\t: never;\n\n/**\n * Type guard to runtime check if an unknown value is a valid `Result<T, E>`.\n *\n * A value is considered a valid `Result` if:\n * 1. It is a non-null object.\n * 2. It has both `data` and `error` properties.\n * 3. At least one of the `data` or `error` channels is `null`. Both being `null` represents `Ok(null)`.\n *\n * This function does not validate the types of `data` or `error` beyond `null` checks.\n *\n * @template T - The expected type of the success value if the value is an `Ok` variant (defaults to `unknown`).\n * @template E - The expected type of the error value if the value is an `Err` variant (defaults to `unknown`).\n * @param value - The value to check.\n * @returns `true` if the value conforms to the `Result` structure, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `value` to `Result<T, E>`.\n * @example\n * ```ts\n * declare const someValue: unknown;\n *\n * if (isResult<string, Error>(someValue)) {\n * // someValue is now typed as Result<string, Error>\n * if (isOk(someValue)) {\n * console.log(someValue.data); // string\n * } else {\n * console.error(someValue.error); // Error\n * }\n * }\n * ```\n */\nexport function isResult<T = unknown, E = unknown>(\n\tvalue: unknown,\n): value is Result<T, E> {\n\tconst isNonNullObject = typeof value === \"object\" && value !== null;\n\tif (!isNonNullObject) return false;\n\n\tconst hasDataProperty = \"data\" in value;\n\tconst hasErrorProperty = \"error\" in value;\n\tif (!hasDataProperty || !hasErrorProperty) return false;\n\n\treturn true;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Ok<T>` variant.\n *\n * This function narrows the type of a `Result` to `Ok<T>` if it represents a successful outcome.\n * An `Ok<T>` variant is identified by its `error` property being `null`.\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Ok<T>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Ok<T>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isOk(myResult)) {\n * // myResult is now typed as Ok<number>\n * console.log(\"Success value:\", myResult.data); // myResult.data is number\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is Ok<T> {\n\treturn result.error === null;\n}\n\n/**\n * Type guard to runtime check if a `Result<T, E>` is an `Err<E>` variant.\n *\n * This function narrows the type of a `Result` to `Err<E>` if it represents a failure outcome.\n * An `Err<E>` variant is identified by its `error` property being non-`null` (and thus `data` being `null`).\n *\n * @template T - The success value type.\n * @template E - The error value type.\n * @param result - The `Result<T, E>` to check.\n * @returns `true` if the `result` is an `Err<E>` variant, `false` otherwise.\n * If `true`, TypeScript's type system will narrow `result` to `Err<E>`.\n * @example\n * ```ts\n * declare const myResult: Result<number, string>;\n *\n * if (isErr(myResult)) {\n * // myResult is now typed as Err<string>\n * console.error(\"Error value:\", myResult.error); // myResult.error is string\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is Err<E> {\n\treturn result.error !== null; // Equivalent to result.data === null\n}\n\n/**\n * Executes a synchronous operation and wraps its outcome in a Result type.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation completes successfully, its return value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation throws an exception, the caught exception (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically narrowed based on what your catch function returns:\n * - If catch always returns `Ok<T>`, the function returns `Ok<T>` (guaranteed success)\n * - If catch always returns `Err<E>`, the function returns `Result<T, E>` (may succeed or fail)\n * - If catch can return either `Ok<T>` or `Err<E>`, the function returns `Result<T, E>` (conditional recovery)\n *\n * @template T - The success value type\n * @template E - The error value type (when catch can return errors)\n * @param options - Configuration object\n * @param options.try - The operation to execute\n * @param options.catch - Error handler that transforms caught exceptions into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Ok<T>` if catch always returns Ok (recovery), otherwise `Result<T, E>` (propagation or conditional recovery)\n *\n * @example\n * ```ts\n * // Returns Ok<string> - guaranteed success since catch always returns Ok\n * const alwaysOk = trySync({\n * try: () => JSON.parse(input),\n * catch: () => Ok(\"fallback\") // Always Ok<T>\n * });\n *\n * // Returns Result<object, string> - may fail since catch always returns Err\n * const mayFail = trySync({\n * try: () => JSON.parse(input),\n * catch: (err) => Err(\"Parse failed\") // Returns Err<E>\n * });\n *\n * // Returns Result<void, MyError> - conditional recovery based on error type\n * const conditional = trySync({\n * try: () => riskyOperation(),\n * catch: (err) => {\n * if (isRecoverable(err)) return Ok(undefined);\n * return MyErr({ message: \"Unrecoverable\" });\n * }\n * });\n * ```\n */\nexport function trySync<T>(options: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Ok<T>;\n}): Ok<T>;\n\nexport function trySync<T, E>(options: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Err<E>;\n}): Result<T, E>;\n\nexport function trySync<T, E>(options: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Result<T, E>;\n\nexport function trySync<T, E>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => T;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Ok<T> | Result<T, E> {\n\ttry {\n\t\tconst data = operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Executes an asynchronous operation and wraps its outcome in a Promise<Result>.\n *\n * This function attempts to execute the `try` operation:\n * - If the `try` operation resolves successfully, its resolved value is wrapped in an `Ok<T>` variant.\n * - If the `try` operation rejects or throws an exception, the caught error (of type `unknown`) is passed to\n * the `catch` function, which transforms it into either an `Ok<T>` (recovery) or `Err<E>` (propagation).\n *\n * The return type is automatically narrowed based on what your catch function returns:\n * - If catch always returns `Ok<T>`, the function returns `Promise<Ok<T>>` (guaranteed success)\n * - If catch always returns `Err<E>`, the function returns `Promise<Result<T, E>>` (may succeed or fail)\n * - If catch can return either `Ok<T>` or `Err<E>`, the function returns `Promise<Result<T, E>>` (conditional recovery)\n *\n * @template T - The success value type\n * @template E - The error value type (when catch can return errors)\n * @param options - Configuration object\n * @param options.try - The async operation to execute\n * @param options.catch - Error handler that transforms caught exceptions/rejections into either `Ok<T>` (recovery) or `Err<E>` (propagation)\n * @returns `Promise<Ok<T>>` if catch always returns Ok (recovery), otherwise `Promise<Result<T, E>>` (propagation or conditional recovery)\n *\n * @example\n * ```ts\n * // Returns Promise<Ok<Response>> - guaranteed success since catch always returns Ok\n * const alwaysOk = tryAsync({\n * try: async () => fetch(url),\n * catch: () => Ok(new Response()) // Always Ok<T>\n * });\n *\n * // Returns Promise<Result<Response, Error>> - may fail since catch always returns Err\n * const mayFail = tryAsync({\n * try: async () => fetch(url),\n * catch: (err) => Err(new Error(\"Fetch failed\")) // Returns Err<E>\n * });\n *\n * // Returns Promise<Result<void, BlobError>> - conditional recovery based on error type\n * const conditional = await tryAsync({\n * try: async () => {\n * await deleteFile(filename);\n * },\n * catch: (err) => {\n * if ((err as { name?: string }).name === 'NotFoundError') {\n * return Ok(undefined); // Already deleted, that's fine\n * }\n * return BlobErr({ message: \"Delete failed\" });\n * }\n * });\n * ```\n */\nexport async function tryAsync<T>(options: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Ok<T>;\n}): Promise<Ok<T>>;\n\nexport async function tryAsync<T, E>(options: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Err<E>;\n}): Promise<Result<T, E>>;\n\nexport async function tryAsync<T, E>(options: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Promise<Result<T, E>>;\n\nexport async function tryAsync<T, E>({\n\ttry: operation,\n\tcatch: catchFn,\n}: {\n\ttry: () => Promise<T>;\n\tcatch: (error: unknown) => Ok<T> | Err<E>;\n}): Promise<Ok<T> | Result<T, E>> {\n\ttry {\n\t\tconst data = await operation();\n\t\treturn Ok(data);\n\t} catch (error) {\n\t\treturn catchFn(error);\n\t}\n}\n\n/**\n * Resolves a value that may or may not be wrapped in a `Result`, returning the final value.\n *\n * This function handles the common pattern where a value might be a `Result<T, E>` or a plain `T`:\n * - If `value` is an `Ok<T>` variant, returns the contained success value.\n * - If `value` is an `Err<E>` variant, throws the contained error value.\n * - If `value` is not a `Result` (i.e., it's already a plain value of type `T`),\n * returns it as-is.\n *\n * This is useful when working with APIs that might return either direct values or Results,\n * allowing you to normalize them to the actual value or propagate errors via throwing.\n *\n * Use `resolve` when the input might or might not be a Result.\n * Use `unwrap` when you know the input is definitely a Result.\n *\n * @template T - The type of the success value (if `value` is `Ok<T>`) or the type of the plain value.\n * @template E - The type of the error value (if `value` is `Err<E>`).\n * @param value - The value to resolve. Can be a `Result<T, E>` or a plain value of type `T`.\n * @returns The final value of type `T` if `value` is `Ok<T>` or if `value` is already a plain `T`.\n * @throws The error value `E` if `value` is an `Err<E>` variant.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const resolved = resolve(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"failure\"));\n * try {\n * resolve(errResult);\n * } catch (e) {\n * console.error(e.message); // \"failure\"\n * }\n *\n * // Example with a plain value\n * const plainValue = \"plain data\";\n * const resolved = resolve(plainValue); // \"plain data\"\n *\n * // Example with a function that might return Result or plain value\n * declare function mightReturnResult(): string | Result<string, Error>;\n * const outcome = mightReturnResult();\n * try {\n * const finalValue = resolve(outcome); // handles both cases\n * console.log(\"Final value:\", finalValue);\n * } catch (e) {\n * console.error(\"Operation failed:\", e);\n * }\n * ```\n */\n/**\n * Unwraps a `Result<T, E>`, returning the success value or throwing the error.\n *\n * This function extracts the data from a `Result`:\n * - If the `Result` is an `Ok<T>` variant, returns the contained success value of type `T`.\n * - If the `Result` is an `Err<E>` variant, throws the contained error value of type `E`.\n *\n * Unlike `resolve`, this function expects the input to always be a `Result` type,\n * making it more direct for cases where you know you're working with a `Result`.\n *\n * @template T - The type of the success value contained in the `Ok<T>` variant.\n * @template E - The type of the error value contained in the `Err<E>` variant.\n * @param result - The `Result<T, E>` to unwrap.\n * @returns The success value of type `T` if the `Result` is `Ok<T>`.\n * @throws The error value of type `E` if the `Result` is `Err<E>`.\n *\n * @example\n * ```ts\n * // Example with an Ok variant\n * const okResult = Ok(\"success data\");\n * const value = unwrap(okResult); // \"success data\"\n *\n * // Example with an Err variant\n * const errResult = Err(new Error(\"something went wrong\"));\n * try {\n * unwrap(errResult);\n * } catch (error) {\n * console.error(error.message); // \"something went wrong\"\n * }\n *\n * // Usage in a function that returns Result\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return Err(\"Division by zero\");\n * return Ok(a / b);\n * }\n *\n * try {\n * const result = unwrap(divide(10, 2)); // 5\n * console.log(\"Result:\", result);\n * } catch (error) {\n * console.error(\"Division failed:\", error);\n * }\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n\tif (isOk(result)) {\n\t\treturn result.data;\n\t}\n\tthrow result.error;\n}\n\nexport function resolve<T, E>(value: T | Result<T, E>): T {\n\tif (isResult<T, E>(value)) {\n\t\tif (isOk(value)) {\n\t\t\treturn value.data;\n\t\t}\n\t\t// If it's a Result and not Ok, it must be Err.\n\t\t// The type guard isResult<T,E>(value) and isOk(value) already refine the type.\n\t\t// So, 'value' here is known to be Err<E>.\n\t\tthrow value.error;\n\t}\n\n\t// If it's not a Result type, return the value as-is.\n\t// 'value' here is known to be of type T.\n\treturn value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8EA,MAAa,KAAK,CAAIA,UAAoB;CAA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aV1 {
|
|
|
132
132
|
/** Infers the output type of a Standard JSON Schema. */
|
|
133
133
|
type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
|
|
134
134
|
}
|
|
135
|
-
/**
|
|
136
|
-
* A schema that implements both StandardSchemaV1 and StandardJSONSchemaV1.
|
|
137
|
-
*/
|
|
138
|
-
type StandardFullSchemaV1<Input = unknown, Output = Input> = {
|
|
139
|
-
readonly "~standard": StandardSchemaV1.Props<Input, Output> & StandardJSONSchemaV1.Props<Input, Output>;
|
|
140
|
-
};
|
|
141
135
|
/**
|
|
142
136
|
* Checks if a schema has validation capability.
|
|
143
137
|
*/
|
|
@@ -367,5 +361,5 @@ declare function ResultSchema<TDataSchema extends StandardTypedV1, TErrorSchema
|
|
|
367
361
|
//# sourceMappingURL=result.d.ts.map
|
|
368
362
|
|
|
369
363
|
//#endregion
|
|
370
|
-
export { Err, ErrSchema, FAILURES, Ok, OkSchema, Result$1 as Result, ResultSchema,
|
|
364
|
+
export { Err, ErrSchema, FAILURES, Ok, OkSchema, Result$1 as Result, ResultSchema, StandardJSONSchemaV1, StandardSchemaV1, StandardTypedV1, hasJsonSchema, hasValidate };
|
|
371
365
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/standard-schema/types.ts","../../src/standard-schema/err.ts","../../src/standard-schema/failures.ts","../../src/standard-schema/ok.ts","../../src/standard-schema/result.ts"],"sourcesContent":[],"mappings":";;AAgBA;;;;;;AAE4C;AAG5C;;;AAQyB,KAbb,eAaa,CAAA,QAAA,OAAA,EAAA,SAb6B,KAa7B,CAAA,GAAA;EAAK;EAAQ,SAAnB,WAAA,EAXI,eAAA,CAAgB,KAWpB,CAX0B,KAW1B,EAXiC,MAWjC,CAAA;CAAK;AAMN,kBAdO,eAAA,CAcP;EAAK;EAEE,KAIO,KAAA,CAAA,QAAA,OAAA,EAAA,SAlBM,KAkBN,CAA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AAW,CAAA;EAAc;EAA1B,KAMf,MAAA,CAAA,MAAA,CAAA,GAjCO,aAiCP,CAjCqB,MAiCrB,CAAA,GAjC+B,aAiC/B;EAAW;EAIoB,KAClB,aAAA,CAAA,MAAA,CAAA,GAAA;IAA3B;IAG+B,SAAA,KAAA,EApCf,MAoCe;IACH;IAA5B,SAAA,MAAgB,CAAA,EAAA,SAAA;EAAW,CAAA;EAYjB;EAAoB,KAAA,OAAA,GAAA;IAA2B;IAET,SAAA,cAAA,CAAA,EA3CtB,MA2CsB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,SAAA;EAAK,CAAA;EAAQ;EAAd,KAAA,aAAA,GAAA;IAGxB;IAAoB,SAAA,MAAA,EAxC1B,aAwC0B,CAxCZ,KAwCY,CAAA;EAAA,CAAA;EAEF;EACpC,KACL,KAAA,GAAA;IAF6C;IAKxB,SAAA,OAAA,EAAA,MAAqB;IAOhC;IACL,SAAA,IAAA,CAAA,EA/CW,aA+CX,CA/CyB,WA+CzB,GA/CuC,WA+CvC,CAAA,GAAA,SAAA;EAAM,CAAA;EAG2B;EAC3B,KAuBM,WAAA,GAAA;IAES;IAII,SAAA,GAAA,EA1EhB,WA0EgB;EAAe,CAAA;EACZ;EAAP,KAGK,UAAA,CAAA,eA1ED,eA0EC,CAAA,GAzE/B,eAAA,CAAgB,UAyEe,CAzEJ,MAyEI,CAAA;EAAe;EACZ,KAAlC,WAAA,CAAA,eAvE+B,eAuEf,CAAA,GAtEhB,eAAA,CAAgB,WAsEA,CAtEY,MAsEZ,CAAA;AAAW;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/standard-schema/types.ts","../../src/standard-schema/err.ts","../../src/standard-schema/failures.ts","../../src/standard-schema/ok.ts","../../src/standard-schema/result.ts"],"sourcesContent":[],"mappings":";;AAgBA;;;;;;AAE4C;AAG5C;;;AAQyB,KAbb,eAaa,CAAA,QAAA,OAAA,EAAA,SAb6B,KAa7B,CAAA,GAAA;EAAK;E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3,"file":"index.js","names":["schema: T","innerSchema: TSchema","value: unknown","issue: StandardSchemaV1.Issue","options: StandardJSONSchemaV1.Options","innerSchema: TSchema","value: unknown","issue: StandardSchemaV1.Issue","options: StandardJSONSchemaV1.Options","dataSchema: TDataSchema","errorSchema: TErrorSchema","value: unknown","innerResult","issue: StandardSchemaV1.Issue","options: StandardJSONSchemaV1.Options"],"sources":["../../src/standard-schema/failures.ts","../../src/standard-schema/types.ts","../../src/standard-schema/err.ts","../../src/standard-schema/ok.ts","../../src/standard-schema/result.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"./types.js\";\n\nexport const FAILURES = {\n\tEXPECTED_OBJECT: { issues: [{ message: \"Expected object\" }] },\n\tEXPECTED_DATA_ERROR_PROPS: {\n\t\tissues: [{ message: \"Expected object with 'data' and 'error' properties\" }],\n\t},\n\tEXPECTED_ERROR_NULL: {\n\t\tissues: [\n\t\t\t{\n\t\t\t\tmessage: \"Expected 'error' to be null for Ok variant\",\n\t\t\t\tpath: [\"error\"],\n\t\t\t},\n\t\t],\n\t},\n\tEXPECTED_ERROR_NOT_NULL: {\n\t\tissues: [\n\t\t\t{\n\t\t\t\tmessage: \"Expected 'error' to be non-null for Err variant\",\n\t\t\t\tpath: [\"error\"],\n\t\t\t},\n\t\t],\n\t},\n} as const satisfies Record<string, StandardSchemaV1.FailureResult>;\n","/**\n * Standard Schema type definitions.\n *\n * These interfaces are copied from the Standard Schema specification\n * (https://standardschema.dev) to avoid external dependencies.\n *\n * @see https://github.com/standard-schema/standard-schema\n */\n\n// #########################\n// ### Standard Typed ###\n// #########################\n\n/**\n * The Standard Typed interface. This is a base type extended by other specs.\n */\nexport type StandardTypedV1<Input = unknown, Output = Input> = {\n\t/** The Standard properties. */\n\treadonly \"~standard\": StandardTypedV1.Props<Input, Output>;\n};\n\nexport declare namespace StandardTypedV1 {\n\t/** The Standard Typed properties interface. */\n\ttype Props<Input = unknown, Output = Input> = {\n\t\t/** The version number of the standard. */\n\t\treadonly version: 1;\n\t\t/** The vendor name of the schema library. */\n\t\treadonly vendor: string;\n\t\t/** Inferred types associated with the schema. */\n\t\treadonly types?: Types<Input, Output> | undefined;\n\t};\n\n\t/** The Standard Typed types interface. */\n\ttype Types<Input = unknown, Output = Input> = {\n\t\t/** The input type of the schema. */\n\t\treadonly input: Input;\n\t\t/** The output type of the schema. */\n\t\treadonly output: Output;\n\t};\n\n\t/** Infers the input type of a Standard Typed. */\n\ttype InferInput<Schema extends StandardTypedV1> = NonNullable<\n\t\tSchema[\"~standard\"][\"types\"]\n\t>[\"input\"];\n\n\t/** Infers the output type of a Standard Typed. */\n\ttype InferOutput<Schema extends StandardTypedV1> = NonNullable<\n\t\tSchema[\"~standard\"][\"types\"]\n\t>[\"output\"];\n}\n\n// ##########################\n// ### Standard Schema ###\n// ##########################\n\n/**\n * The Standard Schema interface.\n *\n * Extends StandardTypedV1 with a validate function for runtime validation.\n */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\t/** The Standard Schema properties. */\n\treadonly \"~standard\": StandardSchemaV1.Props<Input, Output>;\n};\n\nexport declare namespace StandardSchemaV1 {\n\t/** The Standard Schema properties interface. */\n\ttype Props<Input = unknown, Output = Input> = StandardTypedV1.Props<\n\t\tInput,\n\t\tOutput\n\t> & {\n\t\t/** Validates unknown input values. */\n\t\treadonly validate: (\n\t\t\tvalue: unknown,\n\t\t\toptions?: StandardSchemaV1.Options | undefined,\n\t\t) => Result<Output> | Promise<Result<Output>>;\n\t};\n\n\t/** The result interface of the validate function. */\n\ttype Result<Output> = SuccessResult<Output> | FailureResult;\n\n\t/** The result interface if validation succeeds. */\n\ttype SuccessResult<Output> = {\n\t\t/** The typed output value. */\n\t\treadonly value: Output;\n\t\t/** A falsy value for `issues` indicates success. */\n\t\treadonly issues?: undefined;\n\t};\n\n\t/** Options for the validate function. */\n\ttype Options = {\n\t\t/** Explicit support for additional vendor-specific parameters, if needed. */\n\t\treadonly libraryOptions?: Record<string, unknown> | undefined;\n\t};\n\n\t/** The result interface if validation fails. */\n\ttype FailureResult = {\n\t\t/** The issues of failed validation. */\n\t\treadonly issues: ReadonlyArray<Issue>;\n\t};\n\n\t/** The issue interface of the failure output. */\n\ttype Issue = {\n\t\t/** The error message of the issue. */\n\t\treadonly message: string;\n\t\t/** The path of the issue, if any. */\n\t\treadonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n\t};\n\n\t/** The path segment interface of the issue. */\n\ttype PathSegment = {\n\t\t/** The key representing a path segment. */\n\t\treadonly key: PropertyKey;\n\t};\n\n\t/** Infers the input type of a Standard Schema. */\n\ttype InferInput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferInput<Schema>;\n\n\t/** Infers the output type of a Standard Schema. */\n\ttype InferOutput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferOutput<Schema>;\n}\n\n// ###############################\n// ### Standard JSON Schema ###\n// ###############################\n\n/**\n * The Standard JSON Schema interface.\n *\n * Extends StandardTypedV1 with methods for generating JSON Schema.\n */\nexport type StandardJSONSchemaV1<Input = unknown, Output = Input> = {\n\t/** The Standard JSON Schema properties. */\n\treadonly \"~standard\": StandardJSONSchemaV1.Props<Input, Output>;\n};\n\nexport declare namespace StandardJSONSchemaV1 {\n\t/** The Standard JSON Schema properties interface. */\n\ttype Props<Input = unknown, Output = Input> = StandardTypedV1.Props<\n\t\tInput,\n\t\tOutput\n\t> & {\n\t\t/** Methods for generating the input/output JSON Schema. */\n\t\treadonly jsonSchema: StandardJSONSchemaV1.Converter;\n\t};\n\n\t/** The Standard JSON Schema converter interface. */\n\ttype Converter = {\n\t\t/** Converts the input type to JSON Schema. May throw if conversion is not supported. */\n\t\treadonly input: (\n\t\t\toptions: StandardJSONSchemaV1.Options,\n\t\t) => Record<string, unknown>;\n\t\t/** Converts the output type to JSON Schema. May throw if conversion is not supported. */\n\t\treadonly output: (\n\t\t\toptions: StandardJSONSchemaV1.Options,\n\t\t) => Record<string, unknown>;\n\t};\n\n\t/**\n\t * The target version of the generated JSON Schema.\n\t *\n\t * It is *strongly recommended* that implementers support `\"draft-2020-12\"` and `\"draft-07\"`,\n\t * as they are both in wide use. All other targets can be implemented on a best-effort basis.\n\t * Libraries should throw if they don't support a specified target.\n\t *\n\t * The `\"openapi-3.0\"` target is intended as a standardized specifier for OpenAPI 3.0\n\t * which is a superset of JSON Schema `\"draft-04\"`.\n\t */\n\ttype Target =\n\t\t| \"draft-2020-12\"\n\t\t| \"draft-07\"\n\t\t| \"openapi-3.0\"\n\t\t// Accepts any string for future targets while preserving autocomplete\n\t\t| (string & {});\n\n\t/** The options for the input/output methods. */\n\ttype Options = {\n\t\t/** Specifies the target version of the generated JSON Schema. */\n\t\treadonly target: Target;\n\t\t/** Explicit support for additional vendor-specific parameters, if needed. */\n\t\treadonly libraryOptions?: Record<string, unknown> | undefined;\n\t};\n\n\t/** Infers the input type of a Standard JSON Schema. */\n\ttype InferInput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferInput<Schema>;\n\n\t/** Infers the output type of a Standard JSON Schema. */\n\ttype InferOutput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferOutput<Schema>;\n}\n\n// ###############################\n// ### Utility Types ###\n// ###############################\n\n/**\n * A schema that implements both StandardSchemaV1 and StandardJSONSchemaV1.\n */\nexport type StandardFullSchemaV1<Input = unknown, Output = Input> = {\n\treadonly \"~standard\": StandardSchemaV1.Props<Input, Output> &\n\t\tStandardJSONSchemaV1.Props<Input, Output>;\n};\n\n/**\n * Checks if a schema has validation capability.\n */\nexport function hasValidate<T extends StandardTypedV1>(\n\tschema: T,\n): schema is T & StandardSchemaV1 {\n\treturn (\n\t\t\"validate\" in schema[\"~standard\"] &&\n\t\ttypeof schema[\"~standard\"].validate === \"function\"\n\t);\n}\n\n/**\n * Checks if a schema has JSON Schema generation capability.\n */\nexport function hasJsonSchema<T extends StandardTypedV1>(\n\tschema: T,\n): schema is T & StandardJSONSchemaV1 {\n\treturn (\n\t\t\"jsonSchema\" in schema[\"~standard\"] &&\n\t\ttypeof schema[\"~standard\"].jsonSchema === \"object\" &&\n\t\tschema[\"~standard\"].jsonSchema !== null\n\t);\n}\n","import { FAILURES } from \"./failures.js\";\nimport {\n\thasJsonSchema,\n\thasValidate,\n\ttype StandardJSONSchemaV1,\n\ttype StandardSchemaV1,\n\ttype StandardTypedV1,\n} from \"./types.js\";\n\n/**\n * Output type for ErrSchema - wraps inner schema's types with Err structure.\n *\n * Preserves the capabilities of the input schema:\n * - If input has validate, output has validate\n * - If input has jsonSchema, output has jsonSchema\n */\nexport type Err<TSchema extends StandardTypedV1> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: \"wellcrafted\";\n\t\treadonly types: {\n\t\t\treadonly input: {\n\t\t\t\tdata: null;\n\t\t\t\terror: StandardTypedV1.InferInput<TSchema>;\n\t\t\t};\n\t\t\treadonly output: {\n\t\t\t\tdata: null;\n\t\t\t\terror: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t};\n\t\t};\n\t} & (TSchema extends StandardSchemaV1\n\t\t? {\n\t\t\t\treadonly validate: StandardSchemaV1.Props<\n\t\t\t\t\t{ data: null; error: StandardTypedV1.InferInput<TSchema> },\n\t\t\t\t\t{ data: null; error: StandardTypedV1.InferOutput<TSchema> }\n\t\t\t\t>[\"validate\"];\n\t\t\t}\n\t\t: Record<string, never>) &\n\t\t(TSchema extends StandardJSONSchemaV1\n\t\t\t? { readonly jsonSchema: StandardJSONSchemaV1.Converter }\n\t\t\t: Record<string, never>);\n};\n\nfunction createErrValidate<TSchema extends StandardSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardSchemaV1.Props<\n\t{ data: null; error: StandardTypedV1.InferInput<TSchema> },\n\t{ data: null; error: StandardTypedV1.InferOutput<TSchema> }\n>[\"validate\"] {\n\treturn (value: unknown) => {\n\t\tif (typeof value !== \"object\" || value === null) {\n\t\t\treturn FAILURES.EXPECTED_OBJECT;\n\t\t}\n\n\t\tif (!(\"data\" in value) || !(\"error\" in value)) {\n\t\t\treturn FAILURES.EXPECTED_DATA_ERROR_PROPS;\n\t\t}\n\n\t\tconst obj = value as { data: unknown; error: unknown };\n\n\t\tif (obj.error === null) {\n\t\t\treturn FAILURES.EXPECTED_ERROR_NOT_NULL;\n\t\t}\n\n\t\tconst innerResult = innerSchema[\"~standard\"].validate(obj.error);\n\n\t\tif (innerResult instanceof Promise) {\n\t\t\treturn innerResult.then((r) => {\n\t\t\t\tif (r.issues) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t\t\t})),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: { data: null as null, error: r.value } };\n\t\t\t});\n\t\t}\n\n\t\tif (innerResult.issues) {\n\t\t\treturn {\n\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t...issue,\n\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t})),\n\t\t\t};\n\t\t}\n\n\t\treturn { value: { data: null as null, error: innerResult.value } };\n\t};\n}\n\nfunction createErrJsonSchema<TSchema extends StandardJSONSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardJSONSchemaV1.Converter {\n\treturn {\n\t\tinput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\terror: innerSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t\toutput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\terror: innerSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Wraps a Standard Schema into an Err variant schema.\n *\n * Takes a schema for type E and returns a schema for `{ data: null, error: E }`.\n * Preserves the capabilities of the input schema (validate, jsonSchema, or both).\n *\n * @example\n * ```typescript\n * import { z } from \"zod\";\n * import { ErrSchema } from \"wellcrafted/standard-schema\";\n *\n * const errorSchema = z.object({ code: z.string(), message: z.string() });\n * const errResultSchema = ErrSchema(errorSchema);\n *\n * // Validates: { data: null, error: { code: \"NOT_FOUND\", message: \"User not found\" } }\n * const result = errResultSchema[\"~standard\"].validate({\n * data: null,\n * error: { code: \"NOT_FOUND\", message: \"User not found\" },\n * });\n * ```\n */\nexport function ErrSchema<TSchema extends StandardTypedV1>(\n\tinnerSchema: TSchema,\n): Err<TSchema> {\n\tconst base = {\n\t\t\"~standard\": {\n\t\t\tversion: 1 as const,\n\t\t\tvendor: \"wellcrafted\",\n\t\t\ttypes: {\n\t\t\t\tinput: undefined as unknown as {\n\t\t\t\t\tdata: null;\n\t\t\t\t\terror: StandardTypedV1.InferInput<TSchema>;\n\t\t\t\t},\n\t\t\t\toutput: undefined as unknown as {\n\t\t\t\t\tdata: null;\n\t\t\t\t\terror: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n\n\tif (hasValidate(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).validate =\n\t\t\tcreateErrValidate(innerSchema);\n\t}\n\n\tif (hasJsonSchema(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).jsonSchema =\n\t\t\tcreateErrJsonSchema(innerSchema);\n\t}\n\n\treturn base as Err<TSchema>;\n}\n","import { FAILURES } from \"./failures.js\";\nimport {\n\thasJsonSchema,\n\thasValidate,\n\ttype StandardJSONSchemaV1,\n\ttype StandardSchemaV1,\n\ttype StandardTypedV1,\n} from \"./types.js\";\n\n/**\n * Output type for OkSchema - wraps inner schema's types with Ok structure.\n *\n * Preserves the capabilities of the input schema:\n * - If input has validate, output has validate\n * - If input has jsonSchema, output has jsonSchema\n */\nexport type Ok<TSchema extends StandardTypedV1> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: \"wellcrafted\";\n\t\treadonly types: {\n\t\t\treadonly input: {\n\t\t\t\tdata: StandardTypedV1.InferInput<TSchema>;\n\t\t\t\terror: null;\n\t\t\t};\n\t\t\treadonly output: {\n\t\t\t\tdata: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t\terror: null;\n\t\t\t};\n\t\t};\n\t} & (TSchema extends StandardSchemaV1\n\t\t? {\n\t\t\t\treadonly validate: StandardSchemaV1.Props<\n\t\t\t\t\t{ data: StandardTypedV1.InferInput<TSchema>; error: null },\n\t\t\t\t\t{ data: StandardTypedV1.InferOutput<TSchema>; error: null }\n\t\t\t\t>[\"validate\"];\n\t\t\t}\n\t\t: Record<string, never>) &\n\t\t(TSchema extends StandardJSONSchemaV1\n\t\t\t? { readonly jsonSchema: StandardJSONSchemaV1.Converter }\n\t\t\t: Record<string, never>);\n};\n\nfunction createOkValidate<TSchema extends StandardSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardSchemaV1.Props<\n\t{ data: StandardTypedV1.InferInput<TSchema>; error: null },\n\t{ data: StandardTypedV1.InferOutput<TSchema>; error: null }\n>[\"validate\"] {\n\treturn (value: unknown) => {\n\t\tif (typeof value !== \"object\" || value === null) {\n\t\t\treturn FAILURES.EXPECTED_OBJECT;\n\t\t}\n\n\t\tif (!(\"data\" in value) || !(\"error\" in value)) {\n\t\t\treturn FAILURES.EXPECTED_DATA_ERROR_PROPS;\n\t\t}\n\n\t\tconst obj = value as { data: unknown; error: unknown };\n\n\t\tif (obj.error !== null) {\n\t\t\treturn FAILURES.EXPECTED_ERROR_NULL;\n\t\t}\n\n\t\tconst innerResult = innerSchema[\"~standard\"].validate(obj.data);\n\n\t\tif (innerResult instanceof Promise) {\n\t\t\treturn innerResult.then((r) => {\n\t\t\t\tif (r.issues) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t\t\t})),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: { data: r.value, error: null as null } };\n\t\t\t});\n\t\t}\n\n\t\tif (innerResult.issues) {\n\t\t\treturn {\n\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t...issue,\n\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t})),\n\t\t\t};\n\t\t}\n\n\t\treturn { value: { data: innerResult.value, error: null as null } };\n\t};\n}\n\nfunction createOkJsonSchema<TSchema extends StandardJSONSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardJSONSchemaV1.Converter {\n\treturn {\n\t\tinput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: innerSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t\toutput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: innerSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Wraps a Standard Schema into an Ok variant schema.\n *\n * Takes a schema for type T and returns a schema for `{ data: T, error: null }`.\n * Preserves the capabilities of the input schema (validate, jsonSchema, or both).\n *\n * @example\n * ```typescript\n * import { z } from \"zod\";\n * import { OkSchema } from \"wellcrafted/standard-schema\";\n *\n * const userSchema = z.object({ name: z.string() });\n * const okUserSchema = OkSchema(userSchema);\n *\n * // Validates: { data: { name: \"Alice\" }, error: null }\n * const result = okUserSchema[\"~standard\"].validate({\n * data: { name: \"Alice\" },\n * error: null,\n * });\n * ```\n */\nexport function OkSchema<TSchema extends StandardTypedV1>(\n\tinnerSchema: TSchema,\n): Ok<TSchema> {\n\tconst base = {\n\t\t\"~standard\": {\n\t\t\tversion: 1 as const,\n\t\t\tvendor: \"wellcrafted\",\n\t\t\ttypes: {\n\t\t\t\tinput: undefined as unknown as {\n\t\t\t\t\tdata: StandardTypedV1.InferInput<TSchema>;\n\t\t\t\t\terror: null;\n\t\t\t\t},\n\t\t\t\toutput: undefined as unknown as {\n\t\t\t\t\tdata: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t\t\terror: null;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n\n\tif (hasValidate(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).validate =\n\t\t\tcreateOkValidate(innerSchema);\n\t}\n\n\tif (hasJsonSchema(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).jsonSchema =\n\t\t\tcreateOkJsonSchema(innerSchema);\n\t}\n\n\treturn base as Ok<TSchema>;\n}\n","import { FAILURES } from \"./failures.js\";\nimport {\n\thasJsonSchema,\n\thasValidate,\n\ttype StandardJSONSchemaV1,\n\ttype StandardSchemaV1,\n\ttype StandardTypedV1,\n} from \"./types.js\";\n\n/**\n * Output type for ResultSchema - creates a discriminated union of Ok and Err.\n *\n * Preserves the capabilities of the input schemas:\n * - If both inputs have validate, output has validate\n * - If both inputs have jsonSchema, output has jsonSchema\n */\nexport type Result<\n\tTDataSchema extends StandardTypedV1,\n\tTErrorSchema extends StandardTypedV1,\n> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: \"wellcrafted\";\n\t\treadonly types: {\n\t\t\treadonly input:\n\t\t\t\t| { data: StandardTypedV1.InferInput<TDataSchema>; error: null }\n\t\t\t\t| { data: null; error: StandardTypedV1.InferInput<TErrorSchema> };\n\t\t\treadonly output:\n\t\t\t\t| { data: StandardTypedV1.InferOutput<TDataSchema>; error: null }\n\t\t\t\t| { data: null; error: StandardTypedV1.InferOutput<TErrorSchema> };\n\t\t};\n\t} & (TDataSchema extends StandardSchemaV1\n\t\t? TErrorSchema extends StandardSchemaV1\n\t\t\t? {\n\t\t\t\t\treadonly validate: StandardSchemaV1.Props<\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: StandardTypedV1.InferInput<TDataSchema>;\n\t\t\t\t\t\t\t\terror: null;\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: null;\n\t\t\t\t\t\t\t\terror: StandardTypedV1.InferInput<TErrorSchema>;\n\t\t\t\t\t\t },\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: StandardTypedV1.InferOutput<TDataSchema>;\n\t\t\t\t\t\t\t\terror: null;\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: null;\n\t\t\t\t\t\t\t\terror: StandardTypedV1.InferOutput<TErrorSchema>;\n\t\t\t\t\t\t }\n\t\t\t\t\t>[\"validate\"];\n\t\t\t\t}\n\t\t\t: Record<string, never>\n\t\t: Record<string, never>) &\n\t\t(TDataSchema extends StandardJSONSchemaV1\n\t\t\t? TErrorSchema extends StandardJSONSchemaV1\n\t\t\t\t? { readonly jsonSchema: StandardJSONSchemaV1.Converter }\n\t\t\t\t: Record<string, never>\n\t\t\t: Record<string, never>);\n};\n\nfunction createResultValidate<\n\tTDataSchema extends StandardSchemaV1,\n\tTErrorSchema extends StandardSchemaV1,\n>(\n\tdataSchema: TDataSchema,\n\terrorSchema: TErrorSchema,\n): StandardSchemaV1.Props<\n\t| { data: StandardTypedV1.InferInput<TDataSchema>; error: null }\n\t| { data: null; error: StandardTypedV1.InferInput<TErrorSchema> },\n\t| { data: StandardTypedV1.InferOutput<TDataSchema>; error: null }\n\t| { data: null; error: StandardTypedV1.InferOutput<TErrorSchema> }\n>[\"validate\"] {\n\treturn (value: unknown) => {\n\t\tif (typeof value !== \"object\" || value === null) {\n\t\t\treturn FAILURES.EXPECTED_OBJECT;\n\t\t}\n\n\t\tif (!(\"data\" in value) || !(\"error\" in value)) {\n\t\t\treturn FAILURES.EXPECTED_DATA_ERROR_PROPS;\n\t\t}\n\n\t\tconst obj = value as { data: unknown; error: unknown };\n\n\t\tconst isOk = obj.error === null;\n\n\t\tif (isOk) {\n\t\t\tconst innerResult = dataSchema[\"~standard\"].validate(obj.data);\n\n\t\t\tif (innerResult instanceof Promise) {\n\t\t\t\treturn innerResult.then((r) => {\n\t\t\t\t\tif (r.issues) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn { value: { data: r.value, error: null as null } };\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (innerResult.issues) {\n\t\t\t\treturn {\n\t\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t...issue,\n\t\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn { value: { data: innerResult.value, error: null as null } };\n\t\t}\n\n\t\tconst innerResult = errorSchema[\"~standard\"].validate(obj.error);\n\n\t\tif (innerResult instanceof Promise) {\n\t\t\treturn innerResult.then((r) => {\n\t\t\t\tif (r.issues) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t\t\t})),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: { data: null as null, error: r.value } };\n\t\t\t});\n\t\t}\n\n\t\tif (innerResult.issues) {\n\t\t\treturn {\n\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t...issue,\n\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t})),\n\t\t\t};\n\t\t}\n\n\t\treturn { value: { data: null as null, error: innerResult.value } };\n\t};\n}\n\nfunction createResultJsonSchema<\n\tTDataSchema extends StandardJSONSchemaV1,\n\tTErrorSchema extends StandardJSONSchemaV1,\n>(\n\tdataSchema: TDataSchema,\n\terrorSchema: TErrorSchema,\n): StandardJSONSchemaV1.Converter {\n\treturn {\n\t\tinput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\toneOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: dataSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\t\t\terror: errorSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t},\n\t\toutput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\toneOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: dataSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\t\t\terror: errorSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Combines two Standard Schemas into a Result discriminated union schema.\n *\n * Takes a data schema for type T and an error schema for type E, returning a schema\n * for `{ data: T, error: null } | { data: null, error: E }`.\n *\n * Preserves the capabilities of the input schemas - if both have validate, output\n * has validate; if both have jsonSchema, output has jsonSchema.\n *\n * @example\n * ```typescript\n * import { z } from \"zod\";\n * import { ResultSchema } from \"wellcrafted/standard-schema\";\n *\n * const userSchema = z.object({ id: z.string(), name: z.string() });\n * const errorSchema = z.object({ code: z.string(), message: z.string() });\n * const resultSchema = ResultSchema(userSchema, errorSchema);\n *\n * // Validates Ok variant: { data: { id: \"1\", name: \"Alice\" }, error: null }\n * // Validates Err variant: { data: null, error: { code: \"NOT_FOUND\", message: \"...\" } }\n * const result = resultSchema[\"~standard\"].validate({\n * data: { id: \"1\", name: \"Alice\" },\n * error: null,\n * });\n * ```\n */\nexport function ResultSchema<\n\tTDataSchema extends StandardTypedV1,\n\tTErrorSchema extends StandardTypedV1,\n>(\n\tdataSchema: TDataSchema,\n\terrorSchema: TErrorSchema,\n): Result<TDataSchema, TErrorSchema> {\n\tconst base = {\n\t\t\"~standard\": {\n\t\t\tversion: 1 as const,\n\t\t\tvendor: \"wellcrafted\",\n\t\t\ttypes: {\n\t\t\t\tinput: undefined as unknown as\n\t\t\t\t\t| { data: StandardTypedV1.InferInput<TDataSchema>; error: null }\n\t\t\t\t\t| { data: null; error: StandardTypedV1.InferInput<TErrorSchema> },\n\t\t\t\toutput: undefined as unknown as\n\t\t\t\t\t| { data: StandardTypedV1.InferOutput<TDataSchema>; error: null }\n\t\t\t\t\t| { data: null; error: StandardTypedV1.InferOutput<TErrorSchema> },\n\t\t\t},\n\t\t},\n\t};\n\n\tif (hasValidate(dataSchema) && hasValidate(errorSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).validate =\n\t\t\tcreateResultValidate(dataSchema, errorSchema);\n\t}\n\n\tif (hasJsonSchema(dataSchema) && hasJsonSchema(errorSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).jsonSchema =\n\t\t\tcreateResultJsonSchema(dataSchema, errorSchema);\n\t}\n\n\treturn base as Result<TDataSchema, TErrorSchema>;\n}\n"],"mappings":";AAEA,MAAa,WAAW;CACvB,iBAAiB,EAAE,QAAQ,CAAC,EAAE,SAAS,kBAAmB,CAAC,EAAE;CAC7D,2BAA2B,EAC1B,QAAQ,CAAC,EAAE,SAAS,qDAAsD,CAAC,EAC3E;CACD,qBAAqB,EACpB,QAAQ,CACP;EACC,SAAS;EACT,MAAM,CAAC,OAAQ;CACf,CACD,EACD;CACD,yBAAyB,EACxB,QAAQ,CACP;EACC,SAAS;EACT,MAAM,CAAC,OAAQ;CACf,CACD,EACD;AACD;;;;;;;AC0LD,SAAgB,YACfA,QACiC;AACjC,QACC,cAAc,OAAO,uBACd,OAAO,aAAa,aAAa;AAEzC;;;;AAKD,SAAgB,cACfA,QACqC;AACrC,QACC,gBAAgB,OAAO,uBAChB,OAAO,aAAa,eAAe,YAC1C,OAAO,aAAa,eAAe;AAEpC;;;;AC1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Aa,WAAW,OAAO,QAAQ;KACxD,OAAO,EAAE,MAAM,OAAQ;IACvB;IACD,UAAU,CAAC,QAAQ,OAAQ;IAC3B,sBAAsB;GACtB,GACD;IACC,MAAM;IACN,YAAY;KACX,MAAM,EAAE,MAAM,OAAQ;KACtB,OAAO,YAAY,aAAa,WAAW,OAAO,QAAQ;IAC1D;IACD,UAAU,CAAC,QAAQ,OAAQ;IAC3B,sBAAsB;GACtB,CACD,EACD;EACD;CACD;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BD,SAAgB,aAIfL,YACAC,aACoC;CACpC,MAAM,OAAO,EACZ,aAAa;EACZ,SAAS;EACT,QAAQ;EACR,OAAO;GACN;GAGA;EAGA;CACD,EACD;AAED,KAAI,YAAY,WAAW,IAAI,YAAY,YAAY,CACtD,CAAC,KAAK,aAAyC,WAC9C,qBAAqB,YAAY,YAAY;AAG/C,KAAI,cAAc,WAAW,IAAI,cAAc,YAAY,CAC1D,CAAC,KAAK,aAAyC,aAC9C,uBAAuB,YAAY,YAAY;AAGjD,QAAO;AACP"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["schema: T","innerSchema: TSchema","value: unknown","issue: StandardSchemaV1.Issue","options: StandardJSONSchemaV1.Options","innerSchema: TSchema","value: unknown","issue: StandardSchemaV1.Issue","options: StandardJSONSchemaV1.Options","dataSchema: TDataSchema","errorSchema: TErrorSchema","value: unknown","innerResult","issue: StandardSchemaV1.Issue","options: StandardJSONSchemaV1.Options"],"sources":["../../src/standard-schema/failures.ts","../../src/standard-schema/types.ts","../../src/standard-schema/err.ts","../../src/standard-schema/ok.ts","../../src/standard-schema/result.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"./types.js\";\n\nexport const FAILURES = {\n\tEXPECTED_OBJECT: { issues: [{ message: \"Expected object\" }] },\n\tEXPECTED_DATA_ERROR_PROPS: {\n\t\tissues: [{ message: \"Expected object with 'data' and 'error' properties\" }],\n\t},\n\tEXPECTED_ERROR_NULL: {\n\t\tissues: [\n\t\t\t{\n\t\t\t\tmessage: \"Expected 'error' to be null for Ok variant\",\n\t\t\t\tpath: [\"error\"],\n\t\t\t},\n\t\t],\n\t},\n\tEXPECTED_ERROR_NOT_NULL: {\n\t\tissues: [\n\t\t\t{\n\t\t\t\tmessage: \"Expected 'error' to be non-null for Err variant\",\n\t\t\t\tpath: [\"error\"],\n\t\t\t},\n\t\t],\n\t},\n} as const satisfies Record<string, StandardSchemaV1.FailureResult>;\n","/**\n * Standard Schema type definitions.\n *\n * These interfaces are copied from the Standard Schema specification\n * (https://standardschema.dev) to avoid external dependencies.\n *\n * @see https://github.com/standard-schema/standard-schema\n */\n\n// #########################\n// ### Standard Typed ###\n// #########################\n\n/**\n * The Standard Typed interface. This is a base type extended by other specs.\n */\nexport type StandardTypedV1<Input = unknown, Output = Input> = {\n\t/** The Standard properties. */\n\treadonly \"~standard\": StandardTypedV1.Props<Input, Output>;\n};\n\nexport declare namespace StandardTypedV1 {\n\t/** The Standard Typed properties interface. */\n\ttype Props<Input = unknown, Output = Input> = {\n\t\t/** The version number of the standard. */\n\t\treadonly version: 1;\n\t\t/** The vendor name of the schema library. */\n\t\treadonly vendor: string;\n\t\t/** Inferred types associated with the schema. */\n\t\treadonly types?: Types<Input, Output> | undefined;\n\t};\n\n\t/** The Standard Typed types interface. */\n\ttype Types<Input = unknown, Output = Input> = {\n\t\t/** The input type of the schema. */\n\t\treadonly input: Input;\n\t\t/** The output type of the schema. */\n\t\treadonly output: Output;\n\t};\n\n\t/** Infers the input type of a Standard Typed. */\n\ttype InferInput<Schema extends StandardTypedV1> = NonNullable<\n\t\tSchema[\"~standard\"][\"types\"]\n\t>[\"input\"];\n\n\t/** Infers the output type of a Standard Typed. */\n\ttype InferOutput<Schema extends StandardTypedV1> = NonNullable<\n\t\tSchema[\"~standard\"][\"types\"]\n\t>[\"output\"];\n}\n\n// ##########################\n// ### Standard Schema ###\n// ##########################\n\n/**\n * The Standard Schema interface.\n *\n * Extends StandardTypedV1 with a validate function for runtime validation.\n */\nexport type StandardSchemaV1<Input = unknown, Output = Input> = {\n\t/** The Standard Schema properties. */\n\treadonly \"~standard\": StandardSchemaV1.Props<Input, Output>;\n};\n\nexport declare namespace StandardSchemaV1 {\n\t/** The Standard Schema properties interface. */\n\ttype Props<Input = unknown, Output = Input> = StandardTypedV1.Props<\n\t\tInput,\n\t\tOutput\n\t> & {\n\t\t/** Validates unknown input values. */\n\t\treadonly validate: (\n\t\t\tvalue: unknown,\n\t\t\toptions?: StandardSchemaV1.Options | undefined,\n\t\t) => Result<Output> | Promise<Result<Output>>;\n\t};\n\n\t/** The result interface of the validate function. */\n\ttype Result<Output> = SuccessResult<Output> | FailureResult;\n\n\t/** The result interface if validation succeeds. */\n\ttype SuccessResult<Output> = {\n\t\t/** The typed output value. */\n\t\treadonly value: Output;\n\t\t/** A falsy value for `issues` indicates success. */\n\t\treadonly issues?: undefined;\n\t};\n\n\t/** Options for the validate function. */\n\ttype Options = {\n\t\t/** Explicit support for additional vendor-specific parameters, if needed. */\n\t\treadonly libraryOptions?: Record<string, unknown> | undefined;\n\t};\n\n\t/** The result interface if validation fails. */\n\ttype FailureResult = {\n\t\t/** The issues of failed validation. */\n\t\treadonly issues: ReadonlyArray<Issue>;\n\t};\n\n\t/** The issue interface of the failure output. */\n\ttype Issue = {\n\t\t/** The error message of the issue. */\n\t\treadonly message: string;\n\t\t/** The path of the issue, if any. */\n\t\treadonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n\t};\n\n\t/** The path segment interface of the issue. */\n\ttype PathSegment = {\n\t\t/** The key representing a path segment. */\n\t\treadonly key: PropertyKey;\n\t};\n\n\t/** Infers the input type of a Standard Schema. */\n\ttype InferInput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferInput<Schema>;\n\n\t/** Infers the output type of a Standard Schema. */\n\ttype InferOutput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferOutput<Schema>;\n}\n\n// ###############################\n// ### Standard JSON Schema ###\n// ###############################\n\n/**\n * The Standard JSON Schema interface.\n *\n * Extends StandardTypedV1 with methods for generating JSON Schema.\n */\nexport type StandardJSONSchemaV1<Input = unknown, Output = Input> = {\n\t/** The Standard JSON Schema properties. */\n\treadonly \"~standard\": StandardJSONSchemaV1.Props<Input, Output>;\n};\n\nexport declare namespace StandardJSONSchemaV1 {\n\t/** The Standard JSON Schema properties interface. */\n\ttype Props<Input = unknown, Output = Input> = StandardTypedV1.Props<\n\t\tInput,\n\t\tOutput\n\t> & {\n\t\t/** Methods for generating the input/output JSON Schema. */\n\t\treadonly jsonSchema: StandardJSONSchemaV1.Converter;\n\t};\n\n\t/** The Standard JSON Schema converter interface. */\n\ttype Converter = {\n\t\t/** Converts the input type to JSON Schema. May throw if conversion is not supported. */\n\t\treadonly input: (\n\t\t\toptions: StandardJSONSchemaV1.Options,\n\t\t) => Record<string, unknown>;\n\t\t/** Converts the output type to JSON Schema. May throw if conversion is not supported. */\n\t\treadonly output: (\n\t\t\toptions: StandardJSONSchemaV1.Options,\n\t\t) => Record<string, unknown>;\n\t};\n\n\t/**\n\t * The target version of the generated JSON Schema.\n\t *\n\t * It is *strongly recommended* that implementers support `\"draft-2020-12\"` and `\"draft-07\"`,\n\t * as they are both in wide use. All other targets can be implemented on a best-effort basis.\n\t * Libraries should throw if they don't support a specified target.\n\t *\n\t * The `\"openapi-3.0\"` target is intended as a standardized specifier for OpenAPI 3.0\n\t * which is a superset of JSON Schema `\"draft-04\"`.\n\t */\n\ttype Target =\n\t\t| \"draft-2020-12\"\n\t\t| \"draft-07\"\n\t\t| \"openapi-3.0\"\n\t\t// Accepts any string for future targets while preserving autocomplete\n\t\t| (string & {});\n\n\t/** The options for the input/output methods. */\n\ttype Options = {\n\t\t/** Specifies the target version of the generated JSON Schema. */\n\t\treadonly target: Target;\n\t\t/** Explicit support for additional vendor-specific parameters, if needed. */\n\t\treadonly libraryOptions?: Record<string, unknown> | undefined;\n\t};\n\n\t/** Infers the input type of a Standard JSON Schema. */\n\ttype InferInput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferInput<Schema>;\n\n\t/** Infers the output type of a Standard JSON Schema. */\n\ttype InferOutput<Schema extends StandardTypedV1> =\n\t\tStandardTypedV1.InferOutput<Schema>;\n}\n\n/**\n * Checks if a schema has validation capability.\n */\nexport function hasValidate<T extends StandardTypedV1>(\n\tschema: T,\n): schema is T & StandardSchemaV1 {\n\treturn (\n\t\t\"validate\" in schema[\"~standard\"] &&\n\t\ttypeof schema[\"~standard\"].validate === \"function\"\n\t);\n}\n\n/**\n * Checks if a schema has JSON Schema generation capability.\n */\nexport function hasJsonSchema<T extends StandardTypedV1>(\n\tschema: T,\n): schema is T & StandardJSONSchemaV1 {\n\treturn (\n\t\t\"jsonSchema\" in schema[\"~standard\"] &&\n\t\ttypeof schema[\"~standard\"].jsonSchema === \"object\" &&\n\t\tschema[\"~standard\"].jsonSchema !== null\n\t);\n}\n","import { FAILURES } from \"./failures.js\";\nimport {\n\thasJsonSchema,\n\thasValidate,\n\ttype StandardJSONSchemaV1,\n\ttype StandardSchemaV1,\n\ttype StandardTypedV1,\n} from \"./types.js\";\n\n/**\n * Output type for ErrSchema - wraps inner schema's types with Err structure.\n *\n * Preserves the capabilities of the input schema:\n * - If input has validate, output has validate\n * - If input has jsonSchema, output has jsonSchema\n */\nexport type Err<TSchema extends StandardTypedV1> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: \"wellcrafted\";\n\t\treadonly types: {\n\t\t\treadonly input: {\n\t\t\t\tdata: null;\n\t\t\t\terror: StandardTypedV1.InferInput<TSchema>;\n\t\t\t};\n\t\t\treadonly output: {\n\t\t\t\tdata: null;\n\t\t\t\terror: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t};\n\t\t};\n\t} & (TSchema extends StandardSchemaV1\n\t\t? {\n\t\t\t\treadonly validate: StandardSchemaV1.Props<\n\t\t\t\t\t{ data: null; error: StandardTypedV1.InferInput<TSchema> },\n\t\t\t\t\t{ data: null; error: StandardTypedV1.InferOutput<TSchema> }\n\t\t\t\t>[\"validate\"];\n\t\t\t}\n\t\t: Record<string, never>) &\n\t\t(TSchema extends StandardJSONSchemaV1\n\t\t\t? { readonly jsonSchema: StandardJSONSchemaV1.Converter }\n\t\t\t: Record<string, never>);\n};\n\nfunction createErrValidate<TSchema extends StandardSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardSchemaV1.Props<\n\t{ data: null; error: StandardTypedV1.InferInput<TSchema> },\n\t{ data: null; error: StandardTypedV1.InferOutput<TSchema> }\n>[\"validate\"] {\n\treturn (value: unknown) => {\n\t\tif (typeof value !== \"object\" || value === null) {\n\t\t\treturn FAILURES.EXPECTED_OBJECT;\n\t\t}\n\n\t\tif (!(\"data\" in value) || !(\"error\" in value)) {\n\t\t\treturn FAILURES.EXPECTED_DATA_ERROR_PROPS;\n\t\t}\n\n\t\tconst obj = value as { data: unknown; error: unknown };\n\n\t\tif (obj.error === null) {\n\t\t\treturn FAILURES.EXPECTED_ERROR_NOT_NULL;\n\t\t}\n\n\t\tconst innerResult = innerSchema[\"~standard\"].validate(obj.error);\n\n\t\tif (innerResult instanceof Promise) {\n\t\t\treturn innerResult.then((r) => {\n\t\t\t\tif (r.issues) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t\t\t})),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: { data: null as null, error: r.value } };\n\t\t\t});\n\t\t}\n\n\t\tif (innerResult.issues) {\n\t\t\treturn {\n\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t...issue,\n\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t})),\n\t\t\t};\n\t\t}\n\n\t\treturn { value: { data: null as null, error: innerResult.value } };\n\t};\n}\n\nfunction createErrJsonSchema<TSchema extends StandardJSONSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardJSONSchemaV1.Converter {\n\treturn {\n\t\tinput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\terror: innerSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t\toutput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\terror: innerSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Wraps a Standard Schema into an Err variant schema.\n *\n * Takes a schema for type E and returns a schema for `{ data: null, error: E }`.\n * Preserves the capabilities of the input schema (validate, jsonSchema, or both).\n *\n * @example\n * ```typescript\n * import { z } from \"zod\";\n * import { ErrSchema } from \"wellcrafted/standard-schema\";\n *\n * const errorSchema = z.object({ code: z.string(), message: z.string() });\n * const errResultSchema = ErrSchema(errorSchema);\n *\n * // Validates: { data: null, error: { code: \"NOT_FOUND\", message: \"User not found\" } }\n * const result = errResultSchema[\"~standard\"].validate({\n * data: null,\n * error: { code: \"NOT_FOUND\", message: \"User not found\" },\n * });\n * ```\n */\nexport function ErrSchema<TSchema extends StandardTypedV1>(\n\tinnerSchema: TSchema,\n): Err<TSchema> {\n\tconst base = {\n\t\t\"~standard\": {\n\t\t\tversion: 1 as const,\n\t\t\tvendor: \"wellcrafted\",\n\t\t\ttypes: {\n\t\t\t\tinput: undefined as unknown as {\n\t\t\t\t\tdata: null;\n\t\t\t\t\terror: StandardTypedV1.InferInput<TSchema>;\n\t\t\t\t},\n\t\t\t\toutput: undefined as unknown as {\n\t\t\t\t\tdata: null;\n\t\t\t\t\terror: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n\n\tif (hasValidate(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).validate =\n\t\t\tcreateErrValidate(innerSchema);\n\t}\n\n\tif (hasJsonSchema(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).jsonSchema =\n\t\t\tcreateErrJsonSchema(innerSchema);\n\t}\n\n\treturn base as Err<TSchema>;\n}\n","import { FAILURES } from \"./failures.js\";\nimport {\n\thasJsonSchema,\n\thasValidate,\n\ttype StandardJSONSchemaV1,\n\ttype StandardSchemaV1,\n\ttype StandardTypedV1,\n} from \"./types.js\";\n\n/**\n * Output type for OkSchema - wraps inner schema's types with Ok structure.\n *\n * Preserves the capabilities of the input schema:\n * - If input has validate, output has validate\n * - If input has jsonSchema, output has jsonSchema\n */\nexport type Ok<TSchema extends StandardTypedV1> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: \"wellcrafted\";\n\t\treadonly types: {\n\t\t\treadonly input: {\n\t\t\t\tdata: StandardTypedV1.InferInput<TSchema>;\n\t\t\t\terror: null;\n\t\t\t};\n\t\t\treadonly output: {\n\t\t\t\tdata: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t\terror: null;\n\t\t\t};\n\t\t};\n\t} & (TSchema extends StandardSchemaV1\n\t\t? {\n\t\t\t\treadonly validate: StandardSchemaV1.Props<\n\t\t\t\t\t{ data: StandardTypedV1.InferInput<TSchema>; error: null },\n\t\t\t\t\t{ data: StandardTypedV1.InferOutput<TSchema>; error: null }\n\t\t\t\t>[\"validate\"];\n\t\t\t}\n\t\t: Record<string, never>) &\n\t\t(TSchema extends StandardJSONSchemaV1\n\t\t\t? { readonly jsonSchema: StandardJSONSchemaV1.Converter }\n\t\t\t: Record<string, never>);\n};\n\nfunction createOkValidate<TSchema extends StandardSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardSchemaV1.Props<\n\t{ data: StandardTypedV1.InferInput<TSchema>; error: null },\n\t{ data: StandardTypedV1.InferOutput<TSchema>; error: null }\n>[\"validate\"] {\n\treturn (value: unknown) => {\n\t\tif (typeof value !== \"object\" || value === null) {\n\t\t\treturn FAILURES.EXPECTED_OBJECT;\n\t\t}\n\n\t\tif (!(\"data\" in value) || !(\"error\" in value)) {\n\t\t\treturn FAILURES.EXPECTED_DATA_ERROR_PROPS;\n\t\t}\n\n\t\tconst obj = value as { data: unknown; error: unknown };\n\n\t\tif (obj.error !== null) {\n\t\t\treturn FAILURES.EXPECTED_ERROR_NULL;\n\t\t}\n\n\t\tconst innerResult = innerSchema[\"~standard\"].validate(obj.data);\n\n\t\tif (innerResult instanceof Promise) {\n\t\t\treturn innerResult.then((r) => {\n\t\t\t\tif (r.issues) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t\t\t})),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: { data: r.value, error: null as null } };\n\t\t\t});\n\t\t}\n\n\t\tif (innerResult.issues) {\n\t\t\treturn {\n\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t...issue,\n\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t})),\n\t\t\t};\n\t\t}\n\n\t\treturn { value: { data: innerResult.value, error: null as null } };\n\t};\n}\n\nfunction createOkJsonSchema<TSchema extends StandardJSONSchemaV1>(\n\tinnerSchema: TSchema,\n): StandardJSONSchemaV1.Converter {\n\treturn {\n\t\tinput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: innerSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t\toutput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: {\n\t\t\t\t\tdata: innerSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t},\n\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\tadditionalProperties: false,\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Wraps a Standard Schema into an Ok variant schema.\n *\n * Takes a schema for type T and returns a schema for `{ data: T, error: null }`.\n * Preserves the capabilities of the input schema (validate, jsonSchema, or both).\n *\n * @example\n * ```typescript\n * import { z } from \"zod\";\n * import { OkSchema } from \"wellcrafted/standard-schema\";\n *\n * const userSchema = z.object({ name: z.string() });\n * const okUserSchema = OkSchema(userSchema);\n *\n * // Validates: { data: { name: \"Alice\" }, error: null }\n * const result = okUserSchema[\"~standard\"].validate({\n * data: { name: \"Alice\" },\n * error: null,\n * });\n * ```\n */\nexport function OkSchema<TSchema extends StandardTypedV1>(\n\tinnerSchema: TSchema,\n): Ok<TSchema> {\n\tconst base = {\n\t\t\"~standard\": {\n\t\t\tversion: 1 as const,\n\t\t\tvendor: \"wellcrafted\",\n\t\t\ttypes: {\n\t\t\t\tinput: undefined as unknown as {\n\t\t\t\t\tdata: StandardTypedV1.InferInput<TSchema>;\n\t\t\t\t\terror: null;\n\t\t\t\t},\n\t\t\t\toutput: undefined as unknown as {\n\t\t\t\t\tdata: StandardTypedV1.InferOutput<TSchema>;\n\t\t\t\t\terror: null;\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t};\n\n\tif (hasValidate(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).validate =\n\t\t\tcreateOkValidate(innerSchema);\n\t}\n\n\tif (hasJsonSchema(innerSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).jsonSchema =\n\t\t\tcreateOkJsonSchema(innerSchema);\n\t}\n\n\treturn base as Ok<TSchema>;\n}\n","import { FAILURES } from \"./failures.js\";\nimport {\n\thasJsonSchema,\n\thasValidate,\n\ttype StandardJSONSchemaV1,\n\ttype StandardSchemaV1,\n\ttype StandardTypedV1,\n} from \"./types.js\";\n\n/**\n * Output type for ResultSchema - creates a discriminated union of Ok and Err.\n *\n * Preserves the capabilities of the input schemas:\n * - If both inputs have validate, output has validate\n * - If both inputs have jsonSchema, output has jsonSchema\n */\nexport type Result<\n\tTDataSchema extends StandardTypedV1,\n\tTErrorSchema extends StandardTypedV1,\n> = {\n\treadonly \"~standard\": {\n\t\treadonly version: 1;\n\t\treadonly vendor: \"wellcrafted\";\n\t\treadonly types: {\n\t\t\treadonly input:\n\t\t\t\t| { data: StandardTypedV1.InferInput<TDataSchema>; error: null }\n\t\t\t\t| { data: null; error: StandardTypedV1.InferInput<TErrorSchema> };\n\t\t\treadonly output:\n\t\t\t\t| { data: StandardTypedV1.InferOutput<TDataSchema>; error: null }\n\t\t\t\t| { data: null; error: StandardTypedV1.InferOutput<TErrorSchema> };\n\t\t};\n\t} & (TDataSchema extends StandardSchemaV1\n\t\t? TErrorSchema extends StandardSchemaV1\n\t\t\t? {\n\t\t\t\t\treadonly validate: StandardSchemaV1.Props<\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: StandardTypedV1.InferInput<TDataSchema>;\n\t\t\t\t\t\t\t\terror: null;\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: null;\n\t\t\t\t\t\t\t\terror: StandardTypedV1.InferInput<TErrorSchema>;\n\t\t\t\t\t\t },\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: StandardTypedV1.InferOutput<TDataSchema>;\n\t\t\t\t\t\t\t\terror: null;\n\t\t\t\t\t\t }\n\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\tdata: null;\n\t\t\t\t\t\t\t\terror: StandardTypedV1.InferOutput<TErrorSchema>;\n\t\t\t\t\t\t }\n\t\t\t\t\t>[\"validate\"];\n\t\t\t\t}\n\t\t\t: Record<string, never>\n\t\t: Record<string, never>) &\n\t\t(TDataSchema extends StandardJSONSchemaV1\n\t\t\t? TErrorSchema extends StandardJSONSchemaV1\n\t\t\t\t? { readonly jsonSchema: StandardJSONSchemaV1.Converter }\n\t\t\t\t: Record<string, never>\n\t\t\t: Record<string, never>);\n};\n\nfunction createResultValidate<\n\tTDataSchema extends StandardSchemaV1,\n\tTErrorSchema extends StandardSchemaV1,\n>(\n\tdataSchema: TDataSchema,\n\terrorSchema: TErrorSchema,\n): StandardSchemaV1.Props<\n\t| { data: StandardTypedV1.InferInput<TDataSchema>; error: null }\n\t| { data: null; error: StandardTypedV1.InferInput<TErrorSchema> },\n\t| { data: StandardTypedV1.InferOutput<TDataSchema>; error: null }\n\t| { data: null; error: StandardTypedV1.InferOutput<TErrorSchema> }\n>[\"validate\"] {\n\treturn (value: unknown) => {\n\t\tif (typeof value !== \"object\" || value === null) {\n\t\t\treturn FAILURES.EXPECTED_OBJECT;\n\t\t}\n\n\t\tif (!(\"data\" in value) || !(\"error\" in value)) {\n\t\t\treturn FAILURES.EXPECTED_DATA_ERROR_PROPS;\n\t\t}\n\n\t\tconst obj = value as { data: unknown; error: unknown };\n\n\t\tconst isOk = obj.error === null;\n\n\t\tif (isOk) {\n\t\t\tconst innerResult = dataSchema[\"~standard\"].validate(obj.data);\n\n\t\t\tif (innerResult instanceof Promise) {\n\t\t\t\treturn innerResult.then((r) => {\n\t\t\t\t\tif (r.issues) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn { value: { data: r.value, error: null as null } };\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (innerResult.issues) {\n\t\t\t\treturn {\n\t\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t...issue,\n\t\t\t\t\t\tpath: [\"data\", ...(issue.path || [])],\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn { value: { data: innerResult.value, error: null as null } };\n\t\t}\n\n\t\tconst innerResult = errorSchema[\"~standard\"].validate(obj.error);\n\n\t\tif (innerResult instanceof Promise) {\n\t\t\treturn innerResult.then((r) => {\n\t\t\t\tif (r.issues) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tissues: r.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t\t\t})),\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn { value: { data: null as null, error: r.value } };\n\t\t\t});\n\t\t}\n\n\t\tif (innerResult.issues) {\n\t\t\treturn {\n\t\t\t\tissues: innerResult.issues.map((issue: StandardSchemaV1.Issue) => ({\n\t\t\t\t\t...issue,\n\t\t\t\t\tpath: [\"error\", ...(issue.path || [])],\n\t\t\t\t})),\n\t\t\t};\n\t\t}\n\n\t\treturn { value: { data: null as null, error: innerResult.value } };\n\t};\n}\n\nfunction createResultJsonSchema<\n\tTDataSchema extends StandardJSONSchemaV1,\n\tTErrorSchema extends StandardJSONSchemaV1,\n>(\n\tdataSchema: TDataSchema,\n\terrorSchema: TErrorSchema,\n): StandardJSONSchemaV1.Converter {\n\treturn {\n\t\tinput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\toneOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: dataSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\t\t\terror: errorSchema[\"~standard\"].jsonSchema.input(options),\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t},\n\t\toutput(options: StandardJSONSchemaV1.Options) {\n\t\t\treturn {\n\t\t\t\toneOf: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: dataSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t\t\t\terror: { type: \"null\" },\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {\n\t\t\t\t\t\t\tdata: { type: \"null\" },\n\t\t\t\t\t\t\terror: errorSchema[\"~standard\"].jsonSchema.output(options),\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: [\"data\", \"error\"],\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\t\t},\n\t};\n}\n\n/**\n * Combines two Standard Schemas into a Result discriminated union schema.\n *\n * Takes a data schema for type T and an error schema for type E, returning a schema\n * for `{ data: T, error: null } | { data: null, error: E }`.\n *\n * Preserves the capabilities of the input schemas - if both have validate, output\n * has validate; if both have jsonSchema, output has jsonSchema.\n *\n * @example\n * ```typescript\n * import { z } from \"zod\";\n * import { ResultSchema } from \"wellcrafted/standard-schema\";\n *\n * const userSchema = z.object({ id: z.string(), name: z.string() });\n * const errorSchema = z.object({ code: z.string(), message: z.string() });\n * const resultSchema = ResultSchema(userSchema, errorSchema);\n *\n * // Validates Ok variant: { data: { id: \"1\", name: \"Alice\" }, error: null }\n * // Validates Err variant: { data: null, error: { code: \"NOT_FOUND\", message: \"...\" } }\n * const result = resultSchema[\"~standard\"].validate({\n * data: { id: \"1\", name: \"Alice\" },\n * error: null,\n * });\n * ```\n */\nexport function ResultSchema<\n\tTDataSchema extends StandardTypedV1,\n\tTErrorSchema extends StandardTypedV1,\n>(\n\tdataSchema: TDataSchema,\n\terrorSchema: TErrorSchema,\n): Result<TDataSchema, TErrorSchema> {\n\tconst base = {\n\t\t\"~standard\": {\n\t\t\tversion: 1 as const,\n\t\t\tvendor: \"wellcrafted\",\n\t\t\ttypes: {\n\t\t\t\tinput: undefined as unknown as\n\t\t\t\t\t| { data: StandardTypedV1.InferInput<TDataSchema>; error: null }\n\t\t\t\t\t| { data: null; error: StandardTypedV1.InferInput<TErrorSchema> },\n\t\t\t\toutput: undefined as unknown as\n\t\t\t\t\t| { data: StandardTypedV1.InferOutput<TDataSchema>; error: null }\n\t\t\t\t\t| { data: null; error: StandardTypedV1.InferOutput<TErrorSchema> },\n\t\t\t},\n\t\t},\n\t};\n\n\tif (hasValidate(dataSchema) && hasValidate(errorSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).validate =\n\t\t\tcreateResultValidate(dataSchema, errorSchema);\n\t}\n\n\tif (hasJsonSchema(dataSchema) && hasJsonSchema(errorSchema)) {\n\t\t(base[\"~standard\"] as Record<string, unknown>).jsonSchema =\n\t\t\tcreateResultJsonSchema(dataSchema, errorSchema);\n\t}\n\n\treturn base as Result<TDataSchema, TErrorSchema>;\n}\n"],"mappings":";AAEA,MAAa,WAAW;CACvB,iBAAiB,EAAE,QAAQ,CA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
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.0",
|
|
4
4
|
"description": "Delightful TypeScript patterns for elegant, type-safe applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -17,6 +17,10 @@
|
|
|
17
17
|
"types": "./dist/error/index.d.ts",
|
|
18
18
|
"import": "./dist/error/index.js"
|
|
19
19
|
},
|
|
20
|
+
"./json": {
|
|
21
|
+
"types": "./dist/json.d.ts",
|
|
22
|
+
"import": "./dist/json.js"
|
|
23
|
+
},
|
|
20
24
|
"./brand": {
|
|
21
25
|
"types": "./dist/brand.d.ts",
|
|
22
26
|
"import": "./dist/brand.js"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"result-DolxQXIZ.d.ts","names":[],"sources":["../src/result/result.ts"],"sourcesContent":[],"mappings":";;AAWA;AAaA;AAqCA;;;;;;AAAsC;AAiBtC;AAAgE,KAnEpD,EAmEoD,CAAA,CAAA,CAAA,GAAA;EAAA,IAApC,EAnEA,CAmEA;EAAC,KAAM,EAAA,IAAA;CAAC;AAAF;AAiBlC;;;;;AAAqC;AAWrC;;;;AAAsE,KAlF1D,GAkF0D,CAAA,CAAA,CAAA,GAAA;EAAO,KAAA,EAlF/C,CAkF+C;EAcjE,IAAA,EAAA,IAAA;CAAoB;;;;AAA8C;AAuB9E;;;;;;AACI;AAqBJ;;;;;;AAGI;AAgCJ;;;;;AAEkB;AAgClB;;;;;;;AAA8D;AAyB9D;;;AAA8C,KAtMlC,MAsMkC,CAAA,CAAA,EAAA,CAAA,CAAA,GAtMnB,EAsMmB,CAtMhB,CAsMgB,CAAA,GAtMX,GAsMW,CAtMP,CAsMO,CAAA;;;;AAAkB;AAgDhE;;;;;;;AAGM;AAEN;;;AAEgC,cA5OnB,EA4OmB,EAAA,CAAA,CAAA,CAAA,CAAA,IAAA,EA5OJ,CA4OI,EAAA,GA5OA,EA4OA,CA5OG,CA4OH,CAAA;;;;;AACtB;AAEV;;;;;;;;;;AAGU,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