Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/add-contentstack-cda-plugin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@lytics/lio-client-contentstack-cda": minor
---

Add Contentstack Content Delivery API plugin with getContentTypes, getEntries, and getEntry methods
58 changes: 58 additions & 0 deletions packages/contentstack-cda/package.json
Original file line number Diff line number Diff line change
@@ -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"
}
}
7 changes: 7 additions & 0 deletions packages/contentstack-cda/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export { contentstackCdaPlugin } from './plugin';
export type {
CdaContentType,
CdaEntry,
ContentstackCdaConfig,
ContentstackCdaPlugin,
} from './types';
147 changes: 147 additions & 0 deletions packages/contentstack-cda/src/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, any> = {};

const plugin = {
ns: vi.fn(),
expose: vi.fn((obj: Record<string, any>) => {
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<typeof createPluginHarness>;
const fetchSpy =
vi.fn<(input: string | URL | Request, init?: RequestInit) => Promise<Response>>();

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([]);
});
});
103 changes: 103 additions & 0 deletions packages/contentstack-cda/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -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<T>(path: string, params?: Record<string, string>): Promise<T> {
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<CdaContentType[]> {
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<string, string> = {
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<CdaEntry> {
const data = await cdaFetch<{ entry: CdaEntry }>(
`/content_types/${contentTypeUid}/entries/${entryUid}`
);
return data.entry;
},
},
});
};
}
34 changes: 34 additions & 0 deletions packages/contentstack-cda/src/types.ts
Original file line number Diff line number Diff line change
@@ -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<CdaContentType[]>;
getEntries(
contentTypeUid: string,
opts?: {
limit?: number;
query?: string;
include_count?: boolean;
}
): Promise<{ entries: CdaEntry[]; count?: number }>;
getEntry(contentTypeUid: string, entryUid: string): Promise<CdaEntry>;
}
8 changes: 8 additions & 0 deletions packages/contentstack-cda/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
19 changes: 19 additions & 0 deletions packages/contentstack-cda/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -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,
});
Loading