From 46fbc09e9e4465942f909846a048ff1c767b3450 Mon Sep 17 00:00:00 2001 From: prosdev Date: Sun, 22 Feb 2026 09:56:12 -0800 Subject: [PATCH] feat(contentstack-cda): add CDA plugin for content delivery queries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New plugin `@lytics/lio-client-contentstack-cda` with three methods: - getContentTypes() — lists user-defined content types (filters built_io_* system types) - getEntries(uid, opts?) — list entries with optional title search and pagination - getEntry(uid, entryUid) — single entry by UID Uses plain fetch() instead of SDK Kit transport since CDA has header-based auth and a different response envelope than the Lytics API. Co-Authored-By: Claude Opus 4.6 --- .changeset/add-contentstack-cda-plugin.md | 5 + packages/contentstack-cda/package.json | 58 ++++++++ packages/contentstack-cda/src/index.ts | 7 + packages/contentstack-cda/src/plugin.test.ts | 147 +++++++++++++++++++ packages/contentstack-cda/src/plugin.ts | 103 +++++++++++++ packages/contentstack-cda/src/types.ts | 34 +++++ packages/contentstack-cda/tsconfig.json | 8 + packages/contentstack-cda/tsup.config.ts | 19 +++ pnpm-lock.yaml | 16 ++ tsconfig.json | 4 +- 10 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 .changeset/add-contentstack-cda-plugin.md create mode 100644 packages/contentstack-cda/package.json create mode 100644 packages/contentstack-cda/src/index.ts create mode 100644 packages/contentstack-cda/src/plugin.test.ts create mode 100644 packages/contentstack-cda/src/plugin.ts create mode 100644 packages/contentstack-cda/src/types.ts create mode 100644 packages/contentstack-cda/tsconfig.json create mode 100644 packages/contentstack-cda/tsup.config.ts diff --git a/.changeset/add-contentstack-cda-plugin.md b/.changeset/add-contentstack-cda-plugin.md new file mode 100644 index 0000000..85c013d --- /dev/null +++ b/.changeset/add-contentstack-cda-plugin.md @@ -0,0 +1,5 @@ +--- +"@lytics/lio-client-contentstack-cda": minor +--- + +Add Contentstack Content Delivery API plugin with getContentTypes, getEntries, and getEntry methods diff --git a/packages/contentstack-cda/package.json b/packages/contentstack-cda/package.json new file mode 100644 index 0000000..9457990 --- /dev/null +++ b/packages/contentstack-cda/package.json @@ -0,0 +1,58 @@ +{ + "name": "@lytics/lio-client-contentstack-cda", + "version": "0.0.0", + "description": "Contentstack Content Delivery API plugin for Lytics lio-client", + "private": false, + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "files": [ + "dist", + "src", + "README.md", + "LICENSE" + ], + "sideEffects": false, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "keywords": [ + "lytics", + "contentstack", + "cms", + "content-delivery" + ], + "repository": { + "type": "git", + "url": "https://github.com/lytics/lio-client.git", + "directory": "packages/contentstack-cda" + }, + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "clean": "rm -rf dist", + "typecheck": "tsc --noEmit", + "lint": "biome lint ./src", + "format": "biome format --write ./src", + "test": "vitest run", + "test:watch": "vitest" + }, + "dependencies": { + "@lytics/sdk-kit": "^0.2.0" + }, + "peerDependencies": { + "@lytics/lio-client": "workspace:*" + }, + "devDependencies": { + "@lytics/lio-client": "workspace:*", + "tsup": "^8.5.1", + "typescript": "^5.9.3" + } +} diff --git a/packages/contentstack-cda/src/index.ts b/packages/contentstack-cda/src/index.ts new file mode 100644 index 0000000..3b8c027 --- /dev/null +++ b/packages/contentstack-cda/src/index.ts @@ -0,0 +1,7 @@ +export { contentstackCdaPlugin } from './plugin'; +export type { + CdaContentType, + CdaEntry, + ContentstackCdaConfig, + ContentstackCdaPlugin, +} from './types'; diff --git a/packages/contentstack-cda/src/plugin.test.ts b/packages/contentstack-cda/src/plugin.test.ts new file mode 100644 index 0000000..b661d20 --- /dev/null +++ b/packages/contentstack-cda/src/plugin.test.ts @@ -0,0 +1,147 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { contentstackCdaPlugin } from './plugin'; + +// Minimal stub of the SDK Kit plugin API — just enough to test our plugin. +function createPluginHarness() { + let exposed: Record = {}; + + const plugin = { + ns: vi.fn(), + expose: vi.fn((obj: Record) => { + exposed = obj; + }), + }; + + const install = contentstackCdaPlugin({ + apiKey: 'test-api-key', + deliveryToken: 'test-delivery-token', + environment: 'production', + }); + + // Install the plugin — passes the mock plugin object + install(plugin as any, {} as any, {} as any); + + return exposed.contentstackCda; +} + +describe('contentstackCdaPlugin', () => { + let cda: ReturnType; + const fetchSpy = + vi.fn<(input: string | URL | Request, init?: RequestInit) => Promise>(); + + beforeEach(() => { + fetchSpy.mockReset(); + cda = createPluginHarness(); + globalThis.fetch = fetchSpy as any; + }); + + // Helper to create a mock Response + function mockResponse(body: unknown, status = 200) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' }, + }); + } + + it('getContentTypes() filters out built_io_* system types', async () => { + fetchSpy.mockResolvedValueOnce( + mockResponse({ + content_types: [ + { uid: 'product', title: 'Product', description: 'Products' }, + { uid: 'built_io_upload', title: 'Upload', description: 'System uploads' }, + { uid: 'blog_post', title: 'Blog Post', description: 'Blog posts' }, + ], + }) + ); + + const types = await cda.getContentTypes(); + expect(types).toHaveLength(2); + expect(types.map((t: any) => t.uid)).toEqual(['product', 'blog_post']); + }); + + it('getContentTypes() sends correct headers and environment param', async () => { + fetchSpy.mockResolvedValueOnce(mockResponse({ content_types: [] })); + + await cda.getContentTypes(); + + expect(fetchSpy).toHaveBeenCalledOnce(); + const [url, init] = fetchSpy.mock.calls[0]; + expect(String(url)).toContain('/v3/content_types'); + expect(String(url)).toContain('environment=production'); + expect(init?.headers).toEqual({ + api_key: 'test-api-key', + access_token: 'test-delivery-token', + }); + }); + + it('getEntries() defaults to limit 50 and include_count true', async () => { + fetchSpy.mockResolvedValueOnce(mockResponse({ entries: [], count: 0 })); + + await cda.getEntries('product'); + + const [url] = fetchSpy.mock.calls[0]; + const parsed = new URL(String(url)); + expect(parsed.searchParams.get('limit')).toBe('50'); + expect(parsed.searchParams.get('include_count')).toBe('true'); + }); + + it('getEntries() passes query param with escaped regex for title search', async () => { + fetchSpy.mockResolvedValueOnce(mockResponse({ entries: [], count: 0 })); + + await cda.getEntries('product', { query: 'green tea (organic)' }); + + const [url] = fetchSpy.mock.calls[0]; + const parsed = new URL(String(url)); + const query = JSON.parse(parsed.searchParams.get('query')!); + expect(query.title.$regex).toBe('green tea \\(organic\\)'); + expect(query.title.$options).toBe('i'); + }); + + it('getEntry() returns single entry', async () => { + const entry = { + uid: 'blt123', + title: 'Jasmine Green', + created_at: '2025-01-01', + updated_at: '2025-01-02', + }; + fetchSpy.mockResolvedValueOnce(mockResponse({ entry })); + + const result = await cda.getEntry('product', 'blt123'); + + expect(result).toEqual(entry); + const [url] = fetchSpy.mock.calls[0]; + expect(String(url)).toContain('/v3/content_types/product/entries/blt123'); + }); + + it('throws descriptive error on auth failure (401)', async () => { + fetchSpy.mockResolvedValueOnce( + mockResponse({ error_message: 'Unauthorized', error_code: 105 }, 401) + ); + + await expect(cda.getContentTypes()).rejects.toThrow( + 'Invalid delivery token or API key for stack' + ); + }); + + it('throws descriptive error on network failure', async () => { + fetchSpy.mockRejectedValueOnce(new Error('DNS resolution failed')); + + await expect(cda.getContentTypes()).rejects.toThrow( + 'Contentstack CDA request failed: DNS resolution failed' + ); + }); + + it('getContentTypes() returns empty array when CDA returns only system types', async () => { + fetchSpy.mockResolvedValueOnce( + mockResponse({ + content_types: [ + { uid: 'built_io_upload', title: 'Upload', description: 'System uploads' }, + { uid: 'built_io_download', title: 'Download', description: 'System downloads' }, + ], + }) + ); + + const types = await cda.getContentTypes(); + expect(types).toEqual([]); + }); +}); diff --git a/packages/contentstack-cda/src/plugin.ts b/packages/contentstack-cda/src/plugin.ts new file mode 100644 index 0000000..a8519bc --- /dev/null +++ b/packages/contentstack-cda/src/plugin.ts @@ -0,0 +1,103 @@ +import type { PluginFunction } from '@lytics/sdk-kit'; +import type { CdaContentType, CdaEntry, ContentstackCdaConfig } from './types'; + +const DEFAULT_BASE_URL = 'https://cdn.contentstack.io'; + +/** + * Escape special regex characters in a string so it can be safely + * embedded in a CDA `$regex` query. + */ +function escapeRegex(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +export function contentstackCdaPlugin(config: ContentstackCdaConfig): PluginFunction { + const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL; + + return (plugin) => { + plugin.ns('contentstackCda'); + + async function cdaFetch(path: string, params?: Record): Promise { + const url = new URL(`/v3${path}`, baseUrl); + url.searchParams.set('environment', config.environment); + + if (params) { + for (const [key, value] of Object.entries(params)) { + url.searchParams.set(key, value); + } + } + + let response: Response; + try { + response = await fetch(url.toString(), { + headers: { + api_key: config.apiKey, + access_token: config.deliveryToken, + }, + }); + } catch (error) { + throw new Error( + `Contentstack CDA request failed: ${error instanceof Error ? error.message : String(error)} (URL: ${url.pathname}${url.search})` + ); + } + + if (!response.ok) { + let message = `Contentstack CDA error ${response.status}`; + try { + const body = (await response.json()) as { error_message?: string }; + if (body.error_message) { + message = body.error_message; + } + } catch { + // Ignore JSON parse failures — use the status-based message + } + + if (response.status === 401 || response.status === 403) { + throw new Error(`Invalid delivery token or API key for stack: ${message}`); + } + throw new Error(`Contentstack CDA error ${response.status}: ${message}`); + } + + return (await response.json()) as T; + } + + plugin.expose({ + contentstackCda: { + async getContentTypes(): Promise { + const data = await cdaFetch<{ content_types: CdaContentType[] }>('/content_types'); + return data.content_types.filter((t) => !t.uid.startsWith('built_io_')); + }, + + async getEntries( + contentTypeUid: string, + opts?: { limit?: number; query?: string; include_count?: boolean } + ): Promise<{ entries: CdaEntry[]; count?: number }> { + const params: Record = { + limit: String(opts?.limit ?? 50), + include_count: String(opts?.include_count ?? true), + }; + + if (opts?.query) { + const escaped = escapeRegex(opts.query); + params.query = JSON.stringify({ + title: { $regex: escaped, $options: 'i' }, + }); + } + + const data = await cdaFetch<{ entries: CdaEntry[]; count?: number }>( + `/content_types/${contentTypeUid}/entries`, + params + ); + return { entries: data.entries, count: data.count }; + }, + + async getEntry(contentTypeUid: string, entryUid: string): Promise { + const data = await cdaFetch<{ entry: CdaEntry }>( + `/content_types/${contentTypeUid}/entries/${entryUid}` + ); + return data.entry; + }, + }, + }); + }; +} diff --git a/packages/contentstack-cda/src/types.ts b/packages/contentstack-cda/src/types.ts new file mode 100644 index 0000000..03dae5b --- /dev/null +++ b/packages/contentstack-cda/src/types.ts @@ -0,0 +1,34 @@ +export interface ContentstackCdaConfig { + apiKey: string; + deliveryToken: string; + environment: string; + baseUrl?: string; +} + +export interface CdaContentType { + uid: string; + title: string; + description: string; +} + +export interface CdaEntry { + uid: string; + title: string; + url?: string; + created_at: string; + updated_at: string; + [key: string]: unknown; +} + +export interface ContentstackCdaPlugin { + getContentTypes(): Promise; + getEntries( + contentTypeUid: string, + opts?: { + limit?: number; + query?: string; + include_count?: boolean; + } + ): Promise<{ entries: CdaEntry[]; count?: number }>; + getEntry(contentTypeUid: string, entryUid: string): Promise; +} diff --git a/packages/contentstack-cda/tsconfig.json b/packages/contentstack-cda/tsconfig.json new file mode 100644 index 0000000..411c2dc --- /dev/null +++ b/packages/contentstack-cda/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/contentstack-cda/tsup.config.ts b/packages/contentstack-cda/tsup.config.ts new file mode 100644 index 0000000..a57480f --- /dev/null +++ b/packages/contentstack-cda/tsup.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/index.ts'], + format: ['esm'], + dts: { + only: false, + compilerOptions: { + composite: false, // Disable composite for DTS generation + }, + }, + splitting: false, + sourcemap: true, + clean: true, + treeshake: true, + minify: false, + outDir: 'dist', + skipNodeModulesBundle: true, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7c0f6ac..0704ad4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -61,6 +61,22 @@ importers: specifier: ^5.9.3 version: 5.9.3 + packages/contentstack-cda: + dependencies: + '@lytics/sdk-kit': + specifier: ^0.2.0 + version: 0.2.0(typescript@5.9.3) + devDependencies: + '@lytics/lio-client': + specifier: workspace:* + version: link:../core + tsup: + specifier: ^8.5.1 + version: 8.5.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(typescript@5.9.3) + typescript: + specifier: ^5.9.3 + version: 5.9.3 + packages/core: dependencies: '@lytics/sdk-kit': diff --git a/tsconfig.json b/tsconfig.json index c3f2091..6fa0080 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,7 +15,9 @@ "@lytics/lio-client": ["packages/core/src"], "@lytics/lio-client/*": ["packages/core/src/*"], "@lytics/lio-client-contentstack": ["packages/contentstack/src"], - "@lytics/lio-client-contentstack/*": ["packages/contentstack/src/*"] + "@lytics/lio-client-contentstack/*": ["packages/contentstack/src/*"], + "@lytics/lio-client-contentstack-cda": ["packages/contentstack-cda/src"], + "@lytics/lio-client-contentstack-cda/*": ["packages/contentstack-cda/src/*"] } }, "exclude": ["node_modules"]