@flexacms/client 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,8 +10,8 @@ npm install @flexacms/client
10
10
  import { createClient, localize } from '@flexacms/client';
11
11
 
12
12
  const flexa = createClient({
13
- url: process.env.FLEXA_URL!, // https://cms.example.com
14
13
  apiKey: process.env.FLEXA_API_KEY!,
14
+ // url: 'https://staging.example.com', // optional, defaults to https://flexacms.com
15
15
  });
16
16
 
17
17
  const { data: posts, meta } = await flexa
package/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ DEFAULT_URL: () => DEFAULT_URL,
23
24
  EntityClient: () => EntityClient,
24
25
  FlexaClient: () => FlexaClient,
25
26
  FlexaError: () => FlexaError,
@@ -63,6 +64,7 @@ function isFlexaError(error) {
63
64
  }
64
65
 
65
66
  // src/client.ts
67
+ var DEFAULT_URL = "https://flexacms.com";
66
68
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
67
69
  function sleep(milliseconds) {
68
70
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
@@ -71,14 +73,12 @@ var FlexaClient = class {
71
73
  baseUrl;
72
74
  options;
73
75
  constructor(options) {
74
- if (!options.url) {
75
- throw new TypeError('Flexa: the "url" option is required.');
76
- }
77
76
  if (!options.apiKey) {
78
77
  throw new TypeError('Flexa: the "apiKey" option is required.');
79
78
  }
79
+ const url = options.url || DEFAULT_URL;
80
80
  const apiPath = `/${(options.apiPath ?? "/api/v1").replace(/^\/+|\/+$/g, "")}`;
81
- this.baseUrl = `${options.url.replace(/\/+$/, "")}${apiPath}`;
81
+ this.baseUrl = `${url.replace(/\/+$/, "")}${apiPath}`;
82
82
  this.options = { timeout: 3e4, retries: 2, ...options };
83
83
  }
84
84
  /** Entities (content models) the API key can read. */
@@ -341,6 +341,7 @@ function localize(value, locale, fallbacks = []) {
341
341
  }
342
342
  // Annotate the CommonJS export names for ESM import in node:
343
343
  0 && (module.exports = {
344
+ DEFAULT_URL,
344
345
  EntityClient,
345
346
  FlexaClient,
346
347
  FlexaError,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/client.ts","../src/localize.ts"],"sourcesContent":["export { createClient, EntityClient, FlexaClient } from './client';\nexport type { FlexaClientOptions } from './client';\nexport { FlexaError, isFlexaError } from './errors';\nexport { isLocalized, localize } from './localize';\nexport type * from './types';\n","/**\n * Error thrown for every non-2xx response from the content API.\n */\nexport class FlexaError extends Error {\n override readonly name = 'FlexaError';\n\n constructor(\n message: string,\n /** HTTP status, or 0 when the request never reached the server. */\n readonly status: number,\n /** Validation errors keyed by field (422 responses). */\n readonly errors: Record<string, string[]> = {},\n /** Parsed response body, when there was one. */\n readonly body: unknown = null,\n ) {\n super(message);\n }\n\n get isNotFound(): boolean {\n return this.status === 404;\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401;\n }\n\n get isForbidden(): boolean {\n return this.status === 403;\n }\n\n get isValidationError(): boolean {\n return this.status === 422;\n }\n\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\nexport function isFlexaError(error: unknown): error is FlexaError {\n return error instanceof FlexaError;\n}\n","import { FlexaError } from './errors';\nimport type {\n ContentSchema,\n EntitySchema,\n EntitySummary,\n Entry,\n EntryInput,\n EntryValues,\n GetParams,\n ListParams,\n Paginated,\n RequestOptions,\n} from './types';\n\nexport interface FlexaClientOptions {\n /** Base URL of your Flexa installation, e.g. `https://cms.example.com`. */\n url: string;\n /**\n * Workspace API key. Keep it on the server: anyone with the key can do what\n * its abilities allow. Use a Read-only key for public websites.\n */\n apiKey: string;\n /** Path of the content API. Defaults to `/api/v1`. */\n apiPath?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof fetch;\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /** Abort requests that take longer than this, in milliseconds. Defaults to 30s. */\n timeout?: number;\n /**\n * How many times to retry reads after a rate limit (429), a gateway error\n * (502/503/504) or a network failure. Writes are never retried. Defaults to 2.\n */\n retries?: number;\n}\n\ntype ValuesOf<\n TSchema extends object,\n TEntity extends string,\n> = TEntity extends keyof TSchema\n ? TSchema[TEntity] extends object\n ? TSchema[TEntity]\n : EntryValues\n : EntryValues;\n\n/** The part of the client entity helpers need: sending requests. */\ntype RequestSender = Pick<FlexaClient, 'request'>;\n\nconst RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\n/**\n * Content API client for one Flexa workspace (the workspace is set by the API key).\n */\nexport class FlexaClient<TSchema extends object = ContentSchema> {\n readonly baseUrl: string;\n\n private readonly options: Required<\n Pick<FlexaClientOptions, 'timeout' | 'retries'>\n > &\n FlexaClientOptions;\n\n constructor(options: FlexaClientOptions) {\n if (!options.url) {\n throw new TypeError('Flexa: the \"url\" option is required.');\n }\n\n if (!options.apiKey) {\n throw new TypeError('Flexa: the \"apiKey\" option is required.');\n }\n\n const apiPath = `/${(options.apiPath ?? '/api/v1').replace(/^\\/+|\\/+$/g, '')}`;\n\n this.baseUrl = `${options.url.replace(/\\/+$/, '')}${apiPath}`;\n this.options = { timeout: 30_000, retries: 2, ...options };\n }\n\n /** Entities (content models) the API key can read. */\n async entities(options?: RequestOptions): Promise<EntitySummary[]> {\n const response = await this.request<{ data: EntitySummary[] }>(\n 'GET',\n '/entities',\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Typed access to the entries of one entity. */\n entity<TEntity extends Extract<keyof TSchema, string> | (string & {})>(\n slug: TEntity,\n ): EntityClient<ValuesOf<TSchema, TEntity>> {\n return new EntityClient(this, slug);\n }\n\n /**\n * Send a request to the content API. Exposed for endpoints the typed helpers\n * do not cover yet; `path` is relative to the API base (e.g. `/posts`).\n */\n async request<T>(\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n ): Promise<T> {\n const fetchImplementation = this.options.fetch ?? globalThis.fetch;\n\n if (typeof fetchImplementation !== 'function') {\n throw new TypeError(\n 'Flexa: no fetch implementation available. Pass one with the \"fetch\" option.',\n );\n }\n\n const attempts = method === 'GET' ? this.options.retries + 1 : 1;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const signals = [\n AbortSignal.timeout(this.options.timeout),\n options.signal,\n ].filter((signal): signal is AbortSignal => signal !== undefined);\n\n let response: Response;\n\n try {\n response = await fetchImplementation(`${this.baseUrl}${path}`, {\n ...options.init,\n method,\n signal:\n signals.length > 1\n ? AbortSignal.any(signals)\n : signals[0],\n headers: {\n Accept: 'application/json',\n ...(body === undefined\n ? {}\n : { 'Content-Type': 'application/json' }),\n ...this.options.headers,\n ...(options.init?.headers as\n | Record<string, string>\n | undefined),\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (error) {\n if (options.signal?.aborted || attempt === attempts) {\n throw new FlexaError(\n error instanceof Error\n ? `Flexa request failed: ${error.message}`\n : 'Flexa request failed.',\n 0,\n );\n }\n\n lastError = error;\n await sleep(this.backoff(attempt));\n continue;\n }\n\n if (response.ok) {\n return (\n response.status === 204 ? undefined : await response.json()\n ) as T;\n }\n\n if (attempt < attempts && RETRYABLE_STATUSES.has(response.status)) {\n await sleep(\n this.backoff(attempt, response.headers.get('Retry-After')),\n );\n continue;\n }\n\n throw await this.toError(response);\n }\n\n throw lastError;\n }\n\n private backoff(attempt: number, retryAfter?: string | null): number {\n const seconds = Number(retryAfter);\n\n if (retryAfter && Number.isFinite(seconds)) {\n return Math.min(seconds * 1000, 30_000);\n }\n\n return 250 * 2 ** (attempt - 1);\n }\n\n private async toError(response: Response): Promise<FlexaError> {\n let body: unknown = null;\n\n try {\n body = await response.json();\n } catch {\n // Not a JSON body.\n }\n\n const payload = (body ?? {}) as { message?: unknown; errors?: unknown };\n const message =\n typeof payload.message === 'string' && payload.message !== ''\n ? payload.message\n : `Flexa request failed with status ${response.status}.`;\n\n return new FlexaError(\n message,\n response.status,\n (payload.errors && typeof payload.errors === 'object'\n ? payload.errors\n : {}) as Record<string, string[]>,\n body,\n );\n }\n}\n\n/**\n * Entries of one entity: list, read, create, update, delete and restore.\n */\nexport class EntityClient<TValues extends object = EntryValues> {\n constructor(\n private readonly client: RequestSender,\n readonly slug: string,\n ) {}\n\n private get path(): string {\n return `/${encodeURIComponent(this.slug)}`;\n }\n\n /** Fields, groups, categories and locales of the entity. */\n async schema(options?: RequestOptions): Promise<EntitySchema> {\n const response = await this.client.request<{ data: EntitySchema }>(\n 'GET',\n `${this.path}/schema`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** One page of entries. */\n list(\n params: ListParams = {},\n options?: RequestOptions,\n ): Promise<Paginated<Entry<TValues>>> {\n const query = new URLSearchParams();\n\n for (const [key, value] of Object.entries({\n status: params.status,\n search: params.search,\n category: params.category,\n page: params.page,\n per_page: params.perPage,\n trashed: params.trashed,\n include: params.includeRelations ? 'relations' : undefined,\n })) {\n if (value !== undefined && value !== null && value !== '') {\n query.set(key, String(value));\n }\n }\n\n const search = query.toString();\n\n return this.client.request(\n 'GET',\n `${this.path}${search ? `?${search}` : ''}`,\n undefined,\n options,\n );\n }\n\n /** Iterate over every matching entry, fetching pages as needed. */\n async *iterate(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): AsyncGenerator<Entry<TValues>> {\n let page = 1;\n let lastPage = 1;\n\n do {\n const result = await this.list(\n { perPage: 100, ...params, page },\n options,\n );\n\n yield* result.data;\n lastPage = result.meta.last_page;\n page++;\n } while (page <= lastPage);\n }\n\n /** Every matching entry, across all pages. */\n async all(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>[]> {\n const entries: Entry<TValues>[] = [];\n\n for await (const entry of this.iterate(params, options)) {\n entries.push(entry);\n }\n\n return entries;\n }\n\n /** An entry by id or slug. Throws a 404 `FlexaError` when it does not exist. */\n async get(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const query = params.includeRelations ? '?include=relations' : '';\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'GET',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${query}`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Like `get()`, but resolves to `null` when the entry does not exist. */\n async find(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues> | null> {\n try {\n return await this.get(idOrSlug, params, options);\n } catch (error) {\n if (error instanceof FlexaError && error.isNotFound) {\n return null;\n }\n\n throw error;\n }\n }\n\n /** Create an entry. Needs the Write ability. */\n async create(\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n this.path,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Partially update an entry. Needs the Write ability. */\n async update(\n idOrSlug: number | string,\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'PATCH',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}`,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Move an entry to the trash, or delete it for good with `force`. Needs the Delete ability. */\n async delete(\n idOrSlug: number | string,\n params: { force?: boolean } = {},\n options?: RequestOptions,\n ): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${params.force ? '?force=1' : ''}`,\n undefined,\n options,\n );\n }\n\n /** Restore a trashed entry. Needs the Write ability. */\n async restore(\n idOrSlug: number | string,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}/restore`,\n undefined,\n options,\n );\n\n return response.data;\n }\n}\n\nexport function createClient<TSchema extends object = ContentSchema>(\n options: FlexaClientOptions,\n): FlexaClient<TSchema> {\n return new FlexaClient<TSchema>(options);\n}\n","import type { Localized } from './types';\n\n/**\n * Whether a field value is a translatable value ({ \"en\": \"...\", \"es\": \"...\" }).\n */\nexport function isLocalized(\n value: unknown,\n locales?: readonly string[],\n): value is Localized<unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n\n const keys = Object.keys(value);\n\n if (keys.length === 0) {\n return false;\n }\n\n return locales\n ? keys.every((key) => locales.includes(key))\n : keys.every((key) => /^[a-z]{2,3}([_-][A-Za-z]{2,4})?$/.test(key));\n}\n\n/**\n * Pick one locale of a translatable value, falling back to the given locales\n * (and then to the first non-empty translation). Plain values pass through.\n */\nexport function localize<T>(\n value: Localized<T> | T | null | undefined,\n locale: string,\n fallbacks: readonly string[] = [],\n): T | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (!isLocalized(value)) {\n return value as T;\n }\n\n const translations = value as Localized<T>;\n\n for (const candidate of [locale, ...fallbacks]) {\n const translation = translations[candidate];\n\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n for (const translation of Object.values(translations)) {\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAGlC,YACI,SAES,QAEA,SAAmC,CAAC,GAEpC,OAAgB,MAC3B;AACE,UAAM,OAAO;AANJ;AAEA;AAEA;AAAA,EAGb;AAAA,EAPa;AAAA,EAEA;AAAA,EAE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mB,OAAO,QAAQ,CAAC,CAAC;AAAA,MACpD;AAAA,MACA;AAAA,IACJ;AAEA,WAAO,SAAS;AAAA,EACpB;AACJ;AAEO,SAAS,aACZ,SACoB;AACpB,SAAO,IAAI,YAAqB,OAAO;AAC3C;;;ACpZO,SAAS,YACZ,OACA,SAC2B;AAC3B,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;AACrE,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,OAAO,KAAK,KAAK;AAE9B,MAAI,KAAK,WAAW,GAAG;AACnB,WAAO;AAAA,EACX;AAEA,SAAO,UACD,KAAK,MAAM,CAAC,QAAQ,QAAQ,SAAS,GAAG,CAAC,IACzC,KAAK,MAAM,CAAC,QAAQ,mCAAmC,KAAK,GAAG,CAAC;AAC1E;AAMO,SAAS,SACZ,OACA,QACA,YAA+B,CAAC,GACxB;AACR,MAAI,UAAU,QAAQ,UAAU,QAAW;AACvC,WAAO;AAAA,EACX;AAEA,MAAI,CAAC,YAAY,KAAK,GAAG;AACrB,WAAO;AAAA,EACX;AAEA,QAAM,eAAe;AAErB,aAAW,aAAa,CAAC,QAAQ,GAAG,SAAS,GAAG;AAC5C,UAAM,cAAc,aAAa,SAAS;AAE1C,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,aAAW,eAAe,OAAO,OAAO,YAAY,GAAG;AACnD,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,SAAO;AACX;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/client.ts","../src/localize.ts"],"sourcesContent":["export { createClient, DEFAULT_URL, EntityClient, FlexaClient } from './client';\nexport type { FlexaClientOptions } from './client';\nexport { FlexaError, isFlexaError } from './errors';\nexport { isLocalized, localize } from './localize';\nexport type * from './types';\n","/**\n * Error thrown for every non-2xx response from the content API.\n */\nexport class FlexaError extends Error {\n override readonly name = 'FlexaError';\n\n constructor(\n message: string,\n /** HTTP status, or 0 when the request never reached the server. */\n readonly status: number,\n /** Validation errors keyed by field (422 responses). */\n readonly errors: Record<string, string[]> = {},\n /** Parsed response body, when there was one. */\n readonly body: unknown = null,\n ) {\n super(message);\n }\n\n get isNotFound(): boolean {\n return this.status === 404;\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401;\n }\n\n get isForbidden(): boolean {\n return this.status === 403;\n }\n\n get isValidationError(): boolean {\n return this.status === 422;\n }\n\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\nexport function isFlexaError(error: unknown): error is FlexaError {\n return error instanceof FlexaError;\n}\n","import { FlexaError } from './errors';\nimport type {\n ContentSchema,\n EntitySchema,\n EntitySummary,\n Entry,\n EntryInput,\n EntryValues,\n GetParams,\n ListParams,\n Paginated,\n RequestOptions,\n} from './types';\n\nexport const DEFAULT_URL = 'https://flexacms.com';\n\nexport interface FlexaClientOptions {\n /** Base URL of your Flexa installation. Defaults to `https://flexacms.com`. */\n url?: string;\n /**\n * Workspace API key. Keep it on the server: anyone with the key can do what\n * its abilities allow. Use a Read-only key for public websites.\n */\n apiKey: string;\n /** Path of the content API. Defaults to `/api/v1`. */\n apiPath?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof fetch;\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /** Abort requests that take longer than this, in milliseconds. Defaults to 30s. */\n timeout?: number;\n /**\n * How many times to retry reads after a rate limit (429), a gateway error\n * (502/503/504) or a network failure. Writes are never retried. Defaults to 2.\n */\n retries?: number;\n}\n\ntype ValuesOf<\n TSchema extends object,\n TEntity extends string,\n> = TEntity extends keyof TSchema\n ? TSchema[TEntity] extends object\n ? TSchema[TEntity]\n : EntryValues\n : EntryValues;\n\n/** The part of the client entity helpers need: sending requests. */\ntype RequestSender = Pick<FlexaClient, 'request'>;\n\nconst RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\n/**\n * Content API client for one Flexa workspace (the workspace is set by the API key).\n */\nexport class FlexaClient<TSchema extends object = ContentSchema> {\n readonly baseUrl: string;\n\n private readonly options: Required<\n Pick<FlexaClientOptions, 'timeout' | 'retries'>\n > &\n FlexaClientOptions;\n\n constructor(options: FlexaClientOptions) {\n if (!options.apiKey) {\n throw new TypeError('Flexa: the \"apiKey\" option is required.');\n }\n\n const url = options.url || DEFAULT_URL;\n const apiPath = `/${(options.apiPath ?? '/api/v1').replace(/^\\/+|\\/+$/g, '')}`;\n\n this.baseUrl = `${url.replace(/\\/+$/, '')}${apiPath}`;\n this.options = { timeout: 30_000, retries: 2, ...options };\n }\n\n /** Entities (content models) the API key can read. */\n async entities(options?: RequestOptions): Promise<EntitySummary[]> {\n const response = await this.request<{ data: EntitySummary[] }>(\n 'GET',\n '/entities',\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Typed access to the entries of one entity. */\n entity<TEntity extends Extract<keyof TSchema, string> | (string & {})>(\n slug: TEntity,\n ): EntityClient<ValuesOf<TSchema, TEntity>> {\n return new EntityClient(this, slug);\n }\n\n /**\n * Send a request to the content API. Exposed for endpoints the typed helpers\n * do not cover yet; `path` is relative to the API base (e.g. `/posts`).\n */\n async request<T>(\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n ): Promise<T> {\n const fetchImplementation = this.options.fetch ?? globalThis.fetch;\n\n if (typeof fetchImplementation !== 'function') {\n throw new TypeError(\n 'Flexa: no fetch implementation available. Pass one with the \"fetch\" option.',\n );\n }\n\n const attempts = method === 'GET' ? this.options.retries + 1 : 1;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const signals = [\n AbortSignal.timeout(this.options.timeout),\n options.signal,\n ].filter((signal): signal is AbortSignal => signal !== undefined);\n\n let response: Response;\n\n try {\n response = await fetchImplementation(`${this.baseUrl}${path}`, {\n ...options.init,\n method,\n signal:\n signals.length > 1\n ? AbortSignal.any(signals)\n : signals[0],\n headers: {\n Accept: 'application/json',\n ...(body === undefined\n ? {}\n : { 'Content-Type': 'application/json' }),\n ...this.options.headers,\n ...(options.init?.headers as\n | Record<string, string>\n | undefined),\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (error) {\n if (options.signal?.aborted || attempt === attempts) {\n throw new FlexaError(\n error instanceof Error\n ? `Flexa request failed: ${error.message}`\n : 'Flexa request failed.',\n 0,\n );\n }\n\n lastError = error;\n await sleep(this.backoff(attempt));\n continue;\n }\n\n if (response.ok) {\n return (\n response.status === 204 ? undefined : await response.json()\n ) as T;\n }\n\n if (attempt < attempts && RETRYABLE_STATUSES.has(response.status)) {\n await sleep(\n this.backoff(attempt, response.headers.get('Retry-After')),\n );\n continue;\n }\n\n throw await this.toError(response);\n }\n\n throw lastError;\n }\n\n private backoff(attempt: number, retryAfter?: string | null): number {\n const seconds = Number(retryAfter);\n\n if (retryAfter && Number.isFinite(seconds)) {\n return Math.min(seconds * 1000, 30_000);\n }\n\n return 250 * 2 ** (attempt - 1);\n }\n\n private async toError(response: Response): Promise<FlexaError> {\n let body: unknown = null;\n\n try {\n body = await response.json();\n } catch {\n // Not a JSON body.\n }\n\n const payload = (body ?? {}) as { message?: unknown; errors?: unknown };\n const message =\n typeof payload.message === 'string' && payload.message !== ''\n ? payload.message\n : `Flexa request failed with status ${response.status}.`;\n\n return new FlexaError(\n message,\n response.status,\n (payload.errors && typeof payload.errors === 'object'\n ? payload.errors\n : {}) as Record<string, string[]>,\n body,\n );\n }\n}\n\n/**\n * Entries of one entity: list, read, create, update, delete and restore.\n */\nexport class EntityClient<TValues extends object = EntryValues> {\n constructor(\n private readonly client: RequestSender,\n readonly slug: string,\n ) {}\n\n private get path(): string {\n return `/${encodeURIComponent(this.slug)}`;\n }\n\n /** Fields, groups, categories and locales of the entity. */\n async schema(options?: RequestOptions): Promise<EntitySchema> {\n const response = await this.client.request<{ data: EntitySchema }>(\n 'GET',\n `${this.path}/schema`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** One page of entries. */\n list(\n params: ListParams = {},\n options?: RequestOptions,\n ): Promise<Paginated<Entry<TValues>>> {\n const query = new URLSearchParams();\n\n for (const [key, value] of Object.entries({\n status: params.status,\n search: params.search,\n category: params.category,\n page: params.page,\n per_page: params.perPage,\n trashed: params.trashed,\n include: params.includeRelations ? 'relations' : undefined,\n })) {\n if (value !== undefined && value !== null && value !== '') {\n query.set(key, String(value));\n }\n }\n\n const search = query.toString();\n\n return this.client.request(\n 'GET',\n `${this.path}${search ? `?${search}` : ''}`,\n undefined,\n options,\n );\n }\n\n /** Iterate over every matching entry, fetching pages as needed. */\n async *iterate(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): AsyncGenerator<Entry<TValues>> {\n let page = 1;\n let lastPage = 1;\n\n do {\n const result = await this.list(\n { perPage: 100, ...params, page },\n options,\n );\n\n yield* result.data;\n lastPage = result.meta.last_page;\n page++;\n } while (page <= lastPage);\n }\n\n /** Every matching entry, across all pages. */\n async all(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>[]> {\n const entries: Entry<TValues>[] = [];\n\n for await (const entry of this.iterate(params, options)) {\n entries.push(entry);\n }\n\n return entries;\n }\n\n /** An entry by id or slug. Throws a 404 `FlexaError` when it does not exist. */\n async get(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const query = params.includeRelations ? '?include=relations' : '';\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'GET',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${query}`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Like `get()`, but resolves to `null` when the entry does not exist. */\n async find(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues> | null> {\n try {\n return await this.get(idOrSlug, params, options);\n } catch (error) {\n if (error instanceof FlexaError && error.isNotFound) {\n return null;\n }\n\n throw error;\n }\n }\n\n /** Create an entry. Needs the Write ability. */\n async create(\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n this.path,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Partially update an entry. Needs the Write ability. */\n async update(\n idOrSlug: number | string,\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'PATCH',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}`,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Move an entry to the trash, or delete it for good with `force`. Needs the Delete ability. */\n async delete(\n idOrSlug: number | string,\n params: { force?: boolean } = {},\n options?: RequestOptions,\n ): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${params.force ? '?force=1' : ''}`,\n undefined,\n options,\n );\n }\n\n /** Restore a trashed entry. Needs the Write ability. */\n async restore(\n idOrSlug: number | string,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}/restore`,\n undefined,\n options,\n );\n\n return response.data;\n }\n}\n\nexport function createClient<TSchema extends object = ContentSchema>(\n options: FlexaClientOptions,\n): FlexaClient<TSchema> {\n return new FlexaClient<TSchema>(options);\n}\n","import type { Localized } from './types';\n\n/**\n * Whether a field value is a translatable value ({ \"en\": \"...\", \"es\": \"...\" }).\n */\nexport function isLocalized(\n value: unknown,\n locales?: readonly string[],\n): value is Localized<unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n\n const keys = Object.keys(value);\n\n if (keys.length === 0) {\n return false;\n }\n\n return locales\n ? keys.every((key) => locales.includes(key))\n : keys.every((key) => /^[a-z]{2,3}([_-][A-Za-z]{2,4})?$/.test(key));\n}\n\n/**\n * Pick one locale of a translatable value, falling back to the given locales\n * (and then to the first non-empty translation). Plain values pass through.\n */\nexport function localize<T>(\n value: Localized<T> | T | null | undefined,\n locale: string,\n fallbacks: readonly string[] = [],\n): T | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (!isLocalized(value)) {\n return value as T;\n }\n\n const translations = value as Localized<T>;\n\n for (const candidate of [locale, ...fallbacks]) {\n const translation = translations[candidate];\n\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n for (const translation of Object.values(translations)) {\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAGlC,YACI,SAES,QAEA,SAAmC,CAAC,GAEpC,OAAgB,MAC3B;AACE,UAAM,OAAO;AANJ;AAEA;AAEA;AAAA,EAGb;AAAA,EAPa;AAAA,EAEA;AAAA,EAEA;AAAA,EATK,OAAO;AAAA,EAczB,IAAI,aAAsB;AACtB,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,iBAA0B;AAC1B,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,cAAuB;AACvB,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,oBAA6B;AAC7B,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,gBAAyB;AACzB,WAAO,KAAK,WAAW;AAAA,EAC3B;AACJ;AAEO,SAAS,aAAa,OAAqC;AAC9D,SAAO,iBAAiB;AAC5B;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SAAS,GAAG,CAAC,IACzC,KAAK,MAAM,CAAC,QAAQ,mCAAmC,KAAK,GAAG,CAAC;AAC1E;AAMO,SAAS,SACZ,OACA,QACA,YAA+B,CAAC,GACxB;AACR,MAAI,UAAU,QAAQ,UAAU,QAAW;AACvC,WAAO;AAAA,EACX;AAEA,MAAI,CAAC,YAAY,KAAK,GAAG;AACrB,WAAO;AAAA,EACX;AAEA,QAAM,eAAe;AAErB,aAAW,aAAa,CAAC,QAAQ,GAAG,SAAS,GAAG;AAC5C,UAAM,cAAc,aAAa,SAAS;AAE1C,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,aAAW,eAAe,OAAO,OAAO,YAAY,GAAG;AACnD,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,SAAO;AACX;","names":[]}
package/dist/index.d.cts CHANGED
@@ -184,9 +184,10 @@ interface RequestOptions {
184
184
  init?: RequestInit & Record<string, unknown>;
185
185
  }
186
186
 
187
+ declare const DEFAULT_URL = "https://flexacms.com";
187
188
  interface FlexaClientOptions {
188
- /** Base URL of your Flexa installation, e.g. `https://cms.example.com`. */
189
- url: string;
189
+ /** Base URL of your Flexa installation. Defaults to `https://flexacms.com`. */
190
+ url?: string;
190
191
  /**
191
192
  * Workspace API key. Keep it on the server: anyone with the key can do what
192
193
  * its abilities allow. Use a Read-only key for public websites.
@@ -297,4 +298,4 @@ declare function isLocalized(value: unknown, locales?: readonly string[]): value
297
298
  */
298
299
  declare function localize<T>(value: Localized<T> | T | null | undefined, locale: string, fallbacks?: readonly string[]): T | null;
299
300
 
300
- export { type Category, type ContentSchema, EntityClient, type EntitySchema, type EntitySummary, type Entry, type EntryInput, type EntryMedia, type EntryStatus, type EntryValues, type FieldGroupSchema, type FieldSchema, type FieldType, FlexaClient, type FlexaClientOptions, FlexaError, type GetParams, type ListParams, type Localized, type Paginated, type PaginationMeta, type RelatedEntry, type RepeaterSubfield, type RequestOptions, createClient, isFlexaError, isLocalized, localize };
301
+ export { type Category, type ContentSchema, DEFAULT_URL, EntityClient, type EntitySchema, type EntitySummary, type Entry, type EntryInput, type EntryMedia, type EntryStatus, type EntryValues, type FieldGroupSchema, type FieldSchema, type FieldType, FlexaClient, type FlexaClientOptions, FlexaError, type GetParams, type ListParams, type Localized, type Paginated, type PaginationMeta, type RelatedEntry, type RepeaterSubfield, type RequestOptions, createClient, isFlexaError, isLocalized, localize };
package/dist/index.d.ts CHANGED
@@ -184,9 +184,10 @@ interface RequestOptions {
184
184
  init?: RequestInit & Record<string, unknown>;
185
185
  }
186
186
 
187
+ declare const DEFAULT_URL = "https://flexacms.com";
187
188
  interface FlexaClientOptions {
188
- /** Base URL of your Flexa installation, e.g. `https://cms.example.com`. */
189
- url: string;
189
+ /** Base URL of your Flexa installation. Defaults to `https://flexacms.com`. */
190
+ url?: string;
190
191
  /**
191
192
  * Workspace API key. Keep it on the server: anyone with the key can do what
192
193
  * its abilities allow. Use a Read-only key for public websites.
@@ -297,4 +298,4 @@ declare function isLocalized(value: unknown, locales?: readonly string[]): value
297
298
  */
298
299
  declare function localize<T>(value: Localized<T> | T | null | undefined, locale: string, fallbacks?: readonly string[]): T | null;
299
300
 
300
- export { type Category, type ContentSchema, EntityClient, type EntitySchema, type EntitySummary, type Entry, type EntryInput, type EntryMedia, type EntryStatus, type EntryValues, type FieldGroupSchema, type FieldSchema, type FieldType, FlexaClient, type FlexaClientOptions, FlexaError, type GetParams, type ListParams, type Localized, type Paginated, type PaginationMeta, type RelatedEntry, type RepeaterSubfield, type RequestOptions, createClient, isFlexaError, isLocalized, localize };
301
+ export { type Category, type ContentSchema, DEFAULT_URL, EntityClient, type EntitySchema, type EntitySummary, type Entry, type EntryInput, type EntryMedia, type EntryStatus, type EntryValues, type FieldGroupSchema, type FieldSchema, type FieldType, FlexaClient, type FlexaClientOptions, FlexaError, type GetParams, type ListParams, type Localized, type Paginated, type PaginationMeta, type RelatedEntry, type RepeaterSubfield, type RequestOptions, createClient, isFlexaError, isLocalized, localize };
package/dist/index.js CHANGED
@@ -31,6 +31,7 @@ function isFlexaError(error) {
31
31
  }
32
32
 
33
33
  // src/client.ts
34
+ var DEFAULT_URL = "https://flexacms.com";
34
35
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
35
36
  function sleep(milliseconds) {
36
37
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
@@ -39,14 +40,12 @@ var FlexaClient = class {
39
40
  baseUrl;
40
41
  options;
41
42
  constructor(options) {
42
- if (!options.url) {
43
- throw new TypeError('Flexa: the "url" option is required.');
44
- }
45
43
  if (!options.apiKey) {
46
44
  throw new TypeError('Flexa: the "apiKey" option is required.');
47
45
  }
46
+ const url = options.url || DEFAULT_URL;
48
47
  const apiPath = `/${(options.apiPath ?? "/api/v1").replace(/^\/+|\/+$/g, "")}`;
49
- this.baseUrl = `${options.url.replace(/\/+$/, "")}${apiPath}`;
48
+ this.baseUrl = `${url.replace(/\/+$/, "")}${apiPath}`;
50
49
  this.options = { timeout: 3e4, retries: 2, ...options };
51
50
  }
52
51
  /** Entities (content models) the API key can read. */
@@ -308,6 +307,7 @@ function localize(value, locale, fallbacks = []) {
308
307
  return null;
309
308
  }
310
309
  export {
310
+ DEFAULT_URL,
311
311
  EntityClient,
312
312
  FlexaClient,
313
313
  FlexaError,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/localize.ts"],"sourcesContent":["/**\n * Error thrown for every non-2xx response from the content API.\n */\nexport class FlexaError extends Error {\n override readonly name = 'FlexaError';\n\n constructor(\n message: string,\n /** HTTP status, or 0 when the request never reached the server. */\n readonly status: number,\n /** Validation errors keyed by field (422 responses). */\n readonly errors: Record<string, string[]> = {},\n /** Parsed response body, when there was one. */\n readonly body: unknown = null,\n ) {\n super(message);\n }\n\n get isNotFound(): boolean {\n return this.status === 404;\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401;\n }\n\n get isForbidden(): boolean {\n return this.status === 403;\n }\n\n get isValidationError(): boolean {\n return this.status === 422;\n }\n\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\nexport function isFlexaError(error: unknown): error is FlexaError {\n return error instanceof FlexaError;\n}\n","import { FlexaError } from './errors';\nimport type {\n ContentSchema,\n EntitySchema,\n EntitySummary,\n Entry,\n EntryInput,\n EntryValues,\n GetParams,\n ListParams,\n Paginated,\n RequestOptions,\n} from './types';\n\nexport interface FlexaClientOptions {\n /** Base URL of your Flexa installation, e.g. `https://cms.example.com`. */\n url: string;\n /**\n * Workspace API key. Keep it on the server: anyone with the key can do what\n * its abilities allow. Use a Read-only key for public websites.\n */\n apiKey: string;\n /** Path of the content API. Defaults to `/api/v1`. */\n apiPath?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof fetch;\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /** Abort requests that take longer than this, in milliseconds. Defaults to 30s. */\n timeout?: number;\n /**\n * How many times to retry reads after a rate limit (429), a gateway error\n * (502/503/504) or a network failure. Writes are never retried. Defaults to 2.\n */\n retries?: number;\n}\n\ntype ValuesOf<\n TSchema extends object,\n TEntity extends string,\n> = TEntity extends keyof TSchema\n ? TSchema[TEntity] extends object\n ? TSchema[TEntity]\n : EntryValues\n : EntryValues;\n\n/** The part of the client entity helpers need: sending requests. */\ntype RequestSender = Pick<FlexaClient, 'request'>;\n\nconst RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\n/**\n * Content API client for one Flexa workspace (the workspace is set by the API key).\n */\nexport class FlexaClient<TSchema extends object = ContentSchema> {\n readonly baseUrl: string;\n\n private readonly options: Required<\n Pick<FlexaClientOptions, 'timeout' | 'retries'>\n > &\n FlexaClientOptions;\n\n constructor(options: FlexaClientOptions) {\n if (!options.url) {\n throw new TypeError('Flexa: the \"url\" option is required.');\n }\n\n if (!options.apiKey) {\n throw new TypeError('Flexa: the \"apiKey\" option is required.');\n }\n\n const apiPath = `/${(options.apiPath ?? '/api/v1').replace(/^\\/+|\\/+$/g, '')}`;\n\n this.baseUrl = `${options.url.replace(/\\/+$/, '')}${apiPath}`;\n this.options = { timeout: 30_000, retries: 2, ...options };\n }\n\n /** Entities (content models) the API key can read. */\n async entities(options?: RequestOptions): Promise<EntitySummary[]> {\n const response = await this.request<{ data: EntitySummary[] }>(\n 'GET',\n '/entities',\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Typed access to the entries of one entity. */\n entity<TEntity extends Extract<keyof TSchema, string> | (string & {})>(\n slug: TEntity,\n ): EntityClient<ValuesOf<TSchema, TEntity>> {\n return new EntityClient(this, slug);\n }\n\n /**\n * Send a request to the content API. Exposed for endpoints the typed helpers\n * do not cover yet; `path` is relative to the API base (e.g. `/posts`).\n */\n async request<T>(\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n ): Promise<T> {\n const fetchImplementation = this.options.fetch ?? globalThis.fetch;\n\n if (typeof fetchImplementation !== 'function') {\n throw new TypeError(\n 'Flexa: no fetch implementation available. Pass one with the \"fetch\" option.',\n );\n }\n\n const attempts = method === 'GET' ? this.options.retries + 1 : 1;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const signals = [\n AbortSignal.timeout(this.options.timeout),\n options.signal,\n ].filter((signal): signal is AbortSignal => signal !== undefined);\n\n let response: Response;\n\n try {\n response = await fetchImplementation(`${this.baseUrl}${path}`, {\n ...options.init,\n method,\n signal:\n signals.length > 1\n ? AbortSignal.any(signals)\n : signals[0],\n headers: {\n Accept: 'application/json',\n ...(body === undefined\n ? {}\n : { 'Content-Type': 'application/json' }),\n ...this.options.headers,\n ...(options.init?.headers as\n | Record<string, string>\n | undefined),\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (error) {\n if (options.signal?.aborted || attempt === attempts) {\n throw new FlexaError(\n error instanceof Error\n ? `Flexa request failed: ${error.message}`\n : 'Flexa request failed.',\n 0,\n );\n }\n\n lastError = error;\n await sleep(this.backoff(attempt));\n continue;\n }\n\n if (response.ok) {\n return (\n response.status === 204 ? undefined : await response.json()\n ) as T;\n }\n\n if (attempt < attempts && RETRYABLE_STATUSES.has(response.status)) {\n await sleep(\n this.backoff(attempt, response.headers.get('Retry-After')),\n );\n continue;\n }\n\n throw await this.toError(response);\n }\n\n throw lastError;\n }\n\n private backoff(attempt: number, retryAfter?: string | null): number {\n const seconds = Number(retryAfter);\n\n if (retryAfter && Number.isFinite(seconds)) {\n return Math.min(seconds * 1000, 30_000);\n }\n\n return 250 * 2 ** (attempt - 1);\n }\n\n private async toError(response: Response): Promise<FlexaError> {\n let body: unknown = null;\n\n try {\n body = await response.json();\n } catch {\n // Not a JSON body.\n }\n\n const payload = (body ?? {}) as { message?: unknown; errors?: unknown };\n const message =\n typeof payload.message === 'string' && payload.message !== ''\n ? payload.message\n : `Flexa request failed with status ${response.status}.`;\n\n return new FlexaError(\n message,\n response.status,\n (payload.errors && typeof payload.errors === 'object'\n ? payload.errors\n : {}) as Record<string, string[]>,\n body,\n );\n }\n}\n\n/**\n * Entries of one entity: list, read, create, update, delete and restore.\n */\nexport class EntityClient<TValues extends object = EntryValues> {\n constructor(\n private readonly client: RequestSender,\n readonly slug: string,\n ) {}\n\n private get path(): string {\n return `/${encodeURIComponent(this.slug)}`;\n }\n\n /** Fields, groups, categories and locales of the entity. */\n async schema(options?: RequestOptions): Promise<EntitySchema> {\n const response = await this.client.request<{ data: EntitySchema }>(\n 'GET',\n `${this.path}/schema`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** One page of entries. */\n list(\n params: ListParams = {},\n options?: RequestOptions,\n ): Promise<Paginated<Entry<TValues>>> {\n const query = new URLSearchParams();\n\n for (const [key, value] of Object.entries({\n status: params.status,\n search: params.search,\n category: params.category,\n page: params.page,\n per_page: params.perPage,\n trashed: params.trashed,\n include: params.includeRelations ? 'relations' : undefined,\n })) {\n if (value !== undefined && value !== null && value !== '') {\n query.set(key, String(value));\n }\n }\n\n const search = query.toString();\n\n return this.client.request(\n 'GET',\n `${this.path}${search ? `?${search}` : ''}`,\n undefined,\n options,\n );\n }\n\n /** Iterate over every matching entry, fetching pages as needed. */\n async *iterate(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): AsyncGenerator<Entry<TValues>> {\n let page = 1;\n let lastPage = 1;\n\n do {\n const result = await this.list(\n { perPage: 100, ...params, page },\n options,\n );\n\n yield* result.data;\n lastPage = result.meta.last_page;\n page++;\n } while (page <= lastPage);\n }\n\n /** Every matching entry, across all pages. */\n async all(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>[]> {\n const entries: Entry<TValues>[] = [];\n\n for await (const entry of this.iterate(params, options)) {\n entries.push(entry);\n }\n\n return entries;\n }\n\n /** An entry by id or slug. Throws a 404 `FlexaError` when it does not exist. */\n async get(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const query = params.includeRelations ? '?include=relations' : '';\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'GET',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${query}`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Like `get()`, but resolves to `null` when the entry does not exist. */\n async find(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues> | null> {\n try {\n return await this.get(idOrSlug, params, options);\n } catch (error) {\n if (error instanceof FlexaError && error.isNotFound) {\n return null;\n }\n\n throw error;\n }\n }\n\n /** Create an entry. Needs the Write ability. */\n async create(\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n this.path,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Partially update an entry. Needs the Write ability. */\n async update(\n idOrSlug: number | string,\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'PATCH',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}`,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Move an entry to the trash, or delete it for good with `force`. Needs the Delete ability. */\n async delete(\n idOrSlug: number | string,\n params: { force?: boolean } = {},\n options?: RequestOptions,\n ): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${params.force ? '?force=1' : ''}`,\n undefined,\n options,\n );\n }\n\n /** Restore a trashed entry. Needs the Write ability. */\n async restore(\n idOrSlug: number | string,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}/restore`,\n undefined,\n options,\n );\n\n return response.data;\n }\n}\n\nexport function createClient<TSchema extends object = ContentSchema>(\n options: FlexaClientOptions,\n): FlexaClient<TSchema> {\n return new FlexaClient<TSchema>(options);\n}\n","import type { Localized } from './types';\n\n/**\n * Whether a field value is a translatable value ({ \"en\": \"...\", \"es\": \"...\" }).\n */\nexport function isLocalized(\n value: unknown,\n locales?: readonly string[],\n): value is Localized<unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n\n const keys = Object.keys(value);\n\n if (keys.length === 0) {\n return false;\n }\n\n return locales\n ? keys.every((key) => locales.includes(key))\n : keys.every((key) => /^[a-z]{2,3}([_-][A-Za-z]{2,4})?$/.test(key));\n}\n\n/**\n * Pick one locale of a translatable value, falling back to the given locales\n * (and then to the first non-empty translation). Plain values pass through.\n */\nexport function localize<T>(\n value: Localized<T> | T | null | undefined,\n locale: string,\n fallbacks: readonly string[] = [],\n): T | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (!isLocalized(value)) {\n return value as T;\n }\n\n const translations = value as Localized<T>;\n\n for (const candidate of [locale, ...fallbacks]) {\n const translation = translations[candidate];\n\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n for (const translation of Object.values(translations)) {\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n return null;\n}\n"],"mappings":";AAGO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAGlC,YACI,SAES,QAEA,SAAmC,CAAC,GAEpC,OAAgB,MAC3B;AACE,UAAM,OAAO;AANJ;AAEA;AAEA;AAAA,EAGb;AAAA,EAPa;AAAA,EAEA;AAAA,EAEA;AAAA,EATK,OAAO;AAAA,EAczB,IAAI,aAAsB;AACtB,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,iBAA0B;AAC1B,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,cAAuB;AACvB,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,oBAA6B;AAC7B,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,gBAAyB;AACzB,WAAO,KAAK,WAAW;AAAA,EAC3B;AACJ;AAEO,SAAS,aAAa,OAAqC;AAC9D,SAAO,iBAAiB;AAC5B;;;ACQA,IAAM,qBAAqB,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AAEvD,SAAS,MAAM,cAAqC;AAChD,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,YAAY,CAAC;AACrE;AAKO,IAAM,cAAN,MAA0D;AAAA,EACpD;AAAA,EAEQ;AAAA,EAKjB,YAAY,SAA6B;AACrC,QAAI,CAAC,QAAQ,KAAK;AACd,YAAM,IAAI,UAAU,sCAAsC;AAAA,IAC9D;AAEA,QAAI,CAAC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AS,GAAG;AAC5C,UAAM,cAAc,aAAa,SAAS;AAE1C,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,aAAW,eAAe,OAAO,OAAO,YAAY,GAAG;AACnD,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,SAAO;AACX;","names":[]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/localize.ts"],"sourcesContent":["/**\n * Error thrown for every non-2xx response from the content API.\n */\nexport class FlexaError extends Error {\n override readonly name = 'FlexaError';\n\n constructor(\n message: string,\n /** HTTP status, or 0 when the request never reached the server. */\n readonly status: number,\n /** Validation errors keyed by field (422 responses). */\n readonly errors: Record<string, string[]> = {},\n /** Parsed response body, when there was one. */\n readonly body: unknown = null,\n ) {\n super(message);\n }\n\n get isNotFound(): boolean {\n return this.status === 404;\n }\n\n get isUnauthorized(): boolean {\n return this.status === 401;\n }\n\n get isForbidden(): boolean {\n return this.status === 403;\n }\n\n get isValidationError(): boolean {\n return this.status === 422;\n }\n\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\nexport function isFlexaError(error: unknown): error is FlexaError {\n return error instanceof FlexaError;\n}\n","import { FlexaError } from './errors';\nimport type {\n ContentSchema,\n EntitySchema,\n EntitySummary,\n Entry,\n EntryInput,\n EntryValues,\n GetParams,\n ListParams,\n Paginated,\n RequestOptions,\n} from './types';\n\nexport const DEFAULT_URL = 'https://flexacms.com';\n\nexport interface FlexaClientOptions {\n /** Base URL of your Flexa installation. Defaults to `https://flexacms.com`. */\n url?: string;\n /**\n * Workspace API key. Keep it on the server: anyone with the key can do what\n * its abilities allow. Use a Read-only key for public websites.\n */\n apiKey: string;\n /** Path of the content API. Defaults to `/api/v1`. */\n apiPath?: string;\n /** Custom fetch implementation (defaults to the global `fetch`). */\n fetch?: typeof fetch;\n /** Extra headers sent with every request. */\n headers?: Record<string, string>;\n /** Abort requests that take longer than this, in milliseconds. Defaults to 30s. */\n timeout?: number;\n /**\n * How many times to retry reads after a rate limit (429), a gateway error\n * (502/503/504) or a network failure. Writes are never retried. Defaults to 2.\n */\n retries?: number;\n}\n\ntype ValuesOf<\n TSchema extends object,\n TEntity extends string,\n> = TEntity extends keyof TSchema\n ? TSchema[TEntity] extends object\n ? TSchema[TEntity]\n : EntryValues\n : EntryValues;\n\n/** The part of the client entity helpers need: sending requests. */\ntype RequestSender = Pick<FlexaClient, 'request'>;\n\nconst RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);\n\nfunction sleep(milliseconds: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\n/**\n * Content API client for one Flexa workspace (the workspace is set by the API key).\n */\nexport class FlexaClient<TSchema extends object = ContentSchema> {\n readonly baseUrl: string;\n\n private readonly options: Required<\n Pick<FlexaClientOptions, 'timeout' | 'retries'>\n > &\n FlexaClientOptions;\n\n constructor(options: FlexaClientOptions) {\n if (!options.apiKey) {\n throw new TypeError('Flexa: the \"apiKey\" option is required.');\n }\n\n const url = options.url || DEFAULT_URL;\n const apiPath = `/${(options.apiPath ?? '/api/v1').replace(/^\\/+|\\/+$/g, '')}`;\n\n this.baseUrl = `${url.replace(/\\/+$/, '')}${apiPath}`;\n this.options = { timeout: 30_000, retries: 2, ...options };\n }\n\n /** Entities (content models) the API key can read. */\n async entities(options?: RequestOptions): Promise<EntitySummary[]> {\n const response = await this.request<{ data: EntitySummary[] }>(\n 'GET',\n '/entities',\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Typed access to the entries of one entity. */\n entity<TEntity extends Extract<keyof TSchema, string> | (string & {})>(\n slug: TEntity,\n ): EntityClient<ValuesOf<TSchema, TEntity>> {\n return new EntityClient(this, slug);\n }\n\n /**\n * Send a request to the content API. Exposed for endpoints the typed helpers\n * do not cover yet; `path` is relative to the API base (e.g. `/posts`).\n */\n async request<T>(\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n ): Promise<T> {\n const fetchImplementation = this.options.fetch ?? globalThis.fetch;\n\n if (typeof fetchImplementation !== 'function') {\n throw new TypeError(\n 'Flexa: no fetch implementation available. Pass one with the \"fetch\" option.',\n );\n }\n\n const attempts = method === 'GET' ? this.options.retries + 1 : 1;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= attempts; attempt++) {\n const signals = [\n AbortSignal.timeout(this.options.timeout),\n options.signal,\n ].filter((signal): signal is AbortSignal => signal !== undefined);\n\n let response: Response;\n\n try {\n response = await fetchImplementation(`${this.baseUrl}${path}`, {\n ...options.init,\n method,\n signal:\n signals.length > 1\n ? AbortSignal.any(signals)\n : signals[0],\n headers: {\n Accept: 'application/json',\n ...(body === undefined\n ? {}\n : { 'Content-Type': 'application/json' }),\n ...this.options.headers,\n ...(options.init?.headers as\n | Record<string, string>\n | undefined),\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (error) {\n if (options.signal?.aborted || attempt === attempts) {\n throw new FlexaError(\n error instanceof Error\n ? `Flexa request failed: ${error.message}`\n : 'Flexa request failed.',\n 0,\n );\n }\n\n lastError = error;\n await sleep(this.backoff(attempt));\n continue;\n }\n\n if (response.ok) {\n return (\n response.status === 204 ? undefined : await response.json()\n ) as T;\n }\n\n if (attempt < attempts && RETRYABLE_STATUSES.has(response.status)) {\n await sleep(\n this.backoff(attempt, response.headers.get('Retry-After')),\n );\n continue;\n }\n\n throw await this.toError(response);\n }\n\n throw lastError;\n }\n\n private backoff(attempt: number, retryAfter?: string | null): number {\n const seconds = Number(retryAfter);\n\n if (retryAfter && Number.isFinite(seconds)) {\n return Math.min(seconds * 1000, 30_000);\n }\n\n return 250 * 2 ** (attempt - 1);\n }\n\n private async toError(response: Response): Promise<FlexaError> {\n let body: unknown = null;\n\n try {\n body = await response.json();\n } catch {\n // Not a JSON body.\n }\n\n const payload = (body ?? {}) as { message?: unknown; errors?: unknown };\n const message =\n typeof payload.message === 'string' && payload.message !== ''\n ? payload.message\n : `Flexa request failed with status ${response.status}.`;\n\n return new FlexaError(\n message,\n response.status,\n (payload.errors && typeof payload.errors === 'object'\n ? payload.errors\n : {}) as Record<string, string[]>,\n body,\n );\n }\n}\n\n/**\n * Entries of one entity: list, read, create, update, delete and restore.\n */\nexport class EntityClient<TValues extends object = EntryValues> {\n constructor(\n private readonly client: RequestSender,\n readonly slug: string,\n ) {}\n\n private get path(): string {\n return `/${encodeURIComponent(this.slug)}`;\n }\n\n /** Fields, groups, categories and locales of the entity. */\n async schema(options?: RequestOptions): Promise<EntitySchema> {\n const response = await this.client.request<{ data: EntitySchema }>(\n 'GET',\n `${this.path}/schema`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** One page of entries. */\n list(\n params: ListParams = {},\n options?: RequestOptions,\n ): Promise<Paginated<Entry<TValues>>> {\n const query = new URLSearchParams();\n\n for (const [key, value] of Object.entries({\n status: params.status,\n search: params.search,\n category: params.category,\n page: params.page,\n per_page: params.perPage,\n trashed: params.trashed,\n include: params.includeRelations ? 'relations' : undefined,\n })) {\n if (value !== undefined && value !== null && value !== '') {\n query.set(key, String(value));\n }\n }\n\n const search = query.toString();\n\n return this.client.request(\n 'GET',\n `${this.path}${search ? `?${search}` : ''}`,\n undefined,\n options,\n );\n }\n\n /** Iterate over every matching entry, fetching pages as needed. */\n async *iterate(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): AsyncGenerator<Entry<TValues>> {\n let page = 1;\n let lastPage = 1;\n\n do {\n const result = await this.list(\n { perPage: 100, ...params, page },\n options,\n );\n\n yield* result.data;\n lastPage = result.meta.last_page;\n page++;\n } while (page <= lastPage);\n }\n\n /** Every matching entry, across all pages. */\n async all(\n params: Omit<ListParams, 'page'> = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>[]> {\n const entries: Entry<TValues>[] = [];\n\n for await (const entry of this.iterate(params, options)) {\n entries.push(entry);\n }\n\n return entries;\n }\n\n /** An entry by id or slug. Throws a 404 `FlexaError` when it does not exist. */\n async get(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const query = params.includeRelations ? '?include=relations' : '';\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'GET',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${query}`,\n undefined,\n options,\n );\n\n return response.data;\n }\n\n /** Like `get()`, but resolves to `null` when the entry does not exist. */\n async find(\n idOrSlug: number | string,\n params: GetParams = {},\n options?: RequestOptions,\n ): Promise<Entry<TValues> | null> {\n try {\n return await this.get(idOrSlug, params, options);\n } catch (error) {\n if (error instanceof FlexaError && error.isNotFound) {\n return null;\n }\n\n throw error;\n }\n }\n\n /** Create an entry. Needs the Write ability. */\n async create(\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n this.path,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Partially update an entry. Needs the Write ability. */\n async update(\n idOrSlug: number | string,\n input: EntryInput<TValues>,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'PATCH',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}`,\n input,\n options,\n );\n\n return response.data;\n }\n\n /** Move an entry to the trash, or delete it for good with `force`. Needs the Delete ability. */\n async delete(\n idOrSlug: number | string,\n params: { force?: boolean } = {},\n options?: RequestOptions,\n ): Promise<void> {\n await this.client.request(\n 'DELETE',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}${params.force ? '?force=1' : ''}`,\n undefined,\n options,\n );\n }\n\n /** Restore a trashed entry. Needs the Write ability. */\n async restore(\n idOrSlug: number | string,\n options?: RequestOptions,\n ): Promise<Entry<TValues>> {\n const response = await this.client.request<{ data: Entry<TValues> }>(\n 'POST',\n `${this.path}/${encodeURIComponent(String(idOrSlug))}/restore`,\n undefined,\n options,\n );\n\n return response.data;\n }\n}\n\nexport function createClient<TSchema extends object = ContentSchema>(\n options: FlexaClientOptions,\n): FlexaClient<TSchema> {\n return new FlexaClient<TSchema>(options);\n}\n","import type { Localized } from './types';\n\n/**\n * Whether a field value is a translatable value ({ \"en\": \"...\", \"es\": \"...\" }).\n */\nexport function isLocalized(\n value: unknown,\n locales?: readonly string[],\n): value is Localized<unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n\n const keys = Object.keys(value);\n\n if (keys.length === 0) {\n return false;\n }\n\n return locales\n ? keys.every((key) => locales.includes(key))\n : keys.every((key) => /^[a-z]{2,3}([_-][A-Za-z]{2,4})?$/.test(key));\n}\n\n/**\n * Pick one locale of a translatable value, falling back to the given locales\n * (and then to the first non-empty translation). Plain values pass through.\n */\nexport function localize<T>(\n value: Localized<T> | T | null | undefined,\n locale: string,\n fallbacks: readonly string[] = [],\n): T | null {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (!isLocalized(value)) {\n return value as T;\n }\n\n const translations = value as Localized<T>;\n\n for (const candidate of [locale, ...fallbacks]) {\n const translation = translations[candidate];\n\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n for (const translation of Object.values(translations)) {\n if (\n translation !== null &&\n translation !== undefined &&\n translation !== ''\n ) {\n return translation;\n }\n }\n\n return null;\n}\n"],"mappings":";AAGO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAGlC,YACI,SAES,QAEA,SAAmC,CAAC,GAEpC,OAAgB,MAC3B;AACE,UAAM,OAAO;AANJ;AAEA;AAEA;AAAA,EAGb;AAAA,EAPa;AAAA,EAEA;AAAA,EAEA;AAAA,EATK,OAAO;AAAA,EAczB,IAAI,aAAsB;AACtB,WAAO,KAAK,WAAW;AAAA,EAC3B;AAAA,EAEA,IAAI,iBAA0B;AAC1B,WAAO,KAAK,WAAW;AAA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nZO,SAAS,YACZ,OACA,SAC2B;AAC3B,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;AACrE,WAAO;AAAA,EACX;AAEA,QAAM,OAAO,OAAO,KAAK,KAAK;AAE9B,MAAI,KAAK,WAAW,GAAG;AACnB,WAAO;AAAA,EACX;AAEA,SAAO,UACD,KAAK,MAAM,CAAC,QAAQ,QAAQ,SAAS,GAAG,CAAC,IACzC,KAAK,MAAM,CAAC,QAAQ,mCAAmC,KAAK,GAAG,CAAC;AAC1E;AAMO,SAAS,SACZ,OACA,QACA,YAA+B,CAAC,GACxB;AACR,MAAI,UAAU,QAAQ,UAAU,QAAW;AACvC,WAAO;AAAA,EACX;AAEA,MAAI,CAAC,YAAY,KAAK,GAAG;AACrB,WAAO;AAAA,EACX;AAEA,QAAM,eAAe;AAErB,aAAW,aAAa,CAAC,QAAQ,GAAG,SAAS,GAAG;AAC5C,UAAM,cAAc,aAAa,SAAS;AAE1C,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,aAAW,eAAe,OAAO,OAAO,YAAY,GAAG;AACnD,QACI,gBAAgB,QAChB,gBAAgB,UAChB,gBAAgB,IAClB;AACE,aAAO;AAAA,IACX;AAAA,EACJ;AAEA,SAAO;AACX;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flexacms/client",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Typed, dependency-free client for the Flexa headless CMS content API.",
5
5
  "keywords": [
6
6
  "api-client",