From ba853a8be56bba7183cc4fedcd3082bfee4d9488 Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Thu, 29 Oct 2026 21:57:48 +0700 Subject: [PATCH] Add Standard Schema support to `.json()` Fixes #2476 --- documentation/1-promise.md | 26 +++ documentation/2-options.md | 2 + documentation/8-errors.md | 29 ++- documentation/9-hooks.md | 3 + documentation/quick-start.md | 2 +- documentation/typescript.md | 7 + readme.md | 3 +- source/as-promise/index.ts | 37 +++- source/as-promise/types.ts | 36 +++- source/core/errors.ts | 35 ++++ source/core/options.ts | 2 + source/core/response.ts | 1 + source/core/standard-schema.ts | 56 +++++ source/index.ts | 1 + test/error.ts | 2 + test/promise.ts | 365 ++++++++++++++++++++++++++++++++- test/types/standard-schema.ts | 67 ++++++ 17 files changed, 661 insertions(+), 13 deletions(-) create mode 100644 source/core/standard-schema.ts create mode 100644 test/types/standard-schema.ts diff --git a/documentation/1-promise.md b/documentation/1-promise.md index e98dbf975..fee32eec0 100644 --- a/documentation/1-promise.md +++ b/documentation/1-promise.md @@ -34,6 +34,32 @@ A shortcut method that gives a Promise returning a JSON object. It is semantically the same as setting [`options.resolveBodyOnly`](2-options.md#resolvebodyonly) to `true` and [`options.responseType`](2-options.md#responsetype) to `'json'`. +### `promise.json(schema)` + +**Returns: `Promise>`** + +A shortcut method that gives a Promise returning a JSON object validated with a [Standard Schema](https://standardschema.dev)-compatible validator, such as [Zod](https://github.com/colinhacks/zod) or [Valibot](https://valibot.dev). The promise resolves with the output of the schema, and the return type is inferred from it. + +A custom [`parseJson`](2-options.md#parsejson) option runs first, so the schema receives the parsed body. The `validate` method of the schema may return a Promise. + +An empty response body parses to an empty string, the same as for [`promise.json()`](1-promise.md#promisejsont), so the schema receives `''`. + +Throws a [`SchemaValidationError`](8-errors.md#schemavalidationerror) when the body does not match the schema. + +> [!NOTE] +> A `TypeError` is thrown when the argument does not follow the Standard Schema specification, for example when it has no `~standard.validate` method. + +```js +import got from 'got'; +import {z} from 'zod'; + +const userSchema = z.object({name: z.string()}); + +const user = await got('https://example.com/user').json(userSchema); + +console.log(user.name); +``` + ### `promise.buffer()` **Returns: `Promise`** diff --git a/documentation/2-options.md b/documentation/2-options.md index a5f8b15d7..2b2c01fd4 100644 --- a/documentation/2-options.md +++ b/documentation/2-options.md @@ -658,6 +658,8 @@ The parsing method. The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.\ It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. +`.json()` also accepts a [Standard Schema](https://standardschema.dev) validator, in which case the promise resolves with the output of the schema. See [`promise.json(schema)`](1-promise.md#promisejsonschema). + ```js import got from 'got'; diff --git a/documentation/8-errors.md b/documentation/8-errors.md index 46a8743ac..a952682ce 100644 --- a/documentation/8-errors.md +++ b/documentation/8-errors.md @@ -15,6 +15,9 @@ All Got errors contain various metadata, such as: - `response` (optional) - An instance of Got Response, - `timings` (optional) - Points to `response.timings`. +> [!NOTE] +> [`SchemaValidationError`](#schemavalidationerror) is the exception: it comes from the user-provided schema instead of the request lifecycle, so the only metadata it adds is the schema `issues`. + #### Capturing async stack traces Read the article [here](async-stack-traces.md). @@ -27,7 +30,7 @@ Read the article [here](async-stack-traces.md). **Code: `ERR_GOT_REQUEST_ERROR`** -When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. All the errors below inherit this one. +When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. All the errors below inherit this one, except [`SchemaValidationError`](#schemavalidationerror). ### `CacheError` @@ -49,6 +52,30 @@ The error code will be `ERR_HTTP_CONTENT_LENGTH_MISMATCH` when the `strictConten When server response code is 2xx, and parsing body fails. Includes a `response` property. +### `SchemaValidationError` + +When the response body does not match the [Standard Schema](https://standardschema.dev) validator passed to [`promise.json(schema)`](1-promise.md#promisejsonschema). Includes an `issues` property with the issues from the schema. Each issue has a `message` and an optional `path`. + +It intentionally does not extend [`RequestError`](#requesterror), because the request succeeded. The user-provided schema did not accept the data, so it has no `code`, `options`, `request`, `response` or `timings` property, and it is not passed to [`beforeError` hooks](9-hooks.md#beforeerror). + +```js +import got, {SchemaValidationError} from 'got'; +import {z} from 'zod'; + +const userSchema = z.object({name: z.string()}); + +try { + const user = await got('https://example.com/user').json(userSchema); + console.log(user.name); +} catch (error) { + if (error instanceof SchemaValidationError) { + console.error(error.issues); + } else { + throw error; + } +} +``` + ### `UploadError` **Code: `ERR_UPLOAD`** diff --git a/documentation/9-hooks.md b/documentation/9-hooks.md index 7b572899e..2e9899758 100644 --- a/documentation/9-hooks.md +++ b/documentation/9-hooks.md @@ -409,6 +409,9 @@ const instance = got.extend({ Called with a [`RequestError`](8-errors.md#requesterror) instance. The error is passed to the hook right before it's thrown. +> [!NOTE] +> A [`SchemaValidationError`](8-errors.md#schemavalidationerror) is not passed to this hook, because it does not extend `RequestError`. + This hook can return any `Error` instance, allowing you to: - Return custom error classes for better error handling in your application - Extend `RequestError` with additional properties diff --git a/documentation/quick-start.md b/documentation/quick-start.md index 97d93fb7a..1d41617bf 100644 --- a/documentation/quick-start.md +++ b/documentation/quick-start.md @@ -118,7 +118,7 @@ See the documentation for other [options](2-options.md#options). ## Errors -Both Promise and Stream APIs throw errors with metadata. +Both Promise and Stream APIs throw errors with metadata, such as `response` and `timings`. ```js import got from 'got'; diff --git a/documentation/typescript.md b/documentation/typescript.md index 150554db9..1edbf7306 100644 --- a/documentation/typescript.md +++ b/documentation/typescript.md @@ -58,6 +58,7 @@ console.log(result.buzz); // boolean **Note:** > - Use `.json()` to get `RequestPromise` with the body-only response. +> - Use `.json(schema)` to validate the body with a [Standard Schema](https://standardschema.dev) validator and get the output type of the schema. > - Use `.buffer()` or `.text()` for other response types. > - Without calling these methods, you'll get `RequestPromise>`. > - Use `signal` and `AbortController` to abort requests. @@ -111,6 +112,12 @@ Here's a list of types that Got exports: ### [`RequestPromise`](https://github.com/sindresorhus/got/blob/ae04c0e36cf3f5b2e356df7d48a5b19988f935a2/source/as-promise/types.ts#L26) +### [`StandardSchemaV1`](https://github.com/sindresorhus/got/blob/main/source/core/standard-schema.ts) + +### [`StandardSchemaV1InferOutput`](https://github.com/sindresorhus/got/blob/main/source/core/standard-schema.ts) + +### [`StandardSchemaV1Issue`](https://github.com/sindresorhus/got/blob/main/source/core/standard-schema.ts) + ### [`Delays`](https://github.com/sindresorhus/got/blob/ae04c0e36cf3f5b2e356df7d48a5b19988f935a2/source/core/timed-out.ts#L14) ### [`Timings`](https://github.com/sindresorhus/got/blob/main/source/core/utils/timer.ts#L19) diff --git a/readme.md b/readme.md index e6bd0fb40..a04f9b224 100644 --- a/readme.md +++ b/readme.md @@ -82,7 +82,7 @@ npm install got ### JSON mode Got has a dedicated option for handling JSON payload.\ -Furthermore, the promise exposes a `.json()` function that returns `Promise`. +Furthermore, the promise exposes a `.json()` function that returns `Promise`. It also exposes a `.json(schema)` function that validates the payload with a [Standard Schema](https://standardschema.dev) and infers the type from the schema. ```js import got from 'got'; @@ -119,6 +119,7 @@ By default, Got will retry on failure. To disable this option, set [`options.ret - [x] [Advanced HTTPS API](documentation/5-https.md) - [x] [HTTP/2 support](documentation/2-options.md#http2) - [x] [`Response` class](documentation/3-streams.md#response-2) +- [x] [Response validation with Standard Schema](documentation/1-promise.md#promisejsonschema) #### Timeouts and retries diff --git a/source/as-promise/index.ts b/source/as-promise/index.ts index f69d5f77a..4ab31fdc4 100644 --- a/source/as-promise/index.ts +++ b/source/as-promise/index.ts @@ -4,9 +4,11 @@ import { normalizeError, HTTPError, RetryError, + SchemaValidationError, type RequestError, } from '../core/errors.js'; import Request from '../core/index.js'; +import type {StandardSchemaV1} from '../core/standard-schema.js'; import isNonReplayableBody from '../core/utils/is-non-replayable-body.js'; import { decodeUint8Array, @@ -36,6 +38,23 @@ const proxiedRequestEvents = [ 'downloadProgress', ]; +const validateWithSchema = async (value: unknown, schema: StandardSchemaV1): Promise => { + // JavaScript users can pass anything, so check the shape before calling into the schema. + const standardSchema = is.object(schema) ? schema['~standard'] : undefined; + + if (!is.object(standardSchema) || typeof standardSchema.validate !== 'function') { + throw new TypeError('The `schema` argument must follow the Standard Schema specification'); + } + + const validationResult = await standardSchema.validate(value); + + if (validationResult.issues) { + throw new SchemaValidationError(validationResult.issues); + } + + return validationResult.value; +}; + export default function asPromise(firstRequest?: Request): RequestPromise { let globalRequest: Request; let globalResponse: Response; @@ -261,7 +280,7 @@ export default function asPromise(firstRequest?: Request): RequestPromise }; } - const shortcut = (promiseToAwait: RequestPromise, responseType: Options['responseType']): RequestPromise => { + const shortcut = (promiseToAwait: RequestPromise, responseType: Options['responseType'], schema?: StandardSchemaV1): RequestPromise => { const newPromise = (async () => { // Wait until downloading has ended const response = await promiseToAwait as Response | undefined; @@ -275,7 +294,17 @@ export default function asPromise(firstRequest?: Request): RequestPromise // `parseBody` wraps a decode failure in a `ParseError`, so an unusable encoding is // reported with the response attached instead of as a bare `TypeError`. - return parseBody(globalResponse, responseType, options.parseJson, options.encoding) as T; + const body = parseBody(globalResponse, responseType, options.parseJson, options.encoding); + + if (schema === undefined) { + return body as T; + } + + // Awaiting instead of returning the validation promise keeps the caller's frame in the + // async stack trace of a `SchemaValidationError`. + const validatedBody = await validateWithSchema(body, schema); + + return validatedBody as T; })(); // eslint-disable-next-line @typescript-eslint/no-floating-promises @@ -288,7 +317,7 @@ export default function asPromise(firstRequest?: Request): RequestPromise // When custom handlers wrap the promise to transform errors, these methods // are copied to the handler's promise. Using `this` ensures we await the // handler's wrapped promise, not the original, so errors propagate correctly. - promise.json = function (this: RequestPromise) { + promise.json = function (this: RequestPromise, schema?: StandardSchemaV1) { if (globalRequest.options) { const {headers} = globalRequest.options; @@ -297,7 +326,7 @@ export default function asPromise(firstRequest?: Request): RequestPromise } } - return shortcut(this, 'json'); + return shortcut(this, 'json', schema); }; promise.buffer = function (this: RequestPromise) { diff --git a/source/as-promise/types.ts b/source/as-promise/types.ts index 149798dcf..aa98c5342 100644 --- a/source/as-promise/types.ts +++ b/source/as-promise/types.ts @@ -1,14 +1,40 @@ import {type RequestEvents} from '../core/index.js'; import type {Response} from '../core/response.js'; +import type {StandardSchemaV1, StandardSchemaV1InferOutput} from '../core/standard-schema.js'; // eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- Internal recursive shape requires interface; public API remains a type alias. interface RequestPromiseShape extends RequestEvents> { - /** - A shortcut method that gives a Promise returning a JSON object. + json: { + /** + A shortcut method that gives a Promise returning a JSON object. - It is semantically the same as setting `options.resolveBodyOnly` to `true` and `options.responseType` to `'json'`. - */ - json: () => RequestPromise; + It is semantically the same as setting `options.resolveBodyOnly` to `true` and `options.responseType` to `'json'`. + */ + (schema?: undefined): RequestPromise; + + /** + A shortcut method that gives a Promise returning a JSON object validated with a [Standard Schema](https://standardschema.dev)-compatible validator, such as [Zod](https://github.com/colinhacks/zod) or [Valibot](https://valibot.dev). The promise resolves with the output of the schema, and the return type is inferred from it. + + A custom `parseJson` option runs first, so the schema receives the parsed body. The `validate` method of the schema may return a Promise. + + An empty response body parses to an empty string, the same as for `.json()`, so the schema receives `''`. + + Throws a `SchemaValidationError` when the body does not match the schema. + + Throws a `TypeError` when the argument does not follow the Standard Schema specification, for example when it has no `~standard.validate` method. + + @example + ``` + import got from 'got'; + import {z} from 'zod'; + + const userSchema = z.object({name: z.string()}); + + const user = await got('https://example.com/user').json(userSchema); + ``` + */ + (schema: Schema): RequestPromise>; + }; /** A shortcut method that gives a Promise returning a [Uint8Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array). diff --git a/source/core/errors.ts b/source/core/errors.ts index 0f3882578..c23340dbc 100644 --- a/source/core/errors.ts +++ b/source/core/errors.ts @@ -1,5 +1,6 @@ import is from '@sindresorhus/is'; import stripUrlAuth from './utils/strip-url-auth.js'; +import type {StandardSchemaV1Issue} from './standard-schema.js'; import type {Timings} from './utils/timer.js'; import type Options from './options.js'; import type {TimeoutError as TimedOutTimeoutError} from './timed-out.js'; @@ -261,3 +262,37 @@ export class AbortError extends RequestError { } } } + +/** +An error to be thrown when the response body does not match the [Standard Schema](https://standardschema.dev) validator passed to `.json(schema)`. Includes an `issues` property with the issues from the schema. Each issue has a `message` and an optional `path`. + +It intentionally does not extend `RequestError`, because the request succeeded. The user-provided schema did not accept the data, so it has no `code`, `options`, `request`, `response` or `timings` property, and it is not passed to `beforeError` hooks. + +@example +``` +import got, {SchemaValidationError} from 'got'; +import {z} from 'zod'; + +const userSchema = z.object({name: z.string()}); + +try { + const user = await got('https://example.com/user').json(userSchema); + console.log(user.name); +} catch (error) { + if (error instanceof SchemaValidationError) { + console.error(error.issues); + } else { + throw error; + } +} +``` +*/ +export class SchemaValidationError extends Error { + override name = 'SchemaValidationError'; + readonly issues: readonly StandardSchemaV1Issue[]; + + constructor(issues: readonly StandardSchemaV1Issue[]) { + super('Response schema validation failed'); + this.issues = issues; + } +} diff --git a/source/core/options.ts b/source/core/options.ts index 81f7f88b0..371ac3bf1 100644 --- a/source/core/options.ts +++ b/source/core/options.ts @@ -3385,6 +3385,8 @@ export default class Options { It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise. + `.json()` also accepts a [Standard Schema](https://standardschema.dev) validator, in which case the promise resolves with the output of the schema. + __Note__: When using streams, this option is ignored. @example diff --git a/source/core/response.ts b/source/core/response.ts index 3cdf86620..79c5dd2a5 100644 --- a/source/core/response.ts +++ b/source/core/response.ts @@ -195,6 +195,7 @@ export const parseBody = (response: Response, responseType: ResponseType, parseJ } if (responseType === 'json') { + // TODO: In the next major version, return `undefined` instead of `''` for an empty body, to match Ky. This affects `.json()`, `.json(schema)`, and `responseType: 'json'`. Also decide whether a custom `parseJson` should be called with `''` (Ky calls it). if (rawBody.length === 0) { return ''; } diff --git a/source/core/standard-schema.ts b/source/core/standard-schema.ts new file mode 100644 index 000000000..b26e1395d --- /dev/null +++ b/source/core/standard-schema.ts @@ -0,0 +1,56 @@ +/** +The types of the [Standard Schema](https://standardschema.dev) specification (`v1`). + +Copied from the specification so Got does not need a dependency for types only. +*/ +export type StandardSchemaV1Issue = { + readonly message: string; + readonly path?: ReadonlyArray | undefined; +}; + +export type StandardSchemaV1SuccessResult = { + readonly value: OutputType; + readonly issues?: undefined; +}; + +export type StandardSchemaV1FailureResult = { + readonly issues: readonly StandardSchemaV1Issue[]; + readonly value?: undefined; +}; + +export type StandardSchemaV1Result = StandardSchemaV1SuccessResult | StandardSchemaV1FailureResult; + +export type StandardSchemaV1Types = { + readonly input: InputType; + readonly output: OutputType; +}; + +export type StandardSchemaV1Options = { + readonly libraryOptions?: Readonly> | undefined; +}; + +export type StandardSchemaV1 = { + readonly '~standard': { + readonly version: 1; + readonly vendor: string; + readonly validate: ( + value: unknown, + options?: StandardSchemaV1Options, + ) => StandardSchemaV1Result | Promise>; + readonly types?: StandardSchemaV1Types | undefined; + }; +}; + +/** +Infer the output type of a Standard Schema. +*/ +export type StandardSchemaV1InferOutput = Schema['~standard'] extends { + readonly types: StandardSchemaV1Types; +} + ? OutputType + : Extract< + Awaited>, + StandardSchemaV1SuccessResult + > extends StandardSchemaV1SuccessResult + ? OutputType + : unknown; diff --git a/source/index.ts b/source/index.ts index 23fb1ecd8..1762bd5ca 100644 --- a/source/index.ts +++ b/source/index.ts @@ -18,6 +18,7 @@ export * from './core/response.js'; export type {default as Request} from './core/index.js'; export * from './core/index.js'; export * from './core/errors.js'; +export type {StandardSchemaV1, StandardSchemaV1InferOutput, StandardSchemaV1Issue} from './core/standard-schema.js'; export * from './core/diagnostics-channel.js'; export type {Delays} from './core/timed-out.js'; export type {Timings} from './core/utils/timer.js'; diff --git a/test/error.ts b/test/error.ts index fd20d68c8..d8f35ff4f 100644 --- a/test/error.ts +++ b/test/error.ts @@ -15,6 +15,7 @@ import got, { ReadError, UploadError, CacheError, + SchemaValidationError, type Response, } from '../source/index.js'; import {rejects} from './helpers/rejects.js'; @@ -901,6 +902,7 @@ for (const [name, create, expectedName] of [ ['UploadError', () => new UploadError(new Error('inner'), {request: {options: {url: 'http://x/'}}} as never), 'UploadError'], ['CacheError', () => new CacheError(new Error('inner'), {request: {options: {url: 'http://x/'}}} as never), 'CacheError'], ['RequestError', () => new RequestError('plain', new Error('inner'), {options: {url: 'http://x/'}} as never), 'RequestError'], + ['SchemaValidationError', () => new SchemaValidationError([{message: 'Expected a string'}]), 'SchemaValidationError'], ] as Array<[string, () => Error, string]>) { test(`a ${name} reports its own name in the stack`, _t => { const error = create(); diff --git a/test/promise.ts b/test/promise.ts index 8b3c069e5..0642afaa0 100644 --- a/test/promise.ts +++ b/test/promise.ts @@ -1,14 +1,32 @@ import {Buffer} from 'node:buffer'; import {ReadStream} from 'node:fs'; import {ClientRequest} from 'node:http'; +import {setTimeout as delay} from 'node:timers/promises'; import assert from 'node:assert/strict'; import getStream from 'get-stream'; -import {type Response, AbortError, HTTPError} from '../source/index.js'; +import { + type Response, + type StandardSchemaV1, + AbortError, + HTTPError, + ParseError, + SchemaValidationError, +} from '../source/index.js'; import test from './helpers/test.js'; import {errorMatching} from './helpers/error-matching.js'; import {rejects} from './helpers/rejects.js'; import withServer from './helpers/with-server.js'; +const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification'; + +const createSchema = (validate: StandardSchemaV1['~standard']['validate']): StandardSchemaV1 => ({ + '~standard': { + version: 1, + vendor: 'test', + validate, + }, +}); + test('emits request event as promise', withServer, async (_t, server, got) => { server.get('/', (_request, response) => { response.statusCode = 200; @@ -730,3 +748,348 @@ test('the promise response event does not fire when the promise rejects with an assert.strictEqual(responseEvents, 0); }); + +test('promise.json(schema) validates the parsed body and resolves with the schema output', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(JSON.stringify({value: 1})); + }); + + let receivedValue: unknown; + const schema = createSchema<{doubled: number}>(value => { + receivedValue = value; + return {value: {doubled: 2}}; + }); + + assert.deepStrictEqual(await got('').json(schema), {doubled: 2}); + assert.deepStrictEqual(receivedValue, {value: 1}); +}); + +test('promise.json(undefined) parses JSON without validating', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(JSON.stringify({value: 1})); + }); + + assert.deepStrictEqual(await got('').json(undefined), {value: 1}); +}); + +test('promise.json(schema) throws SchemaValidationError when validation fails', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(JSON.stringify({value: 'one'})); + }); + + const issues = [{message: 'Expected number, received string', path: ['value']}]; + const schema = createSchema(() => ({issues})); + + const error = await rejects( + got('').json(schema), + errorMatching(SchemaValidationError, {message: 'Response schema validation failed'}), + ); + + assert.deepStrictEqual(error.issues, issues); +}); + +test('promise.json(schema) supports async validators', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(JSON.stringify({value: 1})); + }); + + const schema = createSchema(async value => { + await delay(1); + + return {value: (value as {value: number}).value}; + }); + + assert.strictEqual(await got('').json(schema), 1); +}); + +test('promise.json(schema) validates the result of the `parseJson` option', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('not json'); + }); + + let receivedValue: unknown; + const schema = createSchema(value => { + receivedValue = value; + return {value: 'validated'}; + }); + + const body = await got('', { + parseJson: () => ({value: 'parsed'}), + }).json(schema); + + assert.strictEqual(body, 'validated'); + assert.deepStrictEqual(receivedValue, {value: 'parsed'}); +}); + +test('promise.json(schema) rejects with a ParseError when the `parseJson` option throws', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('not json'); + }); + + const schema = createSchema(() => { + assert.fail('The schema must not run when parsing fails'); + }); + + const parseFailure = new Error('Custom parse failure'); + + const error = await rejects(got('', { + parseJson() { + throw parseFailure; + }, + }).json(schema), errorMatching(ParseError, {code: 'ERR_BODY_PARSE_FAILURE'})); + + assert.strictEqual(error.cause, parseFailure); +}); + +test('promise.json(schema) rejects with the error the schema throws', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('{}'); + }); + + const thrown = new Error('Validator failure'); + const schema = createSchema(() => { + throw thrown; + }); + + const error = await rejects(got('').json(schema)); + + assert.strictEqual(error, thrown); +}); + +for (const [label, value] of [ + ['an object without `~standard`', {}], + ['`null`', null], + ['a `~standard.validate` that is not a function', {'~standard': {version: 1, vendor: 'test', validate: 'nope'}}], +] as const) { + test(`promise.json(schema) throws a TypeError for ${label}`, withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('{}'); + }); + + // @ts-expect-error Testing invalid input. + await rejects(got('').json(value), errorMatching(TypeError, {message: invalidSchemaMessage})); + }); +} + +test('promise.json(schema) still rejects an HTTP error response before validating', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.statusCode = 404; + response.end('{}'); + }); + + const schema = createSchema(() => { + assert.fail('The schema must not run for an HTTP error'); + }); + + await rejects(got('').json(schema), errorMatching(HTTPError, {code: 'ERR_NON_2XX_3XX_RESPONSE'})); +}); + +test('promise.json(schema) validates an HTTP error response when `throwHttpErrors` is `false`', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.statusCode = 404; + response.end(JSON.stringify({error: 'missing'})); + }); + + let receivedValue: unknown; + const issues = [{message: 'Expected `ok`'}]; + const schema = createSchema(value => { + receivedValue = value; + return {issues}; + }); + + const error = await rejects( + got('', {throwHttpErrors: false}).json(schema), + errorMatching(SchemaValidationError, {message: 'Response schema validation failed'}), + ); + + assert.deepStrictEqual(error.issues, issues); + assert.deepStrictEqual(receivedValue, {error: 'missing'}); +}); + +test('promise.json(schema) treats an empty issues list as a validation failure', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('{}'); + }); + + const error = await rejects( + got('').json(createSchema(() => ({issues: []}))), + errorMatching(SchemaValidationError, {message: 'Response schema validation failed'}), + ); + + assert.deepStrictEqual(error.issues, []); +}); + +test('promise.json(schema) resolves with a falsy schema output', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('{}'); + }); + + for (const value of [undefined, null, 0, false, '']) { + // eslint-disable-next-line no-await-in-loop + assert.strictEqual(await got('').json(createSchema(() => ({value, issues: undefined}))), value); + } +}); + +test('promise.json(schema) validates each call independently and does not reject the request promise', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(JSON.stringify({value: 1})); + }); + + const promise = got(''); + const failingSchema = createSchema(() => ({issues: [{message: 'Expected a string'}]})); + const passingSchema = createSchema(value => ({value: (value as {value: number}).value})); + + const [, result, response] = await Promise.all([ + rejects(promise.json(failingSchema), errorMatching(SchemaValidationError, {message: 'Response schema validation failed'})), + promise.json(passingSchema), + promise, + ]); + + assert.strictEqual(result, 1); + assert.strictEqual(response.statusCode, 200); +}); + +test('promise.json(schema) validates only the final response after a retry, and a validation failure does not retry', withServer, async (_t, server, got) => { + let requestCount = 0; + + server.get('/', (_request, response) => { + requestCount++; + response.statusCode = requestCount === 1 ? 500 : 200; + response.end(JSON.stringify({attempt: requestCount})); + }); + + const receivedValues: unknown[] = []; + const schema = createSchema(value => { + receivedValues.push(value); + return {issues: [{message: 'Expected something else'}]}; + }); + + await rejects( + got('', {retry: {limit: 2, backoffLimit: 0, noise: 0}}).json(schema), + errorMatching(SchemaValidationError, {message: 'Response schema validation failed'}), + ); + + assert.strictEqual(requestCount, 2); + assert.deepStrictEqual(receivedValues, [{attempt: 2}]); +}); + +test('promise.json(schema) works through a handler that recovers an HTTP error response', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.statusCode = 404; + response.end(JSON.stringify({error: 'missing'})); + }); + + const instance = got.extend({ + handlers: [ + async (options, next) => { + try { + return await next(options); + } catch (error) { + if (error instanceof HTTPError) { + return error.response as Awaited>; + } + + throw error; + } + }, + ], + }); + + let receivedValue: unknown; + const schema = createSchema(value => { + receivedValue = value; + return {value: 'validated'}; + }); + + assert.strictEqual(await instance('').json(schema), 'validated'); + assert.deepStrictEqual(receivedValue, {error: 'missing'}); +}); + +test('promise.json(schema) keeps the caller in the error stack', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('{}'); + }); + + const schema = createSchema(() => ({issues: [{message: 'Expected an object'}]})); + + async function schemaValidationCaller() { + await got('').json(schema); + } + + const error = await rejects(schemaValidationCaller()); + + assert.ok(error instanceof SchemaValidationError); + assert.match(error.stack ?? '', /schemaValidationCaller/v); +}); + +test('promise.json(schema) does not run `beforeError` hooks', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end('{}'); + }); + + let calls = 0; + + const error = await rejects(got('', { + hooks: { + beforeError: [ + () => { + calls++; + return new Error('replaced'); + }, + ], + }, + }).json(createSchema(() => ({issues: [{message: 'Expected an object'}]})))); + + assert.ok(error instanceof SchemaValidationError); + assert.strictEqual(calls, 0); +}); + +test('promise.json(schema) accepts a callable schema', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(JSON.stringify({value: 1})); + }); + + // Some validators, such as ArkType, return a callable schema object. + const schema = Object.assign( + () => {}, + { + '~standard': { + version: 1 as const, + vendor: 'test', + validate: (value: unknown) => ({value: {received: value}}), + }, + }, + ); + + assert.deepStrictEqual(await got('').json(schema), {received: {value: 1}}); +}); + +test('promise.json(schema) receives an empty string for an empty body', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(); + }); + + let receivedValue: unknown; + const schema = createSchema(value => { + receivedValue = value; + return {value: 'empty'}; + }); + + assert.strictEqual(await got('').json(schema), 'empty'); + assert.strictEqual(receivedValue, ''); +}); + +test('promise.json(schema) validates when `resolveBodyOnly` is enabled', withServer, async (_t, server, got) => { + server.get('/', (_request, response) => { + response.end(JSON.stringify({value: 1})); + }); + + let receivedValue: unknown; + const schema = createSchema(value => { + receivedValue = value; + return {value: 'validated'}; + }); + + assert.strictEqual(await got('', {resolveBodyOnly: true}).json(schema), 'validated'); + assert.deepStrictEqual(receivedValue, {value: 1}); +}); diff --git a/test/types/standard-schema.ts b/test/types/standard-schema.ts new file mode 100644 index 000000000..a3c6e7b0c --- /dev/null +++ b/test/types/standard-schema.ts @@ -0,0 +1,67 @@ +import {expectTypeOf} from 'expect-type'; +import got, { + type RequestPromise, + type StandardSchemaV1, + type StandardSchemaV1InferOutput, +} from '../../source/index.js'; +import type {StandardSchemaV1Result, StandardSchemaV1Types} from '../../source/core/standard-schema.js'; + +const schema: StandardSchemaV1 = { + '~standard': { + version: 1, + vendor: 'test', + validate: () => ({value: {name: 'Sindre'}}), + }, +}; + +expectTypeOf(got('https://example.com').json()).toEqualTypeOf(); +expectTypeOf(got('https://example.com').json<{name: string}>()).toEqualTypeOf>(); +expectTypeOf(got('https://example.com').json(undefined)).toEqualTypeOf(); +expectTypeOf(got('https://example.com').json<{name: string}>(undefined)).toEqualTypeOf>(); +expectTypeOf(got('https://example.com').json(schema)).toEqualTypeOf>(); + +// A schema without a `types` property infers the output from the successful result of `validate`. +const inferredSchema = { + '~standard': { + version: 1, + vendor: 'test', + validate: async () => ({value: 1}), + }, +} satisfies StandardSchemaV1; + +expectTypeOf(got('https://example.com').json(inferredSchema)).toEqualTypeOf>(); + +// A schema with a loosely typed `validate` but a precise `types` property infers the output from `types`. +type PreciseTypesSchema = { + '~standard': { + readonly version: 1; + readonly vendor: 'test'; + readonly validate: (value: unknown) => StandardSchemaV1Result; + readonly types: StandardSchemaV1Types; + }; +}; + +expectTypeOf(got('https://example.com').json({} as PreciseTypesSchema)).toEqualTypeOf>(); + +// A transforming schema, such as `z.string().transform(Number)`, resolves with its output type, not its input type. +declare const transformingSchema: StandardSchemaV1; +expectTypeOf(got('https://example.com').json(transformingSchema)).toEqualTypeOf>(); + +// A schema annotated with the bare `StandardSchemaV1` must infer `unknown`, not `any`. +const looselyTypedSchema: StandardSchemaV1 = schema; +expectTypeOf(got('https://example.com').json(looselyTypedSchema)).toEqualTypeOf(); + +// The validated type survives chaining through the event methods. +expectTypeOf(got('https://example.com').json(schema).on('response', () => {})).toEqualTypeOf>(); + +// Users who wrap a schema can reuse the helper that the overload uses. +expectTypeOf>().toEqualTypeOf<{name: string}>(); + +// @ts-expect-error Non-schema objects must not match either overload. +expectTypeOf(got('https://example.com').json({})); + +// @ts-expect-error `null` is not a schema. +expectTypeOf(got('https://example.com').json(null)); + +// @ts-expect-error A schema supplies the return type. +expectTypeOf(got('https://example.com').json<{name: string}>(schema));