@sacms/sdk 1.0.1 → 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
@@ -85,6 +85,10 @@ const posts = await sacms.collection("posts").findMany({
85
85
  const post = await sacms.collection("posts").findOne("entry_cuid_123");
86
86
 
87
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.
88
92
  const created = await sacms.collection("posts").create({
89
93
  data: {
90
94
  title: "How We Scaled Next.js to 1M Users",
@@ -92,7 +96,6 @@ const created = await sacms.collection("posts").create({
92
96
  content: "<p>Deep dive into architecture...</p>",
93
97
  },
94
98
  locale: "id",
95
- status: "PUBLISHED",
96
99
  });
97
100
 
98
101
  // 4. Update entry
@@ -143,25 +146,61 @@ const { data, errors } = await sacms.graphql(`
143
146
 
144
147
  ## 🔮 Automated Type Generation CLI
145
148
 
146
- Generate strict TypeScript definitions reflecting your live CMS schemas:
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):
147
150
 
148
151
  ```bash
149
- # Run CLI
150
152
  npx @sacms/sdk generate \
151
153
  --url https://your-sacms-instance.com \
152
154
  --tenant my-tenant \
153
155
  --token cf_live_xxxx \
154
- --out src/types/sacms.d.ts
156
+ --out src/types/sacms.ts
155
157
  ```
156
158
 
157
- Then enjoy full intellisense:
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:
158
160
 
159
161
  ```typescript
160
- import type { Article } from "./types/sacms";
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);
161
199
 
162
- const { data } = await sacms.collection<Article>("articles").findMany();
163
- // data[0].title -> string
164
- // data[0].slug -> string
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);
165
204
  ```
166
205
 
167
206
  ---
@@ -241,9 +280,12 @@ try {
241
280
  const result = await sacms.collection("articles").findOne("invalid-id");
242
281
  } catch (error) {
243
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.
244
286
  console.error(`SaCMS API Error [HTTP ${error.status}]: ${error.message}`);
245
287
  } else {
246
- console.error("Network or unexpected error:", error);
288
+ console.error("Unexpected error:", error);
247
289
  }
248
290
  }
249
291
  ```
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 CHANGED
@@ -1,9 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * SaCMS SDK Type Generator CLI
4
- * Generates TypeScript definitions from a remote SaCMS instance.
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.
5
7
  *
6
8
  * Usage:
7
9
  * npx @sacms/sdk generate --url http://localhost:3000 --tenant demo --token <token> --out src/types/sacms.d.ts
8
10
  */
9
- export {};
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;
package/dist/cli.js CHANGED
@@ -2,7 +2,9 @@
2
2
  "use strict";
3
3
  /**
4
4
  * SaCMS SDK Type Generator CLI
5
- * Generates TypeScript definitions from a remote SaCMS instance.
5
+ * Generates TypeScript definitions from a remote SaCMS instance's real
6
+ * GraphQL schema, via standard introspection — works against any SaCMS
7
+ * instance the token can reach, no local database access needed.
6
8
  *
7
9
  * Usage:
8
10
  * npx @sacms/sdk generate --url http://localhost:3000 --tenant demo --token <token> --out src/types/sacms.d.ts
@@ -11,40 +13,70 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
11
13
  return (mod && mod.__esModule) ? mod : { "default": mod };
12
14
  };
13
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.unwrap = unwrap;
17
+ exports.scalarToTs = scalarToTs;
18
+ exports.buildInterface = buildInterface;
14
19
  const fs_1 = __importDefault(require("fs"));
15
20
  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":
21
+ const INTROSPECTION_QUERY = `
22
+ query SaCMSSdkIntrospection {
23
+ __schema {
24
+ queryType {
25
+ fields {
26
+ name
27
+ type { kind name ofType { kind name ofType { kind name } } }
28
+ }
29
+ }
30
+ types {
31
+ name
32
+ kind
33
+ fields {
34
+ name
35
+ type { kind name ofType { kind name ofType { kind name } } }
36
+ }
37
+ }
38
+ }
39
+ }
40
+ `;
41
+ /** Unwraps NON_NULL/LIST wrappers to the innermost named type, and whether the field is required. */
42
+ function unwrap(ref) {
43
+ let cur = ref;
44
+ let required = false;
45
+ if (cur.kind === "NON_NULL") {
46
+ required = true;
47
+ cur = cur.ofType;
48
+ }
49
+ while (cur && (cur.kind === "LIST" || cur.kind === "NON_NULL")) {
50
+ cur = cur.ofType;
51
+ }
52
+ return { name: cur?.name ?? "Unknown", required };
53
+ }
54
+ function scalarToTs(name) {
55
+ switch (name) {
56
+ case "String":
57
+ case "ID":
27
58
  return "string";
28
- case "number":
29
- case "integer":
30
- case "float":
31
- case "decimal":
32
- case "currency":
33
- case "percent":
34
- case "rating":
59
+ case "Int":
60
+ case "Float":
35
61
  return "number";
36
- case "boolean":
62
+ case "Boolean":
37
63
  return "boolean";
38
- case "json":
39
- case "dynamiczone":
40
- case "component":
64
+ case "JSON":
41
65
  return "Record<string, unknown> | unknown[]";
42
- case "relation":
43
- return "string | Record<string, unknown>";
44
66
  default:
45
67
  return "unknown";
46
68
  }
47
69
  }
70
+ /** Emits one `export interface TypeName { ... }` from a real introspected object type. */
71
+ function buildInterface(typeName, type) {
72
+ const fields = (type.fields ?? [])
73
+ .map((f) => {
74
+ const { name, required } = unwrap(f.type);
75
+ return ` ${f.name}${required ? "" : "?"}: ${scalarToTs(name)}`;
76
+ })
77
+ .join("\n");
78
+ return `export interface ${typeName} {\n${fields}\n}\n\n`;
79
+ }
48
80
  async function main() {
49
81
  const args = process.argv.slice(2);
50
82
  let url = "http://localhost:3000";
@@ -62,66 +94,83 @@ async function main() {
62
94
  outPath = args[++i];
63
95
  }
64
96
  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 });
97
+ const res = await fetch(`${url.replace(/\/+$/, "")}/api/public/${tenant}/graphql`, {
98
+ method: "POST",
99
+ headers: {
100
+ "Content-Type": "application/json",
101
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
102
+ },
103
+ body: JSON.stringify({ query: INTROSPECTION_QUERY }),
104
+ });
105
+ const json = (await res.json().catch(() => null));
106
+ if (!res.ok || !json?.data) {
107
+ const message = json?.errors?.[0]?.message ?? `HTTP ${res.status}`;
108
+ console.error(`❌ Failed to fetch schema from ${url}: ${message}`);
109
+ process.exit(1);
110
+ }
111
+ const { queryType, types } = json.data.__schema;
112
+ const typesByName = new Map(types.filter((t) => t.kind === "OBJECT" && !t.name.startsWith("__")).map((t) => [t.name, t]));
113
+ let body = "";
114
+ const collectionEntries = [];
115
+ const singleEntries = [];
116
+ for (const field of queryType.fields) {
117
+ // `${slug}ById` is the by-id lookup variant of a collection field — the
118
+ // registry only needs the plain, slug-named query field.
119
+ if (field.name.endsWith("ById"))
120
+ continue;
121
+ const { name: returnTypeName } = unwrap(field.type);
122
+ if (returnTypeName.endsWith("Collection")) {
123
+ // A Content Type's query field returns `${TypeName}Collection`, which
124
+ // wraps `data: [${TypeName}!]!` — the real entry shape (id, locale,
125
+ // status, publishedAt, createdAt, updatedAt, and every custom field)
126
+ // lives on `${TypeName}` itself, introspected directly rather than
127
+ // assumed from a hand-written base interface.
128
+ const itemTypeName = returnTypeName.slice(0, -"Collection".length);
129
+ const itemType = typesByName.get(itemTypeName);
130
+ if (!itemType)
131
+ continue;
132
+ body += buildInterface(itemTypeName, itemType);
133
+ collectionEntries.push(` "${field.name}": ${itemTypeName}`);
134
+ }
135
+ else if (returnTypeName.endsWith("Single")) {
136
+ // A Single Type's query field returns `${TypeName}Single` directly —
137
+ // unlike a collection entry, it has no id/locale/status/createdAt,
138
+ // only publishedAt/updatedAt plus its custom fields (see
139
+ // src/lib/graphql-schema.ts's Single Type generation and the real
140
+ // REST response in src/app/api/public/[tenant]/single/[singleType]).
141
+ const singleType = typesByName.get(returnTypeName);
142
+ if (!singleType)
143
+ continue;
144
+ body += buildInterface(returnTypeName, singleType);
145
+ singleEntries.push(` "${field.name}": ${returnTypeName}`);
116
146
  }
117
- fs_1.default.writeFileSync(resolvedOut, code, "utf8");
118
- console.log(`✅ SaCMS TypeScript definitions successfully generated at: ${resolvedOut}`);
119
147
  }
120
- catch (err) {
121
- console.error(`❌ Failed to generate SaCMS types:`, err?.message || err);
122
- process.exit(1);
148
+ const code = `/**
149
+ * AUTO-GENERATED SACMS TYPE DEFINITIONS — DO NOT EDIT DIRECTLY
150
+ * Generated on: ${new Date().toISOString()}
151
+ * Remote URL: ${url} (Tenant: ${tenant})
152
+ */
153
+
154
+ ${body}export interface SaCMSRegistry {
155
+ collections: {
156
+ ${collectionEntries.join(";\n") || " [slug: string]: Record<string, unknown>"}
157
+ }
158
+ singles: {
159
+ ${singleEntries.join(";\n") || " [slug: string]: Record<string, unknown>"}
160
+ }
161
+ }
162
+ `;
163
+ const resolvedOut = path_1.default.resolve(process.cwd(), outPath);
164
+ const outDir = path_1.default.dirname(resolvedOut);
165
+ if (!fs_1.default.existsSync(outDir)) {
166
+ fs_1.default.mkdirSync(outDir, { recursive: true });
123
167
  }
168
+ fs_1.default.writeFileSync(resolvedOut, code, "utf8");
169
+ console.log(`✅ Generated ${collectionEntries.length} collection type(s) and ${singleEntries.length} single type(s) at: ${resolvedOut}`);
124
170
  }
125
171
  if (require.main === module) {
126
- main();
172
+ main().catch((err) => {
173
+ console.error(`❌ Failed to generate SaCMS types:`, err?.message || err);
174
+ process.exit(1);
175
+ });
127
176
  }
package/dist/client.d.ts CHANGED
@@ -1,20 +1,39 @@
1
1
  import type { SaCMSConfig, FindManyParams, FindSingleParams, CollectionResponse, SingleResponse, GraphQLResponse, MutateParams } from "./types";
2
- import type { SaCMSRegistry } from "./generated-types";
3
- export declare class SaCMS {
2
+ import type { EmptyRegistry, SaCMSRegistryShape } from "./generated-types";
3
+ import { AuthClient } from "./auth";
4
+ /**
5
+ * `SaCMS` is generic over your own, per-workspace schema registry — there is
6
+ * no tenant-specific schema baked into this package. Run `npx @sacms/sdk
7
+ * generate --url ... --tenant ... --token ... --out src/types/sacms.ts` to
8
+ * generate one from your real workspace, then:
9
+ *
10
+ * import { SaCMS } from "@sacms/sdk"
11
+ * import type { MyRegistry } from "./types/sacms"
12
+ *
13
+ * const sacms = new SaCMS<MyRegistry>({ baseUrl, tenant, token })
14
+ * // sacms.collection("articles") is now typed from MyRegistry, not a guess.
15
+ *
16
+ * Without a registry type argument, `collection()`/`single()` accept any
17
+ * slug and fall back to `Record<string, unknown>` (or an explicit generic
18
+ * you pass per call) — exactly as if the schema were untyped.
19
+ */
20
+ export declare class SaCMS<Registry extends SaCMSRegistryShape = EmptyRegistry> {
4
21
  private baseUrl;
5
22
  private tenant;
6
23
  private token;
7
24
  private defaultLocale?;
25
+ /** Member (end-user) authentication — login, register, session, profile. */
26
+ readonly auth: AuthClient;
8
27
  constructor(config: SaCMSConfig);
9
28
  /**
10
29
  * Access a collection content type for querying or mutating entries.
11
30
  */
12
- collection<K extends keyof SaCMSRegistry["collections"]>(slug: K): CollectionClient<SaCMSRegistry["collections"][K]>;
31
+ collection<K extends keyof Registry["collections"]>(slug: K): CollectionClient<Registry["collections"][K]>;
13
32
  collection<T = Record<string, unknown>>(slug: string): CollectionClient<T>;
14
33
  /**
15
34
  * Access a single type for querying its content.
16
35
  */
17
- single<K extends keyof SaCMSRegistry["singles"]>(slug: K): SingleClient<SaCMSRegistry["singles"][K]>;
36
+ single<K extends keyof Registry["singles"]>(slug: K): SingleClient<Registry["singles"][K]>;
18
37
  single<T = Record<string, unknown>>(slug: string): SingleClient<T>;
19
38
  /**
20
39
  * Execute a raw GraphQL query or mutation.
@@ -30,7 +49,7 @@ export declare class SaCMS {
30
49
  declare class CollectionClient<T> {
31
50
  private cf;
32
51
  private slug;
33
- constructor(cf: SaCMS, slug: string);
52
+ constructor(cf: SaCMS<any>, slug: string);
34
53
  /**
35
54
  * Start a fluent query builder chain.
36
55
  */
@@ -67,7 +86,7 @@ declare class CollectionClient<T> {
67
86
  declare class SingleClient<T> {
68
87
  private cf;
69
88
  private slug;
70
- constructor(cf: SaCMS, slug: string);
89
+ constructor(cf: SaCMS<any>, slug: string);
71
90
  /**
72
91
  * Get the single type content.
73
92
  */
package/dist/client.js CHANGED
@@ -1,12 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.QueryBuilder = exports.SaCMSError = exports.SaCMS = void 0;
4
+ const auth_1 = require("./auth");
5
+ /**
6
+ * `SaCMS` is generic over your own, per-workspace schema registry — there is
7
+ * no tenant-specific schema baked into this package. Run `npx @sacms/sdk
8
+ * generate --url ... --tenant ... --token ... --out src/types/sacms.ts` to
9
+ * generate one from your real workspace, then:
10
+ *
11
+ * import { SaCMS } from "@sacms/sdk"
12
+ * import type { MyRegistry } from "./types/sacms"
13
+ *
14
+ * const sacms = new SaCMS<MyRegistry>({ baseUrl, tenant, token })
15
+ * // sacms.collection("articles") is now typed from MyRegistry, not a guess.
16
+ *
17
+ * Without a registry type argument, `collection()`/`single()` accept any
18
+ * slug and fall back to `Record<string, unknown>` (or an explicit generic
19
+ * you pass per call) — exactly as if the schema were untyped.
20
+ */
4
21
  class SaCMS {
5
22
  constructor(config) {
6
23
  this.baseUrl = config.baseUrl.replace(/\/+$/, "");
7
24
  this.tenant = config.tenant;
8
25
  this.token = config.token;
9
26
  this.defaultLocale = config.locale ?? "id";
27
+ this.auth = new auth_1.AuthClient(this);
10
28
  }
11
29
  collection(slug) {
12
30
  return new CollectionClient(this, slug);
@@ -32,7 +50,22 @@ class SaCMS {
32
50
  ...init?.headers,
33
51
  };
34
52
  for (let attempt = 0; attempt <= retries; attempt++) {
35
- const res = await fetch(url, { ...init, headers });
53
+ let res;
54
+ try {
55
+ res = await fetch(url, { ...init, headers });
56
+ }
57
+ catch (err) {
58
+ // A pure network failure (connection reset, DNS, timeout) throws
59
+ // before there's any Response to inspect — retry it the same way
60
+ // as a 429, instead of letting it escape as a raw, un-typed
61
+ // exception that the README's `catch (SaCMSError)` pattern can't
62
+ // catch.
63
+ if (attempt < retries) {
64
+ await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, attempt)));
65
+ continue;
66
+ }
67
+ throw new SaCMSError(err instanceof Error ? err.message : "Network request failed", 0);
68
+ }
36
69
  if (res.status === 429 && attempt < retries) {
37
70
  const retryAfter = res.headers.get("Retry-After");
38
71
  const delay = retryAfter ? parseInt(retryAfter, 10) * 1000 : 1000 * Math.pow(2, attempt);
@@ -1,121 +1,24 @@
1
1
  /**
2
- * AUTO-GENERATED FILE — DO NOT EDIT DIRECTLY
3
- * This file was generated by scripts/generate.ts
2
+ * Default, empty registry shipped with the package — no tenant-specific
3
+ * schema is baked in here. `npx @sacms/sdk generate` produces your own
4
+ * registry file from your real workspace; pass it to `new SaCMS<MyRegistry>`
5
+ * instead of relying on this default (see client.ts's class doc comment).
4
6
  */
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;
7
+ export interface SaCMSRegistryShape {
8
+ collections: Record<string, unknown>;
9
+ singles: Record<string, unknown>;
12
10
  }
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
- };
11
+ /**
12
+ * `{}` here is deliberate and load-bearing, not a placeholder for
13
+ * `Record<string, never>`: an index-signature type like `Record<string,
14
+ * never>` still matches *any* string key (just resolving its value to
15
+ * `never`), so `collection("articles")` would keep hitting the typed
16
+ * overload and silently infer `never` instead of falling through to the
17
+ * untyped `Record<string, unknown>` overload. A closed `{}` has no keys at
18
+ * all, so `keyof {}` is `never` and no real slug can ever match it —
19
+ * exactly the "untyped by default" behavior this default is for.
20
+ */
21
+ export interface EmptyRegistry extends SaCMSRegistryShape {
22
+ collections: {};
120
23
  singles: {};
121
24
  }
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  /**
3
- * AUTO-GENERATED FILE — DO NOT EDIT DIRECTLY
4
- * This file was generated by scripts/generate.ts
3
+ * Default, empty registry shipped with the package — no tenant-specific
4
+ * schema is baked in here. `npx @sacms/sdk generate` produces your own
5
+ * registry file from your real workspace; pass it to `new SaCMS<MyRegistry>`
6
+ * instead of relying on this default (see client.ts's class doc comment).
5
7
  */
6
8
  Object.defineProperty(exports, "__esModule", { value: true });
package/dist/index.d.ts CHANGED
@@ -1,2 +1,5 @@
1
1
  export { SaCMS, SaCMSError } from "./client";
2
2
  export type { SaCMSConfig, FindManyParams, FindSingleParams, CollectionResponse, SingleResponse, GraphQLResponse, PaginationMeta, PaginationParams, Filters, FilterOperators, MutateParams, } from "./types";
3
+ export type { SaCMSRegistryShape, EmptyRegistry } from "./generated-types";
4
+ export { AuthClient } from "./auth";
5
+ export type { MemberUser, AuthSession, RegisterParams, RegisterResult, UpdateProfileParams, ChangePasswordParams, ResetPasswordParams, } from "./auth";
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SaCMSError = exports.SaCMS = void 0;
3
+ exports.AuthClient = exports.SaCMSError = exports.SaCMS = void 0;
4
4
  var client_1 = require("./client");
5
5
  Object.defineProperty(exports, "SaCMS", { enumerable: true, get: function () { return client_1.SaCMS; } });
6
6
  Object.defineProperty(exports, "SaCMSError", { enumerable: true, get: function () { return client_1.SaCMSError; } });
7
+ var auth_1 = require("./auth");
8
+ Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return auth_1.AuthClient; } });
package/dist/types.d.ts CHANGED
@@ -57,8 +57,8 @@ export interface SingleResponse<T = Record<string, unknown>> {
57
57
  singleType: {
58
58
  name: string;
59
59
  slug: string;
60
- fields: unknown[];
61
60
  };
61
+ locale: string;
62
62
  };
63
63
  }
64
64
  export interface GraphQLResponse<T = Record<string, unknown>> {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sacms/sdk",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "TypeScript SDK for SaCMS headless CMS",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -14,7 +14,8 @@
14
14
  "clean": "rimraf dist",
15
15
  "build": "npm run clean && tsc",
16
16
  "dev": "tsc --watch",
17
- "prepublishOnly": "npm run build"
17
+ "test": "vitest run",
18
+ "prepublishOnly": "npm run build && npm run test"
18
19
  },
19
20
  "publishConfig": {
20
21
  "access": "public"
@@ -28,6 +29,7 @@
28
29
  "license": "MIT",
29
30
  "devDependencies": {
30
31
  "rimraf": "^5.0.0",
31
- "typescript": "^5.5.0"
32
+ "typescript": "^5.5.0",
33
+ "vitest": "^2.1.9"
32
34
  }
33
35
  }