@notionhq/client 2.0.0 → 2.2.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.
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildRequestError = exports.APIResponseError = exports.UnknownHTTPResponseError = exports.isHTTPResponseError = exports.RequestTimeoutError = exports.isNotionClientError = exports.ClientErrorCode = exports.APIErrorCode = void 0;
4
- const helpers_1 = require("./helpers");
4
+ const utils_1 = require("./utils");
5
5
  /**
6
6
  * Error codes returned in responses from the API.
7
7
  */
@@ -37,7 +37,7 @@ class NotionClientErrorBase extends Error {
37
37
  * @returns `true` if error is a `NotionClientError`.
38
38
  */
39
39
  function isNotionClientError(error) {
40
- return (0, helpers_1.isObject)(error) && error instanceof NotionClientErrorBase;
40
+ return (0, utils_1.isObject)(error) && error instanceof NotionClientErrorBase;
41
41
  }
42
42
  exports.isNotionClientError = isNotionClientError;
43
43
  /**
@@ -186,7 +186,7 @@ function parseAPIErrorResponseBody(body) {
186
186
  catch (parseError) {
187
187
  return;
188
188
  }
189
- if (!(0, helpers_1.isObject)(parsed) ||
189
+ if (!(0, utils_1.isObject)(parsed) ||
190
190
  typeof parsed["message"] !== "string" ||
191
191
  !isAPIErrorCode(parsed["code"])) {
192
192
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";;;AACA,uCAAoC;AAGpC;;GAEG;AACH,IAAY,YAYX;AAZD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,0DAA0C,CAAA;IAC1C,mDAAmC,CAAA;IACnC,4CAA4B,CAAA;IAC5B,4CAA4B,CAAA;IAC5B,yDAAyC,CAAA;IACzC,kDAAkC,CAAA;IAClC,oDAAoC,CAAA;IACpC,gDAAgC,CAAA;IAChC,6DAA6C,CAAA;IAC7C,0DAA0C,CAAA;AAC5C,CAAC,EA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AC;KAC3B,CAAA;AACH,CAAC;AAED,SAAS,cAAc,CAAC,IAAa;IACnC,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,IAAI,aAAa,CAAA;AAC1D,CAAC","sourcesContent":["import { SupportedResponse } from \"./fetch-types\"\nimport { isObject } from \"./helpers\"\nimport { Assert } from \"./type-utils\"\n\n/**\n * Error codes returned in responses from the API.\n */\nexport enum APIErrorCode {\n Unauthorized = \"unauthorized\",\n RestrictedResource = \"restricted_resource\",\n ObjectNotFound = \"object_not_found\",\n RateLimited = \"rate_limited\",\n InvalidJSON = \"invalid_json\",\n InvalidRequestURL = \"invalid_request_url\",\n InvalidRequest = \"invalid_request\",\n ValidationError = \"validation_error\",\n ConflictError = \"conflict_error\",\n InternalServerError = \"internal_server_error\",\n ServiceUnavailable = \"service_unavailable\",\n}\n\n/**\n * Error codes generated for client errors.\n */\nexport enum ClientErrorCode {\n RequestTimeout = \"notionhq_client_request_timeout\",\n ResponseError = \"notionhq_client_response_error\",\n}\n\n/**\n * Error codes on errors thrown by the `Client`.\n */\nexport type NotionErrorCode = APIErrorCode | ClientErrorCode\n\n/**\n * Base error type.\n */\nabstract class NotionClientErrorBase<\n Code extends NotionErrorCode\n> extends Error {\n abstract code: Code\n}\n\n/**\n * Error type that encompasses all the kinds of errors that the Notion client will throw.\n */\nexport type NotionClientError =\n | RequestTimeoutError\n | UnknownHTTPResponseError\n | APIResponseError\n\n// Assert that NotionClientError's `code` property is a narrow type.\n// This prevents us from accidentally regressing to `string`-typed name field.\ntype _assertCodeIsNarrow = Assert<NotionErrorCode, NotionClientError[\"code\"]>\n\n// Assert that the type of `name` in NotionErrorCode is a narrow type.\n// This prevents us from accidentally regressing to `string`-typed name field.\ntype _assertNameIsNarrow = Assert<\n \"RequestTimeoutError\" | \"UnknownHTTPResponseError\" | \"APIResponseError\",\n NotionClientError[\"name\"]\n>\n\n/**\n * @param error any value, usually a caught error.\n * @returns `true` if error is a `NotionClientError`.\n */\nexport function isNotionClientError(\n error: unknown\n): error is NotionClientError {\n return isObject(error) && error instanceof NotionClientErrorBase\n}\n\n/**\n * Narrows down the types of a NotionClientError.\n * @param error any value, usually a caught error.\n * @param codes an object mapping from possible error codes to `true`\n * @returns `true` if error is a `NotionClientError` with a code in `codes`.\n */\nfunction isNotionClientErrorWithCode<Code extends NotionErrorCode>(\n error: unknown,\n codes: { [C in Code]: true }\n): error is NotionClientError & { code: Code } {\n return isNotionClientError(error) && error.code in codes\n}\n\n/**\n * Error thrown by the client if a request times out.\n */\nexport class RequestTimeoutError extends NotionClientErrorBase<ClientErrorCode.RequestTimeout> {\n readonly code = ClientErrorCode.RequestTimeout\n readonly name = \"RequestTimeoutError\"\n\n constructor(message = \"Request to Notion API has timed out\") {\n super(message)\n }\n\n static isRequestTimeoutError(error: unknown): error is RequestTimeoutError {\n return isNotionClientErrorWithCode(error, {\n [ClientErrorCode.RequestTimeout]: true,\n })\n }\n\n static rejectAfterTimeout<T>(\n promise: Promise<T>,\n timeoutMS: number\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new RequestTimeoutError())\n }, timeoutMS)\n\n promise\n .then(resolve)\n .catch(reject)\n .then(() => clearTimeout(timeoutId))\n })\n }\n}\n\ntype HTTPResponseErrorCode = ClientErrorCode.ResponseError | APIErrorCode\n\nclass HTTPResponseError<\n Code extends HTTPResponseErrorCode\n> extends NotionClientErrorBase<Code> {\n readonly name: string = \"HTTPResponseError\"\n readonly code: Code\n readonly status: number\n readonly headers: SupportedResponse[\"headers\"]\n readonly body: string\n\n constructor(args: {\n code: Code\n status: number\n message: string\n headers: SupportedResponse[\"headers\"]\n rawBodyText: string\n }) {\n super(args.message)\n const { code, status, headers, rawBodyText } = args\n this.code = code\n this.status = status\n this.headers = headers\n this.body = rawBodyText\n }\n}\n\nconst httpResponseErrorCodes: { [C in HTTPResponseErrorCode]: true } = {\n [ClientErrorCode.ResponseError]: true,\n [APIErrorCode.Unauthorized]: true,\n [APIErrorCode.RestrictedResource]: true,\n [APIErrorCode.ObjectNotFound]: true,\n [APIErrorCode.RateLimited]: true,\n [APIErrorCode.InvalidJSON]: true,\n [APIErrorCode.InvalidRequestURL]: true,\n [APIErrorCode.InvalidRequest]: true,\n [APIErrorCode.ValidationError]: true,\n [APIErrorCode.ConflictError]: true,\n [APIErrorCode.InternalServerError]: true,\n [APIErrorCode.ServiceUnavailable]: true,\n}\n\nexport function isHTTPResponseError(\n error: unknown\n): error is UnknownHTTPResponseError | APIResponseError {\n if (!isNotionClientErrorWithCode(error, httpResponseErrorCodes)) {\n return false\n }\n\n type _assert = Assert<\n UnknownHTTPResponseError | APIResponseError,\n typeof error\n >\n\n return true\n}\n\n/**\n * Error thrown if an API call responds with an unknown error code, or does not respond with\n * a property-formatted error.\n */\nexport class UnknownHTTPResponseError extends HTTPResponseError<ClientErrorCode.ResponseError> {\n readonly name = \"UnknownHTTPResponseError\"\n\n constructor(args: {\n status: number\n message: string | undefined\n headers: SupportedResponse[\"headers\"]\n rawBodyText: string\n }) {\n super({\n ...args,\n code: ClientErrorCode.ResponseError,\n message:\n args.message ??\n `Request to Notion API failed with status: ${args.status}`,\n })\n }\n\n static isUnknownHTTPResponseError(\n error: unknown\n ): error is UnknownHTTPResponseError {\n return isNotionClientErrorWithCode(error, {\n [ClientErrorCode.ResponseError]: true,\n })\n }\n}\n\nconst apiErrorCodes: { [C in APIErrorCode]: true } = {\n [APIErrorCode.Unauthorized]: true,\n [APIErrorCode.RestrictedResource]: true,\n [APIErrorCode.ObjectNotFound]: true,\n [APIErrorCode.RateLimited]: true,\n [APIErrorCode.InvalidJSON]: true,\n [APIErrorCode.InvalidRequestURL]: true,\n [APIErrorCode.InvalidRequest]: true,\n [APIErrorCode.ValidationError]: true,\n [APIErrorCode.ConflictError]: true,\n [APIErrorCode.InternalServerError]: true,\n [APIErrorCode.ServiceUnavailable]: true,\n}\n\n/**\n * A response from the API indicating a problem.\n * Use the `code` property to handle various kinds of errors. All its possible values are in `APIErrorCode`.\n */\nexport class APIResponseError extends HTTPResponseError<APIErrorCode> {\n readonly name = \"APIResponseError\"\n\n static isAPIResponseError(error: unknown): error is APIResponseError {\n return isNotionClientErrorWithCode(error, apiErrorCodes)\n }\n}\n\nexport function buildRequestError(\n response: SupportedResponse,\n bodyText: string\n): APIResponseError | UnknownHTTPResponseError {\n const apiErrorResponseBody = parseAPIErrorResponseBody(bodyText)\n if (apiErrorResponseBody !== undefined) {\n return new APIResponseError({\n code: apiErrorResponseBody.code,\n message: apiErrorResponseBody.message,\n headers: response.headers,\n status: response.status,\n rawBodyText: bodyText,\n })\n }\n return new UnknownHTTPResponseError({\n message: undefined,\n headers: response.headers,\n status: response.status,\n rawBodyText: bodyText,\n })\n}\n\nfunction parseAPIErrorResponseBody(\n body: string\n): { code: APIErrorCode; message: string } | undefined {\n if (typeof body !== \"string\") {\n return\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch (parseError) {\n return\n }\n\n if (\n !isObject(parsed) ||\n typeof parsed[\"message\"] !== \"string\" ||\n !isAPIErrorCode(parsed[\"code\"])\n ) {\n return\n }\n\n return {\n ...parsed,\n code: parsed[\"code\"],\n message: parsed[\"message\"],\n }\n}\n\nfunction isAPIErrorCode(code: unknown): code is APIErrorCode {\n return typeof code === \"string\" && code in apiErrorCodes\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";;;AACA,mCAAkC;AAGlC;;GAEG;AACH,IAAY,YAYX;AAZD,WAAY,YAAY;IACtB,6CAA6B,CAAA;IAC7B,0DAA0C,CAAA;IAC1C,mDAAmC,CAAA;IACnC,4CAA4B,CAAA;IAC5B,4CAA4B,CAAA;IAC5B,yDAAyC,CAAA;IACzC,kDAAkC,CAAA;IAClC,oDAAoC,CAAA;IACpC,gDAAgC,CAAA;IAChC,6DAA6C,CAAA;IAC7C,0DAA0C,CAAA;AAC5C,CAAC,EAZW,YAAY,GAAZ,oBA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,CAAC;AAED,SAAS,cAAc,CAAC,IAAa;IACnC,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,IAAI,aAAa,CAAA;AAC1D,CAAC","sourcesContent":["import { SupportedResponse } from \"./fetch-types\"\nimport { isObject } from \"./utils\"\nimport { Assert } from \"./type-utils\"\n\n/**\n * Error codes returned in responses from the API.\n */\nexport enum APIErrorCode {\n Unauthorized = \"unauthorized\",\n RestrictedResource = \"restricted_resource\",\n ObjectNotFound = \"object_not_found\",\n RateLimited = \"rate_limited\",\n InvalidJSON = \"invalid_json\",\n InvalidRequestURL = \"invalid_request_url\",\n InvalidRequest = \"invalid_request\",\n ValidationError = \"validation_error\",\n ConflictError = \"conflict_error\",\n InternalServerError = \"internal_server_error\",\n ServiceUnavailable = \"service_unavailable\",\n}\n\n/**\n * Error codes generated for client errors.\n */\nexport enum ClientErrorCode {\n RequestTimeout = \"notionhq_client_request_timeout\",\n ResponseError = \"notionhq_client_response_error\",\n}\n\n/**\n * Error codes on errors thrown by the `Client`.\n */\nexport type NotionErrorCode = APIErrorCode | ClientErrorCode\n\n/**\n * Base error type.\n */\nabstract class NotionClientErrorBase<\n Code extends NotionErrorCode\n> extends Error {\n abstract code: Code\n}\n\n/**\n * Error type that encompasses all the kinds of errors that the Notion client will throw.\n */\nexport type NotionClientError =\n | RequestTimeoutError\n | UnknownHTTPResponseError\n | APIResponseError\n\n// Assert that NotionClientError's `code` property is a narrow type.\n// This prevents us from accidentally regressing to `string`-typed name field.\ntype _assertCodeIsNarrow = Assert<NotionErrorCode, NotionClientError[\"code\"]>\n\n// Assert that the type of `name` in NotionErrorCode is a narrow type.\n// This prevents us from accidentally regressing to `string`-typed name field.\ntype _assertNameIsNarrow = Assert<\n \"RequestTimeoutError\" | \"UnknownHTTPResponseError\" | \"APIResponseError\",\n NotionClientError[\"name\"]\n>\n\n/**\n * @param error any value, usually a caught error.\n * @returns `true` if error is a `NotionClientError`.\n */\nexport function isNotionClientError(\n error: unknown\n): error is NotionClientError {\n return isObject(error) && error instanceof NotionClientErrorBase\n}\n\n/**\n * Narrows down the types of a NotionClientError.\n * @param error any value, usually a caught error.\n * @param codes an object mapping from possible error codes to `true`\n * @returns `true` if error is a `NotionClientError` with a code in `codes`.\n */\nfunction isNotionClientErrorWithCode<Code extends NotionErrorCode>(\n error: unknown,\n codes: { [C in Code]: true }\n): error is NotionClientError & { code: Code } {\n return isNotionClientError(error) && error.code in codes\n}\n\n/**\n * Error thrown by the client if a request times out.\n */\nexport class RequestTimeoutError extends NotionClientErrorBase<ClientErrorCode.RequestTimeout> {\n readonly code = ClientErrorCode.RequestTimeout\n readonly name = \"RequestTimeoutError\"\n\n constructor(message = \"Request to Notion API has timed out\") {\n super(message)\n }\n\n static isRequestTimeoutError(error: unknown): error is RequestTimeoutError {\n return isNotionClientErrorWithCode(error, {\n [ClientErrorCode.RequestTimeout]: true,\n })\n }\n\n static rejectAfterTimeout<T>(\n promise: Promise<T>,\n timeoutMS: number\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(new RequestTimeoutError())\n }, timeoutMS)\n\n promise\n .then(resolve)\n .catch(reject)\n .then(() => clearTimeout(timeoutId))\n })\n }\n}\n\ntype HTTPResponseErrorCode = ClientErrorCode.ResponseError | APIErrorCode\n\nclass HTTPResponseError<\n Code extends HTTPResponseErrorCode\n> extends NotionClientErrorBase<Code> {\n readonly name: string = \"HTTPResponseError\"\n readonly code: Code\n readonly status: number\n readonly headers: SupportedResponse[\"headers\"]\n readonly body: string\n\n constructor(args: {\n code: Code\n status: number\n message: string\n headers: SupportedResponse[\"headers\"]\n rawBodyText: string\n }) {\n super(args.message)\n const { code, status, headers, rawBodyText } = args\n this.code = code\n this.status = status\n this.headers = headers\n this.body = rawBodyText\n }\n}\n\nconst httpResponseErrorCodes: { [C in HTTPResponseErrorCode]: true } = {\n [ClientErrorCode.ResponseError]: true,\n [APIErrorCode.Unauthorized]: true,\n [APIErrorCode.RestrictedResource]: true,\n [APIErrorCode.ObjectNotFound]: true,\n [APIErrorCode.RateLimited]: true,\n [APIErrorCode.InvalidJSON]: true,\n [APIErrorCode.InvalidRequestURL]: true,\n [APIErrorCode.InvalidRequest]: true,\n [APIErrorCode.ValidationError]: true,\n [APIErrorCode.ConflictError]: true,\n [APIErrorCode.InternalServerError]: true,\n [APIErrorCode.ServiceUnavailable]: true,\n}\n\nexport function isHTTPResponseError(\n error: unknown\n): error is UnknownHTTPResponseError | APIResponseError {\n if (!isNotionClientErrorWithCode(error, httpResponseErrorCodes)) {\n return false\n }\n\n type _assert = Assert<\n UnknownHTTPResponseError | APIResponseError,\n typeof error\n >\n\n return true\n}\n\n/**\n * Error thrown if an API call responds with an unknown error code, or does not respond with\n * a property-formatted error.\n */\nexport class UnknownHTTPResponseError extends HTTPResponseError<ClientErrorCode.ResponseError> {\n readonly name = \"UnknownHTTPResponseError\"\n\n constructor(args: {\n status: number\n message: string | undefined\n headers: SupportedResponse[\"headers\"]\n rawBodyText: string\n }) {\n super({\n ...args,\n code: ClientErrorCode.ResponseError,\n message:\n args.message ??\n `Request to Notion API failed with status: ${args.status}`,\n })\n }\n\n static isUnknownHTTPResponseError(\n error: unknown\n ): error is UnknownHTTPResponseError {\n return isNotionClientErrorWithCode(error, {\n [ClientErrorCode.ResponseError]: true,\n })\n }\n}\n\nconst apiErrorCodes: { [C in APIErrorCode]: true } = {\n [APIErrorCode.Unauthorized]: true,\n [APIErrorCode.RestrictedResource]: true,\n [APIErrorCode.ObjectNotFound]: true,\n [APIErrorCode.RateLimited]: true,\n [APIErrorCode.InvalidJSON]: true,\n [APIErrorCode.InvalidRequestURL]: true,\n [APIErrorCode.InvalidRequest]: true,\n [APIErrorCode.ValidationError]: true,\n [APIErrorCode.ConflictError]: true,\n [APIErrorCode.InternalServerError]: true,\n [APIErrorCode.ServiceUnavailable]: true,\n}\n\n/**\n * A response from the API indicating a problem.\n * Use the `code` property to handle various kinds of errors. All its possible values are in `APIErrorCode`.\n */\nexport class APIResponseError extends HTTPResponseError<APIErrorCode> {\n readonly name = \"APIResponseError\"\n\n static isAPIResponseError(error: unknown): error is APIResponseError {\n return isNotionClientErrorWithCode(error, apiErrorCodes)\n }\n}\n\nexport function buildRequestError(\n response: SupportedResponse,\n bodyText: string\n): APIResponseError | UnknownHTTPResponseError {\n const apiErrorResponseBody = parseAPIErrorResponseBody(bodyText)\n if (apiErrorResponseBody !== undefined) {\n return new APIResponseError({\n code: apiErrorResponseBody.code,\n message: apiErrorResponseBody.message,\n headers: response.headers,\n status: response.status,\n rawBodyText: bodyText,\n })\n }\n return new UnknownHTTPResponseError({\n message: undefined,\n headers: response.headers,\n status: response.status,\n rawBodyText: bodyText,\n })\n}\n\nfunction parseAPIErrorResponseBody(\n body: string\n): { code: APIErrorCode; message: string } | undefined {\n if (typeof body !== \"string\") {\n return\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch (parseError) {\n return\n }\n\n if (\n !isObject(parsed) ||\n typeof parsed[\"message\"] !== \"string\" ||\n !isAPIErrorCode(parsed[\"code\"])\n ) {\n return\n }\n\n return {\n ...parsed,\n code: parsed[\"code\"],\n message: parsed[\"message\"],\n }\n}\n\nfunction isAPIErrorCode(code: unknown): code is APIErrorCode {\n return typeof code === \"string\" && code in apiErrorCodes\n}\n"]}
@@ -1,8 +1,7 @@
1
1
  /// <reference lib="dom" />
2
- import type { Await } from "./type-utils";
3
2
  import type { RequestInit as NodeRequestInit, Response as NodeResponse } from "node-fetch";
4
3
  declare type FetchFn = typeof fetch;
5
- declare type FetchResponse = Await<ReturnType<FetchFn>>;
4
+ declare type FetchResponse = Awaited<ReturnType<FetchFn>>;
6
5
  declare type RequestInit = NonNullable<Parameters<FetchFn>[1]>;
7
6
  export declare type SupportedRequestInfo = string;
8
7
  export declare type SupportedRequestInit = {
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-types.d.ts","sourceRoot":"","sources":["../../src/fetch-types.ts"],"names":[],"mappings":";AACA,OAAO,KAA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aAAa,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAA;AAEjD,aAAK,WAAW,GAAG,WAAW,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAEtD,oBAAY,oBAAoB,GAAG,MAAM,CAAA;AAGzC,oBAAY,oBAAoB,GAAG;IACjC,KAAK,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAA;IAChC,IAAI,CAAC,EAAE,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,WAAW,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAAA;IAC9E,OAAO,CAAC,EAAE,WAAW,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,GAC3C,WAAW,CAAC,eAAe,CAAC,SAAS,CAAC,CAAC,CAAA;IACzC,MAAM,CAAC,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAA;IAC9B,QAAQ,CAAC,EAAE,WAAW,CAAC,UAAU,CAAC,CAAA;CACnC,CAAA;AAGD,oBAAY,iBAAiB,GAAG,aAAa,GAAG,YAAY,CAAA;AAE5D,oBAAY,cAAc,GAAG,CAC3B,GAAG,EAAE,oBAAoB,EACzB,IAAI,CAAC,EAAE,oBAAoB,KACxB,OAAO,CAAC,iBAAiB,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-types.js","sourceRoot":"","sources":["../../src/fetch-types.ts"],"names":[],"mappings":"","sourcesContent":["/// <reference lib=\"dom\" />\nimport type { Assert, Await } from \"./type-utils\"\nimport type {\n RequestInit as NodeRequestInit,\n Response as NodeResponse,\n} from \"node-fetch\"\n\ntype FetchFn = typeof fetch\ntype FetchResponse = Await<ReturnType<FetchFn>>\ntype RequestInfo = Parameters<FetchFn>[0]\ntype RequestInit = NonNullable<Parameters<FetchFn>[1]>\n\nexport type SupportedRequestInfo = string\ntype _assertSupportedInfoIsSubtype = Assert<RequestInfo, SupportedRequestInfo>\n\nexport type SupportedRequestInit = {\n agent?: NodeRequestInit[\"agent\"]\n body?: NonNullable<RequestInit[\"body\"]> & NonNullable<NodeRequestInit[\"body\"]>\n headers?: NonNullable<RequestInit[\"headers\"]> &\n NonNullable<NodeRequestInit[\"headers\"]>\n method?: RequestInit[\"method\"]\n redirect?: RequestInit[\"redirect\"]\n}\ntype _assertSupportedInitIsSubtype = Assert<RequestInit, SupportedRequestInit>\n\nexport type SupportedResponse = FetchResponse | NodeResponse\n\nexport type SupportedFetch = (\n url: SupportedRequestInfo,\n init?: SupportedRequestInit\n) => Promise<SupportedResponse>\n"]}
1
+ {"version":3,"file":"fetch-types.js","sourceRoot":"","sources":["../../src/fetch-types.ts"],"names":[],"mappings":"","sourcesContent":["/// <reference lib=\"dom\" />\nimport type { Assert } from \"./type-utils\"\nimport type {\n RequestInit as NodeRequestInit,\n Response as NodeResponse,\n} from \"node-fetch\"\n\ntype FetchFn = typeof fetch\ntype FetchResponse = Awaited<ReturnType<FetchFn>>\ntype RequestInfo = Parameters<FetchFn>[0]\ntype RequestInit = NonNullable<Parameters<FetchFn>[1]>\n\nexport type SupportedRequestInfo = string\ntype _assertSupportedInfoIsSubtype = Assert<RequestInfo, SupportedRequestInfo>\n\nexport type SupportedRequestInit = {\n agent?: NodeRequestInit[\"agent\"]\n body?: NonNullable<RequestInit[\"body\"]> & NonNullable<NodeRequestInit[\"body\"]>\n headers?: NonNullable<RequestInit[\"headers\"]> &\n NonNullable<NodeRequestInit[\"headers\"]>\n method?: RequestInit[\"method\"]\n redirect?: RequestInit[\"redirect\"]\n}\ntype _assertSupportedInitIsSubtype = Assert<RequestInit, SupportedRequestInit>\n\nexport type SupportedResponse = FetchResponse | NodeResponse\n\nexport type SupportedFetch = (\n url: SupportedRequestInfo,\n init?: SupportedRequestInit\n) => Promise<SupportedResponse>\n"]}
@@ -1,13 +1,71 @@
1
+ import { BlockObjectResponse, CommentObjectResponse, DatabaseObjectResponse, PageObjectResponse, PartialBlockObjectResponse, PartialCommentObjectResponse, PartialDatabaseObjectResponse, PartialPageObjectResponse, PartialUserObjectResponse, UserObjectResponse } from "./api-endpoints";
2
+ interface PaginatedArgs {
3
+ start_cursor?: string;
4
+ }
5
+ interface PaginatedList<T> {
6
+ object: "list";
7
+ results: T[];
8
+ next_cursor: string | null;
9
+ has_more: boolean;
10
+ }
1
11
  /**
2
- * Utility for enforcing exhaustiveness checks in the type system.
12
+ * Returns an async iterator over the results of any paginated Notion API.
3
13
  *
4
- * @see https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks
14
+ * Example (given a notion Client called `notion`):
5
15
  *
6
- * @param value The variable with no remaining values
16
+ * ```
17
+ * for await (const block of iteratePaginatedAPI(notion.blocks.children.list, {
18
+ * block_id: parentBlockId,
19
+ * })) {
20
+ * // Do something with block.
21
+ * }
22
+ * ```
23
+ *
24
+ * @param listFn A bound function on the Notion client that represents a conforming paginated
25
+ * API. Example: `notion.blocks.children.list`.
26
+ * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent
27
+ * calls to the API. Any necessary `next_cursor` will be automatically populated by
28
+ * this function. Example: `{ block_id: "<my block id>" }`
29
+ */
30
+ export declare function iteratePaginatedAPI<Args extends PaginatedArgs, Item>(listFn: (args: Args) => Promise<PaginatedList<Item>>, firstPageArgs: Args): AsyncIterableIterator<Item>;
31
+ /**
32
+ * Collect all of the results of paginating an API into an in-memory array.
33
+ *
34
+ * Example (given a notion Client called `notion`):
35
+ *
36
+ * ```
37
+ * const blocks = collectPaginatedAPI(notion.blocks.children.list, {
38
+ * block_id: parentBlockId,
39
+ * })
40
+ * // Do something with blocks.
41
+ * ```
42
+ *
43
+ * @param listFn A bound function on the Notion client that represents a conforming paginated
44
+ * API. Example: `notion.blocks.children.list`.
45
+ * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent
46
+ * calls to the API. Any necessary `next_cursor` will be automatically populated by
47
+ * this function. Example: `{ block_id: "<my block id>" }`
48
+ */
49
+ export declare function collectPaginatedAPI<Args extends PaginatedArgs, Item>(listFn: (args: Args) => Promise<PaginatedList<Item>>, firstPageArgs: Args): Promise<Item[]>;
50
+ /**
51
+ * @returns `true` if `response` is a full `BlockObjectResponse`.
52
+ */
53
+ export declare function isFullBlock(response: BlockObjectResponse | PartialBlockObjectResponse): response is BlockObjectResponse;
54
+ /**
55
+ * @returns `true` if `response` is a full `PageObjectResponse`.
56
+ */
57
+ export declare function isFullPage(response: PageObjectResponse | PartialPageObjectResponse): response is PageObjectResponse;
58
+ /**
59
+ * @returns `true` if `response` is a full `DatabaseObjectResponse`.
60
+ */
61
+ export declare function isFullDatabase(response: DatabaseObjectResponse | PartialDatabaseObjectResponse): response is DatabaseObjectResponse;
62
+ /**
63
+ * @returns `true` if `response` is a full `UserObjectResponse`.
64
+ */
65
+ export declare function isFullUser(response: UserObjectResponse | PartialUserObjectResponse): response is UserObjectResponse;
66
+ /**
67
+ * @returns `true` if `response` is a full `CommentObjectResponse`.
7
68
  */
8
- export declare function assertNever(value: never): never;
9
- declare type AllKeys<T> = T extends unknown ? keyof T : never;
10
- export declare function pick<O extends unknown, K extends AllKeys<O>>(base: O, keys: readonly K[]): Pick<O, K>;
11
- export declare function isObject(o: unknown): o is Record<PropertyKey, unknown>;
69
+ export declare function isFullComment(response: CommentObjectResponse | PartialCommentObjectResponse): response is CommentObjectResponse;
12
70
  export {};
13
71
  //# sourceMappingURL=helpers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,CAE/C;AAED,aAAK,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,OAAO,GAAG,MAAM,CAAC,GAAG,KAAK,CAAA;AAErD,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,EAC1D,IAAI,EAAE,CAAC,EAC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AAG,0BAA0B,GACzD,QAAQ,IAAI,mBAAmB,CAEjC;AAED;;GAEG;AACH,wBAAgB,UAAU,CACxB,QAAQ,EAAE,kBAAkB,GAAG,yBAAyB,GACvD,QAAQ,IAAI,kBAAkB,CAEhC;AAED;;GAEG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,sBAAsB,GAAG,6BAA6B,GAC/D,QAAQ,IAAI,sBAAsB,CAEpC;AAED;;GAEG;AACH,wBAAgB,UAAU,CACxB,QAAQ,EAAE,kBAAkB,GAAG,yBAAyB,GACvD,QAAQ,IAAI,kBAAkB,CAEhC;AAED;;GAEG;AACH,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,qBAAqB,GAAG,4BAA4B,GAC7D,QAAQ,IAAI,qBAAqB,CAEnC"}
@@ -1,24 +1,96 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isObject = exports.pick = exports.assertNever = void 0;
3
+ exports.isFullComment = exports.isFullUser = exports.isFullDatabase = exports.isFullPage = exports.isFullBlock = exports.collectPaginatedAPI = exports.iteratePaginatedAPI = void 0;
4
4
  /**
5
- * Utility for enforcing exhaustiveness checks in the type system.
5
+ * Returns an async iterator over the results of any paginated Notion API.
6
6
  *
7
- * @see https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks
7
+ * Example (given a notion Client called `notion`):
8
8
  *
9
- * @param value The variable with no remaining values
9
+ * ```
10
+ * for await (const block of iteratePaginatedAPI(notion.blocks.children.list, {
11
+ * block_id: parentBlockId,
12
+ * })) {
13
+ * // Do something with block.
14
+ * }
15
+ * ```
16
+ *
17
+ * @param listFn A bound function on the Notion client that represents a conforming paginated
18
+ * API. Example: `notion.blocks.children.list`.
19
+ * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent
20
+ * calls to the API. Any necessary `next_cursor` will be automatically populated by
21
+ * this function. Example: `{ block_id: "<my block id>" }`
22
+ */
23
+ async function* iteratePaginatedAPI(listFn, firstPageArgs) {
24
+ let nextCursor = firstPageArgs.start_cursor;
25
+ do {
26
+ const response = await listFn({
27
+ ...firstPageArgs,
28
+ start_cursor: nextCursor,
29
+ });
30
+ yield* response.results;
31
+ nextCursor = response.next_cursor;
32
+ } while (nextCursor);
33
+ }
34
+ exports.iteratePaginatedAPI = iteratePaginatedAPI;
35
+ /**
36
+ * Collect all of the results of paginating an API into an in-memory array.
37
+ *
38
+ * Example (given a notion Client called `notion`):
39
+ *
40
+ * ```
41
+ * const blocks = collectPaginatedAPI(notion.blocks.children.list, {
42
+ * block_id: parentBlockId,
43
+ * })
44
+ * // Do something with blocks.
45
+ * ```
46
+ *
47
+ * @param listFn A bound function on the Notion client that represents a conforming paginated
48
+ * API. Example: `notion.blocks.children.list`.
49
+ * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent
50
+ * calls to the API. Any necessary `next_cursor` will be automatically populated by
51
+ * this function. Example: `{ block_id: "<my block id>" }`
52
+ */
53
+ async function collectPaginatedAPI(listFn, firstPageArgs) {
54
+ const results = [];
55
+ for await (const item of iteratePaginatedAPI(listFn, firstPageArgs)) {
56
+ results.push(item);
57
+ }
58
+ return results;
59
+ }
60
+ exports.collectPaginatedAPI = collectPaginatedAPI;
61
+ /**
62
+ * @returns `true` if `response` is a full `BlockObjectResponse`.
10
63
  */
11
- function assertNever(value) {
12
- throw new Error(`Unexpected value should never occur: ${value}`);
64
+ function isFullBlock(response) {
65
+ return "type" in response;
13
66
  }
14
- exports.assertNever = assertNever;
15
- function pick(base, keys) {
16
- const entries = keys.map(key => [key, base === null || base === void 0 ? void 0 : base[key]]);
17
- return Object.fromEntries(entries);
67
+ exports.isFullBlock = isFullBlock;
68
+ /**
69
+ * @returns `true` if `response` is a full `PageObjectResponse`.
70
+ */
71
+ function isFullPage(response) {
72
+ return "url" in response;
73
+ }
74
+ exports.isFullPage = isFullPage;
75
+ /**
76
+ * @returns `true` if `response` is a full `DatabaseObjectResponse`.
77
+ */
78
+ function isFullDatabase(response) {
79
+ return "title" in response;
18
80
  }
19
- exports.pick = pick;
20
- function isObject(o) {
21
- return typeof o === "object" && o !== null;
81
+ exports.isFullDatabase = isFullDatabase;
82
+ /**
83
+ * @returns `true` if `response` is a full `UserObjectResponse`.
84
+ */
85
+ function isFullUser(response) {
86
+ return "type" in response;
87
+ }
88
+ exports.isFullUser = isFullUser;
89
+ /**
90
+ * @returns `true` if `response` is a full `CommentObjectResponse`.
91
+ */
92
+ function isFullComment(response) {
93
+ return "created_by" in response;
22
94
  }
23
- exports.isObject = isObject;
95
+ exports.isFullComment = isFullComment;
24
96
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,KAAY;IACtC,MAAM,IAAI,KAAK,CAAC,wCAAwC,KAAK,EAAE,CAAC,CAAA;AAClE,CAAC;AAFD,kCAEC;AAID,SAAgB,IAAI,CAClB,IAAO,EACP,IAAkB;IAElB,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAG,GAAG,CAAC,CAAC,CAAC,CAAA;IACnD,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;AACpC,CAAC;AAND,oBAMC;AAED,SAAgB,QAAQ,CAAC,CAAU;IACjC,OAAO,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,CAAA;AAC5C,CAAC;AAFD,4BAEC","sourcesContent":["/**\n * Utility for enforcing exhaustiveness checks in the type system.\n *\n * @see https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks\n *\n * @param value The variable with no remaining values\n */\nexport function assertNever(value: never): never {\n throw new Error(`Unexpected value should never occur: ${value}`)\n}\n\ntype AllKeys<T> = T extends unknown ? keyof T : never\n\nexport function pick<O extends unknown, K extends AllKeys<O>>(\n base: O,\n keys: readonly K[]\n): Pick<O, K> {\n const entries = keys.map(key => [key, base?.[key]])\n return Object.fromEntries(entries)\n}\n\nexport function isObject(o: unknown): o is Record<PropertyKey, unknown> {\n return typeof o === \"object\" && o !== null\n}\n"]}
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":";;;AAwBA;;;;;;;;;;;;;;;;;;GAkBG;AACI,KAAK,SAAS,CAAC,CAAC,mBAAmB,CACxC,MAAoD,EACpD,aAAmB;IAEnB,IAAI,UAAU,GAA8B,aAAa,CAAC,YAAY,CAAA;IACtE,GAAG;QACD,MAAM,QAAQ,GAAwB,MAAM,MAAM,CAAC;YACjD,GAAG,aAAa;YAChB,YAAY,EAAE,UAAU;SACzB,CAAC,CAAA;QACF,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAA;QACvB,UAAU,GAAG,QAAQ,CAAC,WAAW,CAAA;KAClC,QAAQ,UAAU,EAAC;AACtB,CAAC;AAbD,kDAaC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACI,KAAK,UAAU,mBAAmB,CACvC,MAAoD,EACpD,aAAmB;IAEnB,MAAM,OAAO,GAAW,EAAE,CAAA;IAC1B,IAAI,KAAK,EAAE,MAAM,IAAI,IAAI,mBAAmB,CAAC,MAAM,EAAE,aAAa,CAAC,EAAE;QACnE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;KACnB;IACD,OAAO,OAAO,CAAA;AAChB,CAAC;AATD,kDASC;AAED;;GAEG;AACH,SAAgB,WAAW,CACzB,QAA0D;IAE1D,OAAO,MAAM,IAAI,QAAQ,CAAA;AAC3B,CAAC;AAJD,kCAIC;AAED;;GAEG;AACH,SAAgB,UAAU,CACxB,QAAwD;IAExD,OAAO,KAAK,IAAI,QAAQ,CAAA;AAC1B,CAAC;AAJD,gCAIC;AAED;;GAEG;AACH,SAAgB,cAAc,CAC5B,QAAgE;IAEhE,OAAO,OAAO,IAAI,QAAQ,CAAA;AAC5B,CAAC;AAJD,wCAIC;AAED;;GAEG;AACH,SAAgB,UAAU,CACxB,QAAwD;IAExD,OAAO,MAAM,IAAI,QAAQ,CAAA;AAC3B,CAAC;AAJD,gCAIC;AAED;;GAEG;AACH,SAAgB,aAAa,CAC3B,QAA8D;IAE9D,OAAO,YAAY,IAAI,QAAQ,CAAA;AACjC,CAAC;AAJD,sCAIC","sourcesContent":["import {\n BlockObjectResponse,\n CommentObjectResponse,\n DatabaseObjectResponse,\n PageObjectResponse,\n PartialBlockObjectResponse,\n PartialCommentObjectResponse,\n PartialDatabaseObjectResponse,\n PartialPageObjectResponse,\n PartialUserObjectResponse,\n UserObjectResponse,\n} from \"./api-endpoints\"\n\ninterface PaginatedArgs {\n start_cursor?: string\n}\n\ninterface PaginatedList<T> {\n object: \"list\"\n results: T[]\n next_cursor: string | null\n has_more: boolean\n}\n\n/**\n * Returns an async iterator over the results of any paginated Notion API.\n *\n * Example (given a notion Client called `notion`):\n *\n * ```\n * for await (const block of iteratePaginatedAPI(notion.blocks.children.list, {\n * block_id: parentBlockId,\n * })) {\n * // Do something with block.\n * }\n * ```\n *\n * @param listFn A bound function on the Notion client that represents a conforming paginated\n * API. Example: `notion.blocks.children.list`.\n * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent\n * calls to the API. Any necessary `next_cursor` will be automatically populated by\n * this function. Example: `{ block_id: \"<my block id>\" }`\n */\nexport async function* iteratePaginatedAPI<Args extends PaginatedArgs, Item>(\n listFn: (args: Args) => Promise<PaginatedList<Item>>,\n firstPageArgs: Args\n): AsyncIterableIterator<Item> {\n let nextCursor: string | null | undefined = firstPageArgs.start_cursor\n do {\n const response: PaginatedList<Item> = await listFn({\n ...firstPageArgs,\n start_cursor: nextCursor,\n })\n yield* response.results\n nextCursor = response.next_cursor\n } while (nextCursor)\n}\n\n/**\n * Collect all of the results of paginating an API into an in-memory array.\n *\n * Example (given a notion Client called `notion`):\n *\n * ```\n * const blocks = collectPaginatedAPI(notion.blocks.children.list, {\n * block_id: parentBlockId,\n * })\n * // Do something with blocks.\n * ```\n *\n * @param listFn A bound function on the Notion client that represents a conforming paginated\n * API. Example: `notion.blocks.children.list`.\n * @param firstPageArgs Arguments that should be passed to the API on the first and subsequent\n * calls to the API. Any necessary `next_cursor` will be automatically populated by\n * this function. Example: `{ block_id: \"<my block id>\" }`\n */\nexport async function collectPaginatedAPI<Args extends PaginatedArgs, Item>(\n listFn: (args: Args) => Promise<PaginatedList<Item>>,\n firstPageArgs: Args\n): Promise<Item[]> {\n const results: Item[] = []\n for await (const item of iteratePaginatedAPI(listFn, firstPageArgs)) {\n results.push(item)\n }\n return results\n}\n\n/**\n * @returns `true` if `response` is a full `BlockObjectResponse`.\n */\nexport function isFullBlock(\n response: BlockObjectResponse | PartialBlockObjectResponse\n): response is BlockObjectResponse {\n return \"type\" in response\n}\n\n/**\n * @returns `true` if `response` is a full `PageObjectResponse`.\n */\nexport function isFullPage(\n response: PageObjectResponse | PartialPageObjectResponse\n): response is PageObjectResponse {\n return \"url\" in response\n}\n\n/**\n * @returns `true` if `response` is a full `DatabaseObjectResponse`.\n */\nexport function isFullDatabase(\n response: DatabaseObjectResponse | PartialDatabaseObjectResponse\n): response is DatabaseObjectResponse {\n return \"title\" in response\n}\n\n/**\n * @returns `true` if `response` is a full `UserObjectResponse`.\n */\nexport function isFullUser(\n response: UserObjectResponse | PartialUserObjectResponse\n): response is UserObjectResponse {\n return \"type\" in response\n}\n\n/**\n * @returns `true` if `response` is a full `CommentObjectResponse`.\n */\nexport function isFullComment(\n response: CommentObjectResponse | PartialCommentObjectResponse\n): response is CommentObjectResponse {\n return \"created_by\" in response\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export { default as Client } from "./Client";
2
2
  export { LogLevel, Logger } from "./logging";
3
3
  export { NotionErrorCode, APIErrorCode, ClientErrorCode, NotionClientError, APIResponseError, UnknownHTTPResponseError, RequestTimeoutError, isNotionClientError, } from "./errors";
4
+ export { collectPaginatedAPI, iteratePaginatedAPI, isFullBlock, isFullDatabase, isFullPage, isFullUser, isFullComment, } from "./helpers";
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,UAAU,CAAA;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAC5C,OAAO,EAEL,eAAe,EACf,YAAY,EACZ,eAAe,EAEf,iBAAiB,EACjB,gBAAgB,EAChB,wBAAwB,EACxB,mBAAmB,EAEnB,mBAAmB,GACpB,MAAM,UAAU,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,UAAU,CAAA;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAC5C,OAAO,EAEL,eAAe,EACf,YAAY,EACZ,eAAe,EAEf,iBAAiB,EACjB,gBAAgB,EAChB,wBAAwB,EACxB,mBAAmB,EAEnB,mBAAmB,GACpB,MAAM,UAAU,CAAA;AACjB,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,WAAW,EACX,cAAc,EACd,UAAU,EACV,UAAU,EACV,aAAa,GACd,MAAM,WAAW,CAAA"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isNotionClientError = exports.RequestTimeoutError = exports.UnknownHTTPResponseError = exports.APIResponseError = exports.ClientErrorCode = exports.APIErrorCode = exports.LogLevel = exports.Client = void 0;
3
+ exports.isFullComment = exports.isFullUser = exports.isFullPage = exports.isFullDatabase = exports.isFullBlock = exports.iteratePaginatedAPI = exports.collectPaginatedAPI = exports.isNotionClientError = exports.RequestTimeoutError = exports.UnknownHTTPResponseError = exports.APIResponseError = exports.ClientErrorCode = exports.APIErrorCode = exports.LogLevel = exports.Client = void 0;
4
4
  var Client_1 = require("./Client");
5
5
  Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return Client_1.default; } });
6
6
  var logging_1 = require("./logging");
@@ -13,4 +13,12 @@ Object.defineProperty(exports, "UnknownHTTPResponseError", { enumerable: true, g
13
13
  Object.defineProperty(exports, "RequestTimeoutError", { enumerable: true, get: function () { return errors_1.RequestTimeoutError; } });
14
14
  // Error helpers
15
15
  Object.defineProperty(exports, "isNotionClientError", { enumerable: true, get: function () { return errors_1.isNotionClientError; } });
16
+ var helpers_1 = require("./helpers");
17
+ Object.defineProperty(exports, "collectPaginatedAPI", { enumerable: true, get: function () { return helpers_1.collectPaginatedAPI; } });
18
+ Object.defineProperty(exports, "iteratePaginatedAPI", { enumerable: true, get: function () { return helpers_1.iteratePaginatedAPI; } });
19
+ Object.defineProperty(exports, "isFullBlock", { enumerable: true, get: function () { return helpers_1.isFullBlock; } });
20
+ Object.defineProperty(exports, "isFullDatabase", { enumerable: true, get: function () { return helpers_1.isFullDatabase; } });
21
+ Object.defineProperty(exports, "isFullPage", { enumerable: true, get: function () { return helpers_1.isFullPage; } });
22
+ Object.defineProperty(exports, "isFullUser", { enumerable: true, get: function () { return helpers_1.isFullUser; } });
23
+ Object.defineProperty(exports, "isFullComment", { enumerable: true, get: function () { return helpers_1.isFullComment; } });
16
24
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,mCAA4C;AAAnC,gGAAA,OAAO,OAAU;AAC1B,qCAA4C;AAAnC,mGAAA,QAAQ,OAAA;AACjB,mCAYiB;AATf,sGAAA,YAAY,OAAA;AACZ,yGAAA,eAAe,OAAA;AAGf,0GAAA,gBAAgB,OAAA;AAChB,kHAAA,wBAAwB,OAAA;AACxB,6GAAA,mBAAmB,OAAA;AACnB,gBAAgB;AAChB,6GAAA,mBAAmB,OAAA","sourcesContent":["export { default as Client } from \"./Client\"\nexport { LogLevel, Logger } from \"./logging\"\nexport {\n // Error codes\n NotionErrorCode,\n APIErrorCode,\n ClientErrorCode,\n // Error types\n NotionClientError,\n APIResponseError,\n UnknownHTTPResponseError,\n RequestTimeoutError,\n // Error helpers\n isNotionClientError,\n} from \"./errors\"\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,mCAA4C;AAAnC,gGAAA,OAAO,OAAU;AAC1B,qCAA4C;AAAnC,mGAAA,QAAQ,OAAA;AACjB,mCAYiB;AATf,sGAAA,YAAY,OAAA;AACZ,yGAAA,eAAe,OAAA;AAGf,0GAAA,gBAAgB,OAAA;AAChB,kHAAA,wBAAwB,OAAA;AACxB,6GAAA,mBAAmB,OAAA;AACnB,gBAAgB;AAChB,6GAAA,mBAAmB,OAAA;AAErB,qCAQkB;AAPhB,8GAAA,mBAAmB,OAAA;AACnB,8GAAA,mBAAmB,OAAA;AACnB,sGAAA,WAAW,OAAA;AACX,yGAAA,cAAc,OAAA;AACd,qGAAA,UAAU,OAAA;AACV,qGAAA,UAAU,OAAA;AACV,wGAAA,aAAa,OAAA","sourcesContent":["export { default as Client } from \"./Client\"\nexport { LogLevel, Logger } from \"./logging\"\nexport {\n // Error codes\n NotionErrorCode,\n APIErrorCode,\n ClientErrorCode,\n // Error types\n NotionClientError,\n APIResponseError,\n UnknownHTTPResponseError,\n RequestTimeoutError,\n // Error helpers\n isNotionClientError,\n} from \"./errors\"\nexport {\n collectPaginatedAPI,\n iteratePaginatedAPI,\n isFullBlock,\n isFullDatabase,\n isFullPage,\n isFullUser,\n isFullComment,\n} from \"./helpers\"\n"]}
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.logLevelSeverity = exports.makeConsoleLogger = exports.LogLevel = void 0;
4
- const helpers_1 = require("./helpers");
4
+ const utils_1 = require("./utils");
5
5
  var LogLevel;
6
6
  (function (LogLevel) {
7
7
  LogLevel["DEBUG"] = "debug";
@@ -29,7 +29,7 @@ function logLevelSeverity(level) {
29
29
  case LogLevel.ERROR:
30
30
  return 80;
31
31
  default:
32
- return (0, helpers_1.assertNever)(level);
32
+ return (0, utils_1.assertNever)(level);
33
33
  }
34
34
  }
35
35
  exports.logLevelSeverity = logLevelSeverity;
@@ -1 +1 @@
1
- {"version":3,"file":"logging.js","sourceRoot":"","sources":["../../src/logging.ts"],"names":[],"mappings":";;;AAAA,uCAAuC;AAEvC,IAAY,QAKX;AALD,WAAY,QAAQ;IAClB,2BAAe,CAAA;IACf,yBAAa,CAAA;IACb,yBAAa,CAAA;IACb,2BAAe,CAAA;AACjB,CAAC,EALW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAKnB;AAMD,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE;QACnC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE,OAAO,EAAE,SAAS,CAAC,CAAA;IACzD,CAAC,CAAA;AACH,CAAC;AAJD,8CAIC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,KAAe;IAC9C,QAAQ,KAAK,EAAE;QACb,KAAK,QAAQ,CAAC,KAAK;YACjB,OAAO,EAAE,CAAA;QACX,KAAK,QAAQ,CAAC,IAAI;YAChB,OAAO,EAAE,CAAA;QACX,KAAK,QAAQ,CAAC,IAAI;YAChB,OAAO,EAAE,CAAA;QACX,KAAK,QAAQ,CAAC,KAAK;YACjB,OAAO,EAAE,CAAA;QACX;YACE,OAAO,IAAA,qBAAW,EAAC,KAAK,CAAC,CAAA;KAC5B;AACH,CAAC;AAbD,4CAaC","sourcesContent":["import { assertNever } from \"./helpers\"\n\nexport enum LogLevel {\n DEBUG = \"debug\",\n INFO = \"info\",\n WARN = \"warn\",\n ERROR = \"error\",\n}\n\nexport interface Logger {\n (level: LogLevel, message: string, extraInfo: Record<string, unknown>): void\n}\n\nexport function makeConsoleLogger(name: string): Logger {\n return (level, message, extraInfo) => {\n console[level](`${name} ${level}:`, message, extraInfo)\n }\n}\n\n/**\n * Transforms a log level into a comparable (numerical) value ordered by severity.\n */\nexport function logLevelSeverity(level: LogLevel): number {\n switch (level) {\n case LogLevel.DEBUG:\n return 20\n case LogLevel.INFO:\n return 40\n case LogLevel.WARN:\n return 60\n case LogLevel.ERROR:\n return 80\n default:\n return assertNever(level)\n }\n}\n"]}
1
+ {"version":3,"file":"logging.js","sourceRoot":"","sources":["../../src/logging.ts"],"names":[],"mappings":";;;AAAA,mCAAqC;AAErC,IAAY,QAKX;AALD,WAAY,QAAQ;IAClB,2BAAe,CAAA;IACf,yBAAa,CAAA;IACb,yBAAa,CAAA;IACb,2BAAe,CAAA;AACjB,CAAC,EALW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAKnB;AAMD,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE;QACnC,OAAO,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,IAAI,KAAK,GAAG,EAAE,OAAO,EAAE,SAAS,CAAC,CAAA;IACzD,CAAC,CAAA;AACH,CAAC;AAJD,8CAIC;AAED;;GAEG;AACH,SAAgB,gBAAgB,CAAC,KAAe;IAC9C,QAAQ,KAAK,EAAE;QACb,KAAK,QAAQ,CAAC,KAAK;YACjB,OAAO,EAAE,CAAA;QACX,KAAK,QAAQ,CAAC,IAAI;YAChB,OAAO,EAAE,CAAA;QACX,KAAK,QAAQ,CAAC,IAAI;YAChB,OAAO,EAAE,CAAA;QACX,KAAK,QAAQ,CAAC,KAAK;YACjB,OAAO,EAAE,CAAA;QACX;YACE,OAAO,IAAA,mBAAW,EAAC,KAAK,CAAC,CAAA;KAC5B;AACH,CAAC;AAbD,4CAaC","sourcesContent":["import { assertNever } from \"./utils\"\n\nexport enum LogLevel {\n DEBUG = \"debug\",\n INFO = \"info\",\n WARN = \"warn\",\n ERROR = \"error\",\n}\n\nexport interface Logger {\n (level: LogLevel, message: string, extraInfo: Record<string, unknown>): void\n}\n\nexport function makeConsoleLogger(name: string): Logger {\n return (level, message, extraInfo) => {\n console[level](`${name} ${level}:`, message, extraInfo)\n }\n}\n\n/**\n * Transforms a log level into a comparable (numerical) value ordered by severity.\n */\nexport function logLevelSeverity(level: LogLevel): number {\n switch (level) {\n case LogLevel.DEBUG:\n return 20\n case LogLevel.INFO:\n return 40\n case LogLevel.WARN:\n return 60\n case LogLevel.ERROR:\n return 80\n default:\n return assertNever(level)\n }\n}\n"]}
@@ -1,12 +1,6 @@
1
1
  /**
2
2
  * Utilities for working with typescript types
3
3
  */
4
- /**
5
- * Unwrap the type of a promise
6
- */
7
- export declare type Await<T> = T extends {
8
- then(onfulfilled?: (value: infer U) => unknown): unknown;
9
- } ? U : T;
10
4
  /**
11
5
  * Assert U is assignable to T.
12
6
  */
@@ -1 +1 @@
1
- {"version":3,"file":"type-utils.d.ts","sourceRoot":"","sources":["../../src/type-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,oBAAY,KAAK,CAAC,CAAC,IAAI,CAAC,SAAS;IAC/B,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,KAAK,OAAO,GAAG,OAAO,CAAA;CACzD,GACG,CAAC,GACD,CAAC,CAAA;AAEL;;GAEG;AACH,oBAAY,MAAM,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA"}
1
+ {"version":3,"file":"type-utils.d.ts","sourceRoot":"","sources":["../../src/type-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;GAEG;AACH,oBAAY,MAAM,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"type-utils.js","sourceRoot":"","sources":["../../src/type-utils.ts"],"names":[],"mappings":";AAAA;;GAEG","sourcesContent":["/**\n * Utilities for working with typescript types\n */\n\n/**\n * Unwrap the type of a promise\n */\nexport type Await<T> = T extends {\n then(onfulfilled?: (value: infer U) => unknown): unknown\n}\n ? U\n : T\n\n/**\n * Assert U is assignable to T.\n */\nexport type Assert<T, U extends T> = U\n"]}
1
+ {"version":3,"file":"type-utils.js","sourceRoot":"","sources":["../../src/type-utils.ts"],"names":[],"mappings":";AAAA;;GAEG","sourcesContent":["/**\n * Utilities for working with typescript types\n */\n\n/**\n * Assert U is assignable to T.\n */\nexport type Assert<T, U extends T> = U\n"]}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Utility for enforcing exhaustiveness checks in the type system.
3
+ *
4
+ * @see https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks
5
+ *
6
+ * @param value The variable with no remaining values
7
+ */
8
+ export declare function assertNever(value: never): never;
9
+ declare type AllKeys<T> = T extends unknown ? keyof T : never;
10
+ export declare function pick<O extends unknown, K extends AllKeys<O>>(base: O, keys: readonly K[]): Pick<O, K>;
11
+ export declare function isObject(o: unknown): o is Record<PropertyKey, unknown>;
12
+ export {};
13
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,GAAG,KAAK,CAE/C;AAED,aAAK,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,OAAO,GAAG,MAAM,CAAC,GAAG,KAAK,CAAA;AAErD,wBAAgB,IAAI,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,EAC1D,IAAI,EAAE,CAAC,EACP,IAAI,EAAE,SAAS,CAAC,EAAE,GACjB,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAGZ;AAED,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,MAAM,CAAC,WAAW,EAAE,OAAO,CAAC,CAEtE"}
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isObject = exports.pick = exports.assertNever = void 0;
4
+ /**
5
+ * Utility for enforcing exhaustiveness checks in the type system.
6
+ *
7
+ * @see https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks
8
+ *
9
+ * @param value The variable with no remaining values
10
+ */
11
+ function assertNever(value) {
12
+ throw new Error(`Unexpected value should never occur: ${value}`);
13
+ }
14
+ exports.assertNever = assertNever;
15
+ function pick(base, keys) {
16
+ const entries = keys.map(key => [key, base === null || base === void 0 ? void 0 : base[key]]);
17
+ return Object.fromEntries(entries);
18
+ }
19
+ exports.pick = pick;
20
+ function isObject(o) {
21
+ return typeof o === "object" && o !== null;
22
+ }
23
+ exports.isObject = isObject;
24
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;AAAA;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,KAAY;IACtC,MAAM,IAAI,KAAK,CAAC,wCAAwC,KAAK,EAAE,CAAC,CAAA;AAClE,CAAC;AAFD,kCAEC;AAID,SAAgB,IAAI,CAClB,IAAO,EACP,IAAkB;IAElB,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAG,GAAG,CAAC,CAAC,CAAC,CAAA;IACnD,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;AACpC,CAAC;AAND,oBAMC;AAED,SAAgB,QAAQ,CAAC,CAAU;IACjC,OAAO,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,CAAA;AAC5C,CAAC;AAFD,4BAEC","sourcesContent":["/**\n * Utility for enforcing exhaustiveness checks in the type system.\n *\n * @see https://basarat.gitbook.io/typescript/type-system/discriminated-unions#throw-in-exhaustive-checks\n *\n * @param value The variable with no remaining values\n */\nexport function assertNever(value: never): never {\n throw new Error(`Unexpected value should never occur: ${value}`)\n}\n\ntype AllKeys<T> = T extends unknown ? keyof T : never\n\nexport function pick<O extends unknown, K extends AllKeys<O>>(\n base: O,\n keys: readonly K[]\n): Pick<O, K> {\n const entries = keys.map(key => [key, base?.[key]])\n return Object.fromEntries(entries)\n}\n\nexport function isObject(o: unknown): o is Record<PropertyKey, unknown> {\n return typeof o === \"object\" && o !== null\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@notionhq/client",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "A simple and easy to use client for the Notion API",
5
5
  "engines": {
6
6
  "node": ">=12"
@@ -27,7 +27,7 @@
27
27
  "build": "tsc",
28
28
  "prettier": "prettier --write .",
29
29
  "lint": "prettier --check . && eslint . --ext .ts && cspell '**/*' ",
30
- "test": "ava",
30
+ "test": "jest ./test",
31
31
  "check-links": "git ls-files | grep md$ | xargs -n 1 markdown-link-check",
32
32
  "prebuild": "npm run clean",
33
33
  "clean": "rm -rf ./build",
@@ -44,14 +44,15 @@
44
44
  "node-fetch": "^2.6.1"
45
45
  },
46
46
  "devDependencies": {
47
- "@ava/typescript": "^2.0.0",
47
+ "@types/jest": "^28.1.4",
48
48
  "@typescript-eslint/eslint-plugin": "^4.22.0",
49
49
  "@typescript-eslint/parser": "^4.22.0",
50
- "ava": "^3.15.0",
51
50
  "cspell": "^5.4.1",
52
51
  "eslint": "^7.24.0",
52
+ "jest": "^28.1.2",
53
53
  "markdown-link-check": "^3.8.7",
54
54
  "prettier": "^2.3.0",
55
+ "ts-jest": "^28.0.5",
55
56
  "typescript": "^4.2.4"
56
57
  }
57
58
  }