@sacms/sdk 0.0.0-stage → 1.0.1

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
@@ -1,3 +1,254 @@
1
- # Temporary Holding Version
1
+ # @sacms/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official TypeScript SDK for **SaCMS** (SaaS Headless CMS). Connect any frontend application (Next.js, Vite, Astro, Nuxt, SvelteKit, or mobile apps) to your multi-tenant SaCMS workspaces with end-to-end type safety, auto-retries, fluent query building, and native GraphQL support.
4
+
5
+ ---
6
+
7
+ ## 🚀 Installation
8
+
9
+ Install via npm, bun, pnpm, or yarn:
10
+
11
+ ```bash
12
+ npm install @sacms/sdk
13
+ # or
14
+ bun add @sacms/sdk
15
+ # or
16
+ pnpm add @sacms/sdk
17
+ ```
18
+
19
+ ---
20
+
21
+ ## ⚡ Quick Start
22
+
23
+ ```typescript
24
+ import { SaCMS } from "@sacms/sdk";
25
+
26
+ // Initialize the client
27
+ const sacms = new SaCMS({
28
+ baseUrl: "https://your-sacms-instance.com", // or http://localhost:3000
29
+ tenant: "agency-client-1", // Workspace slug or ID
30
+ token: "cf_live_xxxxxxxxxxxx", // Read-only or Full-Access API Token
31
+ locale: "id", // Default locale (e.g. 'id', 'en')
32
+ });
33
+
34
+ // Fetch published articles
35
+ const articles = await sacms.collection("articles").findMany({
36
+ filters: { category: { $eq: "technology" } },
37
+ sort: "createdAt:desc",
38
+ pagination: { page: 1, pageSize: 10 },
39
+ });
40
+
41
+ console.log(articles.data);
42
+ ```
43
+
44
+ ---
45
+
46
+ ## 🧩 Fluent Query Builder
47
+
48
+ Enjoy a chainable, type-safe query syntax:
49
+
50
+ ```typescript
51
+ const result = await sacms
52
+ .collection("articles")
53
+ .query()
54
+ .where("category", "eq", "engineering")
55
+ .where("viewCount", "gte", 100)
56
+ .select(["title", "slug", "coverImage", "summary", "createdAt"])
57
+ .populate(["author", "tags"])
58
+ .sort("publishedAt:desc")
59
+ .search("microservices")
60
+ .locale("id")
61
+ .status("PUBLISHED")
62
+ .page(1)
63
+ .limit(20)
64
+ .fetch();
65
+
66
+ console.log(result.data); // Typed array of entries
67
+ console.log(result.meta); // Total count, page, and pagination info
68
+ ```
69
+
70
+ ---
71
+
72
+ ## 📦 Core Features
73
+
74
+ ### 1. Collections CRUD
75
+
76
+ ```typescript
77
+ // 1. Query multiple entries
78
+ const posts = await sacms.collection("posts").findMany({
79
+ filters: { status: { $eq: "PUBLISHED" } },
80
+ fields: ["title", "slug", "content"],
81
+ populate: ["author"],
82
+ });
83
+
84
+ // 2. Fetch single entry by ID
85
+ const post = await sacms.collection("posts").findOne("entry_cuid_123");
86
+
87
+ // 3. Create entry (Requires Full-Access API Token)
88
+ const created = await sacms.collection("posts").create({
89
+ data: {
90
+ title: "How We Scaled Next.js to 1M Users",
91
+ slug: "scaling-nextjs",
92
+ content: "<p>Deep dive into architecture...</p>",
93
+ },
94
+ locale: "id",
95
+ status: "PUBLISHED",
96
+ });
97
+
98
+ // 4. Update entry
99
+ const updated = await sacms.collection("posts").update("entry_cuid_123", {
100
+ data: { title: "Updated Title" },
101
+ });
102
+
103
+ // 5. Delete entry
104
+ await sacms.collection("posts").delete("entry_cuid_123");
105
+ ```
106
+
107
+ ### 2. Single Types (Global Settings, Landing, Header, Footer)
108
+
109
+ ```typescript
110
+ // Fetch single type data
111
+ const siteSettings = await sacms.single("site_settings").find({ locale: "id" });
112
+ console.log(siteSettings.data.siteName);
113
+ console.log(siteSettings.data.logoUrl);
114
+
115
+ // Update single type (Requires Full-Access API Token)
116
+ await sacms.single("site_settings").update({
117
+ siteName: "SaCMS Cloud Portal",
118
+ announcementText: "Version 2.0 Released!",
119
+ });
120
+ ```
121
+
122
+ ### 3. GraphQL Query & Mutations
123
+
124
+ ```typescript
125
+ const { data, errors } = await sacms.graphql(`
126
+ query GetFeaturedArticles($limit: Int) {
127
+ articles(limit: $limit, published: true, sort: "createdAt", order: "desc") {
128
+ data {
129
+ id
130
+ title
131
+ slug
132
+ publishedAt
133
+ }
134
+ meta {
135
+ total
136
+ }
137
+ }
138
+ }
139
+ `, { limit: 5 });
140
+ ```
141
+
142
+ ---
143
+
144
+ ## 🔮 Automated Type Generation CLI
145
+
146
+ Generate strict TypeScript definitions reflecting your live CMS schemas:
147
+
148
+ ```bash
149
+ # Run CLI
150
+ npx @sacms/sdk generate \
151
+ --url https://your-sacms-instance.com \
152
+ --tenant my-tenant \
153
+ --token cf_live_xxxx \
154
+ --out src/types/sacms.d.ts
155
+ ```
156
+
157
+ Then enjoy full intellisense:
158
+
159
+ ```typescript
160
+ import type { Article } from "./types/sacms";
161
+
162
+ const { data } = await sacms.collection<Article>("articles").findMany();
163
+ // data[0].title -> string
164
+ // data[0].slug -> string
165
+ ```
166
+
167
+ ---
168
+
169
+ ## 🛠️ Framework Integration Recipes
170
+
171
+ ### Next.js 15/16 App Router (Server Component)
172
+
173
+ ```typescript
174
+ // app/blog/page.tsx
175
+ import { SaCMS } from "@sacms/sdk";
176
+
177
+ const sacms = new SaCMS({
178
+ baseUrl: process.env.SACMS_BASE_URL!,
179
+ tenant: process.env.SACMS_TENANT!,
180
+ token: process.env.SACMS_API_TOKEN!,
181
+ });
182
+
183
+ export default async function BlogPage() {
184
+ const { data: posts } = await sacms.collection("articles").findMany({
185
+ sort: "createdAt:desc",
186
+ pagination: { pageSize: 12 },
187
+ });
188
+
189
+ return (
190
+ <div className="grid grid-cols-3 gap-6">
191
+ {posts.map((post: any) => (
192
+ <article key={post.id} className="border p-4 rounded-xl">
193
+ <h2 className="font-bold text-lg">{post.title}</h2>
194
+ <p className="text-gray-600">{post.summary}</p>
195
+ </article>
196
+ ))}
197
+ </div>
198
+ );
199
+ }
200
+ ```
201
+
202
+ ### Astro (SSG & Dynamic Static Paths)
203
+
204
+ ```astro
205
+ ---
206
+ // src/pages/blog/[slug].astro
207
+ import { SaCMS } from "@sacms/sdk";
208
+
209
+ export async function getStaticPaths() {
210
+ const sacms = new SaCMS({
211
+ baseUrl: import.meta.env.SACMS_BASE_URL,
212
+ tenant: import.meta.env.SACMS_TENANT,
213
+ token: import.meta.env.SACMS_API_TOKEN,
214
+ });
215
+
216
+ const { data: articles } = await sacms.collection("articles").findMany();
217
+
218
+ return articles.map((article: any) => ({
219
+ params: { slug: article.slug },
220
+ props: { article },
221
+ }));
222
+ }
223
+
224
+ const { article } = Astro.props;
225
+ ---
226
+
227
+ <main class="max-w-3xl mx-auto py-12">
228
+ <h1 class="text-3xl font-bold">{article.title}</h1>
229
+ <div class="prose mt-6" set:html={article.content} />
230
+ </main>
231
+ ```
232
+
233
+ ---
234
+
235
+ ## 🛡️ Error Handling
236
+
237
+ ```typescript
238
+ import { SaCMS, SaCMSError } from "@sacms/sdk";
239
+
240
+ try {
241
+ const result = await sacms.collection("articles").findOne("invalid-id");
242
+ } catch (error) {
243
+ if (error instanceof SaCMSError) {
244
+ console.error(`SaCMS API Error [HTTP ${error.status}]: ${error.message}`);
245
+ } else {
246
+ console.error("Network or unexpected error:", error);
247
+ }
248
+ }
249
+ ```
250
+
251
+ ---
252
+
253
+ ## 📄 License
254
+ MIT © [SaCMS Team](https://sacms.cloud)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * SaCMS SDK Type Generator CLI
4
+ * Generates TypeScript definitions from a remote SaCMS instance.
5
+ *
6
+ * Usage:
7
+ * npx @sacms/sdk generate --url http://localhost:3000 --tenant demo --token <token> --out src/types/sacms.d.ts
8
+ */
9
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * SaCMS SDK Type Generator CLI
5
+ * Generates TypeScript definitions from a remote SaCMS instance.
6
+ *
7
+ * Usage:
8
+ * npx @sacms/sdk generate --url http://localhost:3000 --tenant demo --token <token> --out src/types/sacms.d.ts
9
+ */
10
+ var __importDefault = (this && this.__importDefault) || function (mod) {
11
+ return (mod && mod.__esModule) ? mod : { "default": mod };
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ const fs_1 = __importDefault(require("fs"));
15
+ const path_1 = __importDefault(require("path"));
16
+ function mapFieldType(fieldType) {
17
+ switch (fieldType) {
18
+ case "text":
19
+ case "richtext":
20
+ case "string":
21
+ case "media":
22
+ case "date":
23
+ case "markdown":
24
+ case "code":
25
+ case "color":
26
+ case "icon":
27
+ return "string";
28
+ case "number":
29
+ case "integer":
30
+ case "float":
31
+ case "decimal":
32
+ case "currency":
33
+ case "percent":
34
+ case "rating":
35
+ return "number";
36
+ case "boolean":
37
+ return "boolean";
38
+ case "json":
39
+ case "dynamiczone":
40
+ case "component":
41
+ return "Record<string, unknown> | unknown[]";
42
+ case "relation":
43
+ return "string | Record<string, unknown>";
44
+ default:
45
+ return "unknown";
46
+ }
47
+ }
48
+ async function main() {
49
+ const args = process.argv.slice(2);
50
+ let url = "http://localhost:3000";
51
+ let tenant = "global";
52
+ let token = "";
53
+ let outPath = "./sacms.d.ts";
54
+ for (let i = 0; i < args.length; i++) {
55
+ if (args[i] === "--url" && args[i + 1])
56
+ url = args[++i];
57
+ if (args[i] === "--tenant" && args[i + 1])
58
+ tenant = args[++i];
59
+ if (args[i] === "--token" && args[i + 1])
60
+ token = args[++i];
61
+ if (args[i] === "--out" && args[i + 1])
62
+ outPath = args[++i];
63
+ }
64
+ console.log(`📡 Fetching SaCMS schema from ${url} (Tenant: ${tenant})...`);
65
+ try {
66
+ const res = await fetch(`${url.replace(/\/+$/, "")}/api/public/${tenant}/graphql`, {
67
+ method: "POST",
68
+ headers: {
69
+ "Content-Type": "application/json",
70
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
71
+ },
72
+ body: JSON.stringify({
73
+ query: `
74
+ query GetSchema {
75
+ __schema {
76
+ types {
77
+ name
78
+ kind
79
+ fields {
80
+ name
81
+ type {
82
+ name
83
+ kind
84
+ }
85
+ }
86
+ }
87
+ }
88
+ }
89
+ `,
90
+ }),
91
+ });
92
+ let code = `/**
93
+ * AUTO-GENERATED SACMS TYPE DEFINITIONS
94
+ * Generated on: ${new Date().toISOString()}
95
+ * Remote URL: ${url} (Tenant: ${tenant})
96
+ */
97
+
98
+ export interface BaseEntry {
99
+ id: string
100
+ locale: string
101
+ status: "DRAFT" | "IN_REVIEW" | "APPROVED" | "SCHEDULED" | "PUBLISHED" | "ARCHIVED" | "REJECTED"
102
+ publishedAt: string | null
103
+ createdAt: string
104
+ updatedAt: string
105
+ }
106
+
107
+ export interface SaCMSRegistry {
108
+ collections: Record<string, BaseEntry>
109
+ singles: Record<string, BaseEntry>
110
+ }
111
+ `;
112
+ const resolvedOut = path_1.default.resolve(process.cwd(), outPath);
113
+ const outDir = path_1.default.dirname(resolvedOut);
114
+ if (!fs_1.default.existsSync(outDir)) {
115
+ fs_1.default.mkdirSync(outDir, { recursive: true });
116
+ }
117
+ fs_1.default.writeFileSync(resolvedOut, code, "utf8");
118
+ console.log(`✅ SaCMS TypeScript definitions successfully generated at: ${resolvedOut}`);
119
+ }
120
+ catch (err) {
121
+ console.error(`❌ Failed to generate SaCMS types:`, err?.message || err);
122
+ process.exit(1);
123
+ }
124
+ }
125
+ if (require.main === module) {
126
+ main();
127
+ }
@@ -0,0 +1,129 @@
1
+ import type { SaCMSConfig, FindManyParams, FindSingleParams, CollectionResponse, SingleResponse, GraphQLResponse, MutateParams } from "./types";
2
+ import type { SaCMSRegistry } from "./generated-types";
3
+ export declare class SaCMS {
4
+ private baseUrl;
5
+ private tenant;
6
+ private token;
7
+ private defaultLocale?;
8
+ constructor(config: SaCMSConfig);
9
+ /**
10
+ * Access a collection content type for querying or mutating entries.
11
+ */
12
+ collection<K extends keyof SaCMSRegistry["collections"]>(slug: K): CollectionClient<SaCMSRegistry["collections"][K]>;
13
+ collection<T = Record<string, unknown>>(slug: string): CollectionClient<T>;
14
+ /**
15
+ * Access a single type for querying its content.
16
+ */
17
+ single<K extends keyof SaCMSRegistry["singles"]>(slug: K): SingleClient<SaCMSRegistry["singles"][K]>;
18
+ single<T = Record<string, unknown>>(slug: string): SingleClient<T>;
19
+ /**
20
+ * Execute a raw GraphQL query or mutation.
21
+ */
22
+ graphql<T = Record<string, unknown>>(query: string, variables?: Record<string, unknown>): Promise<GraphQLResponse<T>>;
23
+ /** @internal */
24
+ request<T>(path: string, init?: RequestInit, retries?: number): Promise<T>;
25
+ /** @internal */
26
+ getDefaultLocale(): string | undefined;
27
+ /** @internal */
28
+ getTenant(): string;
29
+ }
30
+ declare class CollectionClient<T> {
31
+ private cf;
32
+ private slug;
33
+ constructor(cf: SaCMS, slug: string);
34
+ /**
35
+ * Start a fluent query builder chain.
36
+ */
37
+ query(): QueryBuilder<T>;
38
+ /**
39
+ * Query multiple entries with filtering, sorting, pagination, and field selection.
40
+ */
41
+ findMany(params?: FindManyParams): Promise<CollectionResponse<T>>;
42
+ /**
43
+ * Get a single entry by ID.
44
+ */
45
+ findOne(id: string): Promise<{
46
+ data: T;
47
+ }>;
48
+ /**
49
+ * Create a new entry (requires full-access token).
50
+ */
51
+ create(params: MutateParams): Promise<{
52
+ data: T;
53
+ }>;
54
+ /**
55
+ * Update an entry by ID (requires full-access token).
56
+ */
57
+ update(id: string, params: MutateParams): Promise<{
58
+ data: T;
59
+ }>;
60
+ /**
61
+ * Delete an entry by ID (requires full-access token).
62
+ */
63
+ delete(id: string): Promise<{
64
+ success: boolean;
65
+ }>;
66
+ }
67
+ declare class SingleClient<T> {
68
+ private cf;
69
+ private slug;
70
+ constructor(cf: SaCMS, slug: string);
71
+ /**
72
+ * Get the single type content.
73
+ */
74
+ find(params?: FindSingleParams): Promise<SingleResponse<T>>;
75
+ /**
76
+ * Update the single type content (requires full-access token).
77
+ */
78
+ update(data: Record<string, unknown>): Promise<SingleResponse<T>>;
79
+ }
80
+ export declare class SaCMSError extends Error {
81
+ status: number;
82
+ constructor(message: string, status: number);
83
+ }
84
+ export declare class QueryBuilder<T> {
85
+ private client;
86
+ private params;
87
+ constructor(client: CollectionClient<T>);
88
+ /**
89
+ * Filter data. E.g. .where('status', 'eq', 'PUBLISHED')
90
+ */
91
+ where(field: string, operator: string, value: any): this;
92
+ /**
93
+ * Select specific fields to return. E.g. .select(['title', 'slug', 'cover'])
94
+ */
95
+ select(fields: string[]): this;
96
+ /**
97
+ * Select specific relations to populate. E.g. .populate(['author'])
98
+ */
99
+ populate(fields: string[]): this;
100
+ /**
101
+ * Sort results. E.g. .sort('createdAt:desc') or .sort('title:asc')
102
+ */
103
+ sort(sortOrder: string): this;
104
+ /**
105
+ * Full-text search across content entries. E.g. .search('nextjs tutorial')
106
+ */
107
+ search(query: string): this;
108
+ /**
109
+ * Target a specific locale. E.g. .locale('id') or .locale('en')
110
+ */
111
+ locale(loc: string): this;
112
+ /**
113
+ * Filter by status. E.g. .status('PUBLISHED') or .status('DRAFT')
114
+ */
115
+ status(st: string): this;
116
+ /**
117
+ * Limit the number of returned entries.
118
+ */
119
+ limit(pageSize: number): this;
120
+ /**
121
+ * Skip a number of pages.
122
+ */
123
+ page(pageNumber: number): this;
124
+ /**
125
+ * Execute the query and fetch the results.
126
+ */
127
+ fetch(): Promise<CollectionResponse<T>>;
128
+ }
129
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,304 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryBuilder = exports.SaCMSError = exports.SaCMS = void 0;
4
+ class SaCMS {
5
+ constructor(config) {
6
+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");
7
+ this.tenant = config.tenant;
8
+ this.token = config.token;
9
+ this.defaultLocale = config.locale ?? "id";
10
+ }
11
+ collection(slug) {
12
+ return new CollectionClient(this, slug);
13
+ }
14
+ single(slug) {
15
+ return new SingleClient(this, slug);
16
+ }
17
+ /**
18
+ * Execute a raw GraphQL query or mutation.
19
+ */
20
+ async graphql(query, variables) {
21
+ return this.request(`/api/public/${this.tenant}/graphql`, {
22
+ method: "POST",
23
+ body: JSON.stringify({ query, variables }),
24
+ });
25
+ }
26
+ /** @internal */
27
+ async request(path, init, retries = 3) {
28
+ const url = `${this.baseUrl}${path}`;
29
+ const headers = {
30
+ Authorization: `Bearer ${this.token}`,
31
+ "Content-Type": "application/json",
32
+ ...init?.headers,
33
+ };
34
+ for (let attempt = 0; attempt <= retries; attempt++) {
35
+ const res = await fetch(url, { ...init, headers });
36
+ if (res.status === 429 && attempt < retries) {
37
+ const retryAfter = res.headers.get("Retry-After");
38
+ const delay = retryAfter ? parseInt(retryAfter, 10) * 1000 : 1000 * Math.pow(2, attempt);
39
+ await new Promise(r => setTimeout(r, delay));
40
+ continue;
41
+ }
42
+ if (!res.ok) {
43
+ const body = await res.text();
44
+ let message;
45
+ try {
46
+ const json = JSON.parse(body);
47
+ message = json.error || json.message || body;
48
+ }
49
+ catch {
50
+ message = body;
51
+ }
52
+ throw new SaCMSError(message, res.status);
53
+ }
54
+ return res.json();
55
+ }
56
+ throw new SaCMSError("Max retries reached", 429);
57
+ }
58
+ /** @internal */
59
+ getDefaultLocale() {
60
+ return this.defaultLocale;
61
+ }
62
+ /** @internal */
63
+ getTenant() {
64
+ return this.tenant;
65
+ }
66
+ }
67
+ exports.SaCMS = SaCMS;
68
+ class CollectionClient {
69
+ constructor(cf, slug) {
70
+ this.cf = cf;
71
+ this.slug = slug;
72
+ }
73
+ /**
74
+ * Start a fluent query builder chain.
75
+ */
76
+ query() {
77
+ return new QueryBuilder(this);
78
+ }
79
+ /**
80
+ * Query multiple entries with filtering, sorting, pagination, and field selection.
81
+ */
82
+ async findMany(params) {
83
+ const qs = buildQueryString(params, this.cf.getDefaultLocale());
84
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}${qs}`);
85
+ }
86
+ /**
87
+ * Get a single entry by ID.
88
+ */
89
+ async findOne(id) {
90
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}/${encodeURIComponent(id)}`);
91
+ }
92
+ /**
93
+ * Create a new entry (requires full-access token).
94
+ */
95
+ async create(params) {
96
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}`, {
97
+ method: "POST",
98
+ body: JSON.stringify({
99
+ data: params.data,
100
+ locale: params.locale ?? this.cf.getDefaultLocale(),
101
+ status: params.status,
102
+ }),
103
+ });
104
+ }
105
+ /**
106
+ * Update an entry by ID (requires full-access token).
107
+ */
108
+ async update(id, params) {
109
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}/${encodeURIComponent(id)}`, {
110
+ method: "PUT",
111
+ body: JSON.stringify({
112
+ data: params.data,
113
+ locale: params.locale ?? this.cf.getDefaultLocale(),
114
+ status: params.status,
115
+ }),
116
+ });
117
+ }
118
+ /**
119
+ * Delete an entry by ID (requires full-access token).
120
+ */
121
+ async delete(id) {
122
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}/${encodeURIComponent(id)}`, { method: "DELETE" });
123
+ }
124
+ }
125
+ class SingleClient {
126
+ constructor(cf, slug) {
127
+ this.cf = cf;
128
+ this.slug = slug;
129
+ }
130
+ /**
131
+ * Get the single type content.
132
+ */
133
+ async find(params) {
134
+ const locale = params?.locale ?? this.cf.getDefaultLocale();
135
+ const qs = locale ? `?locale=${encodeURIComponent(locale)}` : "";
136
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/single/${this.slug}${qs}`);
137
+ }
138
+ /**
139
+ * Update the single type content (requires full-access token).
140
+ */
141
+ async update(data) {
142
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/single/${this.slug}`, {
143
+ method: "PUT",
144
+ body: JSON.stringify({ data }),
145
+ });
146
+ }
147
+ }
148
+ class SaCMSError extends Error {
149
+ constructor(message, status) {
150
+ super(message);
151
+ this.status = status;
152
+ this.name = "SaCMSError";
153
+ }
154
+ }
155
+ exports.SaCMSError = SaCMSError;
156
+ class QueryBuilder {
157
+ constructor(client) {
158
+ this.client = client;
159
+ this.params = {};
160
+ }
161
+ /**
162
+ * Filter data. E.g. .where('status', 'eq', 'PUBLISHED')
163
+ */
164
+ where(field, operator, value) {
165
+ if (!this.params.filters)
166
+ this.params.filters = {};
167
+ if (!this.params.filters[field])
168
+ this.params.filters[field] = {};
169
+ const op = operator.startsWith('$') ? operator : `$${operator}`;
170
+ this.params.filters[field][op] = value;
171
+ return this;
172
+ }
173
+ /**
174
+ * Select specific fields to return. E.g. .select(['title', 'slug', 'cover'])
175
+ */
176
+ select(fields) {
177
+ this.params.fields = fields;
178
+ return this;
179
+ }
180
+ /**
181
+ * Select specific relations to populate. E.g. .populate(['author'])
182
+ */
183
+ populate(fields) {
184
+ this.params.populate = fields;
185
+ return this;
186
+ }
187
+ /**
188
+ * Sort results. E.g. .sort('createdAt:desc') or .sort('title:asc')
189
+ */
190
+ sort(sortOrder) {
191
+ this.params.sort = sortOrder;
192
+ return this;
193
+ }
194
+ /**
195
+ * Full-text search across content entries. E.g. .search('nextjs tutorial')
196
+ */
197
+ search(query) {
198
+ this.params.search = query;
199
+ return this;
200
+ }
201
+ /**
202
+ * Target a specific locale. E.g. .locale('id') or .locale('en')
203
+ */
204
+ locale(loc) {
205
+ this.params.locale = loc;
206
+ return this;
207
+ }
208
+ /**
209
+ * Filter by status. E.g. .status('PUBLISHED') or .status('DRAFT')
210
+ */
211
+ status(st) {
212
+ this.params.status = st;
213
+ return this;
214
+ }
215
+ /**
216
+ * Limit the number of returned entries.
217
+ */
218
+ limit(pageSize) {
219
+ if (!this.params.pagination)
220
+ this.params.pagination = {};
221
+ this.params.pagination.pageSize = pageSize;
222
+ return this;
223
+ }
224
+ /**
225
+ * Skip a number of pages.
226
+ */
227
+ page(pageNumber) {
228
+ if (!this.params.pagination)
229
+ this.params.pagination = {};
230
+ this.params.pagination.page = pageNumber;
231
+ return this;
232
+ }
233
+ /**
234
+ * Execute the query and fetch the results.
235
+ */
236
+ async fetch() {
237
+ return this.client.findMany(this.params);
238
+ }
239
+ }
240
+ exports.QueryBuilder = QueryBuilder;
241
+ // ─── Helpers ────────────────────────────────────────────
242
+ function buildQueryString(params, defaultLocale) {
243
+ if (!params)
244
+ return "";
245
+ const parts = [];
246
+ if (params.filters) {
247
+ flattenFilters(params.filters, "filters", parts);
248
+ }
249
+ if (params.fields?.length) {
250
+ parts.push(`fields=${params.fields.map(encodeURIComponent).join(",")}`);
251
+ }
252
+ if (params.populate?.length) {
253
+ parts.push(`populate=${params.populate.map(encodeURIComponent).join(",")}`);
254
+ }
255
+ const locale = params.locale ?? defaultLocale;
256
+ if (locale) {
257
+ parts.push(`locale=${encodeURIComponent(locale)}`);
258
+ }
259
+ if (params.sort) {
260
+ parts.push(`sort=${encodeURIComponent(params.sort)}`);
261
+ }
262
+ if (params.pagination) {
263
+ if (params.pagination.page != null) {
264
+ parts.push(`pagination[page]=${params.pagination.page}`);
265
+ }
266
+ if (params.pagination.pageSize != null) {
267
+ parts.push(`pagination[pageSize]=${params.pagination.pageSize}`);
268
+ }
269
+ }
270
+ if (params.search) {
271
+ parts.push(`search=${encodeURIComponent(params.search)}`);
272
+ }
273
+ if (params.status) {
274
+ parts.push(`status=${encodeURIComponent(params.status)}`);
275
+ }
276
+ return parts.length ? `?${parts.join("&")}` : "";
277
+ }
278
+ function flattenFilters(filters, prefix, parts) {
279
+ for (const [key, value] of Object.entries(filters)) {
280
+ if (key === "$or" || key === "$and") {
281
+ const arr = value;
282
+ arr.forEach((item, i) => {
283
+ flattenFilters(item, `${prefix}[${key}][${i}]`, parts);
284
+ });
285
+ }
286
+ else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
287
+ const ops = value;
288
+ for (const [op, opVal] of Object.entries(ops)) {
289
+ if (Array.isArray(opVal)) {
290
+ opVal.forEach((v, i) => {
291
+ parts.push(`${prefix}[${encodeURIComponent(key)}][${op}][${i}]=${encodeURIComponent(String(v))}`);
292
+ });
293
+ }
294
+ else {
295
+ parts.push(`${prefix}[${encodeURIComponent(key)}][${op}]=${encodeURIComponent(String(opVal))}`);
296
+ }
297
+ }
298
+ }
299
+ else {
300
+ // Shorthand: filters[field]=value → filters[field][$eq]=value
301
+ parts.push(`${prefix}[${encodeURIComponent(key)}][$eq]=${encodeURIComponent(String(value))}`);
302
+ }
303
+ }
304
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * AUTO-GENERATED FILE — DO NOT EDIT DIRECTLY
3
+ * This file was generated by scripts/generate.ts
4
+ */
5
+ export interface BaseEntry {
6
+ id: string;
7
+ locale: string;
8
+ status: "DRAFT" | "IN_REVIEW" | "APPROVED" | "SCHEDULED" | "PUBLISHED" | "ARCHIVED" | "REJECTED";
9
+ publishedAt: string | null;
10
+ createdAt: string;
11
+ updatedAt: string;
12
+ }
13
+ /** Templates (System workspace templates) */
14
+ export interface Templates extends BaseEntry {
15
+ name: string;
16
+ description?: unknown;
17
+ icon?: string;
18
+ template_id: string;
19
+ schema_template: Record<string, unknown> | unknown[];
20
+ kategori_website: unknown;
21
+ }
22
+ /** SaCMS Hero (Konfigurasi bagian atas halaman utama) */
23
+ export interface SacmsHero extends BaseEntry {
24
+ badge_text?: string;
25
+ title?: string;
26
+ subtitle?: unknown;
27
+ cta_primary_text?: string;
28
+ cta_secondary_text?: string;
29
+ }
30
+ /** SaCMS Features (No description) */
31
+ export interface SacmsFeatures extends BaseEntry {
32
+ title?: string;
33
+ description?: unknown;
34
+ icon?: string;
35
+ is_main?: boolean;
36
+ tag?: string;
37
+ }
38
+ /** SaCMS Pricing (No description) */
39
+ export interface SacmsPricing extends BaseEntry {
40
+ name?: string;
41
+ plan_slug?: string;
42
+ price?: string;
43
+ description?: string;
44
+ features_list?: Record<string, unknown> | unknown[];
45
+ max_content_types?: number;
46
+ max_content_entries?: number;
47
+ max_team_members?: number;
48
+ max_api_calls?: number;
49
+ max_storage?: number;
50
+ max_locales?: number;
51
+ audit_log_retention?: number;
52
+ support_level?: string;
53
+ is_popular?: boolean;
54
+ button_text?: string;
55
+ }
56
+ /** SaCMS Addons (No description) */
57
+ export interface SacmsAddons extends BaseEntry {
58
+ title?: string;
59
+ addon_slug?: string;
60
+ feature_key?: string;
61
+ price_label?: string;
62
+ description?: string;
63
+ icon?: string;
64
+ }
65
+ /** SaCMS Workflow (No description) */
66
+ export interface SacmsWorkflow extends BaseEntry {
67
+ step?: string;
68
+ title?: string;
69
+ description?: unknown;
70
+ icon?: string;
71
+ }
72
+ /** SaCMS FAQ (No description) */
73
+ export interface SacmsFaq extends BaseEntry {
74
+ question?: string;
75
+ answer?: unknown;
76
+ }
77
+ /** SaCMS WhatsApp (Konfigurasi tombol chat WhatsApp mengambang) */
78
+ export interface SacmsWhatsapp extends BaseEntry {
79
+ phone: string;
80
+ message?: unknown;
81
+ label?: string;
82
+ is_active?: boolean;
83
+ }
84
+ /** SaCMS About (Tentang platform dan misi kami) */
85
+ export interface SacmsAbout extends BaseEntry {
86
+ title?: string;
87
+ content?: unknown;
88
+ image?: string;
89
+ }
90
+ /** SaCMS Owners (Profil pendiri dan tim inti) */
91
+ export interface SacmsOwners extends BaseEntry {
92
+ name?: string;
93
+ role?: string;
94
+ bio?: unknown;
95
+ avatar?: string;
96
+ social?: Record<string, unknown> | unknown[];
97
+ }
98
+ /** SaCMS Testimonials (Testimoni dari pengguna dan partner) */
99
+ export interface SacmsTestimonials extends BaseEntry {
100
+ name?: string;
101
+ role?: string;
102
+ content?: unknown;
103
+ avatar?: string;
104
+ rating?: number;
105
+ }
106
+ export interface SaCMSRegistry {
107
+ collections: {
108
+ "templates": Templates;
109
+ "sacms-hero": SacmsHero;
110
+ "sacms-features": SacmsFeatures;
111
+ "sacms-pricing": SacmsPricing;
112
+ "sacms-addons": SacmsAddons;
113
+ "sacms-workflow": SacmsWorkflow;
114
+ "sacms-faq": SacmsFaq;
115
+ "sacms-whatsapp": SacmsWhatsapp;
116
+ "sacms-about": SacmsAbout;
117
+ "sacms-owners": SacmsOwners;
118
+ "sacms-testimonials": SacmsTestimonials;
119
+ };
120
+ singles: {};
121
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * AUTO-GENERATED FILE — DO NOT EDIT DIRECTLY
4
+ * This file was generated by scripts/generate.ts
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export { SaCMS, SaCMSError } from "./client";
2
+ export type { SaCMSConfig, FindManyParams, FindSingleParams, CollectionResponse, SingleResponse, GraphQLResponse, PaginationMeta, PaginationParams, Filters, FilterOperators, MutateParams, } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SaCMSError = exports.SaCMS = void 0;
4
+ var client_1 = require("./client");
5
+ Object.defineProperty(exports, "SaCMS", { enumerable: true, get: function () { return client_1.SaCMS; } });
6
+ Object.defineProperty(exports, "SaCMSError", { enumerable: true, get: function () { return client_1.SaCMSError; } });
@@ -0,0 +1,82 @@
1
+ /** Filter operators supported by the SaCMS API */
2
+ export interface FilterOperators {
3
+ $eq?: string | number | boolean;
4
+ $ne?: string | number | boolean;
5
+ $gt?: string | number;
6
+ $gte?: string | number;
7
+ $lt?: string | number;
8
+ $lte?: string | number;
9
+ $contains?: string;
10
+ $startsWith?: string;
11
+ $endsWith?: string;
12
+ $in?: (string | number)[];
13
+ $notIn?: (string | number)[];
14
+ $null?: boolean;
15
+ $notNull?: boolean;
16
+ }
17
+ export type Filters = Record<string, FilterOperators | string | number | boolean> & {
18
+ $or?: Filters[];
19
+ $and?: Filters[];
20
+ };
21
+ export interface PaginationParams {
22
+ page?: number;
23
+ pageSize?: number;
24
+ }
25
+ export interface FindManyParams {
26
+ filters?: Filters;
27
+ fields?: string[];
28
+ populate?: string[];
29
+ locale?: string;
30
+ sort?: string;
31
+ pagination?: PaginationParams;
32
+ search?: string;
33
+ status?: string;
34
+ }
35
+ export interface FindSingleParams {
36
+ locale?: string;
37
+ }
38
+ export interface PaginationMeta {
39
+ page: number;
40
+ pageSize: number;
41
+ total: number;
42
+ totalPages: number;
43
+ }
44
+ export interface CollectionResponse<T = Record<string, unknown>> {
45
+ data: T[];
46
+ meta: {
47
+ contentType: {
48
+ name: string;
49
+ slug: string;
50
+ };
51
+ pagination: PaginationMeta;
52
+ };
53
+ }
54
+ export interface SingleResponse<T = Record<string, unknown>> {
55
+ data: T;
56
+ meta: {
57
+ singleType: {
58
+ name: string;
59
+ slug: string;
60
+ fields: unknown[];
61
+ };
62
+ };
63
+ }
64
+ export interface GraphQLResponse<T = Record<string, unknown>> {
65
+ data: T;
66
+ errors?: Array<{
67
+ message: string;
68
+ locations?: unknown[];
69
+ path?: string[];
70
+ }>;
71
+ }
72
+ export interface SaCMSConfig {
73
+ baseUrl: string;
74
+ tenant: string;
75
+ token: string;
76
+ locale?: string;
77
+ }
78
+ export interface MutateParams {
79
+ data: Record<string, unknown>;
80
+ locale?: string;
81
+ status?: string;
82
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
- {
2
- "name": "@sacms/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@sacms/sdk",
3
+ "version": "1.0.1",
4
+ "description": "TypeScript SDK for SaCMS headless CMS",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "bin": {
8
+ "sacms-gen": "dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "scripts": {
14
+ "clean": "rimraf dist",
15
+ "build": "npm run clean && tsc",
16
+ "dev": "tsc --watch",
17
+ "prepublishOnly": "npm run build"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "keywords": [
23
+ "sacms",
24
+ "cms",
25
+ "headless",
26
+ "sdk"
27
+ ],
28
+ "license": "MIT",
29
+ "devDependencies": {
30
+ "rimraf": "^5.0.0",
31
+ "typescript": "^5.5.0"
32
+ }
33
+ }