UNPKG

next-drupal

Version:
362 lines (357 loc) 12.9 kB
import { J as JsonApiError } from './jsonapi-errors-kdi3GZQy.js'; type BaseUrl = string; type Locale = string; type PathPrefix = string; interface FetchOptions extends RequestInit { withAuth?: boolean | NextDrupalAuth; } /** * JSON:API Related Options */ type JsonApiOptions = { /** * Set to false to return the raw JSON:API response. * */ deserialize?: boolean; /** * JSON:API params such as `filter`, `fields`, `include` or `sort`. */ params?: JsonApiParams; } & JsonApiWithAuthOption & ({ /** The locale to fetch the resource in. */ locale: Locale; /** The default locale of the site. */ defaultLocale: Locale; } | { locale?: undefined; defaultLocale?: never; }); type JsonApiWithAuthOption = { /** Set to true to use the authentication method configured on the client. */ withAuth?: boolean | NextDrupalAuth; }; type JsonApiWithCacheOptions = { /** Set `withCache` if you want to store and retrieve the resource from cache. */ withCache?: boolean; /** The cache key to use. */ cacheKey?: string; }; type JsonApiWithNextFetchOptions = { next?: NextFetchRequestConfig; cache?: RequestCache; }; /** * JSON:API params such as filter, fields, include or sort. */ type JsonApiParams = Record<string, any>; type NextDrupalBaseOptions = { /** * A long-lived access token you can set for the client. * * * **Default value**: `null` * * **Required**: *No* * * [Documentation](https://next-drupal.org/docs/client/configuration#accesstoken) */ accessToken?: AccessToken; /** * Set the JSON:API prefix. * * * **Default value**: `/jsonapi` * * **Required**: *No* * * [Documentation](https://next-drupal.org/docs/client/configuration#apiprefix) */ apiPrefix?: string; /** * Override the default auth. You can use this to implement your own authentication mechanism. * * [Documentation](https://next-drupal.org/docs/client/configuration#auth) */ auth?: NextDrupalAuth; /** * Set debug to true to enable debug messages. * * * **Default value**: `false` * * **Required**: *No* * * [Documentation](https://next-drupal.org/docs/client/configuration#debug) */ debug?: boolean; /** * Override the default fetcher. Use this to add your own fetcher ex. axios. * * * **Default value**: `fetch` * * **Required**: *No* * * [Documentation](https://next-drupal.org/docs/client/configuration#fetcher) */ fetcher?: Fetcher; /** * Set the default frontPage. * * * **Default value**: `/home` * * **Required**: *No* * * [Documentation](https://next-drupal.org/docs/client/configuration#frontpage) */ frontPage?: string; /** * Set custom headers for the fetcher. * * * **Default value**: `{ "Content-Type": "application/vnd.api+json", Accept: "application/vnd.api+json" }` * * **Required**: *No* * * [Documentation](https://next-drupal.org/docs/client/configuration#headers) */ headers?: HeadersInit; /** * Override the default logger. You can use this to send logs to a third-party service. * * * **Default value**: `console` * * **Required**: *No* * * [Documentation](https://next-drupal.org/docs/client/configuration#logger) */ logger?: Logger; /** * Set whether the client should use authenticated requests by default. * * * **Default value**: `true` * * **Required**: **No* * * [Documentation](https://next-drupal.org/docs/client/configuration#withauth) */ withAuth?: boolean; }; type NextDrupalAuth = NextDrupalAuthAccessToken | NextDrupalAuthClientIdSecret | NextDrupalAuthUsernamePassword | (() => string) | string; type NextDrupalAuthAccessToken = AccessToken; interface NextDrupalAuthClientIdSecret { clientId: string; clientSecret: string; url?: string; scope?: string; } interface NextDrupalAuthUsernamePassword { username: string; password: string; } interface AccessToken { token_type: string; access_token: string; expires_in: number; refresh_token?: string; } type AccessTokenScope = string; type Fetcher = WindowOrWorkerGlobalScope["fetch"]; interface Logger { log(message: any): void; debug(message: any): void; warn(message: any): void; error(message: any): void; } type EndpointSearchParams = string | Record<string, string> | URLSearchParams | JsonApiParams; /** * The base class for NextDrupal clients. */ declare class NextDrupalBase { accessToken?: NextDrupalBaseOptions["accessToken"]; baseUrl: BaseUrl; fetcher?: NextDrupalBaseOptions["fetcher"]; frontPage: string; isDebugEnabled: boolean; logger: Logger; withAuth: boolean; private _apiPrefix; private _auth?; private _headers; private _token?; private _tokenExpiresOn?; private _tokenRequestDetails?; /** * Instantiates a new NextDrupalBase. * * const client = new NextDrupalBase(baseUrl) * * @param {baseUrl} baseUrl The baseUrl of your Drupal site. Do not add the /jsonapi suffix. * @param {options} options Options for NextDrupalBase. */ constructor(baseUrl: BaseUrl, options?: NextDrupalBaseOptions); set apiPrefix(apiPrefix: string); get apiPrefix(): string; set auth(auth: NextDrupalAuth); get auth(): NextDrupalAuth; set headers(headers: HeadersInit); get headers(): HeadersInit; set token(token: AccessToken); get token(): AccessToken; /** * Fetches a resource from the given input URL or path. * * @param {RequestInfo} input The url to fetch from. * @param {FetchOptions} init The fetch options with `withAuth`. * If `withAuth` is set, `fetch` will fetch an `Authorization` header before making the request. * @returns {Promise<Response>} The fetch response. * @remarks * To provide your own custom fetcher, see the fetcher docs. * @example * ```ts * const url = drupal.buildUrl("/jsonapi/node/article", { * sort: "-created", * "fields[node--article]": "title,path", * }) * * const response = await drupal.fetch(url.toString()) * ``` */ fetch(input: RequestInfo, { withAuth, ...init }?: FetchOptions): Promise<Response>; /** * Gets the authorization header value based on the provided auth configuration. * * @param {NextDrupalAuth} auth The auth configuration. * @returns {Promise<string>} The authorization header value. */ getAuthorizationHeader(auth: NextDrupalAuth): Promise<string>; /** * Builds a URL with the given path and search parameters. * * @param {string} path The path for the url. Example: "/example" * @param {string | Record<string, string> | URLSearchParams | JsonApiParams} searchParams Optional query parameters. * @returns {URL} The constructed URL. * @example * ```ts * const drupal = new DrupalClient("https://example.com") * * // https://drupal.org * drupal.buildUrl("https://drupal.org").toString() * * // https://example.com/foo * drupal.buildUrl("/foo").toString() * * // https://example.com/foo?bar=baz * client.buildUrl("/foo", { bar: "baz" }).toString() * ``` * * Build a URL from `DrupalJsonApiParams` * ```ts * const params = { * getQueryObject: () => ({ * sort: "-created", * "fields[node--article]": "title,path", * }), * } * * // https://example.com/jsonapi/node/article?sort=-created&fields%5Bnode--article%5D=title%2Cpath * drupal.buildUrl("/jsonapi/node/article", params).toString() * ``` */ buildUrl(path: string, searchParams?: EndpointSearchParams): URL; /** * Builds an endpoint URL with the given options. * * @param {Object} options The options for building the endpoint. * @param {string} options.locale The locale. * @param {string} options.path The path. * @param {EndpointSearchParams} options.searchParams The search parameters. * @returns {Promise<string>} The constructed endpoint URL. */ buildEndpoint({ locale, path, searchParams, }?: { locale?: string; path?: string; searchParams?: EndpointSearchParams; }): Promise<string>; /** * Constructs a path from the given segment and options. * * @param {string | string[]} segment The path segment. * @param {Object} options The options for constructing the path. * @param {Locale} options.locale The locale. * @param {Locale} options.defaultLocale The default locale. * @param {PathPrefix} options.pathPrefix The path prefix. * @returns {string} The constructed path. */ constructPathFromSegment(segment: string | string[], options?: { locale?: Locale; defaultLocale?: Locale; pathPrefix?: PathPrefix; }): string; /** * Adds a locale prefix to the given path. * * @param {string} path The path. * @param {Object} options The options for adding the locale prefix. * @param {Locale} options.locale The locale. * @param {Locale} options.defaultLocale The default locale. * @returns {string} The path with the locale prefix. */ addLocalePrefix(path: string, options?: { locale?: Locale; defaultLocale?: Locale; }): string; /** * Retrieve an access token. * * @param {NextDrupalAuthClientIdSecret} clientIdSecret The client ID and secret. * @returns {Promise<AccessToken>} The access token. * @remarks * If options is not provided, `DrupalClient` will use the `clientId` and `clientSecret` configured in `auth`. * @example * ```ts * const accessToken = await drupal.getAccessToken({ * clientId: "7034f4db-7151-466f-a711-8384bddb9e60", * clientSecret: "d92Fm^ds", * }) * ``` */ getAccessToken(clientIdSecret?: NextDrupalAuthClientIdSecret): Promise<AccessToken>; /** * Validates the draft URL using the provided search parameters. * * @param {URLSearchParams} searchParams The search parameters. * @returns {Promise<Response>} The validation response. */ validateDraftUrl(searchParams: URLSearchParams): Promise<Response>; /** * Logs a debug message if debug mode is enabled. * * @param {string} message The debug message. */ debug(message: any): void; /** * Throws an error if the response contains JSON:API errors. * * @param {Response} response The fetch response. * @param {string} messagePrefix The error message prefix. * @throws {JsonApiErrors} The JSON:API errors. */ throwIfJsonErrors(response: Response, messagePrefix?: string): Promise<void>; /** * Extracts errors from the fetch response. * * @param {Response} response The fetch response. * @returns {Promise<string | JsonApiResponse>} The extracted errors. */ getErrorsFromResponse(response: Response): Promise<string | JsonApiError[]>; } /** * Checks if the provided auth configuration is basic auth. * * @param {NextDrupalAuth} auth The auth configuration. * @returns {boolean} True if the auth configuration is basic auth, false otherwise. */ declare function isBasicAuth(auth: NextDrupalAuth): auth is NextDrupalAuthUsernamePassword; /** * Checks if the provided auth configuration is access token auth. * * @param {NextDrupalAuth} auth The auth configuration. * @returns {boolean} True if the auth configuration is access token auth, false otherwise. */ declare function isAccessTokenAuth(auth: NextDrupalAuth): auth is NextDrupalAuthAccessToken; /** * Checks if the provided auth configuration is client ID and secret auth. * * @param {NextDrupalAuth} auth The auth configuration. * @returns {boolean} True if the auth configuration is client ID and secret auth, false otherwise. */ declare function isClientIdSecretAuth(auth: NextDrupalAuth): auth is NextDrupalAuthClientIdSecret; export { type AccessToken as A, type BaseUrl as B, type EndpointSearchParams as E, type Fetcher as F, type JsonApiOptions as J, type Locale as L, NextDrupalBase as N, type PathPrefix as P, type NextDrupalBaseOptions as a, type NextDrupalAuth as b, type NextDrupalAuthUsernamePassword as c, type NextDrupalAuthClientIdSecret as d, type NextDrupalAuthAccessToken as e, type JsonApiWithNextFetchOptions as f, type JsonApiWithCacheOptions as g, type JsonApiParams as h, type JsonApiWithAuthOption as i, isBasicAuth as j, isAccessTokenAuth as k, isClientIdSecretAuth as l, type AccessTokenScope as m, type Logger as n, type FetchOptions as o };