@byterings-dev/sdk 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ByteRings
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,94 @@
1
+ import type { ConfigDocument, ConfigPlan, CreateEntityRequest, EntityDefinition, FilterOperator, PageMeta, RecordItem, Tenant, UpdateEntityRequest } from '@byterings-dev/contracts';
2
+ export interface ClientOptions {
3
+ /** API origin, e.g. https://cms.example.com (the /api/v1 prefix is added). */
4
+ baseUrl: string;
5
+ /** Tenant API key (Authorization: Bearer). */
6
+ apiKey?: string;
7
+ /** Custom fetch implementation (defaults to global fetch). */
8
+ fetch?: typeof fetch;
9
+ headers?: Record<string, string>;
10
+ }
11
+ /** Error returned by the API, carrying its stable error code. */
12
+ export declare class PlatformError extends Error {
13
+ readonly status: number;
14
+ readonly code: string;
15
+ readonly details?: unknown | undefined;
16
+ constructor(status: number, code: string, message: string, details?: unknown | undefined);
17
+ }
18
+ export type TypedRecord<T> = Omit<RecordItem, 'data'> & {
19
+ data: T;
20
+ };
21
+ export type FilterValue = string | number | boolean | Array<string | number>;
22
+ export type Filter = Record<string, FilterValue | Partial<Record<FilterOperator, FilterValue>>>;
23
+ export interface ListOptions {
24
+ page?: number;
25
+ pageSize?: number;
26
+ /** e.g. ['-price', 'name'] */
27
+ sort?: string[];
28
+ fields?: string[];
29
+ search?: string;
30
+ expand?: string[];
31
+ filter?: Filter;
32
+ deleted?: boolean;
33
+ }
34
+ export interface Page<T> {
35
+ data: T[];
36
+ meta: PageMeta;
37
+ }
38
+ type Query = Record<string, string | undefined>;
39
+ /** Serializes list options to the API's query syntax. */
40
+ export declare function listQuery(options?: ListOptions): Query;
41
+ export declare class PlatformClient {
42
+ private readonly options;
43
+ private readonly baseUrl;
44
+ private readonly fetchImpl;
45
+ constructor(options: ClientOptions);
46
+ request<T>(method: string, path: string, opts?: {
47
+ query?: Query;
48
+ body?: unknown;
49
+ }): Promise<T>;
50
+ /** Current tenant. */
51
+ tenant(): Promise<Tenant>;
52
+ /** Entity (metadata) management. */
53
+ readonly entities: {
54
+ list: () => Promise<EntityDefinition[]>;
55
+ get: (id: string) => Promise<EntityDefinition>;
56
+ create: (input: CreateEntityRequest) => Promise<EntityDefinition>;
57
+ update: (id: string, input: UpdateEntityRequest) => Promise<EntityDefinition>;
58
+ remove: (id: string) => Promise<void>;
59
+ };
60
+ /** Configuration as code. */
61
+ readonly config: {
62
+ export: () => Promise<ConfigDocument>;
63
+ diff: (document: ConfigDocument, opts?: {
64
+ prune?: boolean;
65
+ }) => Promise<ConfigPlan>;
66
+ apply: (document: ConfigDocument, opts?: {
67
+ prune?: boolean;
68
+ confirmDestructive?: boolean;
69
+ }) => Promise<ConfigPlan>;
70
+ };
71
+ /** OpenAPI documents. */
72
+ readonly openapi: {
73
+ platform: () => Promise<Record<string, unknown>>;
74
+ tenant: () => Promise<Record<string, unknown>>;
75
+ };
76
+ /** Records of one entity. Pass a type for typed `data`. */
77
+ records<T extends Record<string, unknown> = Record<string, unknown>>(entityKey: string): {
78
+ list: (options?: ListOptions) => Promise<Page<TypedRecord<T>>>;
79
+ get: (id: string, opts?: {
80
+ fields?: string[];
81
+ expand?: string[];
82
+ }) => Promise<TypedRecord<T>>;
83
+ create: (data: Partial<T>) => Promise<TypedRecord<T>>;
84
+ update: (id: string, data: Partial<T>, opts?: {
85
+ version?: number;
86
+ }) => Promise<TypedRecord<T>>;
87
+ delete: (id: string) => Promise<void>;
88
+ restore: (id: string) => Promise<TypedRecord<T>>;
89
+ };
90
+ /** Async iterator over all matching records of an entity. */
91
+ iterate<T extends Record<string, unknown> = Record<string, unknown>>(entityKey: string, options?: Omit<ListOptions, 'page'>): AsyncGenerator<TypedRecord<T>>;
92
+ }
93
+ export declare function createClient(options: ClientOptions): PlatformClient;
94
+ export {};
package/dist/client.js ADDED
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PlatformClient = exports.PlatformError = void 0;
4
+ exports.listQuery = listQuery;
5
+ exports.createClient = createClient;
6
+ /** Error returned by the API, carrying its stable error code. */
7
+ class PlatformError extends Error {
8
+ status;
9
+ code;
10
+ details;
11
+ constructor(status, code, message, details) {
12
+ super(message);
13
+ this.status = status;
14
+ this.code = code;
15
+ this.details = details;
16
+ this.name = 'PlatformError';
17
+ }
18
+ }
19
+ exports.PlatformError = PlatformError;
20
+ function filterValue(value) {
21
+ return Array.isArray(value) ? value.join(',') : String(value);
22
+ }
23
+ /** Serializes list options to the API's query syntax. */
24
+ function listQuery(options = {}) {
25
+ const query = {
26
+ page: options.page?.toString(),
27
+ pageSize: options.pageSize?.toString(),
28
+ sort: options.sort?.join(','),
29
+ fields: options.fields?.join(','),
30
+ search: options.search,
31
+ expand: options.expand?.join(','),
32
+ deleted: options.deleted ? 'true' : undefined,
33
+ };
34
+ for (const [key, spec] of Object.entries(options.filter ?? {})) {
35
+ if (typeof spec === 'object' && !Array.isArray(spec)) {
36
+ for (const [op, value] of Object.entries(spec)) {
37
+ if (value !== undefined)
38
+ query[`filter[${key}][${op}]`] = filterValue(value);
39
+ }
40
+ }
41
+ else {
42
+ query[`filter[${key}]`] = filterValue(spec);
43
+ }
44
+ }
45
+ return query;
46
+ }
47
+ class PlatformClient {
48
+ options;
49
+ baseUrl;
50
+ fetchImpl;
51
+ constructor(options) {
52
+ this.options = options;
53
+ this.baseUrl = `${options.baseUrl.replace(/\/+$/, '')}/api/v1`;
54
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
55
+ }
56
+ async request(method, path, opts = {}) {
57
+ const url = new URL(`${this.baseUrl}${path}`);
58
+ for (const [key, value] of Object.entries(opts.query ?? {})) {
59
+ if (value !== undefined && value !== '')
60
+ url.searchParams.set(key, value);
61
+ }
62
+ const headers = { accept: 'application/json', ...this.options.headers };
63
+ if (this.options.apiKey)
64
+ headers.authorization = `Bearer ${this.options.apiKey}`;
65
+ if (opts.body !== undefined)
66
+ headers['content-type'] = 'application/json';
67
+ let response;
68
+ try {
69
+ response = await this.fetchImpl(url, {
70
+ method,
71
+ headers,
72
+ body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
73
+ });
74
+ }
75
+ catch (error) {
76
+ throw new PlatformError(0, 'NETWORK_ERROR', `Cannot reach the API at ${url.origin} (${error instanceof Error ? error.message : 'network error'})`);
77
+ }
78
+ if (response.status === 204)
79
+ return undefined;
80
+ const payload = await response.json().catch(() => null);
81
+ if (!response.ok) {
82
+ const error = payload?.error;
83
+ throw new PlatformError(response.status, error?.code ?? 'HTTP_ERROR', error?.message ?? `Request failed with status ${response.status}`, error?.details);
84
+ }
85
+ return payload;
86
+ }
87
+ /** Current tenant. */
88
+ async tenant() {
89
+ return (await this.request('GET', '/tenant')).data;
90
+ }
91
+ /** Entity (metadata) management. */
92
+ entities = {
93
+ list: async () => (await this.request('GET', '/admin/entities')).data,
94
+ get: async (id) => (await this.request('GET', `/admin/entities/${id}`)).data,
95
+ create: async (input) => (await this.request('POST', '/admin/entities', { body: input }))
96
+ .data,
97
+ update: async (id, input) => (await this.request('PATCH', `/admin/entities/${id}`, {
98
+ body: input,
99
+ })).data,
100
+ remove: async (id) => this.request('DELETE', `/admin/entities/${id}`),
101
+ };
102
+ /** Configuration as code. */
103
+ config = {
104
+ export: async () => (await this.request('GET', '/admin/config/export')).data,
105
+ diff: async (document, opts = {}) => (await this.request('POST', '/admin/config/diff', {
106
+ body: document,
107
+ query: { prune: opts.prune ? 'true' : undefined },
108
+ })).data,
109
+ apply: async (document, opts = {}) => (await this.request('POST', '/admin/config/apply', {
110
+ body: {
111
+ ...document,
112
+ prune: opts.prune ?? false,
113
+ confirmDestructive: opts.confirmDestructive ?? false,
114
+ },
115
+ })).data,
116
+ };
117
+ /** OpenAPI documents. */
118
+ openapi = {
119
+ platform: () => this.request('GET', '/openapi.json'),
120
+ tenant: () => this.request('GET', '/openapi/tenant.json'),
121
+ };
122
+ /** Records of one entity. Pass a type for typed `data`. */
123
+ records(entityKey) {
124
+ const base = `/entities/${encodeURIComponent(entityKey)}/records`;
125
+ return {
126
+ list: (options = {}) => this.request('GET', base, { query: listQuery(options) }),
127
+ get: async (id, opts = {}) => (await this.request('GET', `${base}/${id}`, {
128
+ query: { fields: opts.fields?.join(','), expand: opts.expand?.join(',') },
129
+ })).data,
130
+ create: async (data) => (await this.request('POST', base, { body: { data } })).data,
131
+ update: async (id, data, opts = {}) => (await this.request('PATCH', `${base}/${id}`, {
132
+ body: { data, ...(opts.version !== undefined ? { version: opts.version } : {}) },
133
+ })).data,
134
+ delete: (id) => this.request('DELETE', `${base}/${id}`),
135
+ restore: async (id) => (await this.request('POST', `${base}/${id}/restore`)).data,
136
+ };
137
+ }
138
+ /** Async iterator over all matching records of an entity. */
139
+ async *iterate(entityKey, options = {}) {
140
+ const pageSize = options.pageSize ?? 100;
141
+ for (let page = 1;; page++) {
142
+ const result = await this.records(entityKey).list({ ...options, page, pageSize });
143
+ yield* result.data;
144
+ if (page >= result.meta.totalPages)
145
+ return;
146
+ }
147
+ }
148
+ }
149
+ exports.PlatformClient = PlatformClient;
150
+ function createClient(options) {
151
+ return new PlatformClient(options);
152
+ }
153
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAiEA,8BAoBC;AAyJD,oCAEC;AAzND,iEAAiE;AACjE,MAAa,aAAc,SAAQ,KAAK;IAEpB;IACA;IAEA;IAJlB,YACkB,MAAc,EACd,IAAY,EAC5B,OAAe,EACC,OAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QALC,WAAM,GAAN,MAAM,CAAQ;QACd,SAAI,GAAJ,IAAI,CAAQ;QAEZ,YAAO,GAAP,OAAO,CAAU;QAGjC,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AAVD,sCAUC;AA0BD,SAAS,WAAW,CAAC,KAAkB;IACrC,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED,yDAAyD;AACzD,SAAgB,SAAS,CAAC,UAAuB,EAAE;IACjD,MAAM,KAAK,GAAU;QACnB,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE;QAC9B,QAAQ,EAAE,OAAO,CAAC,QAAQ,EAAE,QAAQ,EAAE;QACtC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC;QAC7B,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC;QACjC,MAAM,EAAE,OAAO,CAA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AC,QAAQ,EAAE,GAAG,IAAI,IAAI,EAAE,EAAE,CAAC;YAC9E,OAAO,EAAE,KAAK,EAAE,EAAU,EAA2B,EAAE,CACrD,CAAC,MAAM,IAAI,CAAC,OAAO,CAA2B,MAAM,EAAE,GAAG,IAAI,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,IAAI;SACvF,CAAC;IACJ,CAAC;IAED,6DAA6D;IAC7D,KAAK,CAAC,CAAC,OAAO,CACZ,SAAiB,EACjB,UAAqC,EAAE;QAEvC,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,GAAG,CAAC;QACzC,KAAK,IAAI,IAAI,GAAG,CAAC,GAAI,IAAI,EAAE,EAAE,CAAC;YAC5B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAI,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;YACrF,KAAK,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;YACnB,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,UAAU;gBAAE,OAAO;QAC7C,CAAC;IACH,CAAC;CACF;AArJD,wCAqJC;AAED,SAAgB,YAAY,CAAC,OAAsB;IACjD,OAAO,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;AACrC,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { type EntityDefinition } from '@byterings-dev/contracts';
2
+ /**
3
+ * Generates TypeScript interfaces for entity record data, for use with
4
+ * `client.records<Product>('product')`.
5
+ */
6
+ export declare function generateTypes(entities: EntityDefinition[]): string;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateTypes = generateTypes;
4
+ const contracts_1 = require("@byterings-dev/contracts");
5
+ function pascal(key) {
6
+ return key
7
+ .split(/[^a-zA-Z0-9]+/)
8
+ .filter(Boolean)
9
+ .map((w) => w[0].toUpperCase() + w.slice(1))
10
+ .join('');
11
+ }
12
+ function tsType(field) {
13
+ switch (field.type) {
14
+ case 'text':
15
+ case 'longtext':
16
+ case 'decimal':
17
+ case 'date':
18
+ case 'datetime':
19
+ return 'string';
20
+ case 'integer':
21
+ return 'number';
22
+ case 'boolean':
23
+ return 'boolean';
24
+ case 'select':
25
+ return contracts_1.fieldConfigSchemas.select
26
+ .parse(field.config)
27
+ .options.map((o) => JSON.stringify(o.value))
28
+ .join(' | ');
29
+ case 'multiselect':
30
+ return `Array<${contracts_1.fieldConfigSchemas.multiselect
31
+ .parse(field.config)
32
+ .options.map((o) => JSON.stringify(o.value))
33
+ .join(' | ')}>`;
34
+ case 'relation':
35
+ return contracts_1.fieldConfigSchemas.relation.parse(field.config).cardinality === 'many'
36
+ ? 'string[]'
37
+ : 'string';
38
+ case 'media':
39
+ return contracts_1.fieldConfigSchemas.media.parse(field.config).multiple ? 'string[]' : 'string';
40
+ }
41
+ }
42
+ /**
43
+ * Generates TypeScript interfaces for entity record data, for use with
44
+ * `client.records<Product>('product')`.
45
+ */
46
+ function generateTypes(entities) {
47
+ const lines = [
48
+ '// Generated from platform metadata. Do not edit by hand.',
49
+ '// Regenerate with: bytecontent types',
50
+ '',
51
+ ];
52
+ for (const entity of [...entities].sort((a, b) => a.key.localeCompare(b.key))) {
53
+ lines.push(`/** ${entity.name} (\`${entity.key}\`) */`);
54
+ lines.push(`export interface ${pascal(entity.key)} {`);
55
+ for (const field of entity.fields) {
56
+ const doc = field.description ? ` ${field.description}` : '';
57
+ lines.push(` /** ${field.label}${doc} */`);
58
+ lines.push(` ${field.key}: ${tsType(field)}${field.required ? '' : ' | null'};`);
59
+ }
60
+ lines.push('}', '');
61
+ }
62
+ lines.push('export interface EntityTypes {');
63
+ for (const entity of entities)
64
+ lines.push(` ${JSON.stringify(entity.key)}: ${pascal(entity.key)};`);
65
+ lines.push('}', '');
66
+ return lines.join('\n');
67
+ }
68
+ //# sourceMappingURL=codegen.js.map
@@ -0,0 +1 @@
1
+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AC,CAAC,SAAS,GAAG,CAAC,CAAC;QACpF,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACtB,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;IAC7C,KAAK,MAAM,MAAM,IAAI,QAAQ;QAC3B,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACxE,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './client';
2
+ export * from './codegen';
3
+ export type { ConfigDocument, ConfigPlan, EntityDefinition, FieldDefinition, PageMeta, RecordItem, } from '@byterings-dev/contracts';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./client"), exports);
18
+ __exportStar(require("./codegen"), exports);
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAyB;AACzB,4CAA0B"}
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@byterings-dev/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "https://github.com/byterings/byteringscms.git",
7
+ "directory": "packages/sdk"
8
+ },
9
+ "license": "MIT",
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "description": "TypeScript client for the platform REST API.",
14
+ "main": "dist/index.js",
15
+ "types": "dist/index.d.ts",
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "dependencies": {
20
+ "@byterings-dev/contracts": "0.1.1"
21
+ },
22
+ "devDependencies": {
23
+ "vitest": "^3"
24
+ },
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.build.json",
27
+ "dev": "tsc -p tsconfig.build.json --watch --preserveWatchOutput",
28
+ "lint": "eslint src",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit",
30
+ "test": "vitest run"
31
+ }
6
32
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.