New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@prismicio/client

Package Overview
Dependencies
Maintainers
20
Versions
114
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@prismicio/client - npm Package Compare versions

Comparing version 6.7.1 to 7.0.0-alpha.0

dist/buildQueryURL.cjs

1618

dist/index.d.ts

@@ -1,1526 +0,92 @@

import * as prismicT from '@prismicio/types';
import * as prismicH from '@prismicio/helpers';
/**
* Get a repository's Prismic Rest API V2 endpoint.
*
* @typeParam RepositoryName - Name of the Prismic repository.
* @param repositoryName - Name of the repository.
*
* @returns The repository's Prismic Rest API V2 endpoint
* @throws {@link Error} Thrown if an invalid repository name is provided.
*/
declare const getRepositoryEndpoint: <RepositoryName extends string>(repositoryName: RepositoryName) => `https://${RepositoryName}.cdn.prismic.io/api/v2`;
/**
* Get a Prismic repository's name from its standard Prismic Rest API V2 or
* GraphQL endpoint.
*
* @typeParam RepositoryEndpoint - Prismic Rest API V2 endpoint for the repository.
* @param repositoryEndpoint - Prismic Rest API V2 endpoint for the repository.
*
* @returns The Prismic repository's name.
* @throws {@link Error} Thrown if an invalid Prismic Rest API V2 endpoint is provided.
*/
declare const getRepositoryName: (repositoryEndpoint: string) => string;
/**
* Get a repository's Prismic GraphQL endpoint.
*
* @typeParam RepositoryName - Name of the Prismic repository.
* @param repositoryName - Name of the repository.
*
* @returns The repository's Prismic REST API V2 endpoint
*/
declare const getGraphQLEndpoint: <RepositoryName extends string>(repositoryName: RepositoryName) => `https://${RepositoryName}.cdn.prismic.io/graphql`;
/**
* Determines if an input is a valid Prismic repository name.
*
* @param input - Input to test.
*
* @returns `true` if `input` is a valid Prismic repository name, `false` otherwise.
*/
declare const isRepositoryName: (input: string) => boolean;
/**
* Determines if a string if a Prismic Rest API V2 endpoint. Note that any valid
* URL is a valid endpoint to support network proxies.
*
* @param input - Input to test.
*
* @returns `true` if `input` is a valid Prismic Rest API V2 endpoint, `false` otherwise.
*/
declare const isRepositoryEndpoint: (input: string) => boolean;
/**
* Functions like TypeScript's native `Extract` utility type with added support
* to fall back to a value if the resulting union is `never`.
*
* @example
*
* ```ts
* ExtractOrFallback<"a" | "b", "a"> // => "a"
* ExtractOrFallback<"a" | "b", "c"> // => "a" | "b"
* ExtractOrFallback<"a" | "b", "c", "foo"> // => "foo"
* ```
*
* @typeParam T - The union from which values will be extracted.
* @typeParam U - The extraction condition.
* @typeParam Fallback - The value to return if the resulting union is `never`.
* Defaults to `T`.
*/
declare type ExtractOrFallback<T, U, Fallback = T> = Extract<T, U> extends never ? Fallback : Extract<T, U>;
/**
* Extracts one or more Prismic document types that match a given Prismic
* document type. If no matches are found, no extraction is performed and the
* union of all provided Prismic document types are returned.
*
* @typeParam TDocuments - Prismic document types from which to extract.
* @typeParam TDocumentType - Type(s) to match `TDocuments` against.
*/
declare type ExtractDocumentType<TDocuments extends prismicT.PrismicDocument, TDocumentType extends TDocuments["type"]> = ExtractOrFallback<TDocuments, {
type: TDocumentType;
}>;
/**
* A universal API to make network requests. A subset of the `fetch()` API.
*
* {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch}
*/
declare type FetchLike = (input: string, init?: RequestInitLike) => Promise<ResponseLike>;
/**
* An object that allows you to abort a `fetch()` request if needed via an
* `AbortController` object
*
* {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
*/
declare type AbortSignalLike = any;
/**
* The minimum required properties from RequestInit.
*/
interface RequestInitLike {
headers?: Record<string, string>;
/**
* An object that allows you to abort a `fetch()` request if needed via an
* `AbortController` object
*
* {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
*/
signal?: AbortSignalLike;
}
/**
* The minimum required properties from Response.
*/
interface ResponseLike {
status: number;
json(): Promise<any>;
}
/**
* The minimum required properties to treat as an HTTP Request for automatic
* Prismic preview support.
*/
declare type HttpRequestLike = /**
* Web API Request
*
* @see http://developer.mozilla.org/en-US/docs/Web/API/Request
*/ {
headers?: {
get(name: string): string | null;
};
url?: string;
}
/**
* Express-style Request
*/
| {
headers?: {
cookie?: string;
};
query?: Record<string, unknown>;
};
/**
* An `orderings` parameter that orders the results by the specified field.
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#orderings}
*/
interface Ordering {
field: string;
direction?: "asc" | "desc";
}
/**
* A `routes` parameter that determines how a document's URL field is resolved.
*
* @example With a document's UID field.
*
* ```ts
* {
* "type": "page",
* "path": "/:uid"
* }
* ```
*
* @example With a Content Relationship `parent` field.
*
* ```ts
* {
* "type": "page",
* "path": "/:parent?/:uid",
* "resolvers": {
* "parent": "parent"
* }
* }
* ```
*
* {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
*/
interface Route {
/**
* The Custom Type of the document.
*/
type: string;
/**
* A specific UID to which this route definition is scoped. The route is only
* defined for the document whose UID matches the given UID.
*/
uid?: string;
/**
* A specific language to which this route definition is scoped. The route is
* only defined for documents whose language matches the given language.
*/
lang?: string;
/**
* The resolved path of the document with optional placeholders.
*/
path: string;
/**
* An object that lists the API IDs of the Content Relationships in the route.
*/
resolvers?: Record<string, string>;
}
/**
* Parameters for the Prismic REST API V2.
*
* {@link https://prismic.io/docs/technologies/introduction-to-the-content-query-api}
*/
interface QueryParams {
/**
* The secure token for accessing the API (only needed if your repository is
* set to private).
*
* {@link https://user-guides.prismic.io/en/articles/1036153-generating-an-access-token}
*/
accessToken?: string;
/**
* The `pageSize` parameter defines the maximum number of documents that the
* API will return for your query.
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#pagesize}
*/
pageSize?: number;
/**
* The `page` parameter defines the pagination for the result of your query.
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#page}
*/
page?: number;
/**
* The `after` parameter can be used along with the orderings option. It will
* remove all the documents except for those after the specified document in the list.
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#after}
*/
after?: string;
/**
* The `fetch` parameter is used to make queries faster by only retrieving the
* specified field(s).
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#fetch}
*/
fetch?: string | string[];
/**
* The `fetchLinks` parameter allows you to retrieve a specific content field
* from a linked document and add it to the document response object.
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#fetchlinks}
*/
fetchLinks?: string | string[];
/**
* The `graphQuery` parameter allows you to specify which fields to retrieve
* and what content to retrieve from Linked Documents / Content Relationships.
*
* {@link https://prismic.io/docs/technologies/graphquery-rest-api}
*/
graphQuery?: string;
/**
* The `lang` option defines the language code for the results of your query.
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#lang}
*/
lang?: string;
/**
* The `orderings` parameter orders the results by the specified field(s). You
* can specify as many fields as you want.
*
* {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#orderings}
*/
orderings?: Ordering | string | (Ordering | string)[];
/**
* The `routes` option allows you to define how a document's `url` field is resolved.
*
* {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
*/
routes?: Route | string | (Route | string)[];
/**
* The `brokenRoute` option allows you to define the route populated in the
* `url` property for broken Link or Content Relationship fields. A broken
* link is a Link or Content Relationship field whose linked document has been
* unpublished or deleted.
*
* {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
*/
brokenRoute?: string;
}
/**
* Arguments for `buildQueryURL` to construct a Query URL.
*/
declare type BuildQueryURLParams = {
/**
* Ref used to query documents.
*
* {@link https://prismic.io/docs/technologies/introduction-to-the-content-query-api#prismic-api-ref}
*/
ref: string;
/**
* Ref used to populate Integration Fields with the latest content.
*
* {@link https://prismic.io/docs/core-concepts/integration-fields}
*/
integrationFieldsRef?: string;
/**
* One or more predicates to filter documents for the query.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api}
*/
predicates?: string | string[];
};
declare type BuildQueryURLArgs = QueryParams & BuildQueryURLParams;
/**
* Build a Prismic REST API V2 URL to request documents from a repository. The
* paginated response for this URL includes documents matching the parameters.
*
* A ref is required to make a request. Request the `endpoint` URL to retrieve a
* list of available refs.
*
* Type the JSON response with `Query`.
*
* {@link https://prismic.io/docs/technologies/introduction-to-the-content-query-api#prismic-api-ref}
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api}
*
* @param endpoint - URL to the repository's REST API V2.
* @param args - Arguments to filter and scope the query.
*
* @returns URL that can be used to request documents from the repository.
*/
declare const buildQueryURL: (endpoint: string, args: BuildQueryURLArgs) => string;
/**
* A ref or a function that returns a ref. If a static ref is known, one can be
* given. If the ref must be fetched on-demand, a function can be provided. This
* function can optionally be asynchronous.
*/
declare type RefStringOrThunk = string | (() => string | undefined | Promise<string | undefined>);
/**
* Configuration for clients that determine how content is queried.
*/
declare type ClientConfig = {
/**
* The secure token for accessing the Prismic repository. This is only
* required if the repository is set to private.
*/
accessToken?: string;
/**
* A string representing a version of the Prismic repository's content. This
* may point to the latest version (called the "master ref"), or a preview
* with draft content.
*/
ref?: RefStringOrThunk;
/**
* A list of Route Resolver objects that define how a document's `url` field
* is resolved.
*
* {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
*/
routes?: NonNullable<BuildQueryURLArgs["routes"]>;
/**
* The `brokenRoute` option allows you to define the route populated in the
* `url` property for broken Link or Content Relationship fields. A broken
* link is a Link or Content Relationship field whose linked document has been
* unpublished or deleted.
*
* {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
*/
brokenRoute?: NonNullable<BuildQueryURLArgs["brokenRoute"]>;
/**
* Default parameters that will be sent with each query. These parameters can
* be overridden on each query if needed.
*/
defaultParams?: Omit<BuildQueryURLArgs, "ref" | "integrationFieldsRef" | "accessToken" | "routes" | "brokenRoute">;
/**
* The function used to make network requests to the Prismic REST API. In
* environments where a global `fetch` function does not exist, such as
* Node.js, this function must be provided.
*/
fetch?: FetchLike;
};
/**
* Parameters for any client method that use `fetch()`. Only a subset of
* `fetch()` parameters are exposed.
*/
declare type FetchParams = {
/**
* An `AbortSignal` provided by an `AbortController`. This allows the network
* request to be cancelled if necessary.
*
* {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal}
*/
signal?: AbortSignalLike;
};
/**
* Parameters specific to client methods that fetch all documents. These methods
* start with `getAll` (for example, `getAllByType`).
*/
declare type GetAllParams = {
/**
* Limit the number of documents queried. If a number is not provided, there
* will be no limit and all matching documents will be returned.
*/
limit?: number;
};
/**
* Arguments to determine how the URL for a preview session is resolved.
*/
declare type ResolvePreviewArgs<LinkResolverReturnType> = {
/**
* A function that maps a Prismic document to a URL within your app.
*/
linkResolver?: prismicH.LinkResolverFunction<LinkResolverReturnType>;
/**
* A fallback URL if the Link Resolver does not return a value.
*/
defaultURL: string;
/**
* The preview token (also known as a ref) that will be used to query preview
* content from the Prismic repository.
*/
previewToken?: string;
/**
* The previewed document that will be used to determine the destination URL.
*/
documentID?: string;
};
/**
* Type definitions for the `createClient()` function. May be augmented by
* third-party libraries.
*/
interface CreateClient {
<TDocuments extends prismicT.PrismicDocument>(...args: ConstructorParameters<typeof Client>): Client<TDocuments>;
}
/**
* Creates a Prismic client that can be used to query a repository.
*
* @example
*
* ```ts
* // With a repository name.
* createClient("qwerty");
*
* // Or with a full Prismic Rest API V2 endpoint.
* createClient("https://qwerty.cdn.prismic.io/api/v2");
* ```
*
* @typeParam TDocuments - A map of Prismic document type IDs mapped to their
* TypeScript type.
* @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
* API V2 endpoint for the repository.
* @param options - Configuration that determines how content will be queried
* from the Prismic repository.
*
* @returns A client that can query content from the repository.
*/
declare const createClient: CreateClient;
/**
* A client that allows querying content from a Prismic repository.
*
* If used in an environment where a global `fetch` function is unavailable,
* such as Node.js, the `fetch` option must be provided as part of the `options`
* parameter.
*
* @typeParam TDocuments - Document types that are registered for the Prismic
* repository. Query methods will automatically be typed based on this type.
*/
declare class Client<TDocuments extends prismicT.PrismicDocument = prismicT.PrismicDocument> {
/**
* The Prismic REST API V2 endpoint for the repository (use
* `prismic.getRepositoryEndpoint` for the default endpoint).
*/
endpoint: string;
/**
* The secure token for accessing the API (only needed if your repository is
* set to private).
*
* {@link https://user-guides.prismic.io/en/articles/1036153-generating-an-access-token}
*/
accessToken?: string;
/**
* A list of Route Resolver objects that define how a document's `url` field
* is resolved.
*
* {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
*/
routes?: NonNullable<BuildQueryURLArgs["routes"]>;
/**
* The `brokenRoute` option allows you to define the route populated in the
* `url` property for broken Link or Content Relationship fields. A broken
* link is a Link or Content Relationship field whose linked document has been
* unpublished or deleted.
*
* {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}
*/
brokenRoute?: NonNullable<BuildQueryURLArgs["brokenRoute"]>;
/**
* The function used to make network requests to the Prismic REST API. In
* environments where a global `fetch` function does not exist, such as
* Node.js, this function must be provided.
*/
fetchFn: FetchLike;
/**
* Default parameters that will be sent with each query. These parameters can
* be overridden on each query if needed.
*/
defaultParams?: Omit<BuildQueryURLArgs, "ref" | "integrationFieldsRef" | "accessToken" | "routes">;
/**
* The client's ref mode state. This determines which ref is used during queries.
*/
private refState;
/**
* Cached repository value.
*/
private cachedRepository;
/**
* Timestamp at which the cached repository data is considered stale.
*/
private cachedRepositoryExpiration;
/**
* Creates a Prismic client that can be used to query a repository.
*
* If used in an environment where a global `fetch` function is unavailable,
* such as Node.js, the `fetch` option must be provided as part of the
* `options` parameter.
*
* @param repositoryNameOrEndpoint - The Prismic repository name or full Rest
* API V2 endpoint for the repository.
* @param options - Configuration that determines how content will be queried
* from the Prismic repository.
*
* @returns A client that can query content from the repository.
*/
constructor(repositoryNameOrEndpoint: string, options?: ClientConfig);
/**
* Enables the client to automatically query content from a preview session if
* one is active in browser environments. This is enabled by default in the browser.
*
* For server environments, use `enableAutoPreviewsFromReq`.
*
* @example
*
* ```ts
* client.enableAutoPreviews();
* ```
*
* @see enableAutoPreviewsFromReq
*/
enableAutoPreviews(): void;
/**
* Enables the client to automatically query content from a preview session if
* one is active in server environments. This is disabled by default on the server.
*
* For browser environments, use `enableAutoPreviews`.
*
* @example
*
* ```ts
* // In an express app
* app.get("/", function (req, res) {
* client.enableAutoPreviewsFromReq(req);
* });
* ```
*
* @param req - An HTTP server request object containing the request's cookies.
*/
enableAutoPreviewsFromReq<R extends HttpRequestLike>(req: R): void;
/**
* Disables the client from automatically querying content from a preview
* session if one is active.
*
* Automatic preview content querying is enabled by default unless this method
* is called.
*
* @example
*
* ```ts
* client.disableAutoPreviews();
* ```
*/
disableAutoPreviews(): void;
/**
* Queries content from the Prismic repository.
*
* @deprecated Use `get` instead.
* @example
*
* ```ts
* const response = await client.query(
* prismic.predicate.at("document.type", "page"),
* );
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param params - Parameters to filter, sort, and paginate results.
*
* @returns A paginated response containing the result of the query.
*/
query<TDocument extends TDocuments>(predicates: NonNullable<BuildQueryURLArgs["predicates"]>, params?: Partial<Omit<BuildQueryURLArgs, "predicates">> & FetchParams): Promise<prismicT.Query<TDocument>>;
/**
* Queries content from the Prismic repository.
*
* @example
*
* ```ts
* const response = await client.get();
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param params - Parameters to filter, sort, and paginate results.
*
* @returns A paginated response containing the result of the query.
*/
get<TDocument extends TDocuments>(params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<prismicT.Query<TDocument>>;
/**
* Queries content from the Prismic repository and returns only the first
* result, if any.
*
* @example
*
* ```ts
* const document = await client.getFirst();
* ```
*
* @typeParam TDocument - Type of the Prismic document returned.
* @param params - Parameters to filter, sort, and paginate results. @returns
* The first result of the query, if any.
*/
getFirst<TDocument extends TDocuments>(params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<TDocument>;
/**
* **IMPORTANT**: Avoid using `dangerouslyGetAll` as it may be slower and
* require more resources than other methods. Prefer using other methods that
* filter by predicates such as `getAllByType`.
*
* Queries content from the Prismic repository and returns all matching
* content. If no predicates are provided, all documents will be fetched.
*
* This method may make multiple network requests to query all matching content.
*
* @example
*
* ```ts
* const response = await client.dangerouslyGetAll();
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param params - Parameters to filter, sort, and paginate results.
*
* @returns A list of documents matching the query.
*/
dangerouslyGetAll<TDocument extends TDocuments>(params?: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams & FetchParams): Promise<TDocument[]>;
/**
* Queries a document from the Prismic repository with a specific ID.
*
* @remarks
* A document's UID is different from its ID. An ID is automatically generated
* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* @example
*
* ```ts
* const document = await client.getByID("WW4bKScAAMAqmluX");
* ```
*
* @typeParam TDocument- Type of the Prismic document returned.
* @param id - ID of the document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns The document with an ID matching the `id` parameter, if a matching
* document exists.
*/
getByID<TDocument extends TDocuments>(id: string, params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<TDocument>;
/**
* Queries documents from the Prismic repository with specific IDs.
*
* @remarks
* A document's UID is different from its ID. An ID is automatically generated
* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* @example
*
* ```ts
* const response = await client.getByIDs([
* "WW4bKScAAMAqmluX",
* "U1kTRgEAAC8A5ldS",
* ]);
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param ids - A list of document IDs.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A paginated response containing documents with IDs matching the
* `ids` parameter.
*/
getByIDs<TDocument extends TDocuments>(ids: string[], params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<prismicT.Query<TDocument>>;
/**
* Queries all documents from the Prismic repository with specific IDs.
*
* This method may make multiple network requests to query all matching content.
*
* @remarks
* A document's UID is different from its ID. An ID is automatically generated
* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* @example
*
* ```ts
* const response = await client.getAllByIDs([
* "WW4bKScAAMAqmluX",
* "U1kTRgEAAC8A5ldS",
* ]);
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param ids - A list of document IDs.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A list of documents with IDs matching the `ids` parameter.
*/
getAllByIDs<TDocument extends TDocuments>(ids: string[], params?: Partial<BuildQueryURLArgs> & GetAllParams & FetchParams): Promise<TDocument[]>;
/**
* Queries a document from the Prismic repository with a specific UID and Custom Type.
*
* @remarks
* A document's UID is different from its ID. An ID is automatically generated
* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* @example
*
* ```ts
* const document = await client.getByUID("blog_post", "my-first-post");
* ```
*
* @typeParam TDocument - Type of the Prismic document returned.
* @param documentType - The API ID of the document's Custom Type.
* @param uid - UID of the document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns The document with a UID matching the `uid` parameter, if a
* matching document exists.
*/
getByUID<TDocument extends TDocuments, TDocumentType extends TDocument["type"] = TDocument["type"]>(documentType: TDocumentType, uid: string, params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<ExtractDocumentType<TDocument, TDocumentType>>;
/**
* Queries document from the Prismic repository with specific UIDs and Custom Type.
*
* @remarks
* A document's UID is different from its ID. An ID is automatically generated
* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* @example
*
* ```ts
* const document = await client.getByUIDs("blog_post", [
* "my-first-post",
* "my-second-post",
* ]);
* ```
*
* @typeParam TDocument - Type of the Prismic document returned.
* @param documentType - The API ID of the document's Custom Type.
* @param uids - A list of document UIDs.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A paginated response containing documents with UIDs matching the
* `uids` parameter.
*/
getByUIDs<TDocument extends TDocuments, TDocumentType extends TDocument["type"] = TDocument["type"]>(documentType: TDocumentType, uids: string[], params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<prismicT.Query<ExtractDocumentType<TDocument, TDocumentType>>>;
/**
* Queries all documents from the Prismic repository with specific UIDs and Custom Type.
*
* This method may make multiple network requests to query all matching content.
*
* @remarks
* A document's UID is different from its ID. An ID is automatically generated
* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* @example
*
* ```ts
* const response = await client.getAllByUIDs([
* "my-first-post",
* "my-second-post",
* ]);
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param documentType - The API ID of the document's Custom Type.
* @param uids - A list of document UIDs.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A list of documents with UIDs matching the `uids` parameter.
*/
getAllByUIDs<TDocument extends TDocuments, TDocumentType extends TDocument["type"] = TDocument["type"]>(documentType: TDocumentType, uids: string[], params?: Partial<BuildQueryURLArgs> & GetAllParams & FetchParams): Promise<ExtractDocumentType<TDocument, TDocumentType>[]>;
/**
* Queries a singleton document from the Prismic repository for a specific Custom Type.
*
* @remarks
* A singleton document is one that is configured in Prismic to only allow one
* instance. For example, a repository may be configured to contain just one
* Settings document. This is in contrast to a repeatable Custom Type which
* allows multiple instances of itself.
* @example
*
* ```ts
* const document = await client.getSingle("settings");
* ```
*
* @typeParam TDocument - Type of the Prismic document returned.
* @param documentType - The API ID of the singleton Custom Type.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns The singleton document for the Custom Type, if a matching document exists.
*/
getSingle<TDocument extends TDocuments, TDocumentType extends TDocument["type"] = TDocument["type"]>(documentType: TDocumentType, params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<ExtractDocumentType<TDocument, TDocumentType>>;
/**
* Queries documents from the Prismic repository for a specific Custom Type.
*
* Use `getAllByType` instead if you need to query all documents for a
* specific Custom Type.
*
* @example
*
* ```ts
* const response = await client.getByType("blog_post");
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param documentType - The API ID of the Custom Type.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A paginated response containing documents of the Custom Type.
*/
getByType<TDocument extends TDocuments, TDocumentType extends TDocument["type"] = TDocument["type"]>(documentType: TDocumentType, params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<prismicT.Query<ExtractDocumentType<TDocument, TDocumentType>>>;
/**
* Queries all documents from the Prismic repository for a specific Custom Type.
*
* This method may make multiple network requests to query all matching content.
*
* @example
*
* ```ts
* const response = await client.getByType("blog_post");
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param documentType - The API ID of the Custom Type.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A list of all documents of the Custom Type.
*/
getAllByType<TDocument extends TDocuments, TDocumentType extends TDocument["type"] = TDocument["type"]>(documentType: TDocumentType, params?: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams & FetchParams): Promise<ExtractDocumentType<TDocument, TDocumentType>[]>;
/**
* Queries documents from the Prismic repository with a specific tag.
*
* Use `getAllByTag` instead if you need to query all documents with a specific tag.
*
* @example
*
* ```ts
* const response = await client.getByTag("food");
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param tag - The tag that must be included on a document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A paginated response containing documents with the tag.
*/
getByTag<TDocument extends TDocuments>(tag: string, params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<prismicT.Query<TDocument>>;
/**
* Queries all documents from the Prismic repository with a specific tag.
*
* This method may make multiple network requests to query all matching content.
*
* @example
*
* ```ts
* const response = await client.getAllByTag("food");
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param tag - The tag that must be included on a document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A list of all documents with the tag.
*/
getAllByTag<TDocument extends TDocuments>(tag: string, params?: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams & FetchParams): Promise<TDocument[]>;
/**
* Queries documents from the Prismic repository with specific tags. A
* document must be tagged with all of the queried tags to be included.
*
* @example
*
* ```ts
* const response = await client.getByEveryTag(["food", "fruit"]);
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param tags - A list of tags that must be included on a document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A paginated response containing documents with the tags.
*/
getByEveryTag<TDocument extends TDocuments>(tags: string[], params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<prismicT.Query<TDocument>>;
/**
* Queries documents from the Prismic repository with specific tags. A
* document must be tagged with all of the queried tags to be included.
*
* This method may make multiple network requests to query all matching content.
*
* @example
*
* ```ts
* const response = await client.getAllByEveryTag(["food", "fruit"]);
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param tags - A list of tags that must be included on a document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A list of all documents with the tags.
*/
getAllByEveryTag<TDocument extends TDocuments>(tags: string[], params?: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams & FetchParams): Promise<TDocument[]>;
/**
* Queries documents from the Prismic repository with specific tags. A
* document must be tagged with at least one of the queried tags to be included.
*
* @example
*
* ```ts
* const response = await client.getByEveryTag(["food", "fruit"]);
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param tags - A list of tags that must be included on a document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A paginated response containing documents with at least one of the tags.
*/
getBySomeTags<TDocument extends TDocuments>(tags: string[], params?: Partial<BuildQueryURLArgs> & FetchParams): Promise<prismicT.Query<TDocument>>;
/**
* Queries documents from the Prismic repository with specific tags. A
* document must be tagged with at least one of the queried tags to be included.
*
* This method may make multiple network requests to query all matching content.
*
* @example
*
* ```ts
* const response = await client.getAllByEveryTag(["food", "fruit"]);
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param tags - A list of tags that must be included on a document.
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A list of all documents with at least one of the tags.
*/
getAllBySomeTags<TDocument extends TDocuments>(tags: string[], params?: Partial<Omit<BuildQueryURLArgs, "page">> & GetAllParams & FetchParams): Promise<TDocument[]>;
/**
* Returns metadata about the Prismic repository, such as its refs, releases,
* and custom types.
*
* @returns Repository metadata.
*/
getRepository(params?: FetchParams): Promise<prismicT.Repository>;
/**
* Returns a list of all refs for the Prismic repository.
*
* Refs are used to identify which version of the repository's content should
* be queried. All repositories will have at least one ref pointing to the
* latest published content called the "master ref".
*
* @returns A list of all refs for the Prismic repository.
*/
getRefs(params?: FetchParams): Promise<prismicT.Ref[]>;
/**
* Returns a ref for the Prismic repository with a matching ID.
*
* @param id - ID of the ref.
*
* @returns The ref with a matching ID, if it exists.
*/
getRefByID(id: string, params?: FetchParams): Promise<prismicT.Ref>;
/**
* Returns a ref for the Prismic repository with a matching label.
*
* @param label - Label of the ref.
*
* @returns The ref with a matching label, if it exists.
*/
getRefByLabel(label: string, params?: FetchParams): Promise<prismicT.Ref>;
/**
* Returns the master ref for the Prismic repository. The master ref points to
* the repository's latest published content.
*
* @returns The repository's master ref.
*/
getMasterRef(params?: FetchParams): Promise<prismicT.Ref>;
/**
* Returns a list of all Releases for the Prismic repository. Releases are
* used to group content changes before publishing.
*
* @returns A list of all Releases for the Prismic repository.
*/
getReleases(params?: FetchParams): Promise<prismicT.Ref[]>;
/**
* Returns a Release for the Prismic repository with a matching ID.
*
* @param id - ID of the Release.
*
* @returns The Release with a matching ID, if it exists.
*/
getReleaseByID(id: string, params?: FetchParams): Promise<prismicT.Ref>;
/**
* Returns a Release for the Prismic repository with a matching label.
*
* @param label - Label of the ref.
*
* @returns The ref with a matching label, if it exists.
*/
getReleaseByLabel(label: string, params?: FetchParams): Promise<prismicT.Ref>;
/**
* Returns a list of all tags used in the Prismic repository.
*
* @returns A list of all tags used in the repository.
*/
getTags(params?: FetchParams): Promise<string[]>;
/**
* Builds a URL used to query content from the Prismic repository.
*
* @param params - Parameters to filter, sort, and paginate the results.
*
* @returns A URL string that can be requested to query content.
*/
buildQueryURL({ signal, ...params }?: Partial<BuildQueryURLArgs> & FetchParams): Promise<string>;
/**
* Determines the URL for a previewed document during an active preview
* session. The result of this method should be used to redirect the user to
* the document's URL.
*
* @example
*
* ```ts
* const url = client.resolvePreviewURL({
* linkResolver: (document) => `/${document.uid}`
* defaultURL: '/'
* })
* ```
*
* @param args - Arguments to configure the URL resolving.
*
* @returns The URL for the previewed document during an active preview
* session. The user should be redirected to this URL.
*/
resolvePreviewURL<LinkResolverReturnType>(args: ResolvePreviewArgs<LinkResolverReturnType> & FetchParams): Promise<string>;
/**
* Configures the client to query the latest published content for all future queries.
*
* If the `ref` parameter is provided during a query, it takes priority for that query.
*
* @example
*
* ```ts
* await client.queryLatestContent();
* const document = await client.getByID("WW4bKScAAMAqmluX");
* ```
*/
queryLatestContent(): void;
/**
* Configures the client to query content from a specific Release identified
* by its ID for all future queries.
*
* If the `ref` parameter is provided during a query, it takes priority for that query.
*
* @example
*
* ```ts
* await client.queryContentFromReleaseByID("YLB7OBAAACMA7Cpa");
* const document = await client.getByID("WW4bKScAAMAqmluX");
* ```
*
* @param releaseID - The ID of the Release.
*/
queryContentFromReleaseByID(releaseID: string): void;
/**
* Configures the client to query content from a specific Release identified
* by its label for all future queries.
*
* If the `ref` parameter is provided during a query, it takes priority for that query.
*
* @example
*
* ```ts
* await client.queryContentFromReleaseByLabel("My Release");
* const document = await client.getByID("WW4bKScAAMAqmluX");
* ```
*
* @param releaseLabel - The label of the Release.
*/
queryContentFromReleaseByLabel(releaseLabel: string): void;
/**
* Configures the client to query content from a specific ref. The ref can be
* provided as a string or a function.
*
* If a function is provided, the ref is fetched lazily before each query. The
* function may also be asynchronous.
*
* @example
*
* ```ts
* await client.queryContentFromRef("my-ref");
* const document = await client.getByID("WW4bKScAAMAqmluX");
* ```
*
* @param ref - The ref or a function that returns the ref from which to query content.
*/
queryContentFromRef(ref: RefStringOrThunk): void;
/**
* @deprecated Renamed to `graphQLFetch()` (note the capitalization of "QL").
*/
graphqlFetch: (input: RequestInfo, init?: Omit<RequestInit, "signal"> & {
signal?: AbortSignalLike;
}) => Promise<Response>;
/**
* A `fetch()` function to be used with GraphQL clients configured for
* Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`
* and Authorization headers. Queries will automatically be minified by
* removing whitespace where possible.
*
* @example
*
* ```ts
* const graphqlClient = new ApolloClient({
* link: new HttpLink({
* uri: prismic.getGraphQLEndpoint(repositoryName),
* // Provide `client.graphqlFetch` as the fetch implementation.
* fetch: client.graphqlFetch,
* // Using GET is required.
* useGETForQueries: true,
* }),
* cache: new InMemoryCache(),
* });
* ```
*
* @param input - The `fetch()` `input` parameter. Only strings are supported.
* @param init - The `fetch()` `init` parameter. Only plain objects are supported.
*
* @returns The `fetch()` Response for the request.
* @experimental
*/
graphQLFetch(input: RequestInfo, init?: Omit<RequestInit, "signal"> & {
signal?: AbortSignalLike;
}): Promise<Response>;
/**
* Returns a cached version of `getRepository` with a TTL.
*
* @returns Cached repository metadata.
*/
private getCachedRepository;
/**
* Returns a cached Prismic repository form. Forms are used to determine API
* endpoints for types of repository data.
*
* @param name - Name of the form.
*
* @returns The repository form.
* @throws If a matching form cannot be found.
*/
private getCachedRepositoryForm;
/**
* Returns the ref needed to query based on the client's current state. This
* method may make a network request to fetch a ref or resolve the user's ref thunk.
*
* If auto previews are enabled, the preview ref takes priority if available.
*
* The following strategies are used depending on the client's state:
*
* - If the user called `queryLatestContent`: Use the repository's master ref.
* The ref is cached for 5 seconds. After 5 seconds, a new master ref is fetched.
* - If the user called `queryContentFromReleaseByID`: Use the release's ref.
* The ref is cached for 5 seconds. After 5 seconds, a new ref for the
* release is fetched.
* - If the user called `queryContentFromReleaseByLabel`: Use the release's ref.
* The ref is cached for 5 seconds. After 5 seconds, a new ref for the
* release is fetched.
* - If the user called `queryContentFromRef`: Use the provided ref. Fall back
* to the master ref if the ref is not a string.
*
* @returns The ref to use during a query.
*/
private getResolvedRefString;
/**
* Performs a network request using the configured `fetch` function. It
* assumes all successful responses will have a JSON content type. It also
* normalizes unsuccessful network requests.
*
* @typeParam T - The JSON response.
* @param url - URL to the resource to fetch.
* @param params - Prismic REST API parameters for the network request.
*
* @returns The JSON response from the network request.
*/
private fetch;
}
declare const predicate: {
/**
* The `at` predicate checks that the path matches the described value
* exactly. It takes a single value for a field or an array (only for tags).
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#at}
*/
at: (path: string, value: string | number | boolean | Date | string[]) => string;
/**
* The `not` predicate checks that the path doesn't match the provided value
* exactly. It takes a single value for a field or an array (only for tags).
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#not}
*/
not: (path: string, value: string | number | boolean | Date | string[]) => string;
/**
* The `any` predicate takes an array of values. It works exactly the same way
* as the `at` operator, but checks whether the fragment matches any of the
* values in the array.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#any}
*/
any: (path: string, values: (string | number | boolean | Date)[]) => string;
/**
* The `in` predicate is used specifically to retrieve an array of documents
* by their IDs or UIDs. This predicate is much more efficient at this than
* the any predicate.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#in}
*/
in: (path: string, values: string[]) => string;
/**
* The `fulltext` predicate provides two capabilities:
*
* 1. Checking if a certain string is anywhere inside a document (this is what
* you should use to make your project's search engine feature)
* 2. Checking if the string is contained inside a specific custom type’s Rich
* Text or Key Text fragment.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#fulltext}
*/
fulltext: (path: string, searchTerms: string) => string;
/**
* The `has` predicate checks whether a fragment has a value. It will return
* all the documents of the specified type that contain a value for the
* specified field.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#has}
*/
has: (path: string) => string;
/**
* The `missing` predicate checks if a fragment doesn't have a value. It will
* return all the documents of the specified type that do not contain a value
* for the specified field.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#missing}
*/
missing: (path: string) => string;
/**
* The `similar` predicate takes the ID of a document, and returns a list of
* documents with similar content. This allows you to build an automated
* content discovery feature (for example, a "Related posts" section).
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#similar}
*/
similar: (id: string, value: number) => string;
/**
* The `geopoint.near` predicate checks that the value in the path is within
* the radius of the given coordinates.
*
* This predicate will only work for a GeoPoint field.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#near}
*/
geopointNear: (path: string, latitude: number, longitude: number, radius: number) => string;
/**
* The `number.lt` predicate checks that the value in the number field is less
* than the value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#lt-less-than}
*/
numberLessThan: (path: string, value: number) => string;
/**
* The `number.gt` predicate checks that the value in the number field is
* greater than the value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#gt-greater-than}
*/
numberGreaterThan: (path: string, value: number) => string;
/**
* The `number.inRange` predicate checks that the value in the path is within
* the two values passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/query-predicates-reference-rest-api#inrange}
*/
numberInRange: (path: string, lowerLimit: number, upperLimit: number) => string;
/**
* The `date.after` predicate checks that the value in the path is after the
* date value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#after}
*/
dateAfter: (path: string, date: string | number | Date) => string;
/**
* The `date.before` predicate checks that the value in the path is before the
* date value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#before}
*/
dateBefore: (path: string, date: string | number | Date) => string;
/**
* The `date.between` predicate checks that the value in the path is within
* the date values passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#between}
*/
dateBetween: (path: string, startDate: string | number | Date, endDate: string | number | Date) => string;
/**
* The `date.day-of-month` predicate checks that the value in the path is
* equal to the day of the month passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#dayofmonth}
*/
dateDayOfMonth: (path: string, day: number) => string;
/**
* The `date.day-of-month-after` predicate checks that the value in the path
* is after the day of the month passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#dayofmonthafter}
*/
dateDayOfMonthAfter: (path: string, day: number) => string;
/**
* The `date.day-of-month-before` predicate checks that the value in the path
* is before the day of the month passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#dayofmonthbefore}
*/
dateDayOfMonthBefore: (path: string, day: number) => string;
/**
* The `date.day-of-week` predicate checks that the value in the path is equal
* to the day of the week passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#dayofweek}
*/
dateDayOfWeek: (path: string, day: string | number) => string;
/**
* The `date.day-of-week-after` predicate checks that the value in the path is
* after the day of the week passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#dayofweekafter}
*/
dateDayOfWeekAfter: (path: string, day: string | number) => string;
/**
* The date.day-of-week-before predicate checks that the value in the path is
* before the day of the week passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#dayofweekbefore}
*/
dateDayOfWeekBefore: (path: string, day: string | number) => string;
/**
* The `date.month` predicate checks that the value in the path occurs in the
* month value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#month}
*/
dateMonth: (path: string, month: string | number) => string;
/**
* The `date.month-after` predicate checks that the value in the path occurs
* in any month after the value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#monthafter}
*/
dateMonthAfter: (path: string, month: string | number) => string;
/**
* The `date.month-before` predicate checks that the value in the path occurs
* in any month before the value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#monthbefore}
*/
dateMonthBefore: (path: string, month: string | number) => string;
/**
* The `date.year` predicate checks that the value in the path occurs in the
* year value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#year}
*/
dateYear: (path: string, year: number) => string;
/**
* The `date.hour` predicate checks that the value in the path occurs within
* the hour value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#hour}
*/
dateHour: (path: string, hour: number) => string;
/**
* The `date.hour-after` predicate checks that the value in the path occurs
* after the hour value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#hourafter}
*/
dateHourAfter: (path: string, hour: number) => string;
/**
* The `date.hour-before` predicate checks that the value in the path occurs
* before the hour value passed into the predicate.
*
* {@link https://prismic.io/docs/technologies/date-and-time-based-predicate-reference-rest-api#hourbefore}
*/
dateHourBefore: (path: string, hour: number) => string;
};
declare class PrismicError<Response> extends Error {
url?: string;
response: Response;
constructor(message: string | undefined, url: string | undefined, response: Response);
}
declare type ForbiddenErrorRepositoryAPIResponse = {
type: string;
message: string;
};
declare type ForbiddenErrorQueryAPIResponse = {
error: string;
};
declare class ForbiddenError extends PrismicError<ForbiddenErrorRepositoryAPIResponse | ForbiddenErrorQueryAPIResponse> {
}
declare type ParsingErrorAPIResponse = {
type: "parsing-error";
message: string;
line: number;
column: number;
id: number;
location: string;
};
declare class ParsingError extends PrismicError<ParsingErrorAPIResponse> {
}
declare class NotFoundError extends PrismicError<undefined> {
}
/**
* The well-known name of the cookie used to store a Prismic preview session's ref.
*/
declare const preview = "io.prismic.preview";
declare const cookie_preview: typeof preview;
declare namespace cookie {
export {
cookie_preview as preview,
};
}
/**
* @deprecated Renamed to `getRepositoryEndpoint`.
*/
declare const getEndpoint: <RepositoryName extends string>(repositoryName: RepositoryName) => `https://${RepositoryName}.cdn.prismic.io/api/v2`;
/**
* @deprecated Renamed to `predicate` (without an "s").
*/
declare const predicates: {
at: (path: string, value: string | number | boolean | Date | string[]) => string;
not: (path: string, value: string | number | boolean | Date | string[]) => string;
any: (path: string, values: (string | number | boolean | Date)[]) => string;
in: (path: string, values: string[]) => string;
fulltext: (path: string, searchTerms: string) => string;
has: (path: string) => string;
missing: (path: string) => string;
similar: (id: string, value: number) => string;
geopointNear: (path: string, latitude: number, longitude: number, radius: number) => string;
numberLessThan: (path: string, value: number) => string;
numberGreaterThan: (path: string, value: number) => string;
numberInRange: (path: string, lowerLimit: number, upperLimit: number) => string;
dateAfter: (path: string, date: string | number | Date) => string;
dateBefore: (path: string, date: string | number | Date) => string;
dateBetween: (path: string, startDate: string | number | Date, endDate: string | number | Date) => string;
dateDayOfMonth: (path: string, day: number) => string;
dateDayOfMonthAfter: (path: string, day: number) => string;
dateDayOfMonthBefore: (path: string, day: number) => string;
dateDayOfWeek: (path: string, day: string | number) => string;
dateDayOfWeekAfter: (path: string, day: string | number) => string;
dateDayOfWeekBefore: (path: string, day: string | number) => string;
dateMonth: (path: string, month: string | number) => string;
dateMonthAfter: (path: string, month: string | number) => string;
dateMonthBefore: (path: string, month: string | number) => string;
dateYear: (path: string, year: number) => string;
dateHour: (path: string, hour: number) => string;
dateHourAfter: (path: string, hour: number) => string;
dateHourBefore: (path: string, hour: number) => string;
};
/**
* @deprecated Renamed to `predicate` (lowercase and without an "s").
*/
declare const Predicates: {
at: (path: string, value: string | number | boolean | Date | string[]) => string;
not: (path: string, value: string | number | boolean | Date | string[]) => string;
any: (path: string, values: (string | number | boolean | Date)[]) => string;
in: (path: string, values: string[]) => string;
fulltext: (path: string, searchTerms: string) => string;
has: (path: string) => string;
missing: (path: string) => string;
similar: (id: string, value: number) => string;
geopointNear: (path: string, latitude: number, longitude: number, radius: number) => string;
numberLessThan: (path: string, value: number) => string;
numberGreaterThan: (path: string, value: number) => string;
numberInRange: (path: string, lowerLimit: number, upperLimit: number) => string;
dateAfter: (path: string, date: string | number | Date) => string;
dateBefore: (path: string, date: string | number | Date) => string;
dateBetween: (path: string, startDate: string | number | Date, endDate: string | number | Date) => string;
dateDayOfMonth: (path: string, day: number) => string;
dateDayOfMonthAfter: (path: string, day: number) => string;
dateDayOfMonthBefore: (path: string, day: number) => string;
dateDayOfWeek: (path: string, day: string | number) => string;
dateDayOfWeekAfter: (path: string, day: string | number) => string;
dateDayOfWeekBefore: (path: string, day: string | number) => string;
dateMonth: (path: string, month: string | number) => string;
dateMonthAfter: (path: string, month: string | number) => string;
dateMonthBefore: (path: string, month: string | number) => string;
dateYear: (path: string, year: number) => string;
dateHour: (path: string, hour: number) => string;
dateHourAfter: (path: string, hour: number) => string;
dateHourBefore: (path: string, hour: number) => string;
};
export { AbortSignalLike, BuildQueryURLArgs, Client, ClientConfig, CreateClient, FetchLike, ForbiddenError, HttpRequestLike, NotFoundError, Ordering, ParsingError, Predicates, PrismicError, QueryParams, RequestInitLike, ResponseLike, Route, buildQueryURL, cookie, createClient, getEndpoint, getGraphQLEndpoint, getRepositoryEndpoint, getRepositoryName, isRepositoryEndpoint, isRepositoryName, predicate, predicates };
export { getRepositoryEndpoint } from "./getRepositoryEndpoint";
export { getRepositoryName } from "./getRepositoryName";
export { getGraphQLEndpoint } from "./getGraphQLEndpoint";
export { isRepositoryName } from "./isRepositoryName";
export { isRepositoryEndpoint } from "./isRepositoryEndpoint";
export { buildQueryURL } from "./buildQueryURL";
export { createClient, Client } from "./client";
export { predicate } from "./predicate";
export { PrismicError } from "./PrismicError";
export { ForbiddenError } from "./ForbiddenError";
export { ParsingError } from "./ParsingError";
export { NotFoundError } from "./NotFoundError";
export * as cookie from "./cookie";
export type { CreateClient, ClientConfig } from "./client";
export type { QueryParams, BuildQueryURLArgs } from "./buildQueryURL";
export type { AbortSignalLike, FetchLike, HttpRequestLike, Ordering, RequestInitLike, ResponseLike, Route, } from "./types/client";
export { asDate } from "./helpers/asDate";
export { asLink } from "./helpers/asLink";
export { asText } from "./helpers/asText";
export { asHTML } from "./helpers/asHTML";
export { asImageSrc } from "./helpers/asImageSrc";
export { asImageWidthSrcSet } from "./helpers/asImageWidthSrcSet";
export { asImagePixelDensitySrcSet } from "./helpers/asImagePixelDensitySrcSet";
export * as isFilled from "./helpers/isFilled";
export { documentToLinkField } from "./helpers/documentToLinkField";
export { Element } from "@prismicio/richtext";
export type { LinkResolverFunction, HTMLFunctionSerializer, HTMLMapSerializer, } from "./types/helpers";
export { RichTextNodeType } from "./types/value/richText";
export { LinkType } from "./types/value/link";
export { OEmbedType } from "./types/value/embed";
export type { PrismicDocument, PrismicDocumentWithUID, PrismicDocumentWithoutUID, PrismicDocumentHeader, AlternateLanguage, } from "./types/value/document";
export type { RichTextField, RTTextNodeBase, RTHeading1Node, RTHeading2Node, RTHeading3Node, RTHeading4Node, RTHeading5Node, RTHeading6Node, RTParagraphNode, RTPreformattedNode, RTListItemNode, RTOListItemNode, RTSpanNodeBase, RTStrongNode, RTEmNode, RTLabelNode, RTImageNode, RTEmbedNode, RTLinkNode, RTListNode, RTOListNode, RTSpanNode, RTNode, RTTextNode, RTBlockNode, RTInlineNode, RTAnyNode, } from "./types/value/richText";
export type { TitleField } from "./types/value/title";
export type { ImageField, ImageFieldImage, FilledImageFieldImage, EmptyImageFieldImage, } from "./types/value/image";
export type { EmptyLinkField, LinkField, FilledLinkToWebField, } from "./types/value/link";
export type { ContentRelationshipField, FilledContentRelationshipField, } from "./types/value/contentRelationship";
export type { LinkToMediaField, FilledLinkToMediaField, } from "./types/value/linkToMedia";
export type { OEmbedExtra, PhotoOEmbed, VideoOEmbed, LinkOEmbed, RichOEmbed, AnyOEmbed, EmbedField, } from "./types/value/embed";
export type { BooleanField } from "./types/value/boolean";
export type { ColorField } from "./types/value/color";
export type { DateField } from "./types/value/date";
export type { KeyTextField } from "./types/value/keyText";
export type { NumberField } from "./types/value/number";
export type { SelectField } from "./types/value/select";
export type { TimestampField } from "./types/value/timestamp";
export type { GeoPointField } from "./types/value/geoPoint";
export type { IntegrationFields } from "./types/value/integrationFields";
export type { GroupField } from "./types/value/group";
export type { SliceZone } from "./types/value/sliceZone";
export type { Slice } from "./types/value/slice";
export type { SharedSlice } from "./types/value/sharedSlice";
export type { SharedSliceVariation } from "./types/value/sharedSliceVariation";
export type { FieldState, AnyRegularField } from "./types/value/types";
export { CustomTypeModelFieldType } from "./types/model/types";
export { CustomTypeModelLinkSelectType } from "./types/model/link";
export { CustomTypeModelSliceType } from "./types/model/sliceZone";
export { CustomTypeModelSliceDisplay } from "./types/model/slice";
export type { CustomTypeModel, CustomTypeModelDefinition, CustomTypeModelTab, } from "./types/model/customType";
export type { CustomTypeModelRichTextField, CustomTypeModelRichTextMultiField, CustomTypeModelRichTextSingleField, } from "./types/model/richText";
export type { CustomTypeModelTitleField } from "./types/model/title";
export type { CustomTypeModelImageField, CustomTypeModelImageConstraint, CustomTypeModelImageThumbnail, } from "./types/model/image";
export type { CustomTypeModelContentRelationshipField } from "./types/model/contentRelationship";
export type { CustomTypeModelLinkField } from "./types/model/link";
export type { CustomTypeModelLinkToMediaField } from "./types/model/linkToMedia";
export type { CustomTypeModelEmbedField } from "./types/model/embed";
export type { CustomTypeModelBooleanField } from "./types/model/boolean";
export type { CustomTypeModelColorField } from "./types/model/color";
export type { CustomTypeModelDateField } from "./types/model/date";
export type { CustomTypeModelKeyTextField } from "./types/model/keyText";
export type { CustomTypeModelNumberField } from "./types/model/number";
export type { CustomTypeModelSelectField } from "./types/model/select";
export type { CustomTypeModelTimestampField } from "./types/model/timestamp";
export type { CustomTypeModelGeoPointField } from "./types/model/geoPoint";
export type { CustomTypeModelIntegrationFieldsField } from "./types/model/integrationFields";
export type { CustomTypeModelGroupField } from "./types/model/group";
export type { CustomTypeModelSliceZoneField, CustomTypeModelSliceLabel, CustomTypeModelSharedSlice, } from "./types/model/sliceZone";
export type { CustomTypeModelSlice, CustomTypeModelLegacySlice, } from "./types/model/slice";
export type { SharedSliceModel } from "./types/model/sharedSlice";
export type { SharedSliceModelVariation } from "./types/model/sharedSliceVariation";
export type { CustomTypeModelUIDField } from "./types/model/uid";
export type { CustomTypeModelRangeField } from "./types/model/range";
export type { CustomTypeModelSeparatorField } from "./types/model/separator";
export type { CustomTypeModelField, CustomTypeModelFieldForGroup, } from "./types/model/types";
export type { Query } from "./types/api/query";
export type { Ref } from "./types/api/ref";
export type { Release } from "./types/api/release";
export type { Repository, Language, Form, FormField, } from "./types/api/repository";
export type { Tags } from "./types/api/tags";
export { WebhookType } from "./types/webhook/types";
export type { WebhookBody } from "./types/webhook/types";
export type { WebhookBodyAPIUpdate } from "./types/webhook/apiUpdate";
export type { WebhookBodyTestTrigger } from "./types/webhook/testTrigger";

@@ -1,683 +0,66 @@

import * as prismicH from '@prismicio/helpers';
const isRepositoryName = (input) => {
return /^[a-zA-Z0-9][-a-zA-Z0-9]{2,}[a-zA-Z0-9]$/.test(input);
import { getRepositoryEndpoint } from "./getRepositoryEndpoint.js";
import { getRepositoryName } from "./getRepositoryName.js";
import { getGraphQLEndpoint } from "./getGraphQLEndpoint.js";
import { isRepositoryName } from "./isRepositoryName.js";
import { isRepositoryEndpoint } from "./isRepositoryEndpoint.js";
import { buildQueryURL } from "./buildQueryURL.js";
import { Client, createClient } from "./client.js";
import { predicate } from "./predicate.js";
import { PrismicError } from "./PrismicError.js";
import { ForbiddenError } from "./ForbiddenError.js";
import { ParsingError } from "./ParsingError.js";
import { NotFoundError } from "./NotFoundError.js";
import * as cookie from "./cookie.js";
import { asDate } from "./helpers/asDate.js";
import { asLink } from "./helpers/asLink.js";
import { asText } from "./helpers/asText.js";
import { asHTML } from "./helpers/asHTML.js";
import { asImageSrc } from "./helpers/asImageSrc.js";
import { asImageWidthSrcSet } from "./helpers/asImageWidthSrcSet.js";
import { asImagePixelDensitySrcSet } from "./helpers/asImagePixelDensitySrcSet.js";
import * as isFilled from "./helpers/isFilled.js";
import { documentToLinkField } from "./helpers/documentToLinkField.js";
import { Element } from "@prismicio/richtext";
import { RichTextNodeType } from "./types/value/richText.js";
import { LinkType } from "./types/value/link.js";
import { OEmbedType } from "./types/value/embed.js";
import { CustomTypeModelFieldType } from "./types/model/types.js";
import { CustomTypeModelLinkSelectType } from "./types/model/link.js";
import { CustomTypeModelSliceType } from "./types/model/sliceZone.js";
import { CustomTypeModelSliceDisplay } from "./types/model/slice.js";
import { WebhookType } from "./types/webhook/types.js";
export {
Client,
CustomTypeModelFieldType,
CustomTypeModelLinkSelectType,
CustomTypeModelSliceDisplay,
CustomTypeModelSliceType,
Element,
ForbiddenError,
LinkType,
NotFoundError,
OEmbedType,
ParsingError,
PrismicError,
RichTextNodeType,
WebhookType,
asDate,
asHTML,
asImagePixelDensitySrcSet,
asImageSrc,
asImageWidthSrcSet,
asLink,
asText,
buildQueryURL,
cookie,
createClient,
documentToLinkField,
getGraphQLEndpoint,
getRepositoryEndpoint,
getRepositoryName,
isFilled,
isRepositoryEndpoint,
isRepositoryName,
predicate
};
class PrismicError extends Error {
constructor(message = "An invalid API response was returned", url, response) {
super(message);
this.url = url;
this.response = response;
}
}
const getRepositoryEndpoint = (repositoryName) => {
if (isRepositoryName(repositoryName)) {
return `https://${repositoryName}.cdn.prismic.io/api/v2`;
} else {
throw new PrismicError(
`An invalid Prismic repository name was given: ${repositoryName}`,
void 0,
void 0
);
}
};
const getRepositoryName = (repositoryEndpoint) => {
try {
return new URL(repositoryEndpoint).hostname.split(".")[0];
} catch (e) {
throw new PrismicError(
`An invalid Prismic Rest API V2 endpoint was provided: ${repositoryEndpoint}`,
void 0,
void 0
);
}
};
const getGraphQLEndpoint = (repositoryName) => {
if (isRepositoryName(repositoryName)) {
return `https://${repositoryName}.cdn.prismic.io/graphql`;
} else {
throw new PrismicError(
`An invalid Prismic repository name was given: ${repositoryName}`,
void 0,
void 0
);
}
};
const isRepositoryEndpoint = (input) => {
try {
new URL(input);
return true;
} catch (e) {
return false;
}
};
const castArray = (a) => Array.isArray(a) ? a : [a];
const RENAMED_PARAMS = {
accessToken: "access_token"
};
const castOrderingToString = (ordering) => typeof ordering === "string" ? ordering : [
ordering.field,
ordering.direction === "desc" ? ordering.direction : void 0
].filter(Boolean).join(" ");
const buildQueryURL = (endpoint, args) => {
var _a;
const { predicates, ...params } = args;
const url = new URL(`documents/search`, `${endpoint}/`);
if (predicates) {
for (const predicate of castArray(predicates)) {
url.searchParams.append("q", `[${predicate}]`);
}
}
for (const k in params) {
const name = (_a = RENAMED_PARAMS[k]) != null ? _a : k;
let value = params[k];
if (name === "orderings") {
const scopedValue = params[name];
if (scopedValue != null) {
const v = castArray(scopedValue).map((ordering) => castOrderingToString(ordering)).join(",");
value = `[${v}]`;
}
} else if (name === "routes") {
if (typeof params[name] === "object") {
value = JSON.stringify(castArray(params[name]));
}
}
if (value != null) {
url.searchParams.set(name, castArray(value).join(","));
}
}
return url.toString();
};
const appendPredicates = (objWithPredicates = {}, predicates) => {
return {
...objWithPredicates,
predicates: [
...objWithPredicates.predicates || [],
...castArray(predicates)
]
};
};
const castThunk = (a) => typeof a === "function" ? a : () => a;
const findRef = (refs, predicate) => {
const ref = refs.find((ref2) => predicate(ref2));
if (!ref) {
throw new PrismicError("Ref could not be found.", void 0, void 0);
}
return ref;
};
const findMasterRef = (refs) => {
return findRef(refs, (ref) => ref.isMasterRef);
};
const findRefByID = (refs, id) => {
return findRef(refs, (ref) => ref.id === id);
};
const findRefByLabel = (refs, label) => {
return findRef(refs, (ref) => ref.label === label);
};
const preview = "io.prismic.preview";
var cookie = /*#__PURE__*/Object.freeze({
__proto__: null,
preview: preview
});
const readValue = (value) => {
return value.replace(/%3B/g, ";");
};
const getPreviewCookie = (cookieJar) => {
const cookies = cookieJar.split("; ");
let value;
for (const cookie of cookies) {
const parts = cookie.split("=");
const name = readValue(parts[0]).replace(/%3D/g, "=");
if (name === preview) {
value = readValue(parts.slice(1).join("="));
continue;
}
}
return value;
};
const minifyGraphQLQuery = (query) => {
return query.replace(
/(\n| )*( |{|})(\n| )*/gm,
(_chars, _spaces, brackets) => brackets
);
};
class ForbiddenError extends PrismicError {
}
class NotFoundError extends PrismicError {
}
class ParsingError extends PrismicError {
}
const formatValue = (value) => {
if (Array.isArray(value)) {
return `[${value.map(formatValue).join(", ")}]`;
}
if (typeof value === "string") {
return `"${value}"`;
}
if (value instanceof Date) {
return `${value.getTime()}`;
}
return `${value}`;
};
const pathWithArgsPredicate = (name) => {
const fn = (path, ...args) => {
const formattedArgs = args.map(formatValue).join(", ");
const joiner = path && args.length ? ", " : "";
return `[${name}(${path}${joiner}${formattedArgs})]`;
};
return fn;
};
const pathPredicate = (name) => {
const predicateFn = pathWithArgsPredicate(name);
const fn = (path) => {
return predicateFn(path);
};
return fn;
};
const argsPredicate = (name) => {
const predicateFn = pathWithArgsPredicate(name);
const fn = (...args) => {
return predicateFn("", ...args);
};
return fn;
};
const predicate = {
at: pathWithArgsPredicate("at"),
not: pathWithArgsPredicate("not"),
any: pathWithArgsPredicate(
"any"
),
in: pathWithArgsPredicate("in"),
fulltext: pathWithArgsPredicate("fulltext"),
has: pathPredicate("has"),
missing: pathPredicate("missing"),
similar: argsPredicate("similar"),
geopointNear: pathWithArgsPredicate("geopoint.near"),
numberLessThan: pathWithArgsPredicate("number.lt"),
numberGreaterThan: pathWithArgsPredicate("number.gt"),
numberInRange: pathWithArgsPredicate(
"number.inRange"
),
dateAfter: pathWithArgsPredicate("date.after"),
dateBefore: pathWithArgsPredicate("date.before"),
dateBetween: pathWithArgsPredicate("date.between"),
dateDayOfMonth: pathWithArgsPredicate("date.day-of-month"),
dateDayOfMonthAfter: pathWithArgsPredicate(
"date.day-of-month-after"
),
dateDayOfMonthBefore: pathWithArgsPredicate(
"date.day-of-month-before"
),
dateDayOfWeek: pathWithArgsPredicate("date.day-of-week"),
dateDayOfWeekAfter: pathWithArgsPredicate(
"date.day-of-week-after"
),
dateDayOfWeekBefore: pathWithArgsPredicate(
"date.day-of-week-before"
),
dateMonth: pathWithArgsPredicate("date.month"),
dateMonthAfter: pathWithArgsPredicate("date.month-after"),
dateMonthBefore: pathWithArgsPredicate("date.month-before"),
dateYear: pathWithArgsPredicate("date.year"),
dateHour: pathWithArgsPredicate("date.hour"),
dateHourAfter: pathWithArgsPredicate("date.hour-after"),
dateHourBefore: pathWithArgsPredicate("date.hour-before")
};
const MAX_PAGE_SIZE = 100;
const REPOSITORY_CACHE_TTL = 5e3;
const GET_ALL_QUERY_DELAY = 500;
const typePredicate = (documentType) => predicate.at("document.type", documentType);
const everyTagPredicate = (tags) => predicate.at("document.tags", castArray(tags));
const someTagsPredicate = (tags) => predicate.any("document.tags", castArray(tags));
const createClient = (repositoryNameOrEndpoint, options) => new Client(repositoryNameOrEndpoint, options);
class Client {
constructor(repositoryNameOrEndpoint, options = {}) {
this.refState = {
mode: "Master" /* Master */,
autoPreviewsEnabled: true
};
this.cachedRepositoryExpiration = 0;
this.graphqlFetch = this.graphQLFetch.bind(this);
if (isRepositoryEndpoint(repositoryNameOrEndpoint)) {
if (process.env.NODE_ENV === "development" && /\.prismic\.io\/(?!api\/v2\/?)/.test(repositoryNameOrEndpoint)) {
throw new PrismicError(
"@prismicio/client only supports Prismic Rest API V2. Please provide only the repository name to the first createClient() parameter or use the getRepositoryEndpoint() helper to generate a valid Rest API V2 endpoint URL.",
void 0,
void 0
);
}
this.endpoint = repositoryNameOrEndpoint;
} else {
this.endpoint = getRepositoryEndpoint(repositoryNameOrEndpoint);
}
this.accessToken = options.accessToken;
this.routes = options.routes;
this.brokenRoute = options.brokenRoute;
this.defaultParams = options.defaultParams;
if (options.ref) {
this.queryContentFromRef(options.ref);
}
if (typeof options.fetch === "function") {
this.fetchFn = options.fetch;
} else if (typeof globalThis.fetch === "function") {
this.fetchFn = globalThis.fetch;
} else {
throw new PrismicError(
"A valid fetch implementation was not provided. In environments where fetch is not available (including Node.js), a fetch implementation must be provided via a polyfill or the `fetch` option.",
void 0,
void 0
);
}
if (this.fetchFn === globalThis.fetch) {
this.fetchFn = this.fetchFn.bind(globalThis);
}
this.graphQLFetch = this.graphQLFetch.bind(this);
}
enableAutoPreviews() {
this.refState.autoPreviewsEnabled = true;
}
enableAutoPreviewsFromReq(req) {
this.refState.httpRequest = req;
this.refState.autoPreviewsEnabled = true;
}
disableAutoPreviews() {
this.refState.autoPreviewsEnabled = false;
}
async query(predicates, params) {
const url = await this.buildQueryURL({ ...params, predicates });
return await this.fetch(url, params);
}
async get(params) {
const url = await this.buildQueryURL(params);
return await this.fetch(url, params);
}
async getFirst(params) {
var _a, _b;
const actualParams = { ...params };
if (!(params && params.page) && !(params == null ? void 0 : params.pageSize)) {
actualParams.pageSize = (_b = (_a = this.defaultParams) == null ? void 0 : _a.pageSize) != null ? _b : 1;
}
const url = await this.buildQueryURL(actualParams);
const result = await this.fetch(url, params);
const firstResult = result.results[0];
if (firstResult) {
return firstResult;
}
throw new PrismicError("No documents were returned", url, void 0);
}
async dangerouslyGetAll(params = {}) {
var _a;
const { limit = Infinity, ...actualParams } = params;
const resolvedParams = {
...actualParams,
pageSize: Math.min(
limit,
actualParams.pageSize || ((_a = this.defaultParams) == null ? void 0 : _a.pageSize) || MAX_PAGE_SIZE
)
};
const documents = [];
let latestResult;
while ((!latestResult || latestResult.next_page) && documents.length < limit) {
const page = latestResult ? latestResult.page + 1 : void 0;
latestResult = await this.get({ ...resolvedParams, page });
documents.push(...latestResult.results);
if (latestResult.next_page) {
await new Promise((res) => setTimeout(res, GET_ALL_QUERY_DELAY));
}
}
return documents.slice(0, limit);
}
async getByID(id, params) {
return await this.getFirst(
appendPredicates(params, predicate.at("document.id", id))
);
}
async getByIDs(ids, params) {
return await this.get(
appendPredicates(params, predicate.in("document.id", ids))
);
}
async getAllByIDs(ids, params) {
return await this.dangerouslyGetAll(
appendPredicates(params, predicate.in("document.id", ids))
);
}
async getByUID(documentType, uid, params) {
return await this.getFirst(
appendPredicates(params, [
typePredicate(documentType),
predicate.at(`my.${documentType}.uid`, uid)
])
);
}
async getByUIDs(documentType, uids, params) {
return await this.get(
appendPredicates(params, [
typePredicate(documentType),
predicate.in(`my.${documentType}.uid`, uids)
])
);
}
async getAllByUIDs(documentType, uids, params) {
return await this.dangerouslyGetAll(
appendPredicates(params, [
typePredicate(documentType),
predicate.in(`my.${documentType}.uid`, uids)
])
);
}
async getSingle(documentType, params) {
return await this.getFirst(
appendPredicates(params, typePredicate(documentType))
);
}
async getByType(documentType, params) {
return await this.get(
appendPredicates(params, typePredicate(documentType))
);
}
async getAllByType(documentType, params) {
return await this.dangerouslyGetAll(appendPredicates(params, typePredicate(documentType)));
}
async getByTag(tag, params) {
return await this.get(
appendPredicates(params, someTagsPredicate(tag))
);
}
async getAllByTag(tag, params) {
return await this.dangerouslyGetAll(
appendPredicates(params, someTagsPredicate(tag))
);
}
async getByEveryTag(tags, params) {
return await this.get(
appendPredicates(params, everyTagPredicate(tags))
);
}
async getAllByEveryTag(tags, params) {
return await this.dangerouslyGetAll(
appendPredicates(params, everyTagPredicate(tags))
);
}
async getBySomeTags(tags, params) {
return await this.get(
appendPredicates(params, someTagsPredicate(tags))
);
}
async getAllBySomeTags(tags, params) {
return await this.dangerouslyGetAll(
appendPredicates(params, someTagsPredicate(tags))
);
}
async getRepository(params) {
const url = new URL(this.endpoint);
if (this.accessToken) {
url.searchParams.set("access_token", this.accessToken);
}
return await this.fetch(url.toString(), params);
}
async getRefs(params) {
const repository = await this.getRepository(params);
return repository.refs;
}
async getRefByID(id, params) {
const refs = await this.getRefs(params);
return findRefByID(refs, id);
}
async getRefByLabel(label, params) {
const refs = await this.getRefs(params);
return findRefByLabel(refs, label);
}
async getMasterRef(params) {
const refs = await this.getRefs(params);
return findMasterRef(refs);
}
async getReleases(params) {
const refs = await this.getRefs(params);
return refs.filter((ref) => !ref.isMasterRef);
}
async getReleaseByID(id, params) {
const releases = await this.getReleases(params);
return findRefByID(releases, id);
}
async getReleaseByLabel(label, params) {
const releases = await this.getReleases(params);
return findRefByLabel(releases, label);
}
async getTags(params) {
try {
const tagsForm = await this.getCachedRepositoryForm("tags", params);
const url = new URL(tagsForm.action);
if (this.accessToken) {
url.searchParams.set("access_token", this.accessToken);
}
return await this.fetch(url.toString(), params);
} catch (e) {
const repository = await this.getRepository(params);
return repository.tags;
}
}
async buildQueryURL({
signal,
...params
} = {}) {
const ref = params.ref || await this.getResolvedRefString();
const integrationFieldsRef = params.integrationFieldsRef || (await this.getCachedRepository({ signal })).integrationFieldsRef || void 0;
return buildQueryURL(this.endpoint, {
...this.defaultParams,
...params,
ref,
integrationFieldsRef,
routes: params.routes || this.routes,
brokenRoute: params.brokenRoute || this.brokenRoute,
accessToken: params.accessToken || this.accessToken
});
}
async resolvePreviewURL(args) {
var _a, _b;
let documentID = args.documentID;
let previewToken = args.previewToken;
if (typeof globalThis.location !== "undefined") {
const searchParams = new URLSearchParams(globalThis.location.search);
documentID = documentID || searchParams.get("documentId");
previewToken = previewToken || searchParams.get("token");
} else if (this.refState.httpRequest) {
if ("query" in this.refState.httpRequest) {
documentID = documentID || ((_a = this.refState.httpRequest.query) == null ? void 0 : _a.documentId);
previewToken = previewToken || ((_b = this.refState.httpRequest.query) == null ? void 0 : _b.token);
} else if ("url" in this.refState.httpRequest && this.refState.httpRequest.url) {
const searchParams = new URL(this.refState.httpRequest.url).searchParams;
documentID = documentID || searchParams.get("documentId");
previewToken = previewToken || searchParams.get("token");
}
}
if (documentID != null && previewToken != null) {
const document = await this.getByID(documentID, {
signal: args.signal,
ref: previewToken,
lang: "*"
});
const url = prismicH.asLink(document, args.linkResolver);
if (typeof url === "string") {
return url;
}
}
return args.defaultURL;
}
queryLatestContent() {
this.refState.mode = "Master" /* Master */;
}
queryContentFromReleaseByID(releaseID) {
this.refState = {
...this.refState,
mode: "ReleaseID" /* ReleaseID */,
releaseID
};
}
queryContentFromReleaseByLabel(releaseLabel) {
this.refState = {
...this.refState,
mode: "ReleaseLabel" /* ReleaseLabel */,
releaseLabel
};
}
queryContentFromRef(ref) {
this.refState = {
...this.refState,
mode: "Manual" /* Manual */,
ref
};
}
async graphQLFetch(input, init) {
const cachedRepository = await this.getCachedRepository();
const ref = await this.getResolvedRefString();
const unsanitizedHeaders = {
"Prismic-ref": ref,
Authorization: this.accessToken ? `Token ${this.accessToken}` : "",
...init ? init.headers : {}
};
if (cachedRepository.integrationFieldsRef) {
unsanitizedHeaders["Prismic-integration-field-ref"] = cachedRepository.integrationFieldsRef;
}
const headers = {};
for (const key in unsanitizedHeaders) {
if (unsanitizedHeaders[key]) {
headers[key.toLowerCase()] = unsanitizedHeaders[key];
}
}
const url = new URL(
input
);
url.searchParams.set("ref", ref);
const query = url.searchParams.get("query");
if (query) {
url.searchParams.set(
"query",
minifyGraphQLQuery(query)
);
}
return await this.fetchFn(url.toString(), {
...init,
headers
});
}
async getCachedRepository(params) {
if (!this.cachedRepository || Date.now() >= this.cachedRepositoryExpiration) {
this.cachedRepositoryExpiration = Date.now() + REPOSITORY_CACHE_TTL;
this.cachedRepository = await this.getRepository(params);
}
return this.cachedRepository;
}
async getCachedRepositoryForm(name, params) {
const cachedRepository = await this.getCachedRepository(params);
const form = cachedRepository.forms[name];
if (!form) {
throw new PrismicError(
`Form with name "${name}" could not be found`,
void 0,
void 0
);
}
return form;
}
async getResolvedRefString(params) {
var _a, _b;
if (this.refState.autoPreviewsEnabled) {
let previewRef;
let cookieJar;
if ((_a = this.refState.httpRequest) == null ? void 0 : _a.headers) {
if ("get" in this.refState.httpRequest.headers && typeof this.refState.httpRequest.headers.get === "function") {
cookieJar = this.refState.httpRequest.headers.get("cookie");
} else if ("cookie" in this.refState.httpRequest.headers) {
cookieJar = this.refState.httpRequest.headers.cookie;
}
} else if ((_b = globalThis.document) == null ? void 0 : _b.cookie) {
cookieJar = globalThis.document.cookie;
}
if (cookieJar) {
previewRef = getPreviewCookie(cookieJar);
}
if (previewRef) {
return previewRef;
}
}
const cachedRepository = await this.getCachedRepository(params);
const refModeType = this.refState.mode;
if (refModeType === "ReleaseID" /* ReleaseID */) {
return findRefByID(cachedRepository.refs, this.refState.releaseID).ref;
} else if (refModeType === "ReleaseLabel" /* ReleaseLabel */) {
return findRefByLabel(cachedRepository.refs, this.refState.releaseLabel).ref;
} else if (refModeType === "Manual" /* Manual */) {
const res = await castThunk(this.refState.ref)();
if (typeof res === "string") {
return res;
}
}
return findMasterRef(cachedRepository.refs).ref;
}
async fetch(url, params = {}) {
const res = await this.fetchFn(url, {
signal: params.signal
});
let json;
try {
json = await res.json();
} catch (e) {
if (res.status === 404) {
throw new NotFoundError(
`Prismic repository not found. Check that "${this.endpoint}" is pointing to the correct repository.`,
url,
void 0
);
} else {
throw new PrismicError(void 0, url, void 0);
}
}
switch (res.status) {
case 200: {
return json;
}
case 400: {
throw new ParsingError(json.message, url, json);
}
case 401:
case 403: {
throw new ForbiddenError(
"error" in json ? json.error : json.message,
url,
json
);
}
}
throw new PrismicError(void 0, url, json);
}
}
const getEndpoint = getRepositoryEndpoint;
const predicates = predicate;
const Predicates = predicate;
export { Client, ForbiddenError, NotFoundError, ParsingError, Predicates, PrismicError, buildQueryURL, cookie, createClient, getEndpoint, getGraphQLEndpoint, getRepositoryEndpoint, getRepositoryName, isRepositoryEndpoint, isRepositoryName, predicate, predicates };
//# sourceMappingURL=index.js.map
{
"name": "@prismicio/client",
"version": "6.7.1",
"version": "7.0.0-alpha.0",
"description": "The official JavaScript + TypeScript client library for Prismic",
"keywords": [
"typescript",
"client",
"helpers",
"types",
"utils",
"toolbox",
"cms",
"prismic",
"prismic.io",
"cms",
"content",
"api",
"typescript"
"prismic.io"
],

@@ -37,45 +40,49 @@ "repository": {

"scripts": {
"build": "siroc build",
"dev": "siroc build --watch",
"format": "prettier --write README.md .eslintrc.cjs ava.config.js package.json tsconfig.json {src,examples,test}/**",
"lint": "eslint --ext .js,.ts .",
"build": "vite build",
"dev": "vite build --watch",
"format": "prettier --write .",
"prepare": "npm run build",
"release": "npm run build && npm run test && standard-version && git push --follow-tags && npm run build && npm publish",
"release:beta": "npm run build && npm run test && standard-version --release-as major --prerelease beta && git push --follow-tags && npm run build && npm publish --tag beta",
"release:beta:dry": "standard-version --release-as major --prerelease beta --dry-run",
"release": "npm run test && standard-version && git push --follow-tags && npm run build && npm publish",
"release:dry": "standard-version --dry-run",
"release:alpha": "npm run test && standard-version --release-as major --prerelease alpha && git push --follow-tags && npm run build && npm publish --tag alpha",
"release:alpha:dry": "standard-version --release-as major --prerelease alpha --dry-run",
"lint": "eslint --ext .js,.ts .",
"types": "tsc --noEmit",
"unit": "vitest run --coverage",
"unit:watch": "vitest watch",
"size": "size-limit",
"test": "npm run lint && npm run unit && npm run build && npm run size",
"unit": "vitest run --coverage",
"unit:watch": "vitest watch"
"test": "npm run lint && npm run types && npm run unit && npm run build && npm run size"
},
"dependencies": {
"@prismicio/helpers": "^2.3.3",
"@prismicio/types": "^0.2.3"
"@prismicio/richtext": "^2.1.1",
"escape-html": "^1.0.3",
"imgix-url-builder": "^0.0.3"
},
"devDependencies": {
"@prismicio/mock": "^0.1.1",
"@size-limit/preset-small-lib": "^8.0.1",
"@types/sinon": "^10.0.13",
"@typescript-eslint/eslint-plugin": "^5.34.0",
"@typescript-eslint/parser": "^5.34.0",
"@vitest/coverage-c8": "^0.22.1",
"@prismicio/types-internal": "^1.1.1",
"@size-limit/preset-small-lib": "^8.1.0",
"@types/escape-html": "^1.0.2",
"@typescript-eslint/eslint-plugin": "^5.39.0",
"@typescript-eslint/parser": "^5.39.0",
"@vitest/coverage-c8": "^0.23.4",
"abort-controller": "^3.0.0",
"eslint": "^8.22.0",
"eslint": "^8.24.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-tsdoc": "^0.2.16",
"msw": "^0.45.0",
"eslint-plugin-tsdoc": "^0.2.17",
"msw": "^0.47.4",
"node-fetch": "^3.2.10",
"nyc": "^15.1.0",
"prettier": "^2.7.1",
"prettier-plugin-jsdoc": "^0.3.38",
"siroc": "^0.16.0",
"size-limit": "^8.0.1",
"prettier-plugin-jsdoc": "^0.4.2",
"size-limit": "^8.1.0",
"standard-version": "^9.5.0",
"typescript": "^4.7.4",
"vitest": "^0.22.1"
"ts-expect": "^1.3.0",
"typescript": "^4.8.4",
"vite": "^3.1.4",
"vite-plugin-sdk": "^0.0.3",
"vitest": "^0.23.4"
},
"engines": {
"node": ">=12.13.0"
"node": ">=14.15.0"
},

@@ -82,0 +89,0 @@ "publishConfig": {

import { castArray } from "./lib/castArray";
import { ValueOf, Ordering, Route } from "./types";
import type { ValueOf } from "./types/utils";
import type { Ordering, Route } from "./types/client";

@@ -36,3 +37,4 @@ /**

* The `after` parameter can be used along with the orderings option. It will
* remove all the documents except for those after the specified document in the list.
* remove all the documents except for those after the specified document in
* the list.
*

@@ -61,3 +63,4 @@ * {@link https://prismic.io/docs/technologies/search-parameters-reference-rest-api#after}

* The `graphQuery` parameter allows you to specify which fields to retrieve
* and what content to retrieve from Linked Documents / Content Relationships.
* and what content to retrieve from Linked Documents / Content
* Relationships.
*

@@ -84,3 +87,4 @@ * {@link https://prismic.io/docs/technologies/graphquery-rest-api}

/**
* The `routes` option allows you to define how a document's `url` field is resolved.
* The `routes` option allows you to define how a document's `url` field is
* resolved.
*

@@ -87,0 +91,0 @@ * {@link https://prismic.io/docs/core-concepts/link-resolver-route-resolver#route-resolver}

@@ -1,4 +0,1 @@

import * as prismicT from "@prismicio/types";
import * as prismicH from "@prismicio/helpers";
import { appendPredicates } from "./lib/appendPredicates";

@@ -13,3 +10,3 @@ import { castArray } from "./lib/castArray";

import {
import type {
AbortSignalLike,

@@ -19,3 +16,11 @@ FetchLike,

ExtractDocumentType,
} from "./types";
} from "./types/client";
import type { LinkResolverFunction } from "./types/helpers";
import type { PrismicDocument } from "./types/value/document";
import type { Form, Repository } from "./types/api/repository";
import type { Query } from "./types/api/query";
import type { Ref } from "./types/api/ref";
import { asLink } from "./helpers/asLink";
import { ForbiddenError } from "./ForbiddenError";

@@ -204,3 +209,3 @@ import { NotFoundError } from "./NotFoundError";

*/
linkResolver?: prismicH.LinkResolverFunction<LinkResolverReturnType>;
linkResolver?: LinkResolverFunction<LinkResolverReturnType>;

@@ -261,3 +266,3 @@ /**

export interface CreateClient {
<TDocuments extends prismicT.PrismicDocument>(
<TDocuments extends PrismicDocument>(
...args: ConstructorParameters<typeof Client>

@@ -289,5 +294,3 @@ ): Client<TDocuments>;

*/
export const createClient: CreateClient = <
TDocuments extends prismicT.PrismicDocument,
>(
export const createClient: CreateClient = <TDocuments extends PrismicDocument>(
repositoryNameOrEndpoint: string,

@@ -307,5 +310,3 @@ options?: ClientConfig,

*/
export class Client<
TDocuments extends prismicT.PrismicDocument = prismicT.PrismicDocument,
> {
export class Client<TDocuments extends PrismicDocument = PrismicDocument> {
/**

@@ -360,3 +361,4 @@ * The Prismic REST API V2 endpoint for the repository (use

/**
* The client's ref mode state. This determines which ref is used during queries.
* The client's ref mode state. This determines which ref is used during
* queries.
*/

@@ -371,3 +373,3 @@ private refState: RefState = {

*/
private cachedRepository: prismicT.Repository | undefined;
private cachedRepository: Repository | undefined;

@@ -442,3 +444,4 @@ /**

* Enables the client to automatically query content from a preview session if
* one is active in browser environments. This is enabled by default in the browser.
* one is active in browser environments. This is enabled by default in the
* browser.
*

@@ -461,3 +464,4 @@ * For server environments, use `enableAutoPreviewsFromReq`.

* Enables the client to automatically query content from a preview session if
* one is active in server environments. This is disabled by default on the server.
* one is active in server environments. This is disabled by default on the
* server.
*

@@ -475,3 +479,4 @@ * For browser environments, use `enableAutoPreviews`.

*
* @param req - An HTTP server request object containing the request's cookies.
* @param req - An HTTP server request object containing the request's
* cookies.
*/

@@ -503,31 +508,5 @@ enableAutoPreviewsFromReq<R extends HttpRequestLike>(req: R): void {

*
* @deprecated Use `get` instead.
* @example
*
* ```ts
* const response = await client.query(
* prismic.predicate.at("document.type", "page"),
* );
* ```
*
* @typeParam TDocument - Type of Prismic documents returned.
* @param params - Parameters to filter, sort, and paginate results.
*
* @returns A paginated response containing the result of the query.
*/
async query<TDocument extends TDocuments>(
predicates: NonNullable<BuildQueryURLArgs["predicates"]>,
params?: Partial<Omit<BuildQueryURLArgs, "predicates">> & FetchParams,
): Promise<prismicT.Query<TDocument>> {
const url = await this.buildQueryURL({ ...params, predicates });
return await this.fetch<prismicT.Query<TDocument>>(url, params);
}
/**
* Queries content from the Prismic repository.
*
* @example
*
* ```ts
* const response = await client.get();

@@ -543,6 +522,6 @@ * ```

params?: Partial<BuildQueryURLArgs> & FetchParams,
): Promise<prismicT.Query<TDocument>> {
): Promise<Query<TDocument>> {
const url = await this.buildQueryURL(params);
return await this.fetch<prismicT.Query<TDocument>>(url, params);
return await this.fetch<Query<TDocument>>(url, params);
}

@@ -572,3 +551,3 @@

const url = await this.buildQueryURL(actualParams);
const result = await this.fetch<prismicT.Query<TDocument>>(url, params);
const result = await this.fetch<Query<TDocument>>(url, params);

@@ -592,3 +571,4 @@ const firstResult = result.results[0];

*
* This method may make multiple network requests to query all matching content.
* This method may make multiple network requests to query all matching
* content.
*

@@ -621,3 +601,3 @@ * @example

const documents: TDocument[] = [];
let latestResult: prismicT.Query<TDocument> | undefined;
let latestResult: Query<TDocument> | undefined;

@@ -647,3 +627,4 @@ while (

* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* provided in the Prismic editor and is unique among all documents of its
* Custom Type.
* @example

@@ -677,3 +658,4 @@ *

* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* provided in the Prismic editor and is unique among all documents of its
* Custom Type.
* @example

@@ -698,3 +680,3 @@ *

params?: Partial<BuildQueryURLArgs> & FetchParams,
): Promise<prismicT.Query<TDocument>> {
): Promise<Query<TDocument>> {
return await this.get<TDocument>(

@@ -708,3 +690,4 @@ appendPredicates(params, predicate.in("document.id", ids)),

*
* This method may make multiple network requests to query all matching content.
* This method may make multiple network requests to query all matching
* content.
*

@@ -714,3 +697,4 @@ * @remarks

* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* provided in the Prismic editor and is unique among all documents of its
* Custom Type.
* @example

@@ -741,3 +725,4 @@ *

/**
* Queries a document from the Prismic repository with a specific UID and Custom Type.
* Queries a document from the Prismic repository with a specific UID and
* Custom Type.
*

@@ -747,3 +732,4 @@ * @remarks

* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* provided in the Prismic editor and is unique among all documents of its
* Custom Type.
* @example

@@ -780,3 +766,4 @@ *

/**
* Queries document from the Prismic repository with specific UIDs and Custom Type.
* Queries document from the Prismic repository with specific UIDs and Custom
* Type.
*

@@ -786,3 +773,4 @@ * @remarks

* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* provided in the Prismic editor and is unique among all documents of its
* Custom Type.
* @example

@@ -812,3 +800,3 @@ *

params?: Partial<BuildQueryURLArgs> & FetchParams,
): Promise<prismicT.Query<ExtractDocumentType<TDocument, TDocumentType>>> {
): Promise<Query<ExtractDocumentType<TDocument, TDocumentType>>> {
return await this.get<ExtractDocumentType<TDocument, TDocumentType>>(

@@ -823,5 +811,7 @@ appendPredicates(params, [

/**
* Queries all documents from the Prismic repository with specific UIDs and Custom Type.
* Queries all documents from the Prismic repository with specific UIDs and
* Custom Type.
*
* This method may make multiple network requests to query all matching content.
* This method may make multiple network requests to query all matching
* content.
*

@@ -831,3 +821,4 @@ * @remarks

* for all documents and is made available on its `id` property. A UID is
* provided in the Prismic editor and is unique among all documents of its Custom Type.
* provided in the Prismic editor and is unique among all documents of its
* Custom Type.
* @example

@@ -868,3 +859,4 @@ *

/**
* Queries a singleton document from the Prismic repository for a specific Custom Type.
* Queries a singleton document from the Prismic repository for a specific
* Custom Type.
*

@@ -886,3 +878,4 @@ * @remarks

*
* @returns The singleton document for the Custom Type, if a matching document exists.
* @returns The singleton document for the Custom Type, if a matching document
* exists.
*/

@@ -925,3 +918,3 @@ async getSingle<

params?: Partial<BuildQueryURLArgs> & FetchParams,
): Promise<prismicT.Query<ExtractDocumentType<TDocument, TDocumentType>>> {
): Promise<Query<ExtractDocumentType<TDocument, TDocumentType>>> {
return await this.get<ExtractDocumentType<TDocument, TDocumentType>>(

@@ -933,5 +926,7 @@ appendPredicates(params, typePredicate(documentType)),

/**
* Queries all documents from the Prismic repository for a specific Custom Type.
* Queries all documents from the Prismic repository for a specific Custom
* Type.
*
* This method may make multiple network requests to query all matching content.
* This method may make multiple network requests to query all matching
* content.
*

@@ -967,3 +962,4 @@ * @example

*
* Use `getAllByTag` instead if you need to query all documents with a specific tag.
* Use `getAllByTag` instead if you need to query all documents with a
* specific tag.
*

@@ -985,3 +981,3 @@ * @example

params?: Partial<BuildQueryURLArgs> & FetchParams,
): Promise<prismicT.Query<TDocument>> {
): Promise<Query<TDocument>> {
return await this.get<TDocument>(

@@ -995,3 +991,4 @@ appendPredicates(params, someTagsPredicate(tag)),

*
* This method may make multiple network requests to query all matching content.
* This method may make multiple network requests to query all matching
* content.
*

@@ -1040,3 +1037,3 @@ * @example

params?: Partial<BuildQueryURLArgs> & FetchParams,
): Promise<prismicT.Query<TDocument>> {
): Promise<Query<TDocument>> {
return await this.get<TDocument>(

@@ -1051,3 +1048,4 @@ appendPredicates(params, everyTagPredicate(tags)),

*
* This method may make multiple network requests to query all matching content.
* This method may make multiple network requests to query all matching
* content.
*

@@ -1079,3 +1077,4 @@ * @example

* Queries documents from the Prismic repository with specific tags. A
* document must be tagged with at least one of the queried tags to be included.
* document must be tagged with at least one of the queried tags to be
* included.
*

@@ -1092,3 +1091,4 @@ * @example

*
* @returns A paginated response containing documents with at least one of the tags.
* @returns A paginated response containing documents with at least one of the
* tags.
*/

@@ -1098,3 +1098,3 @@ async getBySomeTags<TDocument extends TDocuments>(

params?: Partial<BuildQueryURLArgs> & FetchParams,
): Promise<prismicT.Query<TDocument>> {
): Promise<Query<TDocument>> {
return await this.get<TDocument>(

@@ -1107,5 +1107,7 @@ appendPredicates(params, someTagsPredicate(tags)),

* Queries documents from the Prismic repository with specific tags. A
* document must be tagged with at least one of the queried tags to be included.
* document must be tagged with at least one of the queried tags to be
* included.
*
* This method may make multiple network requests to query all matching content.
* This method may make multiple network requests to query all matching
* content.
*

@@ -1141,5 +1143,5 @@ * @example

*/
async getRepository(params?: FetchParams): Promise<prismicT.Repository> {
async getRepository(params?: FetchParams): Promise<Repository> {
// TODO: Restore when Authorization header support works in browsers with CORS.
// return await this.fetch<prismicT.Repository>(this.endpoint);
// return await this.fetch<Repository>(this.endpoint);

@@ -1152,3 +1154,3 @@ const url = new URL(this.endpoint);

return await this.fetch<prismicT.Repository>(url.toString(), params);
return await this.fetch<Repository>(url.toString(), params);
}

@@ -1165,3 +1167,3 @@

*/
async getRefs(params?: FetchParams): Promise<prismicT.Ref[]> {
async getRefs(params?: FetchParams): Promise<Ref[]> {
const repository = await this.getRepository(params);

@@ -1179,3 +1181,3 @@

*/
async getRefByID(id: string, params?: FetchParams): Promise<prismicT.Ref> {
async getRefByID(id: string, params?: FetchParams): Promise<Ref> {
const refs = await this.getRefs(params);

@@ -1193,6 +1195,3 @@

*/
async getRefByLabel(
label: string,
params?: FetchParams,
): Promise<prismicT.Ref> {
async getRefByLabel(label: string, params?: FetchParams): Promise<Ref> {
const refs = await this.getRefs(params);

@@ -1209,3 +1208,3 @@

*/
async getMasterRef(params?: FetchParams): Promise<prismicT.Ref> {
async getMasterRef(params?: FetchParams): Promise<Ref> {
const refs = await this.getRefs(params);

@@ -1222,3 +1221,3 @@

*/
async getReleases(params?: FetchParams): Promise<prismicT.Ref[]> {
async getReleases(params?: FetchParams): Promise<Ref[]> {
const refs = await this.getRefs(params);

@@ -1236,6 +1235,3 @@

*/
async getReleaseByID(
id: string,
params?: FetchParams,
): Promise<prismicT.Ref> {
async getReleaseByID(id: string, params?: FetchParams): Promise<Ref> {
const releases = await this.getReleases(params);

@@ -1253,6 +1249,3 @@

*/
async getReleaseByLabel(
label: string,
params?: FetchParams,
): Promise<prismicT.Ref> {
async getReleaseByLabel(label: string, params?: FetchParams): Promise<Ref> {
const releases = await this.getReleases(params);

@@ -1369,3 +1362,3 @@

const url = prismicH.asLink(document, args.linkResolver);
const url = asLink(document, args.linkResolver);

@@ -1381,5 +1374,7 @@ if (typeof url === "string") {

/**
* Configures the client to query the latest published content for all future queries.
* Configures the client to query the latest published content for all future
* queries.
*
* If the `ref` parameter is provided during a query, it takes priority for that query.
* If the `ref` parameter is provided during a query, it takes priority for
* that query.
*

@@ -1401,3 +1396,4 @@ * @example

*
* If the `ref` parameter is provided during a query, it takes priority for that query.
* If the `ref` parameter is provided during a query, it takes priority for
* that query.
*

@@ -1425,3 +1421,4 @@ * @example

*
* If the `ref` parameter is provided during a query, it takes priority for that query.
* If the `ref` parameter is provided during a query, it takes priority for
* that query.
*

@@ -1459,3 +1456,4 @@ * @example

*
* @param ref - The ref or a function that returns the ref from which to query content.
* @param ref - The ref or a function that returns the ref from which to query
* content.
*/

@@ -1471,8 +1469,2 @@ queryContentFromRef(ref: RefStringOrThunk): void {

/**
* @deprecated Renamed to `graphQLFetch()` (note the capitalization of "QL").
*/
// TODO: Remove in v7
graphqlFetch = this.graphQLFetch.bind(this);
/**
* A `fetch()` function to be used with GraphQL clients configured for

@@ -1486,7 +1478,7 @@ * Prismic's GraphQL API. It automatically applies the necessary `prismic-ref`

* ```ts
* const graphqlClient = new ApolloClient({
* const graphQLClient = new ApolloClient({
* link: new HttpLink({
* uri: prismic.getGraphQLEndpoint(repositoryName),
* // Provide `client.graphqlFetch` as the fetch implementation.
* fetch: client.graphqlFetch,
* // Provide `client.graphQLFetch` as the fetch implementation.
* fetch: client.graphQLFetch,
* // Using GET is required.

@@ -1500,3 +1492,4 @@ * useGETForQueries: true,

* @param input - The `fetch()` `input` parameter. Only strings are supported.
* @param init - The `fetch()` `init` parameter. Only plain objects are supported.
* @param init - The `fetch()` `init` parameter. Only plain objects are
* supported.
*

@@ -1579,5 +1572,3 @@ * @returns The `fetch()` Response for the request.

*/
private async getCachedRepository(
params?: FetchParams,
): Promise<prismicT.Repository> {
private async getCachedRepository(params?: FetchParams): Promise<Repository> {
if (

@@ -1606,3 +1597,3 @@ !this.cachedRepository ||

params?: FetchParams,
): Promise<prismicT.Form> {
): Promise<Form> {
const cachedRepository = await this.getCachedRepository(params);

@@ -1624,3 +1615,4 @@ const form = cachedRepository.forms[name];

* Returns the ref needed to query based on the client's current state. This
* method may make a network request to fetch a ref or resolve the user's ref thunk.
* method may make a network request to fetch a ref or resolve the user's ref
* thunk.
*

@@ -1632,3 +1624,4 @@ * If auto previews are enabled, the preview ref takes priority if available.

* - If the user called `queryLatestContent`: Use the repository's master ref.
* The ref is cached for 5 seconds. After 5 seconds, a new master ref is fetched.
* The ref is cached for 5 seconds. After 5 seconds, a new master ref is
* fetched.
* - If the user called `queryContentFromReleaseByID`: Use the release's ref.

@@ -1635,0 +1628,0 @@ * The ref is cached for 5 seconds. After 5 seconds, a new ref for the

/**
* The well-known name of the cookie used to store a Prismic preview session's ref.
* The well-known name of the cookie used to store a Prismic preview session's
* ref.
*/
export const preview = "io.prismic.preview";

@@ -7,7 +7,9 @@ import { PrismicError } from "./PrismicError";

*
* @typeParam RepositoryEndpoint - Prismic Rest API V2 endpoint for the repository.
* @typeParam RepositoryEndpoint - Prismic Rest API V2 endpoint for the
* repository.
* @param repositoryEndpoint - Prismic Rest API V2 endpoint for the repository.
*
* @returns The Prismic repository's name.
* @throws {@link Error} Thrown if an invalid Prismic Rest API V2 endpoint is provided.
* @throws {@link Error} Thrown if an invalid Prismic Rest API V2 endpoint is
* provided.
*/

@@ -14,0 +16,0 @@ export const getRepositoryName = (repositoryEndpoint: string): string => {

@@ -1,9 +0,7 @@

// Primary library API.
import { getRepositoryEndpoint } from "./getRepositoryEndpoint";
export { getRepositoryEndpoint };
/**
* @deprecated Renamed to `getRepositoryEndpoint`.
*/
// TODO: Remove in v3.
export const getEndpoint = getRepositoryEndpoint;
//=============================================================================
// Client - Everything you need to query data from Prismic.
//=============================================================================
// Primary Client API.
export { getRepositoryEndpoint } from "./getRepositoryEndpoint";
export { getRepositoryName } from "./getRepositoryName";

@@ -17,14 +15,3 @@ export { getGraphQLEndpoint } from "./getGraphQLEndpoint";

// Predicates API.
import { predicate } from "./predicate";
export { predicate };
/**
* @deprecated Renamed to `predicate` (without an "s").
*/
// TODO: Remove in v3.
export const predicates = predicate;
/**
* @deprecated Renamed to `predicate` (lowercase and without an "s").
*/
// TODO: Remove in v3.
export const Predicates = predicate;
export { predicate } from "./predicate";

@@ -51,2 +38,231 @@ // Custom errors used by Client.

Route,
} from "./types";
} from "./types/client";
//=============================================================================
// Helpers - Everything you need to template Prismic data.
//=============================================================================
// Primary Helpers API.
export { asDate } from "./helpers/asDate";
export { asLink } from "./helpers/asLink";
export { asText } from "./helpers/asText";
export { asHTML } from "./helpers/asHTML";
export { asImageSrc } from "./helpers/asImageSrc";
export { asImageWidthSrcSet } from "./helpers/asImageWidthSrcSet";
export { asImagePixelDensitySrcSet } from "./helpers/asImagePixelDensitySrcSet";
export * as isFilled from "./helpers/isFilled";
// Conversion helper.
export { documentToLinkField } from "./helpers/documentToLinkField";
// RichText element types.
export { Element } from "@prismicio/richtext";
export type {
LinkResolverFunction,
HTMLFunctionSerializer,
HTMLMapSerializer,
} from "./types/helpers";
//=============================================================================
// Value - Types representing Prismic document and field values.
//=============================================================================
export { RichTextNodeType } from "./types/value/richText";
export { LinkType } from "./types/value/link";
export { OEmbedType } from "./types/value/embed";
export type {
PrismicDocument,
PrismicDocumentWithUID,
PrismicDocumentWithoutUID,
PrismicDocumentHeader,
AlternateLanguage,
} from "./types/value/document";
export type {
// RichText & Title
RichTextField,
// RichText & Title (block nodes)
RTTextNodeBase,
RTHeading1Node,
RTHeading2Node,
RTHeading3Node,
RTHeading4Node,
RTHeading5Node,
RTHeading6Node,
RTParagraphNode,
RTPreformattedNode,
RTListItemNode,
RTOListItemNode,
// RichText & Title (span nodes)
RTSpanNodeBase,
RTStrongNode,
RTEmNode,
RTLabelNode,
// RichText & Title (media nodes)
RTImageNode,
RTEmbedNode,
// RichText & Title (link nodes)
RTLinkNode,
// RichText & Title (serialization related nodes)
RTListNode,
RTOListNode,
RTSpanNode,
// RichText & Title (helpers)
RTNode,
RTTextNode,
RTBlockNode,
RTInlineNode,
RTAnyNode,
} from "./types/value/richText";
export type { TitleField } from "./types/value/title";
export type {
ImageField,
ImageFieldImage,
FilledImageFieldImage,
EmptyImageFieldImage,
} from "./types/value/image";
export type {
EmptyLinkField,
LinkField,
FilledLinkToWebField,
} from "./types/value/link";
export type {
ContentRelationshipField,
FilledContentRelationshipField,
} from "./types/value/contentRelationship";
export type {
LinkToMediaField,
FilledLinkToMediaField,
} from "./types/value/linkToMedia";
export type {
OEmbedExtra,
PhotoOEmbed,
VideoOEmbed,
LinkOEmbed,
RichOEmbed,
AnyOEmbed,
EmbedField,
} from "./types/value/embed";
export type { BooleanField } from "./types/value/boolean";
export type { ColorField } from "./types/value/color";
export type { DateField } from "./types/value/date";
export type { KeyTextField } from "./types/value/keyText";
export type { NumberField } from "./types/value/number";
export type { SelectField } from "./types/value/select";
export type { TimestampField } from "./types/value/timestamp";
export type { GeoPointField } from "./types/value/geoPoint";
export type { IntegrationFields } from "./types/value/integrationFields";
export type { GroupField } from "./types/value/group";
export type { SliceZone } from "./types/value/sliceZone";
export type { Slice } from "./types/value/slice";
export type { SharedSlice } from "./types/value/sharedSlice";
export type { SharedSliceVariation } from "./types/value/sharedSliceVariation";
export type { FieldState, AnyRegularField } from "./types/value/types";
//=============================================================================
// Model - Types representing Prismic Custom Type and Shared Slice models.
//=============================================================================
export { CustomTypeModelFieldType } from "./types/model/types";
export { CustomTypeModelLinkSelectType } from "./types/model/link";
export { CustomTypeModelSliceType } from "./types/model/sliceZone";
export { CustomTypeModelSliceDisplay } from "./types/model/slice";
export type {
CustomTypeModel,
CustomTypeModelDefinition,
CustomTypeModelTab,
} from "./types/model/customType";
export type {
CustomTypeModelRichTextField,
CustomTypeModelRichTextMultiField,
CustomTypeModelRichTextSingleField,
} from "./types/model/richText";
export type { CustomTypeModelTitleField } from "./types/model/title";
export type {
CustomTypeModelImageField,
CustomTypeModelImageConstraint,
CustomTypeModelImageThumbnail,
} from "./types/model/image";
export type { CustomTypeModelContentRelationshipField } from "./types/model/contentRelationship";
export type { CustomTypeModelLinkField } from "./types/model/link";
export type { CustomTypeModelLinkToMediaField } from "./types/model/linkToMedia";
export type { CustomTypeModelEmbedField } from "./types/model/embed";
export type { CustomTypeModelBooleanField } from "./types/model/boolean";
export type { CustomTypeModelColorField } from "./types/model/color";
export type { CustomTypeModelDateField } from "./types/model/date";
export type { CustomTypeModelKeyTextField } from "./types/model/keyText";
export type { CustomTypeModelNumberField } from "./types/model/number";
export type { CustomTypeModelSelectField } from "./types/model/select";
export type { CustomTypeModelTimestampField } from "./types/model/timestamp";
export type { CustomTypeModelGeoPointField } from "./types/model/geoPoint";
export type { CustomTypeModelIntegrationFieldsField } from "./types/model/integrationFields";
export type { CustomTypeModelGroupField } from "./types/model/group";
export type {
CustomTypeModelSliceZoneField,
CustomTypeModelSliceLabel,
CustomTypeModelSharedSlice,
} from "./types/model/sliceZone";
export type {
CustomTypeModelSlice,
CustomTypeModelLegacySlice,
} from "./types/model/slice";
export type { SharedSliceModel } from "./types/model/sharedSlice";
export type { SharedSliceModelVariation } from "./types/model/sharedSliceVariation";
export type { CustomTypeModelUIDField } from "./types/model/uid";
export type { CustomTypeModelRangeField } from "./types/model/range";
export type { CustomTypeModelSeparatorField } from "./types/model/separator";
export type {
CustomTypeModelField,
CustomTypeModelFieldForGroup,
} from "./types/model/types";
//=============================================================================
// API - Types representing Prismic Rest API V2 responses.
//=============================================================================
export type { Query } from "./types/api/query";
export type { Ref } from "./types/api/ref";
export type { Release } from "./types/api/release";
export type {
Repository,
Language,
Form,
FormField,
} from "./types/api/repository";
export type { Tags } from "./types/api/tags";
//=============================================================================
// Webhook - Types representing Prismic webhooks.
//=============================================================================
export { WebhookType } from "./types/webhook/types";
export type { WebhookBody } from "./types/webhook/types";
export type { WebhookBodyAPIUpdate } from "./types/webhook/apiUpdate";
export type { WebhookBodyTestTrigger } from "./types/webhook/testTrigger";

@@ -7,3 +7,4 @@ /**

*
* @returns `true` if `input` is a valid Prismic Rest API V2 endpoint, `false` otherwise.
* @returns `true` if `input` is a valid Prismic Rest API V2 endpoint, `false`
* otherwise.
*/

@@ -10,0 +11,0 @@ export const isRepositoryEndpoint = (input: string): boolean => {

@@ -6,3 +6,4 @@ /**

*
* @returns `true` if `input` is a valid Prismic repository name, `false` otherwise.
* @returns `true` if `input` is a valid Prismic repository name, `false`
* otherwise.
*/

@@ -9,0 +10,0 @@ export const isRepositoryName = (input: string): boolean => {

@@ -12,3 +12,4 @@ import { castArray } from "./castArray";

* @typeParam T - Object to which predicates will be append.
* @param objWithPredicates - Object to append predicates on the `predicates` property.
* @param objWithPredicates - Object to append predicates on the `predicates`
* property.
* @param predicates - One or more predicates to append.

@@ -15,0 +16,0 @@ *

@@ -1,2 +0,2 @@

import * as prismicT from "@prismicio/types";
import { Ref } from "../types/api/ref";

@@ -13,4 +13,4 @@ import { findRef } from "./findRef";

*/
export const findMasterRef = (refs: prismicT.Ref[]): prismicT.Ref => {
export const findMasterRef = (refs: Ref[]): Ref => {
return findRef(refs, (ref) => ref.isMasterRef);
};

@@ -1,2 +0,2 @@

import * as prismicT from "@prismicio/types";
import { Ref } from "../types/api/ref";

@@ -16,6 +16,3 @@ import { PrismicError } from "../PrismicError";

*/
export const findRef = (
refs: prismicT.Ref[],
predicate: (ref: prismicT.Ref) => boolean,
): prismicT.Ref => {
export const findRef = (refs: Ref[], predicate: (ref: Ref) => boolean): Ref => {
const ref = refs.find((ref) => predicate(ref));

@@ -22,0 +19,0 @@

@@ -1,2 +0,2 @@

import * as prismicT from "@prismicio/types";
import { Ref } from "../types/api/ref";

@@ -14,4 +14,4 @@ import { findRef } from "./findRef";

*/
export const findRefByID = (refs: prismicT.Ref[], id: string): prismicT.Ref => {
export const findRefByID = (refs: Ref[], id: string): Ref => {
return findRef(refs, (ref) => ref.id === id);
};

@@ -1,2 +0,2 @@

import * as prismicT from "@prismicio/types";
import { Ref } from "../types/api/ref";

@@ -14,7 +14,4 @@ import { findRef } from "./findRef";

*/
export const findRefByLabel = (
refs: prismicT.Ref[],
label: string,
): prismicT.Ref => {
export const findRefByLabel = (refs: Ref[], label: string): Ref => {
return findRef(refs, (ref) => ref.label === label);
};

@@ -10,3 +10,4 @@ import { preview as previewCookieName } from "../cookie";

*
* @param cookieJar - The stringified cookie store from which to read the cookie.
* @param cookieJar - The stringified cookie store from which to read the
* cookie.
*

@@ -26,3 +27,3 @@ * @returns The value of the cookie, if it exists.

value = readValue(parts.slice(1).join("="));
continue;
break;
}

@@ -29,0 +30,0 @@ }

@@ -33,3 +33,4 @@ /**

/**
* Creates a predicate builder function for predicates with a path and arguments.
* Creates a predicate builder function for predicates with a path and
* arguments.
*

@@ -76,3 +77,4 @@ * @typeParam Args - Arguments for the predicate.

/**
* Creates a predicate builder function for predicates with only arguments and no path.
* Creates a predicate builder function for predicates with only arguments and
* no path.
*

@@ -79,0 +81,0 @@ * @param name - Name of the predicate used in the resulting string.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc