@sacms/sdk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,296 @@
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
+ // New entries created through the public API are always saved as DRAFT —
89
+ // the `status` param is accepted for forward-compatibility but has no
90
+ // effect on create today; publishing goes through the CMS's own review
91
+ // workflow (the dashboard, or an authenticated staff action), not this API.
92
+ const created = await sacms.collection("posts").create({
93
+ data: {
94
+ title: "How We Scaled Next.js to 1M Users",
95
+ slug: "scaling-nextjs",
96
+ content: "<p>Deep dive into architecture...</p>",
97
+ },
98
+ locale: "id",
99
+ });
100
+
101
+ // 4. Update entry
102
+ const updated = await sacms.collection("posts").update("entry_cuid_123", {
103
+ data: { title: "Updated Title" },
104
+ });
105
+
106
+ // 5. Delete entry
107
+ await sacms.collection("posts").delete("entry_cuid_123");
108
+ ```
109
+
110
+ ### 2. Single Types (Global Settings, Landing, Header, Footer)
111
+
112
+ ```typescript
113
+ // Fetch single type data
114
+ const siteSettings = await sacms.single("site_settings").find({ locale: "id" });
115
+ console.log(siteSettings.data.siteName);
116
+ console.log(siteSettings.data.logoUrl);
117
+
118
+ // Update single type (Requires Full-Access API Token)
119
+ await sacms.single("site_settings").update({
120
+ siteName: "SaCMS Cloud Portal",
121
+ announcementText: "Version 2.0 Released!",
122
+ });
123
+ ```
124
+
125
+ ### 3. GraphQL Query & Mutations
126
+
127
+ ```typescript
128
+ const { data, errors } = await sacms.graphql(`
129
+ query GetFeaturedArticles($limit: Int) {
130
+ articles(limit: $limit, published: true, sort: "createdAt", order: "desc") {
131
+ data {
132
+ id
133
+ title
134
+ slug
135
+ publishedAt
136
+ }
137
+ meta {
138
+ total
139
+ }
140
+ }
141
+ }
142
+ `, { limit: 5 });
143
+ ```
144
+
145
+ ---
146
+
147
+ ## 🔮 Automated Type Generation CLI
148
+
149
+ Generate strict TypeScript definitions from your **real, live** schema — the CLI introspects your actual GraphQL schema over the network (no local database access needed, works against any SaCMS instance your token can reach):
150
+
151
+ ```bash
152
+ npx @sacms/sdk generate \
153
+ --url https://your-sacms-instance.com \
154
+ --tenant my-tenant \
155
+ --token cf_live_xxxx \
156
+ --out src/types/sacms.ts
157
+ ```
158
+
159
+ This writes one interface per Content Type / Single Type, plus a `SaCMSRegistry`-shaped type (named `SaCMSRegistry` in the file, but you can import it under whatever name you like). Pass it to `SaCMS` as a type argument for full, automatic per-slug intellisense — no `<Article>` on every call:
160
+
161
+ ```typescript
162
+ import { SaCMS } from "@sacms/sdk";
163
+ import type { SaCMSRegistry } from "./types/sacms";
164
+
165
+ const sacms = new SaCMS<SaCMSRegistry>({ baseUrl, tenant, token });
166
+
167
+ const { data } = await sacms.collection("articles").findMany();
168
+ // data[0].title -> string, inferred from your real "articles" Content Type — no explicit <Article> needed
169
+ ```
170
+
171
+ Without a registry type argument, `SaCMS` is untyped by default (every `collection()`/`single()` call accepts any slug and returns `Record<string, unknown>`, or an explicit generic you pass per call) — there is no tenant-specific schema baked into the package itself.
172
+
173
+ ---
174
+
175
+ ## 👤 Member Authentication
176
+
177
+ For apps with end-user accounts (a SaaS dashboard, a forum, a marketplace — anything where *visitors*, not just your backend, sign in), use `sacms.auth`. This is separate from the `token` you configured `SaCMS` with: that's your workspace's own service credential, used for every other method above. Member auth is stateless — the SDK doesn't store sessions for you; keep the tokens `login`/`register`/`refresh` return wherever your app keeps its own session state (a cookie, usually), and pass the current one back in on each authenticated call.
178
+
179
+ ```typescript
180
+ // Sign up / sign in
181
+ const session = await sacms.auth.register({ email, password, name });
182
+ // or: const session = await sacms.auth.login(email, password);
183
+ if ("requiresEmailVerification" in session) {
184
+ // registration succeeded but needs email confirmation before a session is issued
185
+ } else {
186
+ // session.user, session.accessToken, session.refreshToken, session.expiresIn
187
+ }
188
+
189
+ // Authenticated calls use that member's own accessToken, not your service token
190
+ const { user } = await sacms.auth.me(session.accessToken);
191
+ await sacms.auth.updateMe(session.accessToken, { name: "New Name" });
192
+ await sacms.auth.changePassword(session.accessToken, { currentPassword, password, passwordConfirmation });
193
+
194
+ // Refresh when the access token expires (rotates the refresh token too)
195
+ const refreshed = await sacms.auth.refresh(session.refreshToken);
196
+
197
+ // Sign out (revokes the refresh token server-side)
198
+ await sacms.auth.logout(session.refreshToken);
199
+
200
+ // Forgot/reset password, and consuming an email-verification link
201
+ await sacms.auth.forgotPassword(email);
202
+ await sacms.auth.resetPassword({ code, password, passwordConfirmation });
203
+ await sacms.auth.confirmEmail(code);
204
+ ```
205
+
206
+ ---
207
+
208
+ ## 🛠️ Framework Integration Recipes
209
+
210
+ ### Next.js 15/16 App Router (Server Component)
211
+
212
+ ```typescript
213
+ // app/blog/page.tsx
214
+ import { SaCMS } from "@sacms/sdk";
215
+
216
+ const sacms = new SaCMS({
217
+ baseUrl: process.env.SACMS_BASE_URL!,
218
+ tenant: process.env.SACMS_TENANT!,
219
+ token: process.env.SACMS_API_TOKEN!,
220
+ });
221
+
222
+ export default async function BlogPage() {
223
+ const { data: posts } = await sacms.collection("articles").findMany({
224
+ sort: "createdAt:desc",
225
+ pagination: { pageSize: 12 },
226
+ });
227
+
228
+ return (
229
+ <div className="grid grid-cols-3 gap-6">
230
+ {posts.map((post: any) => (
231
+ <article key={post.id} className="border p-4 rounded-xl">
232
+ <h2 className="font-bold text-lg">{post.title}</h2>
233
+ <p className="text-gray-600">{post.summary}</p>
234
+ </article>
235
+ ))}
236
+ </div>
237
+ );
238
+ }
239
+ ```
240
+
241
+ ### Astro (SSG & Dynamic Static Paths)
242
+
243
+ ```astro
244
+ ---
245
+ // src/pages/blog/[slug].astro
246
+ import { SaCMS } from "@sacms/sdk";
247
+
248
+ export async function getStaticPaths() {
249
+ const sacms = new SaCMS({
250
+ baseUrl: import.meta.env.SACMS_BASE_URL,
251
+ tenant: import.meta.env.SACMS_TENANT,
252
+ token: import.meta.env.SACMS_API_TOKEN,
253
+ });
254
+
255
+ const { data: articles } = await sacms.collection("articles").findMany();
256
+
257
+ return articles.map((article: any) => ({
258
+ params: { slug: article.slug },
259
+ props: { article },
260
+ }));
261
+ }
262
+
263
+ const { article } = Astro.props;
264
+ ---
265
+
266
+ <main class="max-w-3xl mx-auto py-12">
267
+ <h1 class="text-3xl font-bold">{article.title}</h1>
268
+ <div class="prose mt-6" set:html={article.content} />
269
+ </main>
270
+ ```
271
+
272
+ ---
273
+
274
+ ## 🛡️ Error Handling
275
+
276
+ ```typescript
277
+ import { SaCMS, SaCMSError } from "@sacms/sdk";
278
+
279
+ try {
280
+ const result = await sacms.collection("articles").findOne("invalid-id");
281
+ } catch (error) {
282
+ if (error instanceof SaCMSError) {
283
+ // error.status is the real HTTP status for an API-level error (404, 403, …),
284
+ // or 0 if every retry hit a pure network failure (DNS, connection reset, timeout) —
285
+ // those are retried with backoff first, same as a 429, before being thrown.
286
+ console.error(`SaCMS API Error [HTTP ${error.status}]: ${error.message}`);
287
+ } else {
288
+ console.error("Unexpected error:", error);
289
+ }
290
+ }
291
+ ```
292
+
293
+ ---
294
+
295
+ ## 📄 License
296
+ MIT © [SaCMS Team](https://sacms.cloud)
package/dist/auth.d.ts ADDED
@@ -0,0 +1,105 @@
1
+ import type { SaCMS } from "./client";
2
+ export interface MemberUser {
3
+ id: string;
4
+ email: string;
5
+ name: string | null;
6
+ avatar: string | null;
7
+ role: string;
8
+ status: string;
9
+ metadata: Record<string, unknown> | null;
10
+ createdAt: string;
11
+ lastLoginAt?: string | null;
12
+ }
13
+ export interface AuthSession {
14
+ message: string;
15
+ user: MemberUser;
16
+ accessToken: string;
17
+ refreshToken: string;
18
+ expiresIn: number;
19
+ tokenType: "Bearer";
20
+ }
21
+ export interface RegisterParams {
22
+ email: string;
23
+ password: string;
24
+ name?: string;
25
+ avatar?: string;
26
+ metadata?: Record<string, unknown>;
27
+ }
28
+ export type RegisterResult = AuthSession | {
29
+ message: string;
30
+ requiresEmailVerification: true;
31
+ };
32
+ export interface UpdateProfileParams {
33
+ name?: string;
34
+ avatar?: string;
35
+ metadata?: Record<string, unknown>;
36
+ currentPassword?: string;
37
+ newPassword?: string;
38
+ }
39
+ export interface ChangePasswordParams {
40
+ currentPassword: string;
41
+ password: string;
42
+ passwordConfirmation: string;
43
+ }
44
+ export interface ResetPasswordParams {
45
+ code: string;
46
+ password: string;
47
+ passwordConfirmation: string;
48
+ }
49
+ /**
50
+ * Member (end-user) authentication for this workspace — login, registration,
51
+ * session refresh/logout, and profile management for people who sign in to
52
+ * the *generated site itself* (not the SDK's own service token, which is a
53
+ * separate, workspace-level credential used for every other method).
54
+ *
55
+ * `me`/`updateMe`/`changePassword` act on a specific member and need that
56
+ * member's own `accessToken` from `login`/`register`/`refresh` — the SDK is
57
+ * stateless and does not store or manage sessions/cookies for you; keep the
58
+ * tokens wherever your app keeps its own session state (a cookie, usually)
59
+ * and pass the current one in on each call.
60
+ */
61
+ export declare class AuthClient {
62
+ private cf;
63
+ constructor(cf: SaCMS<any>);
64
+ /** Sign in an existing member. Throws `SaCMSError` (401) on a wrong email/password. */
65
+ login(email: string, password: string): Promise<AuthSession>;
66
+ /**
67
+ * Register a new member. Returns a full session immediately, unless the
68
+ * workspace requires email verification first — check
69
+ * `"requiresEmailVerification" in result` to tell the two apart.
70
+ */
71
+ register(params: RegisterParams): Promise<RegisterResult>;
72
+ /** Consume the one-time code from a registration verification email. */
73
+ confirmEmail(code: string): Promise<{
74
+ message: string;
75
+ }>;
76
+ /** Exchange a refresh token for a new access + refresh token pair (rotates the refresh token). */
77
+ refresh(refreshToken: string): Promise<Omit<AuthSession, "user" | "message"> & {
78
+ message: string;
79
+ }>;
80
+ /** Revoke a session. Pass the refresh token to invalidate it server-side; always resolves. */
81
+ logout(refreshToken?: string): Promise<{
82
+ message: string;
83
+ }>;
84
+ /** The signed-in member's own profile. `memberAccessToken` is that member's token from login/register/refresh. */
85
+ me(memberAccessToken: string): Promise<{
86
+ user: MemberUser;
87
+ }>;
88
+ /** Update the signed-in member's own profile (name/avatar/metadata), or change their password. */
89
+ updateMe(memberAccessToken: string, data: UpdateProfileParams): Promise<{
90
+ message: string;
91
+ user: MemberUser;
92
+ }>;
93
+ /** Dedicated password-change call (requires the current password). */
94
+ changePassword(memberAccessToken: string, params: ChangePasswordParams): Promise<{
95
+ message: string;
96
+ }>;
97
+ /** Request a password-reset email for the given address. Always resolves (never reveals whether the email exists). */
98
+ forgotPassword(email: string): Promise<{
99
+ message: string;
100
+ }>;
101
+ /** Complete a password reset using the code from the reset email. */
102
+ resetPassword(params: ResetPasswordParams): Promise<{
103
+ message: string;
104
+ }>;
105
+ }
package/dist/auth.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AuthClient = void 0;
4
+ /**
5
+ * Member (end-user) authentication for this workspace — login, registration,
6
+ * session refresh/logout, and profile management for people who sign in to
7
+ * the *generated site itself* (not the SDK's own service token, which is a
8
+ * separate, workspace-level credential used for every other method).
9
+ *
10
+ * `me`/`updateMe`/`changePassword` act on a specific member and need that
11
+ * member's own `accessToken` from `login`/`register`/`refresh` — the SDK is
12
+ * stateless and does not store or manage sessions/cookies for you; keep the
13
+ * tokens wherever your app keeps its own session state (a cookie, usually)
14
+ * and pass the current one in on each call.
15
+ */
16
+ class AuthClient {
17
+ constructor(cf) {
18
+ this.cf = cf;
19
+ }
20
+ /** Sign in an existing member. Throws `SaCMSError` (401) on a wrong email/password. */
21
+ login(email, password) {
22
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/login`, {
23
+ method: "POST",
24
+ body: JSON.stringify({ email, password }),
25
+ });
26
+ }
27
+ /**
28
+ * Register a new member. Returns a full session immediately, unless the
29
+ * workspace requires email verification first — check
30
+ * `"requiresEmailVerification" in result` to tell the two apart.
31
+ */
32
+ register(params) {
33
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/register`, {
34
+ method: "POST",
35
+ body: JSON.stringify(params),
36
+ });
37
+ }
38
+ /** Consume the one-time code from a registration verification email. */
39
+ confirmEmail(code) {
40
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/email-confirmation`, {
41
+ method: "POST",
42
+ body: JSON.stringify({ code }),
43
+ });
44
+ }
45
+ /** Exchange a refresh token for a new access + refresh token pair (rotates the refresh token). */
46
+ refresh(refreshToken) {
47
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/refresh`, {
48
+ method: "POST",
49
+ body: JSON.stringify({ refreshToken }),
50
+ });
51
+ }
52
+ /** Revoke a session. Pass the refresh token to invalidate it server-side; always resolves. */
53
+ logout(refreshToken) {
54
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/logout`, {
55
+ method: "POST",
56
+ body: JSON.stringify(refreshToken ? { refreshToken } : {}),
57
+ });
58
+ }
59
+ /** The signed-in member's own profile. `memberAccessToken` is that member's token from login/register/refresh. */
60
+ me(memberAccessToken) {
61
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/me`, {
62
+ headers: { Authorization: `Bearer ${memberAccessToken}` },
63
+ });
64
+ }
65
+ /** Update the signed-in member's own profile (name/avatar/metadata), or change their password. */
66
+ updateMe(memberAccessToken, data) {
67
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/me`, {
68
+ method: "PATCH",
69
+ headers: { Authorization: `Bearer ${memberAccessToken}` },
70
+ body: JSON.stringify(data),
71
+ });
72
+ }
73
+ /** Dedicated password-change call (requires the current password). */
74
+ changePassword(memberAccessToken, params) {
75
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/change-password`, {
76
+ method: "POST",
77
+ headers: { Authorization: `Bearer ${memberAccessToken}` },
78
+ body: JSON.stringify(params),
79
+ });
80
+ }
81
+ /** Request a password-reset email for the given address. Always resolves (never reveals whether the email exists). */
82
+ forgotPassword(email) {
83
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/forgot-password`, {
84
+ method: "POST",
85
+ body: JSON.stringify({ email }),
86
+ });
87
+ }
88
+ /** Complete a password reset using the code from the reset email. */
89
+ resetPassword(params) {
90
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/auth/reset-password`, {
91
+ method: "POST",
92
+ body: JSON.stringify(params),
93
+ });
94
+ }
95
+ }
96
+ exports.AuthClient = AuthClient;
package/dist/cli.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * SaCMS SDK Type Generator CLI
4
+ * Generates TypeScript definitions from a remote SaCMS instance's real
5
+ * GraphQL schema, via standard introspection — works against any SaCMS
6
+ * instance the token can reach, no local database access needed.
7
+ *
8
+ * Usage:
9
+ * npx @sacms/sdk generate --url http://localhost:3000 --tenant demo --token <token> --out src/types/sacms.d.ts
10
+ */
11
+ export interface TypeRef {
12
+ kind: string;
13
+ name: string | null;
14
+ ofType: TypeRef | null;
15
+ }
16
+ export interface IntrospectionField {
17
+ name: string;
18
+ type: TypeRef;
19
+ }
20
+ export interface IntrospectionType {
21
+ name: string;
22
+ kind: string;
23
+ fields: IntrospectionField[] | null;
24
+ }
25
+ /** Unwraps NON_NULL/LIST wrappers to the innermost named type, and whether the field is required. */
26
+ export declare function unwrap(ref: TypeRef): {
27
+ name: string;
28
+ required: boolean;
29
+ };
30
+ export declare function scalarToTs(name: string): string;
31
+ /** Emits one `export interface TypeName { ... }` from a real introspected object type. */
32
+ export declare function buildInterface(typeName: string, type: IntrospectionType): string;