@unchainedshop/cockpit-api 2.3.1 → 2.4.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/dist/client.d.ts CHANGED
@@ -3,11 +3,11 @@
3
3
  */
4
4
  import type { DocumentNode } from "graphql";
5
5
  import { type CockpitAPIOptions } from "./core/config.ts";
6
- import { type ContentItemQueryOptions, type ContentListQueryOptions, type TreeQueryOptions, type AggregateQueryOptions, type CockpitContentItem, type CockpitTreeNode, type CockpitListResponse } from "./methods/content.ts";
6
+ import { type ContentItemQueryOptions, type ContentListQueryOptions, type UnchainedContentListQueryOptions, type TreeQueryOptions, type AggregateQueryOptions, type CockpitContentItem, type CockpitTreeNode, type CockpitListResponse } from "./methods/content.ts";
7
7
  import { type PageByIdOptions, type CockpitPage } from "./methods/pages.ts";
8
8
  import { type MenuQueryOptions, type CockpitMenu } from "./methods/menus.ts";
9
9
  import { type CockpitRoutesResponse, type CockpitSitemapEntry, type CockpitSettings } from "./methods/routes.ts";
10
- import { type ImageAssetQueryParams, type CockpitAsset } from "./methods/assets.ts";
10
+ import { type ImageAssetQueryParams, type CockpitAsset, type UploadAssetsOptions, type UploadAssetsResponse } from "./methods/assets.ts";
11
11
  import { type SearchQueryOptions, type CockpitSearchResult } from "./methods/search.ts";
12
12
  import { type LocalizeOptions } from "./methods/localize.ts";
13
13
  /**
@@ -17,6 +17,12 @@ export interface CockpitAPIClient {
17
17
  graphQL<T = unknown>(document: DocumentNode, variables?: Record<string, unknown>): Promise<T | null>;
18
18
  getContentItem<T = unknown>(options: ContentItemQueryOptions): Promise<T | null>;
19
19
  getContentItems<T = CockpitContentItem>(model: string, options?: ContentListQueryOptions): Promise<CockpitListResponse<T> | null>;
20
+ /**
21
+ * Get content items including unpublished via Unchained module.
22
+ *
23
+ * Requires admin access with content/{model}/read permission.
24
+ */
25
+ getUnchainedContentItems<T = CockpitContentItem>(model: string, options?: UnchainedContentListQueryOptions): Promise<CockpitListResponse<T> | null>;
20
26
  getContentTree<T = CockpitContentItem>(model: string, options?: TreeQueryOptions): Promise<CockpitTreeNode<T>[] | null>;
21
27
  getAggregateModel<T = unknown>(options: AggregateQueryOptions): Promise<T[] | null>;
22
28
  postContentItem<T = unknown>(model: string, item: Record<string, unknown>): Promise<T | null>;
@@ -47,6 +53,12 @@ export interface CockpitAPIClient {
47
53
  * @returns URL string to the generated image, or null if not found
48
54
  */
49
55
  imageAssetById(assetId: string, queryParams: ImageAssetQueryParams): Promise<string | null>;
56
+ /**
57
+ * Upload assets to Cockpit CMS (Unchained module).
58
+ *
59
+ * Requires admin access (API key with assets/upload permission).
60
+ */
61
+ uploadAssets(files: File[], options?: UploadAssetsOptions): Promise<UploadAssetsResponse | null>;
50
62
  getFullRouteForSlug(slug: string): Promise<string | undefined>;
51
63
  /**
52
64
  * Clear cache entries matching pattern
package/dist/client.js CHANGED
@@ -82,7 +82,7 @@ export async function CockpitAPI(options = {}) {
82
82
  baseUrl: config.endpoint.origin,
83
83
  replacements: routeReplacements,
84
84
  };
85
- if (options.tenant !== undefined)
85
+ if (options.tenant)
86
86
  transformerConfig.tenant = options.tenant;
87
87
  const transformer = createImagePathTransformer(transformerConfig);
88
88
  // Create URL builder
@@ -95,7 +95,7 @@ export async function CockpitAPI(options = {}) {
95
95
  url: urlBuilder,
96
96
  cache,
97
97
  endpoint: endpointString,
98
- ...(options.tenant !== undefined && { tenant: options.tenant }),
98
+ ...(options.tenant && { tenant: options.tenant }),
99
99
  };
100
100
  // Create method groups
101
101
  const contentMethods = createContentMethods(ctx);
@@ -17,7 +17,7 @@ export function createConfig(options = {}) {
17
17
  ? undefined
18
18
  : options.tenant;
19
19
  // Validate tenant format to prevent path traversal
20
- if (tenant !== undefined && !VALID_TENANT_PATTERN.test(tenant)) {
20
+ if (tenant && !VALID_TENANT_PATTERN.test(tenant)) {
21
21
  throw new Error("Cockpit: Invalid tenant format (only alphanumeric, hyphens, and underscores allowed)");
22
22
  }
23
23
  const endpoint = new URL(endpointStr);
@@ -28,7 +28,7 @@ export function createConfig(options = {}) {
28
28
  useAdminAccess: options.useAdminAccess ?? false,
29
29
  defaultLanguage: options.defaultLanguage ?? null,
30
30
  cachePrefix: `${endpointStr}:${tenant ?? "default"}:`,
31
- ...(tenant !== undefined && { tenant }),
31
+ ...(tenant && { tenant }),
32
32
  ...(apiKey !== undefined && { apiKey }),
33
33
  });
34
34
  return config;
@@ -23,6 +23,10 @@ export interface HttpClient {
23
23
  * Make a POST request with JSON body
24
24
  */
25
25
  post<T>(url: URL | string, body: unknown, options?: HttpFetchOptions): Promise<T | null>;
26
+ /**
27
+ * Make a POST request with FormData body (multipart/form-data)
28
+ */
29
+ postFormData<T>(url: URL | string, formData: FormData, options?: HttpFetchOptions): Promise<T | null>;
26
30
  /**
27
31
  * Make a DELETE request
28
32
  */
package/dist/core/http.js CHANGED
@@ -91,6 +91,18 @@ export function createHttpClient(config, transformer) {
91
91
  async post(url, body, options = {}) {
92
92
  return fetchData(url, prepareJsonRequestOptions(options, "POST", body));
93
93
  },
94
+ async postFormData(url, formData, options = {}) {
95
+ const { useAdminAccess, headers, ...restOptions } = options;
96
+ const customHeaders = normalizeHeaders(headers);
97
+ // Do NOT set Content-Type - let browser set it with correct boundary
98
+ return fetchData(url, {
99
+ ...restOptions,
100
+ method: "POST",
101
+ body: formData,
102
+ headers: customHeaders,
103
+ ...(useAdminAccess !== undefined && { useAdminAccess }),
104
+ });
105
+ },
94
106
  async delete(url, options = {}) {
95
107
  return fetchData(url, prepareJsonRequestOptions(options, "DELETE"));
96
108
  },
@@ -7,7 +7,7 @@ import { createLocaleNormalizer } from "./locale.js";
7
7
  * Creates a URL builder for the given configuration
8
8
  */
9
9
  export function createUrlBuilder(config) {
10
- const apiBasePath = config.tenant !== undefined ? `/:${config.tenant}/api` : "/api";
10
+ const apiBasePath = config.tenant ? `/:${config.tenant}/api` : "/api";
11
11
  const normalizeLocale = createLocaleNormalizer(config.defaultLanguage);
12
12
  return {
13
13
  build(path, options = {}) {
@@ -26,7 +26,7 @@ export function createUrlBuilder(config) {
26
26
  },
27
27
  graphqlEndpoint() {
28
28
  const url = new URL(config.endpoint);
29
- if (config.tenant !== undefined) {
29
+ if (config.tenant) {
30
30
  url.pathname = `/:${config.tenant}${url.pathname}`;
31
31
  }
32
32
  return url;
@@ -14,7 +14,7 @@ import { createLocaleNormalizer } from "../core/locale.js";
14
14
  */
15
15
  function buildApiBaseUrl(endpoint, tenant) {
16
16
  const url = new URL(endpoint);
17
- const basePath = tenant !== undefined && tenant !== null ? `/:${tenant}/api` : "/api";
17
+ const basePath = tenant ? `/:${tenant}/api` : "/api";
18
18
  return `${url.origin}${basePath}`;
19
19
  }
20
20
  /**
package/dist/index.d.ts CHANGED
@@ -11,16 +11,16 @@ export { getTenantIds, resolveTenantFromUrl, resolveTenantFromSubdomain, } from
11
11
  export type { TenantUrlResult, ResolveTenantFromUrlOptions, ResolveTenantFromSubdomainOptions, } from "./utils/tenant.ts";
12
12
  export { generateCmsRouteReplacements, generateCollectionAndSingletonSlugRouteMap, } from "./utils/route-map.ts";
13
13
  export type { ResponseTransformer } from "./transformers/image-path.ts";
14
- export { createImagePathTransformer, identityTransformer, FixImagePaths, } from "./transformers/image-path.ts";
14
+ export { createImagePathTransformer, identityTransformer, } from "./transformers/image-path.ts";
15
15
  export { createAssetPathTransformer, createPageLinkTransformer, composeTransformers, } from "./transformers/index.ts";
16
- export type { MethodContext, ListQueryOptions, ContentItemQueryOptions, ContentListQueryOptions, TreeQueryOptions, AggregateQueryOptions, } from "./methods/content.ts";
16
+ export type { MethodContext, ListQueryOptions, ContentItemQueryOptions, ContentListQueryOptions, UnchainedContentListQueryOptions, TreeQueryOptions, AggregateQueryOptions, } from "./methods/content.ts";
17
17
  export type { PageByIdOptions, PageByRouteOptions } from "./methods/pages.ts";
18
18
  export type { MenuQueryOptions } from "./methods/menus.ts";
19
19
  export type { SearchQueryOptions } from "./methods/search.ts";
20
20
  export type { LocalizeOptions } from "./methods/localize.ts";
21
21
  export type { CockpitContentItem, CockpitNewsItem, CockpitTreeNode, CockpitListResponse, CockpitListMeta, } from "./methods/content.ts";
22
22
  export { ImageSizeMode, MimeType } from "./methods/assets.ts";
23
- export type { CockpitAsset, ImageAssetQueryParams } from "./methods/assets.ts";
23
+ export type { CockpitAsset, ImageAssetQueryParams, UploadAssetsOptions, UploadAssetsResponse, } from "./methods/assets.ts";
24
24
  export type { CockpitPageType, CockpitPageMeta, CockpitPageSeo, CockpitLayoutBlock, CockpitPage, } from "./methods/pages.ts";
25
25
  export type { CockpitMenuUrl, CockpitMenuLink, CockpitMenu, } from "./methods/menus.ts";
26
26
  export type { CockpitRoute, CockpitRoutesResponse, CockpitSitemapEntry, CockpitPreviewConfig, CockpitSettings, } from "./methods/routes.ts";
package/dist/index.js CHANGED
@@ -6,9 +6,7 @@
6
6
  export { CockpitAPI } from "./client.js";
7
7
  export { getTenantIds, resolveTenantFromUrl, resolveTenantFromSubdomain, } from "./utils/tenant.js";
8
8
  export { generateCmsRouteReplacements, generateCollectionAndSingletonSlugRouteMap, } from "./utils/route-map.js";
9
- export { createImagePathTransformer, identityTransformer,
10
- // eslint-disable-next-line @typescript-eslint/no-deprecated
11
- FixImagePaths, } from "./transformers/image-path.js";
9
+ export { createImagePathTransformer, identityTransformer, } from "./transformers/image-path.js";
12
10
  export { createAssetPathTransformer, createPageLinkTransformer, composeTransformers, } from "./transformers/index.js";
13
11
  export { ImageSizeMode, MimeType } from "./methods/assets.js";
14
12
  export { parseCockpitUrl, isCockpitPageUrl, isCockpitAssetUrl, extractPageId, extractAssetId, } from "./utils/url-protocols.js";
@@ -58,6 +58,19 @@ export type ImageAssetQueryParams = {
58
58
  w?: number;
59
59
  h: number;
60
60
  });
61
+ /**
62
+ * Options for uploading assets
63
+ */
64
+ export interface UploadAssetsOptions {
65
+ /** Target folder name for upload */
66
+ folder?: string;
67
+ }
68
+ /**
69
+ * Response from asset upload
70
+ */
71
+ export interface UploadAssetsResponse {
72
+ assets: CockpitAsset[];
73
+ }
61
74
  export interface AssetMethods {
62
75
  assetById<T = CockpitAsset>(assetId: string): Promise<T | null>;
63
76
  /**
@@ -71,5 +84,22 @@ export interface AssetMethods {
71
84
  * @returns URL string to the generated image, or null if not found
72
85
  */
73
86
  imageAssetById(assetId: string, queryParams: ImageAssetQueryParams): Promise<string | null>;
87
+ /**
88
+ * Upload assets to Cockpit CMS (Unchained module).
89
+ *
90
+ * Requires admin access (API key with assets/upload permission).
91
+ *
92
+ * @param files - Files to upload (File objects or Blob with name)
93
+ * @param options - Upload options (optional folder name)
94
+ * @returns Uploaded assets metadata
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * const file = new File(['content'], 'test.txt', { type: 'text/plain' });
99
+ * const result = await client.uploadAssets([file], { folder: 'documents' });
100
+ * console.log(result?.assets);
101
+ * ```
102
+ */
103
+ uploadAssets(files: File[], options?: UploadAssetsOptions): Promise<UploadAssetsResponse | null>;
74
104
  }
75
105
  export declare function createAssetMethods(ctx: MethodContext): AssetMethods;
@@ -33,5 +33,23 @@ export function createAssetMethods(ctx) {
33
33
  });
34
34
  return ctx.http.fetchText(url);
35
35
  },
36
+ async uploadAssets(files, options = {}) {
37
+ requireParam(files, "files");
38
+ if (files.length === 0) {
39
+ return { assets: [] };
40
+ }
41
+ const formData = new FormData();
42
+ for (const file of files) {
43
+ formData.append("files[]", file);
44
+ }
45
+ const url = ctx.url.build("/unchained/assets/upload", {
46
+ queryParams: {
47
+ ...(options.folder && { folder: options.folder }),
48
+ },
49
+ });
50
+ return ctx.http.postFormData(url, formData, {
51
+ useAdminAccess: true,
52
+ });
53
+ },
36
54
  };
37
55
  }
@@ -30,6 +30,16 @@ export interface ContentItemQueryOptions extends ListQueryOptions {
30
30
  export interface ContentListQueryOptions extends ListQueryOptions {
31
31
  queryParams?: Record<string, unknown>;
32
32
  }
33
+ /**
34
+ * Query options for Unchained content endpoint (supports unpublished items)
35
+ */
36
+ export interface UnchainedContentListQueryOptions extends ContentListQueryOptions {
37
+ /**
38
+ * Include unpublished items in results.
39
+ * Requires admin access with content/{model}/read permission.
40
+ */
41
+ includeUnpublished?: boolean;
42
+ }
33
43
  export interface TreeQueryOptions {
34
44
  parent?: string;
35
45
  filter?: Record<string, unknown>;
@@ -101,6 +111,24 @@ export interface ContentMethods {
101
111
  * const total = response?.meta?.total;
102
112
  */
103
113
  getContentItems<T = CockpitContentItem>(model: string, options?: ContentListQueryOptions): Promise<CockpitListResponse<T> | null>;
114
+ /**
115
+ * Get content items including unpublished via Unchained module.
116
+ *
117
+ * Requires admin access with content/{model}/read permission.
118
+ *
119
+ * @returns Always returns `CockpitListResponse<T>` with data array.
120
+ * Returns `null` if model doesn't exist.
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * const response = await cockpit.getUnchainedContentItems('posts', {
125
+ * limit: 10,
126
+ * includeUnpublished: true,
127
+ * });
128
+ * const items = response?.data || [];
129
+ * ```
130
+ */
131
+ getUnchainedContentItems<T = CockpitContentItem>(model: string, options?: UnchainedContentListQueryOptions): Promise<CockpitListResponse<T> | null>;
104
132
  getContentTree<T = CockpitContentItem>(model: string, options?: TreeQueryOptions): Promise<CockpitTreeNode<T>[] | null>;
105
133
  getAggregateModel<T = unknown>(options: AggregateQueryOptions): Promise<T[] | null>;
106
134
  postContentItem<T = unknown>(model: string, item: Record<string, unknown>): Promise<T | null>;
@@ -43,6 +43,35 @@ export function createContentMethods(ctx) {
43
43
  }
44
44
  return result;
45
45
  },
46
+ async getUnchainedContentItems(model, options = {}) {
47
+ requireParam(model, "a model");
48
+ validatePathSegment(model, "model");
49
+ const { locale = "default", limit, skip, sort, filter, fields, populate, includeUnpublished, queryParams = {}, } = options;
50
+ const url = ctx.url.build(`/unchained/content/items/${model}`, {
51
+ locale,
52
+ queryParams: {
53
+ ...queryParams,
54
+ limit,
55
+ skip,
56
+ sort,
57
+ filter,
58
+ fields,
59
+ populate,
60
+ ...(includeUnpublished && { includeUnpublished: 1 }),
61
+ },
62
+ });
63
+ const result = await ctx.http.fetch(url, {
64
+ useAdminAccess: true,
65
+ });
66
+ // Normalize response to always return { data, meta? }
67
+ if (result === null) {
68
+ return null;
69
+ }
70
+ if (Array.isArray(result)) {
71
+ return { data: result };
72
+ }
73
+ return result;
74
+ },
46
75
  async getContentTree(model, options = {}) {
47
76
  requireParam(model, "a model");
48
77
  validatePathSegment(model, "model");
@@ -59,7 +59,7 @@ export function createRemoteExecutor(options = {}) {
59
59
  preloadRoutes: true,
60
60
  ...cockpitOptions,
61
61
  };
62
- if (tenant !== undefined)
62
+ if (tenant)
63
63
  clientOpts.tenant = tenant;
64
64
  const clientPromise = CockpitAPI(clientOpts);
65
65
  pendingClients.set(key, clientPromise);
@@ -8,7 +8,7 @@ import { logger } from "../cockpit-logger.js";
8
8
  */
9
9
  export function transformAssetPaths(jsonString, config) {
10
10
  const { baseUrl, tenant } = config;
11
- const tenantUrl = `${baseUrl}${tenant !== undefined ? `/:${tenant}` : ""}`;
11
+ const tenantUrl = `${baseUrl}${tenant ? `/:${tenant}` : ""}`;
12
12
  return (jsonString
13
13
  // Fix asset paths in "path" fields
14
14
  .replace(/"path":"\//g, `"path":"${tenantUrl}/storage/uploads/`)
@@ -19,10 +19,3 @@ export interface ImagePathTransformerConfig extends AssetPathConfig {
19
19
  * Uses a single JSON stringify/parse cycle for efficiency.
20
20
  */
21
21
  export declare function createImagePathTransformer(config: ImagePathTransformerConfig): ResponseTransformer;
22
- /**
23
- * Legacy export for backwards compatibility
24
- * @deprecated Use createImagePathTransformer instead
25
- */
26
- export declare function FixImagePaths(endpoint: string, replacements: Record<string, string>, tenant?: string): {
27
- transformResult<T>(originalResponse: T): T;
28
- };
@@ -21,7 +21,7 @@ export function createImagePathTransformer(config) {
21
21
  const { baseUrl, tenant, replacements } = config;
22
22
  // Build asset config, only including tenant if defined
23
23
  const assetConfig = { baseUrl };
24
- if (tenant !== undefined)
24
+ if (tenant)
25
25
  assetConfig.tenant = tenant;
26
26
  return {
27
27
  transform(originalResponse) {
@@ -41,20 +41,3 @@ export function createImagePathTransformer(config) {
41
41
  },
42
42
  };
43
43
  }
44
- /**
45
- * Legacy export for backwards compatibility
46
- * @deprecated Use createImagePathTransformer instead
47
- */
48
- export function FixImagePaths(endpoint, replacements, tenant) {
49
- const baseUrl = new URL(endpoint).origin;
50
- const config = {
51
- baseUrl,
52
- replacements,
53
- };
54
- if (tenant !== undefined)
55
- config.tenant = tenant;
56
- const transformer = createImagePathTransformer(config);
57
- return {
58
- transformResult: transformer.transform.bind(transformer),
59
- };
60
- }
@@ -2,7 +2,7 @@
2
2
  * Transformer exports
3
3
  */
4
4
  export type { ResponseTransformer } from "./image-path.ts";
5
- export { identityTransformer, createImagePathTransformer, FixImagePaths, } from "./image-path.ts";
5
+ export { identityTransformer, createImagePathTransformer, } from "./image-path.ts";
6
6
  export { composeTransformers } from "./compose.ts";
7
7
  export { createAssetPathTransformer, transformAssetPaths, type AssetPathConfig, } from "./asset-path.ts";
8
8
  export { createPageLinkTransformer, transformPageLinks } from "./page-link.ts";
@@ -1,9 +1,7 @@
1
1
  /**
2
2
  * Transformer exports
3
3
  */
4
- export { identityTransformer, createImagePathTransformer,
5
- // eslint-disable-next-line @typescript-eslint/no-deprecated
6
- FixImagePaths, } from "./image-path.js";
4
+ export { identityTransformer, createImagePathTransformer, } from "./image-path.js";
7
5
  export { composeTransformers } from "./compose.js";
8
6
  export { createAssetPathTransformer, transformAssetPaths, } from "./asset-path.js";
9
7
  export { createPageLinkTransformer, transformPageLinks } from "./page-link.js";
@@ -17,7 +17,7 @@ export async function generateCmsRouteReplacements(endpoint, tenant, cache) {
17
17
  };
18
18
  try {
19
19
  const origin = new URL(endpoint).origin;
20
- const apiPath = tenant !== undefined ? `/:${tenant}/api` : "/api";
20
+ const apiPath = tenant ? `/:${tenant}/api` : "/api";
21
21
  const response = await fetch(`${origin}${apiPath}/pages/pages?${new URLSearchParams(filterParams).toString()}`);
22
22
  if (!response.ok) {
23
23
  logger.warn(`Cockpit: Failed to fetch route replacements (status ${String(response.status)})`);
@@ -60,7 +60,7 @@ export async function generateCollectionAndSingletonSlugRouteMap(endpoint, tenan
60
60
  };
61
61
  try {
62
62
  const origin = new URL(endpoint).origin;
63
- const apiPath = tenant !== undefined ? `/:${tenant}/api` : "/api";
63
+ const apiPath = tenant ? `/:${tenant}/api` : "/api";
64
64
  const response = await fetch(`${origin}${apiPath}/pages/pages?locale=default&${new URLSearchParams(filterParams).toString()}`);
65
65
  if (!response.ok) {
66
66
  logger.warn(`Cockpit: Failed to fetch slug route map (status ${String(response.status)})`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unchainedshop/cockpit-api",
3
- "version": "2.3.1",
3
+ "version": "2.4.0",
4
4
  "description": "A package to interact with the Cockpit CMS API, including functionalities to handle GraphQL requests and various CMS content manipulations.",
5
5
  "main": "dist/index.js",
6
6
  "homepage": "https://unchained.shop",