@chigisoft-web/cms-sdk 1.0.3
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 +278 -0
- package/dist/cli.js +313 -0
- package/dist/index.d.mts +164 -0
- package/dist/index.d.ts +164 -0
- package/dist/index.global.js +245 -0
- package/dist/index.global.js.map +1 -0
- package/dist/index.js +249 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +222 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +29 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
ChigiSoftClient: () => ChigiSoftClient,
|
|
24
|
+
ChigiSoftError: () => ChigiSoftError,
|
|
25
|
+
createClient: () => createClient
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
var ChigiSoftError = class extends Error {
|
|
29
|
+
constructor(message, status, response) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "ChigiSoftError";
|
|
32
|
+
this.status = status;
|
|
33
|
+
this.response = response;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
var ChigiSoftClient = class {
|
|
37
|
+
constructor(config = {}) {
|
|
38
|
+
const defaultBaseUrl = "https://cms-api.staging.chigisoft.co/";
|
|
39
|
+
const env = globalThis.process?.env || {};
|
|
40
|
+
const projectId = config.projectId || env.CHIGISOFT_PROJECT_ID || "";
|
|
41
|
+
const token = config.token || env.CHIGISOFT_API_TOKEN || "";
|
|
42
|
+
if (!projectId) {
|
|
43
|
+
throw new Error("[ChigiSoft SDK] Missing required option: projectId (or CHIGISOFT_PROJECT_ID env variable)");
|
|
44
|
+
}
|
|
45
|
+
if (!token) {
|
|
46
|
+
throw new Error("[ChigiSoft SDK] Missing required option: token (or CHIGISOFT_API_TOKEN env variable)");
|
|
47
|
+
}
|
|
48
|
+
this.config = {
|
|
49
|
+
baseUrl: config.baseUrl || defaultBaseUrl,
|
|
50
|
+
projectId,
|
|
51
|
+
token,
|
|
52
|
+
useCdn: config.useCdn ?? false,
|
|
53
|
+
apiVersion: config.apiVersion,
|
|
54
|
+
fetch: config.fetch
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Generic fetch method to query custom endpoints or arbitrary CMS paths.
|
|
59
|
+
*/
|
|
60
|
+
async fetch(path, options) {
|
|
61
|
+
return this.request(path, options);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Fetch all pages associated with the project.
|
|
65
|
+
*/
|
|
66
|
+
async getPages(options) {
|
|
67
|
+
const params = { pageType: "PAGE", ...options?.params || {} };
|
|
68
|
+
return this.request(`/v1/projects/${this.config.projectId}/pages`, {
|
|
69
|
+
...options,
|
|
70
|
+
params
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Fetch a single page by its slug or ID.
|
|
75
|
+
*/
|
|
76
|
+
async getPageBySlug(slug, options) {
|
|
77
|
+
const pages = await this.getPages(options);
|
|
78
|
+
return pages.find((p) => p.slug === slug || p.id === slug) || null;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Fetch all blog posts associated with the project.
|
|
82
|
+
*/
|
|
83
|
+
async getBlogs(options) {
|
|
84
|
+
const params = { pageType: "ARTICLE", category: "BLOG", ...options?.params || {} };
|
|
85
|
+
return this.request(`/v1/projects/${this.config.projectId}/pages`, {
|
|
86
|
+
...options,
|
|
87
|
+
params
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Fetch a single blog post by its slug or ID.
|
|
92
|
+
*/
|
|
93
|
+
async getBlogBySlug(slug, options) {
|
|
94
|
+
const blogs = await this.getBlogs(options);
|
|
95
|
+
return blogs.find((b) => b.slug === slug || b.id === slug) || null;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Fetch all testimonies associated with the project.
|
|
99
|
+
*/
|
|
100
|
+
async getTestimonies(options) {
|
|
101
|
+
const params = { pageType: "ARTICLE", category: "GENERAL", ...options?.params || {} };
|
|
102
|
+
const articles = await this.request(`/v1/projects/${this.config.projectId}/pages`, {
|
|
103
|
+
...options,
|
|
104
|
+
params
|
|
105
|
+
});
|
|
106
|
+
return articles.filter((p) => p.tags && p.tags.includes("testimonial"));
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Fetch a single testimony by its slug or ID.
|
|
110
|
+
*/
|
|
111
|
+
async getTestimonyBySlug(slug, options) {
|
|
112
|
+
const testimonies = await this.getTestimonies(options);
|
|
113
|
+
return testimonies.find((t) => t.slug === slug || t.id === slug) || null;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Fetch all menus associated with the project.
|
|
117
|
+
*/
|
|
118
|
+
async getMenus(options) {
|
|
119
|
+
return this.request(`/v1/projects/${this.config.projectId}/menus`, options);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Fetch a single menu by its ID.
|
|
123
|
+
*/
|
|
124
|
+
async getMenuById(id, options) {
|
|
125
|
+
try {
|
|
126
|
+
return await this.request(`/v1/menus/${id}`, options);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof ChigiSoftError && error.status === 404) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Fetch a single menu by its name (e.g., 'header', 'footer').
|
|
136
|
+
*/
|
|
137
|
+
async getMenuByName(name, options) {
|
|
138
|
+
const menus = await this.getMenus(options);
|
|
139
|
+
return menus.find((m) => m.name === name) || null;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Mounts the ChigiSoft CMS Studio interface (login/dashboard) inside a container.
|
|
143
|
+
* Works in Next.js, Nuxt.js, HTML, PHP, and any other environment.
|
|
144
|
+
*/
|
|
145
|
+
mountStudio(target, options) {
|
|
146
|
+
if (typeof window === "undefined" || typeof document === "undefined") {
|
|
147
|
+
throw new Error("[ChigiSoft SDK] mountStudio can only be called in a browser environment.");
|
|
148
|
+
}
|
|
149
|
+
let container = null;
|
|
150
|
+
if (typeof target === "string") {
|
|
151
|
+
container = document.querySelector(target);
|
|
152
|
+
} else {
|
|
153
|
+
container = target;
|
|
154
|
+
}
|
|
155
|
+
if (!container) {
|
|
156
|
+
throw new Error(`[ChigiSoft SDK] Target container element not found: ${target}`);
|
|
157
|
+
}
|
|
158
|
+
const baseUrl = options?.studioUrl || this.config.baseUrl.replace(/\/v1\/?$/, "").replace(/\/api\/v1\/?$/, "").replace(/\/+$/, "");
|
|
159
|
+
const url = new URL(baseUrl);
|
|
160
|
+
url.searchParams.set("projectId", this.config.projectId);
|
|
161
|
+
url.searchParams.set("token", this.config.token);
|
|
162
|
+
url.searchParams.set("embed", "true");
|
|
163
|
+
const iframe = document.createElement("iframe");
|
|
164
|
+
iframe.src = url.toString();
|
|
165
|
+
iframe.setAttribute("frameborder", "0");
|
|
166
|
+
iframe.setAttribute("allow", "clipboard-write");
|
|
167
|
+
const defaultStyles = {
|
|
168
|
+
width: "100%",
|
|
169
|
+
height: "100%",
|
|
170
|
+
minHeight: "650px",
|
|
171
|
+
border: "none"
|
|
172
|
+
};
|
|
173
|
+
const finalStyles = { ...defaultStyles, ...options?.style };
|
|
174
|
+
Object.assign(iframe.style, finalStyles);
|
|
175
|
+
container.innerHTML = "";
|
|
176
|
+
container.appendChild(iframe);
|
|
177
|
+
return iframe;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Generic request wrapper to handle responses and errors using fetch.
|
|
181
|
+
*/
|
|
182
|
+
async request(url, requestConfig) {
|
|
183
|
+
const fetchFn = this.config.fetch || globalThis.fetch;
|
|
184
|
+
if (!fetchFn) {
|
|
185
|
+
throw new Error("[ChigiSoft SDK] No fetch implementation found. Ensure you are in a supported environment or pass a custom fetch implementation.");
|
|
186
|
+
}
|
|
187
|
+
const baseUrl = this.config.baseUrl.replace(/\/+$/, "");
|
|
188
|
+
const cleanUrl = url.startsWith("/") ? url : `/${url}`;
|
|
189
|
+
let fullUrl = `${baseUrl}${cleanUrl}`;
|
|
190
|
+
if (requestConfig?.params) {
|
|
191
|
+
const searchParams = new URLSearchParams();
|
|
192
|
+
Object.entries(requestConfig.params).forEach(([key, value]) => {
|
|
193
|
+
if (value !== void 0) {
|
|
194
|
+
searchParams.append(key, String(value));
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
const queryStr = searchParams.toString();
|
|
198
|
+
if (queryStr) {
|
|
199
|
+
fullUrl += `?${queryStr}`;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const headers = {
|
|
203
|
+
"x-project-id": this.config.projectId,
|
|
204
|
+
"Authorization": `Bearer ${this.config.token}`,
|
|
205
|
+
"Content-Type": "application/json",
|
|
206
|
+
...requestConfig?.headers || {}
|
|
207
|
+
};
|
|
208
|
+
if (this.config.apiVersion) {
|
|
209
|
+
headers["x-api-version"] = this.config.apiVersion;
|
|
210
|
+
}
|
|
211
|
+
if (this.config.useCdn) {
|
|
212
|
+
headers["Cache-Control"] = "max-age=60";
|
|
213
|
+
}
|
|
214
|
+
const { params, ...fetchOptions } = requestConfig || {};
|
|
215
|
+
try {
|
|
216
|
+
const response = await fetchFn(fullUrl, {
|
|
217
|
+
method: "GET",
|
|
218
|
+
headers,
|
|
219
|
+
...fetchOptions
|
|
220
|
+
});
|
|
221
|
+
if (!response.ok) {
|
|
222
|
+
let message = "API request failed";
|
|
223
|
+
try {
|
|
224
|
+
const errData = await response.json();
|
|
225
|
+
message = errData?.message || message;
|
|
226
|
+
} catch {
|
|
227
|
+
}
|
|
228
|
+
throw new ChigiSoftError(`[ChigiSoft SDK] ${message}`, response.status, response);
|
|
229
|
+
}
|
|
230
|
+
const json = await response.json();
|
|
231
|
+
return json && json.data !== void 0 ? json.data : json;
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (error instanceof ChigiSoftError) {
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
throw new ChigiSoftError(`[ChigiSoft SDK] ${error.message || "API request failed"}`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
function createClient(config) {
|
|
241
|
+
return new ChigiSoftClient(config);
|
|
242
|
+
}
|
|
243
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
244
|
+
0 && (module.exports = {
|
|
245
|
+
ChigiSoftClient,
|
|
246
|
+
ChigiSoftError,
|
|
247
|
+
createClient
|
|
248
|
+
});
|
|
249
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export interface ChigiSoftConfig {\n /**\n * The base URL of the ChigiSoft CMS backend API.\n * @default 'https://cms-api.staging.chigisoft.co/'\n */\n baseUrl?: string;\n /**\n * The unique ID of the project. If not provided, it will fallback to process.env.CHIGISOFT_PROJECT_ID\n */\n projectId?: string;\n /**\n * The personalized API token. If not provided, it will fallback to process.env.CHIGISOFT_API_TOKEN\n */\n token?: string;\n /**\n * Optional boolean to toggle using a cached CDN endpoint or cache headers.\n */\n useCdn?: boolean;\n /**\n * Optional custom fetch implementation (e.g., node-fetch, or Next.js fetch wrapper).\n */\n fetch?: typeof fetch;\n /**\n * Optional API version parameter.\n */\n apiVersion?: string;\n}\n\nexport interface ChigiSoftRequestInit extends Omit<RequestInit, 'method'> {\n /**\n * Optional query parameters to append to the URL.\n */\n params?: Record<string, string | number | boolean | undefined>;\n}\n\nexport interface CMSBlock {\n id: string;\n type: string;\n content: Record<string, any>;\n [key: string]: any;\n}\n\nexport interface CMSPage {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n description?: string;\n blocks: CMSBlock[];\n published: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CMSBlog {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n description?: string;\n blocks: CMSBlock[];\n published: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CMSTestimony {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n description?: string;\n blocks: CMSBlock[];\n published: boolean;\n createdAt: string;\n updatedAt: string;\n tags?: string[];\n [key: string]: any;\n}\n\nexport interface CMSMenuItem {\n id: string;\n label: string;\n url: string | null;\n pageId: string | null;\n order: number;\n parentId: string | null;\n menuId: string;\n openInNewTab: boolean;\n [key: string]: any;\n}\n\nexport interface CMSMenu {\n id: string;\n name: string;\n projectId: string;\n createdAt: string;\n updatedAt: string;\n items: CMSMenuItem[];\n}\n\nexport class ChigiSoftError extends Error {\n status?: number;\n response?: Response;\n\n constructor(message: string, status?: number, response?: Response) {\n super(message);\n this.name = 'ChigiSoftError';\n this.status = status;\n this.response = response;\n }\n}\n\nexport class ChigiSoftClient {\n private config: Required<Omit<ChigiSoftConfig, 'fetch' | 'apiVersion'>> & {\n apiVersion?: string;\n fetch?: typeof fetch;\n };\n\n constructor(config: ChigiSoftConfig = {}) {\n const defaultBaseUrl = 'https://cms-api.staging.chigisoft.co/';\n \n // Safely extract environment variables across environments (Node, Next, Nuxt, Vite)\n const env = (globalThis as any).process?.env || {};\n const projectId = config.projectId || env.CHIGISOFT_PROJECT_ID || '';\n const token = config.token || env.CHIGISOFT_API_TOKEN || '';\n\n if (!projectId) {\n throw new Error('[ChigiSoft SDK] Missing required option: projectId (or CHIGISOFT_PROJECT_ID env variable)');\n }\n if (!token) {\n throw new Error('[ChigiSoft SDK] Missing required option: token (or CHIGISOFT_API_TOKEN env variable)');\n }\n\n this.config = {\n baseUrl: config.baseUrl || defaultBaseUrl,\n projectId,\n token,\n useCdn: config.useCdn ?? false,\n apiVersion: config.apiVersion,\n fetch: config.fetch,\n };\n }\n\n /**\n * Generic fetch method to query custom endpoints or arbitrary CMS paths.\n */\n public async fetch<T>(path: string, options?: ChigiSoftRequestInit): Promise<T> {\n return this.request<T>(path, options);\n }\n\n /**\n * Fetch all pages associated with the project.\n */\n public async getPages(options?: ChigiSoftRequestInit): Promise<CMSPage[]> {\n const params = { pageType: 'PAGE', ...(options?.params || {}) };\n return this.request<CMSPage[]>(`/v1/projects/${this.config.projectId}/pages`, {\n ...options,\n params,\n });\n }\n\n /**\n * Fetch a single page by its slug or ID.\n */\n public async getPageBySlug(slug: string, options?: ChigiSoftRequestInit): Promise<CMSPage | null> {\n const pages = await this.getPages(options);\n return pages.find(p => p.slug === slug || p.id === slug) || null;\n }\n\n /**\n * Fetch all blog posts associated with the project.\n */\n public async getBlogs(options?: ChigiSoftRequestInit): Promise<CMSBlog[]> {\n const params = { pageType: 'ARTICLE', category: 'BLOG', ...(options?.params || {}) };\n return this.request<CMSBlog[]>(`/v1/projects/${this.config.projectId}/pages`, {\n ...options,\n params,\n });\n }\n\n /**\n * Fetch a single blog post by its slug or ID.\n */\n public async getBlogBySlug(slug: string, options?: ChigiSoftRequestInit): Promise<CMSBlog | null> {\n const blogs = await this.getBlogs(options);\n return blogs.find(b => b.slug === slug || b.id === slug) || null;\n }\n\n /**\n * Fetch all testimonies associated with the project.\n */\n public async getTestimonies(options?: ChigiSoftRequestInit): Promise<CMSTestimony[]> {\n const params = { pageType: 'ARTICLE', category: 'GENERAL', ...(options?.params || {}) };\n const articles = await this.request<CMSTestimony[]>(`/v1/projects/${this.config.projectId}/pages`, {\n ...options,\n params,\n });\n return articles.filter(p => p.tags && p.tags.includes('testimonial'));\n }\n\n /**\n * Fetch a single testimony by its slug or ID.\n */\n public async getTestimonyBySlug(slug: string, options?: ChigiSoftRequestInit): Promise<CMSTestimony | null> {\n const testimonies = await this.getTestimonies(options);\n return testimonies.find(t => t.slug === slug || t.id === slug) || null;\n }\n\n /**\n * Fetch all menus associated with the project.\n */\n public async getMenus(options?: ChigiSoftRequestInit): Promise<CMSMenu[]> {\n return this.request<CMSMenu[]>(`/v1/projects/${this.config.projectId}/menus`, options);\n }\n\n /**\n * Fetch a single menu by its ID.\n */\n public async getMenuById(id: string, options?: ChigiSoftRequestInit): Promise<CMSMenu | null> {\n try {\n return await this.request<CMSMenu>(`/v1/menus/${id}`, options);\n } catch (error) {\n if (error instanceof ChigiSoftError && error.status === 404) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Fetch a single menu by its name (e.g., 'header', 'footer').\n */\n public async getMenuByName(name: string, options?: ChigiSoftRequestInit): Promise<CMSMenu | null> {\n const menus = await this.getMenus(options);\n return menus.find(m => m.name === name) || null;\n }\n\n /**\n * Mounts the ChigiSoft CMS Studio interface (login/dashboard) inside a container.\n * Works in Next.js, Nuxt.js, HTML, PHP, and any other environment.\n */\n public mountStudio(\n target: string | HTMLElement,\n options?: {\n /**\n * Custom URL for the CMS Studio dashboard.\n * @default The client config's baseUrl (without api/v1/v1 paths)\n */\n studioUrl?: string;\n /**\n * Custom styling for the iframe container.\n */\n style?: Partial<CSSStyleDeclaration>;\n }\n ): HTMLIFrameElement {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new Error('[ChigiSoft SDK] mountStudio can only be called in a browser environment.');\n }\n\n let container: HTMLElement | null = null;\n if (typeof target === 'string') {\n container = document.querySelector(target);\n } else {\n container = target;\n }\n\n if (!container) {\n throw new Error(`[ChigiSoft SDK] Target container element not found: ${target}`);\n }\n\n const baseUrl = options?.studioUrl || this.config.baseUrl.replace(/\\/v1\\/?$/, '').replace(/\\/api\\/v1\\/?$/, '').replace(/\\/+$/, '');\n \n // Construct the embed URL passing project ID and Token\n const url = new URL(baseUrl);\n url.searchParams.set('projectId', this.config.projectId);\n url.searchParams.set('token', this.config.token);\n url.searchParams.set('embed', 'true');\n\n // Create the iframe\n const iframe = document.createElement('iframe');\n iframe.src = url.toString();\n iframe.setAttribute('frameborder', '0');\n iframe.setAttribute('allow', 'clipboard-write');\n \n // Default styling to fill the container nicely\n const defaultStyles: Partial<CSSStyleDeclaration> = {\n width: '100%',\n height: '100%',\n minHeight: '650px',\n border: 'none',\n };\n\n const finalStyles = { ...defaultStyles, ...options?.style };\n Object.assign(iframe.style, finalStyles);\n\n // Empty container and append iframe\n container.innerHTML = '';\n container.appendChild(iframe);\n\n return iframe;\n }\n\n /**\n * Generic request wrapper to handle responses and errors using fetch.\n */\n private async request<T>(url: string, requestConfig?: ChigiSoftRequestInit): Promise<T> {\n const fetchFn = this.config.fetch || globalThis.fetch;\n if (!fetchFn) {\n throw new Error('[ChigiSoft SDK] No fetch implementation found. Ensure you are in a supported environment or pass a custom fetch implementation.');\n }\n\n const baseUrl = this.config.baseUrl.replace(/\\/+$/, '');\n const cleanUrl = url.startsWith('/') ? url : `/${url}`;\n \n // Construct Query Parameters\n let fullUrl = `${baseUrl}${cleanUrl}`;\n if (requestConfig?.params) {\n const searchParams = new URLSearchParams();\n Object.entries(requestConfig.params).forEach(([key, value]) => {\n if (value !== undefined) {\n searchParams.append(key, String(value));\n }\n });\n const queryStr = searchParams.toString();\n if (queryStr) {\n fullUrl += `?${queryStr}`;\n }\n }\n\n const headers: Record<string, string> = {\n 'x-project-id': this.config.projectId,\n 'Authorization': `Bearer ${this.config.token}`,\n 'Content-Type': 'application/json',\n ...((requestConfig?.headers as Record<string, string>) || {}),\n };\n\n if (this.config.apiVersion) {\n headers['x-api-version'] = this.config.apiVersion;\n }\n\n // Set client-side Cache-Control header if useCdn is true\n if (this.config.useCdn) {\n headers['Cache-Control'] = 'max-age=60';\n }\n\n // Extract framework specific options (e.g. next, cache) and exclude params\n const { params, ...fetchOptions } = requestConfig || {};\n\n try {\n const response = await fetchFn(fullUrl, {\n method: 'GET',\n headers,\n ...fetchOptions,\n });\n\n if (!response.ok) {\n let message = 'API request failed';\n try {\n const errData = await response.json();\n message = errData?.message || message;\n } catch {}\n throw new ChigiSoftError(`[ChigiSoft SDK] ${message}`, response.status, response);\n }\n\n const json = await response.json() as any;\n return (json && json.data !== undefined) ? json.data : json;\n } catch (error: any) {\n if (error instanceof ChigiSoftError) {\n throw error;\n }\n throw new ChigiSoftError(`[ChigiSoft SDK] ${error.message || 'API request failed'}`);\n }\n }\n}\n\nexport function createClient(config?: ChigiSoftConfig): ChigiSoftClient {\n return new ChigiSoftClient(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqGO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAIxC,YAAY,SAAiB,QAAiB,UAAqB;AACjE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,WAAW;AAAA,EAClB;AACF;AAEO,IAAM,kBAAN,MAAsB;AAAA,EAM3B,YAAY,SAA0B,CAAC,GAAG;AACxC,UAAM,iBAAiB;AAGvB,UAAM,MAAO,WAAmB,SAAS,OAAO,CAAC;AACjD,UAAM,YAAY,OAAO,aAAa,IAAI,wBAAwB;AAClE,UAAM,QAAQ,OAAO,SAAS,IAAI,uBAAuB;AAEzD,QAAI,CAAC,WAAW;AACd,YAAM,IAAI,MAAM,2FAA2F;A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AAS,aAAa,QAA2C;AACtE,SAAO,IAAI,gBAAgB,MAAM;AACnC;","names":[]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var ChigiSoftError = class extends Error {
|
|
3
|
+
constructor(message, status, response) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "ChigiSoftError";
|
|
6
|
+
this.status = status;
|
|
7
|
+
this.response = response;
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var ChigiSoftClient = class {
|
|
11
|
+
constructor(config = {}) {
|
|
12
|
+
const defaultBaseUrl = "https://cms-api.staging.chigisoft.co/";
|
|
13
|
+
const env = globalThis.process?.env || {};
|
|
14
|
+
const projectId = config.projectId || env.CHIGISOFT_PROJECT_ID || "";
|
|
15
|
+
const token = config.token || env.CHIGISOFT_API_TOKEN || "";
|
|
16
|
+
if (!projectId) {
|
|
17
|
+
throw new Error("[ChigiSoft SDK] Missing required option: projectId (or CHIGISOFT_PROJECT_ID env variable)");
|
|
18
|
+
}
|
|
19
|
+
if (!token) {
|
|
20
|
+
throw new Error("[ChigiSoft SDK] Missing required option: token (or CHIGISOFT_API_TOKEN env variable)");
|
|
21
|
+
}
|
|
22
|
+
this.config = {
|
|
23
|
+
baseUrl: config.baseUrl || defaultBaseUrl,
|
|
24
|
+
projectId,
|
|
25
|
+
token,
|
|
26
|
+
useCdn: config.useCdn ?? false,
|
|
27
|
+
apiVersion: config.apiVersion,
|
|
28
|
+
fetch: config.fetch
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Generic fetch method to query custom endpoints or arbitrary CMS paths.
|
|
33
|
+
*/
|
|
34
|
+
async fetch(path, options) {
|
|
35
|
+
return this.request(path, options);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Fetch all pages associated with the project.
|
|
39
|
+
*/
|
|
40
|
+
async getPages(options) {
|
|
41
|
+
const params = { pageType: "PAGE", ...options?.params || {} };
|
|
42
|
+
return this.request(`/v1/projects/${this.config.projectId}/pages`, {
|
|
43
|
+
...options,
|
|
44
|
+
params
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Fetch a single page by its slug or ID.
|
|
49
|
+
*/
|
|
50
|
+
async getPageBySlug(slug, options) {
|
|
51
|
+
const pages = await this.getPages(options);
|
|
52
|
+
return pages.find((p) => p.slug === slug || p.id === slug) || null;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Fetch all blog posts associated with the project.
|
|
56
|
+
*/
|
|
57
|
+
async getBlogs(options) {
|
|
58
|
+
const params = { pageType: "ARTICLE", category: "BLOG", ...options?.params || {} };
|
|
59
|
+
return this.request(`/v1/projects/${this.config.projectId}/pages`, {
|
|
60
|
+
...options,
|
|
61
|
+
params
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Fetch a single blog post by its slug or ID.
|
|
66
|
+
*/
|
|
67
|
+
async getBlogBySlug(slug, options) {
|
|
68
|
+
const blogs = await this.getBlogs(options);
|
|
69
|
+
return blogs.find((b) => b.slug === slug || b.id === slug) || null;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Fetch all testimonies associated with the project.
|
|
73
|
+
*/
|
|
74
|
+
async getTestimonies(options) {
|
|
75
|
+
const params = { pageType: "ARTICLE", category: "GENERAL", ...options?.params || {} };
|
|
76
|
+
const articles = await this.request(`/v1/projects/${this.config.projectId}/pages`, {
|
|
77
|
+
...options,
|
|
78
|
+
params
|
|
79
|
+
});
|
|
80
|
+
return articles.filter((p) => p.tags && p.tags.includes("testimonial"));
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Fetch a single testimony by its slug or ID.
|
|
84
|
+
*/
|
|
85
|
+
async getTestimonyBySlug(slug, options) {
|
|
86
|
+
const testimonies = await this.getTestimonies(options);
|
|
87
|
+
return testimonies.find((t) => t.slug === slug || t.id === slug) || null;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Fetch all menus associated with the project.
|
|
91
|
+
*/
|
|
92
|
+
async getMenus(options) {
|
|
93
|
+
return this.request(`/v1/projects/${this.config.projectId}/menus`, options);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Fetch a single menu by its ID.
|
|
97
|
+
*/
|
|
98
|
+
async getMenuById(id, options) {
|
|
99
|
+
try {
|
|
100
|
+
return await this.request(`/v1/menus/${id}`, options);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
if (error instanceof ChigiSoftError && error.status === 404) {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Fetch a single menu by its name (e.g., 'header', 'footer').
|
|
110
|
+
*/
|
|
111
|
+
async getMenuByName(name, options) {
|
|
112
|
+
const menus = await this.getMenus(options);
|
|
113
|
+
return menus.find((m) => m.name === name) || null;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Mounts the ChigiSoft CMS Studio interface (login/dashboard) inside a container.
|
|
117
|
+
* Works in Next.js, Nuxt.js, HTML, PHP, and any other environment.
|
|
118
|
+
*/
|
|
119
|
+
mountStudio(target, options) {
|
|
120
|
+
if (typeof window === "undefined" || typeof document === "undefined") {
|
|
121
|
+
throw new Error("[ChigiSoft SDK] mountStudio can only be called in a browser environment.");
|
|
122
|
+
}
|
|
123
|
+
let container = null;
|
|
124
|
+
if (typeof target === "string") {
|
|
125
|
+
container = document.querySelector(target);
|
|
126
|
+
} else {
|
|
127
|
+
container = target;
|
|
128
|
+
}
|
|
129
|
+
if (!container) {
|
|
130
|
+
throw new Error(`[ChigiSoft SDK] Target container element not found: ${target}`);
|
|
131
|
+
}
|
|
132
|
+
const baseUrl = options?.studioUrl || this.config.baseUrl.replace(/\/v1\/?$/, "").replace(/\/api\/v1\/?$/, "").replace(/\/+$/, "");
|
|
133
|
+
const url = new URL(baseUrl);
|
|
134
|
+
url.searchParams.set("projectId", this.config.projectId);
|
|
135
|
+
url.searchParams.set("token", this.config.token);
|
|
136
|
+
url.searchParams.set("embed", "true");
|
|
137
|
+
const iframe = document.createElement("iframe");
|
|
138
|
+
iframe.src = url.toString();
|
|
139
|
+
iframe.setAttribute("frameborder", "0");
|
|
140
|
+
iframe.setAttribute("allow", "clipboard-write");
|
|
141
|
+
const defaultStyles = {
|
|
142
|
+
width: "100%",
|
|
143
|
+
height: "100%",
|
|
144
|
+
minHeight: "650px",
|
|
145
|
+
border: "none"
|
|
146
|
+
};
|
|
147
|
+
const finalStyles = { ...defaultStyles, ...options?.style };
|
|
148
|
+
Object.assign(iframe.style, finalStyles);
|
|
149
|
+
container.innerHTML = "";
|
|
150
|
+
container.appendChild(iframe);
|
|
151
|
+
return iframe;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Generic request wrapper to handle responses and errors using fetch.
|
|
155
|
+
*/
|
|
156
|
+
async request(url, requestConfig) {
|
|
157
|
+
const fetchFn = this.config.fetch || globalThis.fetch;
|
|
158
|
+
if (!fetchFn) {
|
|
159
|
+
throw new Error("[ChigiSoft SDK] No fetch implementation found. Ensure you are in a supported environment or pass a custom fetch implementation.");
|
|
160
|
+
}
|
|
161
|
+
const baseUrl = this.config.baseUrl.replace(/\/+$/, "");
|
|
162
|
+
const cleanUrl = url.startsWith("/") ? url : `/${url}`;
|
|
163
|
+
let fullUrl = `${baseUrl}${cleanUrl}`;
|
|
164
|
+
if (requestConfig?.params) {
|
|
165
|
+
const searchParams = new URLSearchParams();
|
|
166
|
+
Object.entries(requestConfig.params).forEach(([key, value]) => {
|
|
167
|
+
if (value !== void 0) {
|
|
168
|
+
searchParams.append(key, String(value));
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
const queryStr = searchParams.toString();
|
|
172
|
+
if (queryStr) {
|
|
173
|
+
fullUrl += `?${queryStr}`;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const headers = {
|
|
177
|
+
"x-project-id": this.config.projectId,
|
|
178
|
+
"Authorization": `Bearer ${this.config.token}`,
|
|
179
|
+
"Content-Type": "application/json",
|
|
180
|
+
...requestConfig?.headers || {}
|
|
181
|
+
};
|
|
182
|
+
if (this.config.apiVersion) {
|
|
183
|
+
headers["x-api-version"] = this.config.apiVersion;
|
|
184
|
+
}
|
|
185
|
+
if (this.config.useCdn) {
|
|
186
|
+
headers["Cache-Control"] = "max-age=60";
|
|
187
|
+
}
|
|
188
|
+
const { params, ...fetchOptions } = requestConfig || {};
|
|
189
|
+
try {
|
|
190
|
+
const response = await fetchFn(fullUrl, {
|
|
191
|
+
method: "GET",
|
|
192
|
+
headers,
|
|
193
|
+
...fetchOptions
|
|
194
|
+
});
|
|
195
|
+
if (!response.ok) {
|
|
196
|
+
let message = "API request failed";
|
|
197
|
+
try {
|
|
198
|
+
const errData = await response.json();
|
|
199
|
+
message = errData?.message || message;
|
|
200
|
+
} catch {
|
|
201
|
+
}
|
|
202
|
+
throw new ChigiSoftError(`[ChigiSoft SDK] ${message}`, response.status, response);
|
|
203
|
+
}
|
|
204
|
+
const json = await response.json();
|
|
205
|
+
return json && json.data !== void 0 ? json.data : json;
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if (error instanceof ChigiSoftError) {
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
throw new ChigiSoftError(`[ChigiSoft SDK] ${error.message || "API request failed"}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
function createClient(config) {
|
|
215
|
+
return new ChigiSoftClient(config);
|
|
216
|
+
}
|
|
217
|
+
export {
|
|
218
|
+
ChigiSoftClient,
|
|
219
|
+
ChigiSoftError,
|
|
220
|
+
createClient
|
|
221
|
+
};
|
|
222
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export interface ChigiSoftConfig {\n /**\n * The base URL of the ChigiSoft CMS backend API.\n * @default 'https://cms-api.staging.chigisoft.co/'\n */\n baseUrl?: string;\n /**\n * The unique ID of the project. If not provided, it will fallback to process.env.CHIGISOFT_PROJECT_ID\n */\n projectId?: string;\n /**\n * The personalized API token. If not provided, it will fallback to process.env.CHIGISOFT_API_TOKEN\n */\n token?: string;\n /**\n * Optional boolean to toggle using a cached CDN endpoint or cache headers.\n */\n useCdn?: boolean;\n /**\n * Optional custom fetch implementation (e.g., node-fetch, or Next.js fetch wrapper).\n */\n fetch?: typeof fetch;\n /**\n * Optional API version parameter.\n */\n apiVersion?: string;\n}\n\nexport interface ChigiSoftRequestInit extends Omit<RequestInit, 'method'> {\n /**\n * Optional query parameters to append to the URL.\n */\n params?: Record<string, string | number | boolean | undefined>;\n}\n\nexport interface CMSBlock {\n id: string;\n type: string;\n content: Record<string, any>;\n [key: string]: any;\n}\n\nexport interface CMSPage {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n description?: string;\n blocks: CMSBlock[];\n published: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CMSBlog {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n description?: string;\n blocks: CMSBlock[];\n published: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface CMSTestimony {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n description?: string;\n blocks: CMSBlock[];\n published: boolean;\n createdAt: string;\n updatedAt: string;\n tags?: string[];\n [key: string]: any;\n}\n\nexport interface CMSMenuItem {\n id: string;\n label: string;\n url: string | null;\n pageId: string | null;\n order: number;\n parentId: string | null;\n menuId: string;\n openInNewTab: boolean;\n [key: string]: any;\n}\n\nexport interface CMSMenu {\n id: string;\n name: string;\n projectId: string;\n createdAt: string;\n updatedAt: string;\n items: CMSMenuItem[];\n}\n\nexport class ChigiSoftError extends Error {\n status?: number;\n response?: Response;\n\n constructor(message: string, status?: number, response?: Response) {\n super(message);\n this.name = 'ChigiSoftError';\n this.status = status;\n this.response = response;\n }\n}\n\nexport class ChigiSoftClient {\n private config: Required<Omit<ChigiSoftConfig, 'fetch' | 'apiVersion'>> & {\n apiVersion?: string;\n fetch?: typeof fetch;\n };\n\n constructor(config: ChigiSoftConfig = {}) {\n const defaultBaseUrl = 'https://cms-api.staging.chigisoft.co/';\n \n // Safely extract environment variables across environments (Node, Next, Nuxt, Vite)\n const env = (globalThis as any).process?.env || {};\n const projectId = config.projectId || env.CHIGISOFT_PROJECT_ID || '';\n const token = config.token || env.CHIGISOFT_API_TOKEN || '';\n\n if (!projectId) {\n throw new Error('[ChigiSoft SDK] Missing required option: projectId (or CHIGISOFT_PROJECT_ID env variable)');\n }\n if (!token) {\n throw new Error('[ChigiSoft SDK] Missing required option: token (or CHIGISOFT_API_TOKEN env variable)');\n }\n\n this.config = {\n baseUrl: config.baseUrl || defaultBaseUrl,\n projectId,\n token,\n useCdn: config.useCdn ?? false,\n apiVersion: config.apiVersion,\n fetch: config.fetch,\n };\n }\n\n /**\n * Generic fetch method to query custom endpoints or arbitrary CMS paths.\n */\n public async fetch<T>(path: string, options?: ChigiSoftRequestInit): Promise<T> {\n return this.request<T>(path, options);\n }\n\n /**\n * Fetch all pages associated with the project.\n */\n public async getPages(options?: ChigiSoftRequestInit): Promise<CMSPage[]> {\n const params = { pageType: 'PAGE', ...(options?.params || {}) };\n return this.request<CMSPage[]>(`/v1/projects/${this.config.projectId}/pages`, {\n ...options,\n params,\n });\n }\n\n /**\n * Fetch a single page by its slug or ID.\n */\n public async getPageBySlug(slug: string, options?: ChigiSoftRequestInit): Promise<CMSPage | null> {\n const pages = await this.getPages(options);\n return pages.find(p => p.slug === slug || p.id === slug) || null;\n }\n\n /**\n * Fetch all blog posts associated with the project.\n */\n public async getBlogs(options?: ChigiSoftRequestInit): Promise<CMSBlog[]> {\n const params = { pageType: 'ARTICLE', category: 'BLOG', ...(options?.params || {}) };\n return this.request<CMSBlog[]>(`/v1/projects/${this.config.projectId}/pages`, {\n ...options,\n params,\n });\n }\n\n /**\n * Fetch a single blog post by its slug or ID.\n */\n public async getBlogBySlug(slug: string, options?: ChigiSoftRequestInit): Promise<CMSBlog | null> {\n const blogs = await this.getBlogs(options);\n return blogs.find(b => b.slug === slug || b.id === slug) || null;\n }\n\n /**\n * Fetch all testimonies associated with the project.\n */\n public async getTestimonies(options?: ChigiSoftRequestInit): Promise<CMSTestimony[]> {\n const params = { pageType: 'ARTICLE', category: 'GENERAL', ...(options?.params || {}) };\n const articles = await this.request<CMSTestimony[]>(`/v1/projects/${this.config.projectId}/pages`, {\n ...options,\n params,\n });\n return articles.filter(p => p.tags && p.tags.includes('testimonial'));\n }\n\n /**\n * Fetch a single testimony by its slug or ID.\n */\n public async getTestimonyBySlug(slug: string, options?: ChigiSoftRequestInit): Promise<CMSTestimony | null> {\n const testimonies = await this.getTestimonies(options);\n return testimonies.find(t => t.slug === slug || t.id === slug) || null;\n }\n\n /**\n * Fetch all menus associated with the project.\n */\n public async getMenus(options?: ChigiSoftRequestInit): Promise<CMSMenu[]> {\n return this.request<CMSMenu[]>(`/v1/projects/${this.config.projectId}/menus`, options);\n }\n\n /**\n * Fetch a single menu by its ID.\n */\n public async getMenuById(id: string, options?: ChigiSoftRequestInit): Promise<CMSMenu | null> {\n try {\n return await this.request<CMSMenu>(`/v1/menus/${id}`, options);\n } catch (error) {\n if (error instanceof ChigiSoftError && error.status === 404) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Fetch a single menu by its name (e.g., 'header', 'footer').\n */\n public async getMenuByName(name: string, options?: ChigiSoftRequestInit): Promise<CMSMenu | null> {\n const menus = await this.getMenus(options);\n return menus.find(m => m.name === name) || null;\n }\n\n /**\n * Mounts the ChigiSoft CMS Studio interface (login/dashboard) inside a container.\n * Works in Next.js, Nuxt.js, HTML, PHP, and any other environment.\n */\n public mountStudio(\n target: string | HTMLElement,\n options?: {\n /**\n * Custom URL for the CMS Studio dashboard.\n * @default The client config's baseUrl (without api/v1/v1 paths)\n */\n studioUrl?: string;\n /**\n * Custom styling for the iframe container.\n */\n style?: Partial<CSSStyleDeclaration>;\n }\n ): HTMLIFrameElement {\n if (typeof window === 'undefined' || typeof document === 'undefined') {\n throw new Error('[ChigiSoft SDK] mountStudio can only be called in a browser environment.');\n }\n\n let container: HTMLElement | null = null;\n if (typeof target === 'string') {\n container = document.querySelector(target);\n } else {\n container = target;\n }\n\n if (!container) {\n throw new Error(`[ChigiSoft SDK] Target container element not found: ${target}`);\n }\n\n const baseUrl = options?.studioUrl || this.config.baseUrl.replace(/\\/v1\\/?$/, '').replace(/\\/api\\/v1\\/?$/, '').replace(/\\/+$/, '');\n \n // Construct the embed URL passing project ID and Token\n const url = new URL(baseUrl);\n url.searchParams.set('projectId', this.config.projectId);\n url.searchParams.set('token', this.config.token);\n url.searchParams.set('embed', 'true');\n\n // Create the iframe\n const iframe = document.createElement('iframe');\n iframe.src = url.toString();\n iframe.setAttribute('frameborder', '0');\n iframe.setAttribute('allow', 'clipboard-write');\n \n // Default styling to fill the container nicely\n const defaultStyles: Partial<CSSStyleDeclaration> = {\n width: '100%',\n height: '100%',\n minHeight: '650px',\n border: 'none',\n };\n\n const finalStyles = { ...defaultStyles, ...options?.style };\n Object.assign(iframe.style, finalStyles);\n\n // Empty container and append iframe\n container.innerHTML = '';\n container.appendChild(iframe);\n\n return iframe;\n }\n\n /**\n * Generic request wrapper to handle responses and errors using fetch.\n */\n private async request<T>(url: string, requestConfig?: ChigiSoftRequestInit): Promise<T> {\n const fetchFn = this.config.fetch || globalThis.fetch;\n if (!fetchFn) {\n throw new Error('[ChigiSoft SDK] No fetch implementation found. Ensure you are in a supported environment or pass a custom fetch implementation.');\n }\n\n const baseUrl = this.config.baseUrl.replace(/\\/+$/, '');\n const cleanUrl = url.startsWith('/') ? url : `/${url}`;\n \n // Construct Query Parameters\n let fullUrl = `${baseUrl}${cleanUrl}`;\n if (requestConfig?.params) {\n const searchParams = new URLSearchParams();\n Object.entries(requestConfig.params).forEach(([key, value]) => {\n if (value !== undefined) {\n searchParams.append(key, String(value));\n }\n });\n const queryStr = searchParams.toString();\n if (queryStr) {\n fullUrl += `?${queryStr}`;\n }\n }\n\n const headers: Record<string, string> = {\n 'x-project-id': this.config.projectId,\n 'Authorization': `Bearer ${this.config.token}`,\n 'Content-Type': 'application/json',\n ...((requestConfig?.headers as Record<string, string>) || {}),\n };\n\n if (this.config.apiVersion) {\n headers['x-api-version'] = this.config.apiVersion;\n }\n\n // Set client-side Cache-Control header if useCdn is true\n if (this.config.useCdn) {\n headers['Cache-Control'] = 'max-age=60';\n }\n\n // Extract framework specific options (e.g. next, cache) and exclude params\n const { params, ...fetchOptions } = requestConfig || {};\n\n try {\n const response = await fetchFn(fullUrl, {\n method: 'GET',\n headers,\n ...fetchOptions,\n });\n\n if (!response.ok) {\n let message = 'API request failed';\n try {\n const errData = await response.json();\n message = errData?.message || message;\n } catch {}\n throw new ChigiSoftError(`[ChigiSoft SDK] ${message}`, response.status, response);\n }\n\n const json = await response.json() as any;\n return (json && json.data !== undefined) ? json.data : json;\n } catch (error: any) {\n if (error instanceof ChigiSoftError) {\n throw error;\n }\n throw new ChigiSoftError(`[ChigiSoft SDK] ${error.message || 'API request failed'}`);\n }\n }\n}\n\nexport function createClient(config?: ChigiSoftConfig): ChigiSoftClient {\n return new ChigiSoftClient(config);\n}\n"],"mappings":";AAqGO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAIxC,YAAY,SAAiB,QAAiB,UAAqB;AACjE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,WAAW;AAAA,EAClB;AACF;AAEO,IAAM,kBAAN,MAAsB;AAAA,EAM3B,YAAY,SAA0B,CAAC,GAAG;AACxC,UAAM,iBAAiB;AAGvB,UAAM,MAAO,WAAmB,SAAS,OAAO,CAAC;AACjD,UAAM,YAAY,OAAO,aAAa,IAAI,wBAAwB;AAClE,UAAM,QAAQ,OAAO,SAAS,IAAI,uBAAuB;AAEzD,QAAI,CAAC,WAAW;AACd,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ACrF;AAAA,EACF;AACF;AAEO,SAAS,aAAa,QAA2C;AACtE,SAAO,IAAI,gBAAgB,MAAM;AACnC;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@chigisoft-web/cms-sdk",
|
|
3
|
+
"version": "1.0.3",
|
|
4
|
+
"description": "SDK client for ChigiSoft CMS",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"require": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"bin": {
|
|
16
|
+
"chigisoft": "./dist/cli.js"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsup",
|
|
23
|
+
"dev": "tsup --watch"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"tsup": "^8.0.2",
|
|
27
|
+
"typescript": "^5.3.3"
|
|
28
|
+
}
|
|
29
|
+
}
|