@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/dist/cli.js ADDED
@@ -0,0 +1,176 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * SaCMS SDK Type Generator CLI
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.
8
+ *
9
+ * Usage:
10
+ * npx @sacms/sdk generate --url http://localhost:3000 --tenant demo --token <token> --out src/types/sacms.d.ts
11
+ */
12
+ var __importDefault = (this && this.__importDefault) || function (mod) {
13
+ return (mod && mod.__esModule) ? mod : { "default": mod };
14
+ };
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.unwrap = unwrap;
17
+ exports.scalarToTs = scalarToTs;
18
+ exports.buildInterface = buildInterface;
19
+ const fs_1 = __importDefault(require("fs"));
20
+ const path_1 = __importDefault(require("path"));
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":
58
+ return "string";
59
+ case "Int":
60
+ case "Float":
61
+ return "number";
62
+ case "Boolean":
63
+ return "boolean";
64
+ case "JSON":
65
+ return "Record<string, unknown> | unknown[]";
66
+ default:
67
+ return "unknown";
68
+ }
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
+ }
80
+ async function main() {
81
+ const args = process.argv.slice(2);
82
+ let url = "http://localhost:3000";
83
+ let tenant = "global";
84
+ let token = "";
85
+ let outPath = "./sacms.d.ts";
86
+ for (let i = 0; i < args.length; i++) {
87
+ if (args[i] === "--url" && args[i + 1])
88
+ url = args[++i];
89
+ if (args[i] === "--tenant" && args[i + 1])
90
+ tenant = args[++i];
91
+ if (args[i] === "--token" && args[i + 1])
92
+ token = args[++i];
93
+ if (args[i] === "--out" && args[i + 1])
94
+ outPath = args[++i];
95
+ }
96
+ console.log(`📡 Fetching SaCMS schema from ${url} (Tenant: ${tenant})...`);
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}`);
146
+ }
147
+ }
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 });
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}`);
170
+ }
171
+ if (require.main === module) {
172
+ main().catch((err) => {
173
+ console.error(`❌ Failed to generate SaCMS types:`, err?.message || err);
174
+ process.exit(1);
175
+ });
176
+ }
@@ -0,0 +1,148 @@
1
+ import type { SaCMSConfig, FindManyParams, FindSingleParams, CollectionResponse, SingleResponse, GraphQLResponse, MutateParams } from "./types";
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> {
21
+ private baseUrl;
22
+ private tenant;
23
+ private token;
24
+ private defaultLocale?;
25
+ /** Member (end-user) authentication — login, register, session, profile. */
26
+ readonly auth: AuthClient;
27
+ constructor(config: SaCMSConfig);
28
+ /**
29
+ * Access a collection content type for querying or mutating entries.
30
+ */
31
+ collection<K extends keyof Registry["collections"]>(slug: K): CollectionClient<Registry["collections"][K]>;
32
+ collection<T = Record<string, unknown>>(slug: string): CollectionClient<T>;
33
+ /**
34
+ * Access a single type for querying its content.
35
+ */
36
+ single<K extends keyof Registry["singles"]>(slug: K): SingleClient<Registry["singles"][K]>;
37
+ single<T = Record<string, unknown>>(slug: string): SingleClient<T>;
38
+ /**
39
+ * Execute a raw GraphQL query or mutation.
40
+ */
41
+ graphql<T = Record<string, unknown>>(query: string, variables?: Record<string, unknown>): Promise<GraphQLResponse<T>>;
42
+ /** @internal */
43
+ request<T>(path: string, init?: RequestInit, retries?: number): Promise<T>;
44
+ /** @internal */
45
+ getDefaultLocale(): string | undefined;
46
+ /** @internal */
47
+ getTenant(): string;
48
+ }
49
+ declare class CollectionClient<T> {
50
+ private cf;
51
+ private slug;
52
+ constructor(cf: SaCMS<any>, slug: string);
53
+ /**
54
+ * Start a fluent query builder chain.
55
+ */
56
+ query(): QueryBuilder<T>;
57
+ /**
58
+ * Query multiple entries with filtering, sorting, pagination, and field selection.
59
+ */
60
+ findMany(params?: FindManyParams): Promise<CollectionResponse<T>>;
61
+ /**
62
+ * Get a single entry by ID.
63
+ */
64
+ findOne(id: string): Promise<{
65
+ data: T;
66
+ }>;
67
+ /**
68
+ * Create a new entry (requires full-access token).
69
+ */
70
+ create(params: MutateParams): Promise<{
71
+ data: T;
72
+ }>;
73
+ /**
74
+ * Update an entry by ID (requires full-access token).
75
+ */
76
+ update(id: string, params: MutateParams): Promise<{
77
+ data: T;
78
+ }>;
79
+ /**
80
+ * Delete an entry by ID (requires full-access token).
81
+ */
82
+ delete(id: string): Promise<{
83
+ success: boolean;
84
+ }>;
85
+ }
86
+ declare class SingleClient<T> {
87
+ private cf;
88
+ private slug;
89
+ constructor(cf: SaCMS<any>, slug: string);
90
+ /**
91
+ * Get the single type content.
92
+ */
93
+ find(params?: FindSingleParams): Promise<SingleResponse<T>>;
94
+ /**
95
+ * Update the single type content (requires full-access token).
96
+ */
97
+ update(data: Record<string, unknown>): Promise<SingleResponse<T>>;
98
+ }
99
+ export declare class SaCMSError extends Error {
100
+ status: number;
101
+ constructor(message: string, status: number);
102
+ }
103
+ export declare class QueryBuilder<T> {
104
+ private client;
105
+ private params;
106
+ constructor(client: CollectionClient<T>);
107
+ /**
108
+ * Filter data. E.g. .where('status', 'eq', 'PUBLISHED')
109
+ */
110
+ where(field: string, operator: string, value: any): this;
111
+ /**
112
+ * Select specific fields to return. E.g. .select(['title', 'slug', 'cover'])
113
+ */
114
+ select(fields: string[]): this;
115
+ /**
116
+ * Select specific relations to populate. E.g. .populate(['author'])
117
+ */
118
+ populate(fields: string[]): this;
119
+ /**
120
+ * Sort results. E.g. .sort('createdAt:desc') or .sort('title:asc')
121
+ */
122
+ sort(sortOrder: string): this;
123
+ /**
124
+ * Full-text search across content entries. E.g. .search('nextjs tutorial')
125
+ */
126
+ search(query: string): this;
127
+ /**
128
+ * Target a specific locale. E.g. .locale('id') or .locale('en')
129
+ */
130
+ locale(loc: string): this;
131
+ /**
132
+ * Filter by status. E.g. .status('PUBLISHED') or .status('DRAFT')
133
+ */
134
+ status(st: string): this;
135
+ /**
136
+ * Limit the number of returned entries.
137
+ */
138
+ limit(pageSize: number): this;
139
+ /**
140
+ * Skip a number of pages.
141
+ */
142
+ page(pageNumber: number): this;
143
+ /**
144
+ * Execute the query and fetch the results.
145
+ */
146
+ fetch(): Promise<CollectionResponse<T>>;
147
+ }
148
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,337 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
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
+ */
21
+ class SaCMS {
22
+ constructor(config) {
23
+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");
24
+ this.tenant = config.tenant;
25
+ this.token = config.token;
26
+ this.defaultLocale = config.locale ?? "id";
27
+ this.auth = new auth_1.AuthClient(this);
28
+ }
29
+ collection(slug) {
30
+ return new CollectionClient(this, slug);
31
+ }
32
+ single(slug) {
33
+ return new SingleClient(this, slug);
34
+ }
35
+ /**
36
+ * Execute a raw GraphQL query or mutation.
37
+ */
38
+ async graphql(query, variables) {
39
+ return this.request(`/api/public/${this.tenant}/graphql`, {
40
+ method: "POST",
41
+ body: JSON.stringify({ query, variables }),
42
+ });
43
+ }
44
+ /** @internal */
45
+ async request(path, init, retries = 3) {
46
+ const url = `${this.baseUrl}${path}`;
47
+ const headers = {
48
+ Authorization: `Bearer ${this.token}`,
49
+ "Content-Type": "application/json",
50
+ ...init?.headers,
51
+ };
52
+ for (let attempt = 0; attempt <= retries; attempt++) {
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
+ }
69
+ if (res.status === 429 && attempt < retries) {
70
+ const retryAfter = res.headers.get("Retry-After");
71
+ const delay = retryAfter ? parseInt(retryAfter, 10) * 1000 : 1000 * Math.pow(2, attempt);
72
+ await new Promise(r => setTimeout(r, delay));
73
+ continue;
74
+ }
75
+ if (!res.ok) {
76
+ const body = await res.text();
77
+ let message;
78
+ try {
79
+ const json = JSON.parse(body);
80
+ message = json.error || json.message || body;
81
+ }
82
+ catch {
83
+ message = body;
84
+ }
85
+ throw new SaCMSError(message, res.status);
86
+ }
87
+ return res.json();
88
+ }
89
+ throw new SaCMSError("Max retries reached", 429);
90
+ }
91
+ /** @internal */
92
+ getDefaultLocale() {
93
+ return this.defaultLocale;
94
+ }
95
+ /** @internal */
96
+ getTenant() {
97
+ return this.tenant;
98
+ }
99
+ }
100
+ exports.SaCMS = SaCMS;
101
+ class CollectionClient {
102
+ constructor(cf, slug) {
103
+ this.cf = cf;
104
+ this.slug = slug;
105
+ }
106
+ /**
107
+ * Start a fluent query builder chain.
108
+ */
109
+ query() {
110
+ return new QueryBuilder(this);
111
+ }
112
+ /**
113
+ * Query multiple entries with filtering, sorting, pagination, and field selection.
114
+ */
115
+ async findMany(params) {
116
+ const qs = buildQueryString(params, this.cf.getDefaultLocale());
117
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}${qs}`);
118
+ }
119
+ /**
120
+ * Get a single entry by ID.
121
+ */
122
+ async findOne(id) {
123
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}/${encodeURIComponent(id)}`);
124
+ }
125
+ /**
126
+ * Create a new entry (requires full-access token).
127
+ */
128
+ async create(params) {
129
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}`, {
130
+ method: "POST",
131
+ body: JSON.stringify({
132
+ data: params.data,
133
+ locale: params.locale ?? this.cf.getDefaultLocale(),
134
+ status: params.status,
135
+ }),
136
+ });
137
+ }
138
+ /**
139
+ * Update an entry by ID (requires full-access token).
140
+ */
141
+ async update(id, params) {
142
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}/${encodeURIComponent(id)}`, {
143
+ method: "PUT",
144
+ body: JSON.stringify({
145
+ data: params.data,
146
+ locale: params.locale ?? this.cf.getDefaultLocale(),
147
+ status: params.status,
148
+ }),
149
+ });
150
+ }
151
+ /**
152
+ * Delete an entry by ID (requires full-access token).
153
+ */
154
+ async delete(id) {
155
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/content/${this.slug}/${encodeURIComponent(id)}`, { method: "DELETE" });
156
+ }
157
+ }
158
+ class SingleClient {
159
+ constructor(cf, slug) {
160
+ this.cf = cf;
161
+ this.slug = slug;
162
+ }
163
+ /**
164
+ * Get the single type content.
165
+ */
166
+ async find(params) {
167
+ const locale = params?.locale ?? this.cf.getDefaultLocale();
168
+ const qs = locale ? `?locale=${encodeURIComponent(locale)}` : "";
169
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/single/${this.slug}${qs}`);
170
+ }
171
+ /**
172
+ * Update the single type content (requires full-access token).
173
+ */
174
+ async update(data) {
175
+ return this.cf.request(`/api/public/${this.cf.getTenant()}/single/${this.slug}`, {
176
+ method: "PUT",
177
+ body: JSON.stringify({ data }),
178
+ });
179
+ }
180
+ }
181
+ class SaCMSError extends Error {
182
+ constructor(message, status) {
183
+ super(message);
184
+ this.status = status;
185
+ this.name = "SaCMSError";
186
+ }
187
+ }
188
+ exports.SaCMSError = SaCMSError;
189
+ class QueryBuilder {
190
+ constructor(client) {
191
+ this.client = client;
192
+ this.params = {};
193
+ }
194
+ /**
195
+ * Filter data. E.g. .where('status', 'eq', 'PUBLISHED')
196
+ */
197
+ where(field, operator, value) {
198
+ if (!this.params.filters)
199
+ this.params.filters = {};
200
+ if (!this.params.filters[field])
201
+ this.params.filters[field] = {};
202
+ const op = operator.startsWith('$') ? operator : `$${operator}`;
203
+ this.params.filters[field][op] = value;
204
+ return this;
205
+ }
206
+ /**
207
+ * Select specific fields to return. E.g. .select(['title', 'slug', 'cover'])
208
+ */
209
+ select(fields) {
210
+ this.params.fields = fields;
211
+ return this;
212
+ }
213
+ /**
214
+ * Select specific relations to populate. E.g. .populate(['author'])
215
+ */
216
+ populate(fields) {
217
+ this.params.populate = fields;
218
+ return this;
219
+ }
220
+ /**
221
+ * Sort results. E.g. .sort('createdAt:desc') or .sort('title:asc')
222
+ */
223
+ sort(sortOrder) {
224
+ this.params.sort = sortOrder;
225
+ return this;
226
+ }
227
+ /**
228
+ * Full-text search across content entries. E.g. .search('nextjs tutorial')
229
+ */
230
+ search(query) {
231
+ this.params.search = query;
232
+ return this;
233
+ }
234
+ /**
235
+ * Target a specific locale. E.g. .locale('id') or .locale('en')
236
+ */
237
+ locale(loc) {
238
+ this.params.locale = loc;
239
+ return this;
240
+ }
241
+ /**
242
+ * Filter by status. E.g. .status('PUBLISHED') or .status('DRAFT')
243
+ */
244
+ status(st) {
245
+ this.params.status = st;
246
+ return this;
247
+ }
248
+ /**
249
+ * Limit the number of returned entries.
250
+ */
251
+ limit(pageSize) {
252
+ if (!this.params.pagination)
253
+ this.params.pagination = {};
254
+ this.params.pagination.pageSize = pageSize;
255
+ return this;
256
+ }
257
+ /**
258
+ * Skip a number of pages.
259
+ */
260
+ page(pageNumber) {
261
+ if (!this.params.pagination)
262
+ this.params.pagination = {};
263
+ this.params.pagination.page = pageNumber;
264
+ return this;
265
+ }
266
+ /**
267
+ * Execute the query and fetch the results.
268
+ */
269
+ async fetch() {
270
+ return this.client.findMany(this.params);
271
+ }
272
+ }
273
+ exports.QueryBuilder = QueryBuilder;
274
+ // ─── Helpers ────────────────────────────────────────────
275
+ function buildQueryString(params, defaultLocale) {
276
+ if (!params)
277
+ return "";
278
+ const parts = [];
279
+ if (params.filters) {
280
+ flattenFilters(params.filters, "filters", parts);
281
+ }
282
+ if (params.fields?.length) {
283
+ parts.push(`fields=${params.fields.map(encodeURIComponent).join(",")}`);
284
+ }
285
+ if (params.populate?.length) {
286
+ parts.push(`populate=${params.populate.map(encodeURIComponent).join(",")}`);
287
+ }
288
+ const locale = params.locale ?? defaultLocale;
289
+ if (locale) {
290
+ parts.push(`locale=${encodeURIComponent(locale)}`);
291
+ }
292
+ if (params.sort) {
293
+ parts.push(`sort=${encodeURIComponent(params.sort)}`);
294
+ }
295
+ if (params.pagination) {
296
+ if (params.pagination.page != null) {
297
+ parts.push(`pagination[page]=${params.pagination.page}`);
298
+ }
299
+ if (params.pagination.pageSize != null) {
300
+ parts.push(`pagination[pageSize]=${params.pagination.pageSize}`);
301
+ }
302
+ }
303
+ if (params.search) {
304
+ parts.push(`search=${encodeURIComponent(params.search)}`);
305
+ }
306
+ if (params.status) {
307
+ parts.push(`status=${encodeURIComponent(params.status)}`);
308
+ }
309
+ return parts.length ? `?${parts.join("&")}` : "";
310
+ }
311
+ function flattenFilters(filters, prefix, parts) {
312
+ for (const [key, value] of Object.entries(filters)) {
313
+ if (key === "$or" || key === "$and") {
314
+ const arr = value;
315
+ arr.forEach((item, i) => {
316
+ flattenFilters(item, `${prefix}[${key}][${i}]`, parts);
317
+ });
318
+ }
319
+ else if (typeof value === "object" && value !== null && !Array.isArray(value)) {
320
+ const ops = value;
321
+ for (const [op, opVal] of Object.entries(ops)) {
322
+ if (Array.isArray(opVal)) {
323
+ opVal.forEach((v, i) => {
324
+ parts.push(`${prefix}[${encodeURIComponent(key)}][${op}][${i}]=${encodeURIComponent(String(v))}`);
325
+ });
326
+ }
327
+ else {
328
+ parts.push(`${prefix}[${encodeURIComponent(key)}][${op}]=${encodeURIComponent(String(opVal))}`);
329
+ }
330
+ }
331
+ }
332
+ else {
333
+ // Shorthand: filters[field]=value → filters[field][$eq]=value
334
+ parts.push(`${prefix}[${encodeURIComponent(key)}][$eq]=${encodeURIComponent(String(value))}`);
335
+ }
336
+ }
337
+ }
@@ -0,0 +1,24 @@
1
+ /**
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).
6
+ */
7
+ export interface SaCMSRegistryShape {
8
+ collections: Record<string, unknown>;
9
+ singles: Record<string, unknown>;
10
+ }
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: {};
23
+ singles: {};
24
+ }
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ /**
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).
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });