shelving 1.168.1 → 1.169.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.
@@ -33,8 +33,11 @@ export declare class Endpoint<P, R> {
33
33
  * @param callback The endpoint callback function that implements the logic for this endpoint by receiving the payload and returning the response.
34
34
  * @param unsafePayload The payload to pass into the callback (will be validated against this endpoint's payload schema).
35
35
  * @param request The entire HTTP request that is being handled (payload was possibly extracted from this somehow).
36
+ *
37
+ * @throws `Feedback` if the payload is invalid.
38
+ * @throws `ValueError` if `callback()` returns an invalid result.
36
39
  */
37
- handle(callback: EndpointCallback<P, R>, unsafePayload: unknown, request: Request): Promise<Response>;
40
+ handle(callback: EndpointCallback<P, R>, unsafePayload: unknown, request: Request, caller?: AnyCaller): Promise<Response>;
38
41
  /**
39
42
  * Render the URL for this endpoint with the given payload.
40
43
  * - URL mioght contain `{placeholder}` values that are replaced with values from the payload.
@@ -45,13 +48,14 @@ export declare class Endpoint<P, R> {
45
48
  * - Validates a payload against this endpoints payload schema
46
49
  * - Return an HTTP `Request` that will send it the valid payload to this endpoint.
47
50
  *
48
- * @throws Feedback if the payload is invalid.
51
+ * @throws `Feedback` if the payload is invalid.
49
52
  */
50
53
  request(payload: P, options?: RequestOptions, caller?: AnyCaller): Request;
51
54
  /**
52
55
  * Validate an HTTP `Response` against this endpoint.
53
- * @throws ResponseError if the response status is not ok (200-299)
54
- * @throws ResponseError if the response content is invalid.
56
+ *
57
+ * @throws `ResponseError` if the response status is not ok (200-299)
58
+ * @throws `ResponseError` if the response content is invalid.
55
59
  */
56
60
  response(response: Response, caller?: AnyCaller): Promise<R>;
57
61
  /**
@@ -59,9 +63,9 @@ export declare class Endpoint<P, R> {
59
63
  * - Validate the `payload` against this endpoint's payload schema.
60
64
  * - Validate the returned response against this endpoint's result schema.
61
65
  *
62
- * @throws Feedback if the payload is invalid.
63
- * @throws ResponseError if the response status is not ok (200-299)
64
- * @throws ResponseError if the response content is invalid.
66
+ * @throws `Feedback` if the payload is invalid.
67
+ * @throws `ResponseError` if the response status is not ok (200-299)
68
+ * @throws `ResponseError` if the response content is invalid.
65
69
  */
66
70
  fetch(payload: P, options?: RequestOptions, caller?: AnyCaller): Promise<R>;
67
71
  /** Convert to string, e.g. `GET https://a.com/user/{id}` */
@@ -1,10 +1,11 @@
1
1
  import { ResponseError } from "../error/ResponseError.js";
2
+ import { ValueError } from "../error/ValueError.js";
3
+ import { Feedback } from "../feedback/Feedback.js";
2
4
  import { UNDEFINED } from "../schema/Schema.js";
3
5
  import { assertDictionary } from "../util/dictionary.js";
4
6
  import { getMessage } from "../util/error.js";
5
7
  import { getRequest, getResponse, getResponseContent } from "../util/http.js";
6
8
  import { getPlaceholders, renderTemplate } from "../util/template.js";
7
- import { getValid } from "../util/validate.js";
8
9
  /**
9
10
  * An abstract API resource definition, used to specify types for e.g. serverless functions.
10
11
  *
@@ -42,16 +43,29 @@ export class Endpoint {
42
43
  * @param callback The endpoint callback function that implements the logic for this endpoint by receiving the payload and returning the response.
43
44
  * @param unsafePayload The payload to pass into the callback (will be validated against this endpoint's payload schema).
44
45
  * @param request The entire HTTP request that is being handled (payload was possibly extracted from this somehow).
46
+ *
47
+ * @throws `Feedback` if the payload is invalid.
48
+ * @throws `ValueError` if `callback()` returns an invalid result.
45
49
  */
46
- async handle(callback, unsafePayload, request) {
50
+ async handle(callback, unsafePayload, request, caller = this.handle) {
47
51
  // Validate the payload against this endpoint's payload type.
48
52
  const payload = this.payload.validate(unsafePayload);
49
53
  // Call the callback with the validated payload to get the result.
50
54
  const unsafeResult = await callback(payload, request);
51
- // Validate the result against this endpoint's result type.
52
- const result = getValid(unsafeResult, this.result);
53
- // Convert the result to a `Response` object.
54
- return getResponse(result);
55
+ try {
56
+ // Convert the result to a `Response` object.
57
+ return getResponse(this.result.validate(unsafeResult));
58
+ }
59
+ catch (thrown) {
60
+ if (thrown instanceof Feedback)
61
+ throw new ValueError(`Invalid result for ${this.toString()}:\n${thrown.message}`, {
62
+ endpoint: this,
63
+ callback,
64
+ cause: thrown,
65
+ caller,
66
+ });
67
+ throw thrown;
68
+ }
55
69
  }
56
70
  /**
57
71
  * Render the URL for this endpoint with the given payload.
@@ -73,15 +87,16 @@ export class Endpoint {
73
87
  * - Validates a payload against this endpoints payload schema
74
88
  * - Return an HTTP `Request` that will send it the valid payload to this endpoint.
75
89
  *
76
- * @throws Feedback if the payload is invalid.
90
+ * @throws `Feedback` if the payload is invalid.
77
91
  */
78
92
  request(payload, options = {}, caller = this.request) {
79
93
  return getRequest(this.method, this.url, this.payload.validate(payload), options, caller);
80
94
  }
81
95
  /**
82
96
  * Validate an HTTP `Response` against this endpoint.
83
- * @throws ResponseError if the response status is not ok (200-299)
84
- * @throws ResponseError if the response content is invalid.
97
+ *
98
+ * @throws `ResponseError` if the response status is not ok (200-299)
99
+ * @throws `ResponseError` if the response content is invalid.
85
100
  */
86
101
  async response(response, caller = this.response) {
87
102
  // Get the response.
@@ -89,18 +104,30 @@ export class Endpoint {
89
104
  const content = await getResponseContent(response, caller);
90
105
  // Throw `ResponseError` if the API returns status outside the 200-299 range.
91
106
  if (!ok)
92
- throw new ResponseError(getMessage(content) ?? `Error ${status}`, { cause: Response, caller });
107
+ throw new ResponseError(getMessage(content) ?? `Error ${status}`, { code: status, cause: response, caller });
93
108
  // Validate the success response.
94
- return getValid(content, this.result, ResponseError, caller);
109
+ try {
110
+ return this.result.validate(content);
111
+ }
112
+ catch (thrown) {
113
+ if (thrown instanceof Feedback)
114
+ throw new ResponseError(`Invalid result for ${this.toString()}:\n${thrown.message}`, {
115
+ endpoint: this,
116
+ code: 422,
117
+ cause: thrown,
118
+ caller,
119
+ });
120
+ throw thrown;
121
+ }
95
122
  }
96
123
  /**
97
124
  * Perform a fetch to this endpoint.
98
125
  * - Validate the `payload` against this endpoint's payload schema.
99
126
  * - Validate the returned response against this endpoint's result schema.
100
127
  *
101
- * @throws Feedback if the payload is invalid.
102
- * @throws ResponseError if the response status is not ok (200-299)
103
- * @throws ResponseError if the response content is invalid.
128
+ * @throws `Feedback` if the payload is invalid.
129
+ * @throws `ResponseError` if the response status is not ok (200-299)
130
+ * @throws `ResponseError` if the response content is invalid.
104
131
  */
105
132
  async fetch(payload, options = {}, caller = this.fetch) {
106
133
  const response = await fetch(this.request(payload, options, caller));
package/endpoint/util.js CHANGED
@@ -46,5 +46,5 @@ async function handleEndpoint(endpoint, callback, params, request, caller = hand
46
46
  // - If the content is anything else (e.g. string, number, array), return it directly (but you'll have no way to access the other params).
47
47
  const payload = content === undefined ? params : isPlainObject(content) ? { ...content, ...params } : content;
48
48
  // Call `endpoint.handle()` with the payload and request.
49
- return endpoint.handle(callback, payload, request);
49
+ return endpoint.handle(callback, payload, request, caller);
50
50
  }
@@ -1,27 +1,28 @@
1
1
  import { BaseError, type BaseErrorOptions } from "./BaseError.js";
2
- /** Error thrown when a request isn't well-formed. */
2
+ /** Options for `RequestError`. */
3
+ interface RequestErrorOptions extends BaseErrorOptions {
4
+ readonly code?: number;
5
+ }
6
+ /** Throw when a request isn't well-formed or is unacceptable in some way. */
3
7
  export declare class RequestError extends BaseError {
4
- /** The corresponding HTTP status code for this error, in the range `400-499` */
8
+ /** HTTP status code for this error, in the range `400-499` */
5
9
  readonly code: number;
6
- constructor(message?: string, options?: BaseErrorOptions);
10
+ constructor(message?: string, options?: RequestErrorOptions);
7
11
  }
8
- /** Thrown if an operation failed because the user is not logged in, or the login information is not well-formed. */
12
+ /** Throw if an operation failed because the user is not logged in, or the login information is not well-formed. */
9
13
  export declare class UnauthorizedError extends RequestError {
10
- readonly code: number;
11
- constructor(message?: string, options?: BaseErrorOptions);
14
+ constructor(message?: string, options?: RequestErrorOptions);
12
15
  }
13
- /** Thrown if the requested content is not found. */
16
+ /** Throw if the requested content is not found. */
14
17
  export declare class NotFoundError extends RequestError {
15
- readonly code: number;
16
- constructor(message?: string, options?: BaseErrorOptions);
18
+ constructor(message?: string, options?: RequestErrorOptions);
17
19
  }
18
- /** Error thrown when a request is is valid and well-formed, but its actual data is not. */
20
+ /** Throw when a request is valid and well-formed, but its actual data is not. */
19
21
  export declare class UnprocessableError extends RequestError {
20
- readonly code: number;
21
- constructor(message?: string, options?: BaseErrorOptions);
22
+ constructor(message?: string, options?: RequestErrorOptions);
22
23
  }
23
- /** Thrown if an operation failed because the user is logged in, but does not have sufficient privileges to access this content. */
24
+ /** Throw if an operation failed because the user is logged in, but does not have sufficient privileges to access this content. */
24
25
  export declare class ForbiddenError extends RequestError {
25
- readonly code: number;
26
- constructor(message?: string, options?: BaseErrorOptions);
26
+ constructor(message?: string, options?: RequestErrorOptions);
27
27
  }
28
+ export {};
@@ -1,42 +1,39 @@
1
1
  import { BaseError } from "./BaseError.js";
2
- /** Error thrown when a request isn't well-formed. */
2
+ /** Throw when a request isn't well-formed or is unacceptable in some way. */
3
3
  export class RequestError extends BaseError {
4
- /** The corresponding HTTP status code for this error, in the range `400-499` */
5
- code = 400;
4
+ /** HTTP status code for this error, in the range `400-499` */
5
+ code;
6
6
  constructor(message, options) {
7
7
  super(message, { caller: RequestError, ...options });
8
+ this.code = options?.code ?? 400;
8
9
  }
9
10
  }
10
11
  RequestError.prototype.name = "RequestError";
11
- /** Thrown if an operation failed because the user is not logged in, or the login information is not well-formed. */
12
+ /** Throw if an operation failed because the user is not logged in, or the login information is not well-formed. */
12
13
  export class UnauthorizedError extends RequestError {
13
- code = 401;
14
14
  constructor(message, options) {
15
- super(message, { caller: UnauthorizedError, ...options });
15
+ super(message, { caller: UnauthorizedError, code: 401, ...options });
16
16
  }
17
17
  }
18
18
  UnauthorizedError.prototype.name = "UnauthorizedError";
19
- /** Thrown if the requested content is not found. */
19
+ /** Throw if the requested content is not found. */
20
20
  export class NotFoundError extends RequestError {
21
- code = 404;
22
21
  constructor(message, options) {
23
- super(message, { caller: NotFoundError, ...options });
22
+ super(message, { caller: NotFoundError, code: 404, ...options });
24
23
  }
25
24
  }
26
25
  NotFoundError.prototype.name = "NotFoundError";
27
- /** Error thrown when a request is is valid and well-formed, but its actual data is not. */
26
+ /** Throw when a request is valid and well-formed, but its actual data is not. */
28
27
  export class UnprocessableError extends RequestError {
29
- code = 422;
30
28
  constructor(message, options) {
31
- super(message, { caller: UnprocessableError, ...options });
29
+ super(message, { caller: UnprocessableError, code: 422, ...options });
32
30
  }
33
31
  }
34
32
  UnprocessableError.prototype.name = "UnprocessableError";
35
- /** Thrown if an operation failed because the user is logged in, but does not have sufficient privileges to access this content. */
33
+ /** Throw if an operation failed because the user is logged in, but does not have sufficient privileges to access this content. */
36
34
  export class ForbiddenError extends RequestError {
37
- code = 403;
38
35
  constructor(message, options) {
39
- super(message, { caller: ForbiddenError, ...options });
36
+ super(message, { caller: ForbiddenError, code: 403, ...options });
40
37
  }
41
38
  }
42
39
  ForbiddenError.prototype.name = "ForbiddenError";
@@ -1,5 +1,12 @@
1
1
  import { BaseError, type BaseErrorOptions } from "./BaseError.js";
2
- /** Error thrown when an HTTP response isn't well-formed. */
2
+ /** Options for `ResponseError`. */
3
+ interface ResponseErrorOptions extends BaseErrorOptions {
4
+ readonly code?: number;
5
+ }
6
+ /** Error thrown when a received HTTP response isn't OK. */
3
7
  export declare class ResponseError extends BaseError {
4
- constructor(message?: string, options?: BaseErrorOptions);
8
+ /** HTTP status code for the response. */
9
+ readonly code: number;
10
+ constructor(message?: string, options?: ResponseErrorOptions);
5
11
  }
12
+ export {};
@@ -1,8 +1,11 @@
1
1
  import { BaseError } from "./BaseError.js";
2
- /** Error thrown when an HTTP response isn't well-formed. */
2
+ /** Error thrown when a received HTTP response isn't OK. */
3
3
  export class ResponseError extends BaseError {
4
+ /** HTTP status code for the response. */
5
+ code;
4
6
  constructor(message = ResponseError.prototype.message, options) {
5
7
  super(message, { caller: ResponseError, ...options });
8
+ this.code = options?.code ?? 400;
6
9
  }
7
10
  }
8
11
  ResponseError.prototype.name = "ResponseError";
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "state-management",
12
12
  "query-builder"
13
13
  ],
14
- "version": "1.168.1",
14
+ "version": "1.169.0",
15
15
  "repository": "https://github.com/dhoulb/shelving",
16
16
  "author": "Dave Houlbrooke <dave@shax.com>",
17
17
  "license": "0BSD",
@@ -1,6 +1,5 @@
1
- import type { Data } from "../util/data.js";
2
- import { type PossibleURIParams, type URIParams } from "../util/uri.js";
3
- import { type PossibleURL, type URL } from "../util/url.js";
1
+ import { type PossibleURIParams, type URIParams, type URIScheme } from "../util/uri.js";
2
+ import { type PossibleURL, type URL, type URLString } from "../util/url.js";
4
3
  import { Store } from "./Store.js";
5
4
  /** Store a URL, e.g. `https://top.com/a/b/c` */
6
5
  export declare class URLStore extends Store<URL> {
@@ -8,10 +7,10 @@ export declare class URLStore extends Store<URL> {
8
7
  constructor(url: PossibleURL, base?: PossibleURL);
9
8
  set value(url: PossibleURL);
10
9
  get value(): URL;
11
- get href(): string;
12
- set href(href: string);
13
- get origin(): string;
14
- get protocol(): string;
10
+ get href(): URLString;
11
+ set href(href: URLString);
12
+ get origin(): URLString;
13
+ get protocol(): URIScheme;
15
14
  get username(): string;
16
15
  get password(): string;
17
16
  get hostname(): string;
@@ -29,7 +28,7 @@ export declare class URLStore extends Store<URL> {
29
28
  /** Update a single param in this URL. */
30
29
  setParam(key: string, value: unknown): void;
31
30
  /** Update several params in this URL. */
32
- setParams(params: Data): void;
31
+ setParams(params: PossibleURIParams): void;
33
32
  /** Delete one or more params in this URL. */
34
33
  deleteParam(key: string, ...keys: string[]): void;
35
34
  /** Delete one or more params in this URL. */
package/util/uri.js CHANGED
@@ -19,13 +19,14 @@ export function getURI(possible) {
19
19
  if (isURI(possible))
20
20
  return possible;
21
21
  try {
22
- return new globalThis.URL(possible);
22
+ return new globalThis.URL(possible, _BASE);
23
23
  }
24
24
  catch {
25
25
  return undefined;
26
26
  }
27
27
  }
28
28
  }
29
+ const _BASE = typeof document === "object" ? document.baseURI : undefined;
29
30
  /** Convert a possible URI to a URI, or throw `RequiredError` if conversion fails. */
30
31
  export function requireURI(possible, caller = requireURI) {
31
32
  const url = getURI(possible);
@@ -1,6 +1,4 @@
1
- import type { BaseError, BaseErrorOptions } from "../error/BaseError.js";
2
1
  import type { ImmutableArray, PossibleArray } from "./array.js";
3
- import type { Constructor } from "./class.js";
4
2
  import type { Data } from "./data.js";
5
3
  import type { ImmutableDictionary } from "./dictionary.js";
6
4
  import type { AnyCaller } from "./function.js";
@@ -28,8 +26,10 @@ export type Validators<T extends Data = Data> = {
28
26
  export type ValidatorsType<T> = {
29
27
  readonly [K in keyof T]: ValidatorType<T[K]>;
30
28
  };
31
- /** Get value that validates against a given `Validator`, or throw `ValueError` */
32
- export declare function getValid<T>(value: unknown, validator: Validator<T>, ErrorConstructor?: Constructor<BaseError, [string, BaseErrorOptions]>, caller?: AnyCaller): T;
29
+ /** Require a valid value for a given validator, or return `undefined` if the value could not be validated. */
30
+ export declare function getValid<T>(value: unknown, validator: Validator<T>): T | undefined;
31
+ /** Require a valid value for a given validator, or throw `RequiredError` if the value could not be validated. */
32
+ export declare function requireValid<T>(value: unknown, validator: Validator<T>, caller?: AnyCaller): T;
33
33
  /**
34
34
  * Validate an iterable set of items with a validator.
35
35
  *
package/util/validate.js CHANGED
@@ -1,20 +1,29 @@
1
- import { ValueError } from "../error/ValueError.js";
1
+ import { RequiredError } from "../error/RequiredError.js";
2
2
  import { Feedback, ValueFeedback } from "../feedback/Feedback.js";
3
3
  import { isArray } from "./array.js";
4
4
  import { getDataProps } from "./data.js";
5
5
  import { getDictionaryItems } from "./dictionary.js";
6
6
  import { getNamedMessage } from "./error.js";
7
7
  import { isIterable } from "./iterate.js";
8
- /** Get value that validates against a given `Validator`, or throw `ValueError` */
9
- export function getValid(value, validator, ErrorConstructor = ValueError, caller = getValid) {
8
+ /** Require a valid value for a given validator, or return `undefined` if the value could not be validated. */
9
+ export function getValid(value, validator) {
10
10
  try {
11
11
  return validator.validate(value);
12
12
  }
13
13
  catch (thrown) {
14
- if (thrown instanceof Feedback) {
15
- const { message, ...rest } = thrown;
16
- throw new ErrorConstructor(message, { ...rest, cause: thrown, caller });
17
- }
14
+ if (thrown instanceof Feedback)
15
+ return undefined;
16
+ throw thrown;
17
+ }
18
+ }
19
+ /** Require a valid value for a given validator, or throw `RequiredError` if the value could not be validated. */
20
+ export function requireValid(value, validator, caller = requireValid) {
21
+ try {
22
+ return validator.validate(value);
23
+ }
24
+ catch (thrown) {
25
+ if (thrown instanceof Feedback)
26
+ throw new RequiredError(thrown.message, { cause: thrown, caller });
18
27
  throw thrown;
19
28
  }
20
29
  }