@cogover/sdk 0.1.2 → 0.5.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.
Files changed (46) hide show
  1. package/README.md +250 -24
  2. package/dist/data.d.ts +44 -0
  3. package/dist/data.js +143 -0
  4. package/dist/errors.d.ts +30 -0
  5. package/dist/errors.js +62 -0
  6. package/dist/fetch.d.ts +28 -0
  7. package/dist/fetch.js +96 -0
  8. package/dist/index.d.ts +21 -3
  9. package/dist/index.js +7 -5
  10. package/dist/internal/bridge.js +48 -0
  11. package/dist/internal/invocation.js +57 -0
  12. package/dist/internal/request.js +87 -0
  13. package/dist/internal/validation.js +28 -0
  14. package/dist/internal/values.js +6 -0
  15. package/dist/invocation.d.ts +40 -0
  16. package/dist/invocation.js +1 -0
  17. package/dist/legacy.d.ts +2 -0
  18. package/dist/legacy.js +4 -0
  19. package/dist/locks.d.ts +19 -0
  20. package/dist/locks.js +68 -0
  21. package/dist/logger.d.ts +6 -0
  22. package/dist/logger.js +14 -0
  23. package/dist/query.d.ts +52 -0
  24. package/dist/query.js +59 -0
  25. package/dist/records.d.ts +74 -0
  26. package/dist/records.js +1 -0
  27. package/dist/request.d.ts +18 -0
  28. package/dist/request.js +1 -0
  29. package/dist/response.d.ts +21 -0
  30. package/dist/response.js +108 -0
  31. package/dist/router.d.ts +13 -0
  32. package/dist/router.js +104 -0
  33. package/dist/schema.d.ts +26 -0
  34. package/dist/schema.js +11 -0
  35. package/dist/script.d.ts +23 -0
  36. package/dist/script.js +56 -0
  37. package/dist/state.d.ts +24 -0
  38. package/dist/state.js +91 -0
  39. package/dist/workspace.d.ts +8 -0
  40. package/dist/workspace.js +1 -0
  41. package/docs/en/api-reference.md +948 -0
  42. package/docs/en/usage-guide.md +284 -0
  43. package/package.json +17 -5
  44. package/scripts/generate-workspace-types.mjs +135 -0
  45. package/dist/index.d.ts.map +0 -1
  46. package/dist/index.js.map +0 -1
package/README.md CHANGED
@@ -1,7 +1,12 @@
1
1
  # `@cogover/sdk`
2
2
 
3
- The TypeScript SDK for customer code running on Cogover. The package includes
4
- type declarations for IDE autocomplete, inline documentation, and type checking.
3
+ The TypeScript SDK for developing **Custom Backend Modules** on Cogover. These
4
+ modules run server-side business logic, work with workspace data, expose HTTP
5
+ routes, and connect to external services. They are separate from Custom Frontend
6
+ Modules, which implement user interfaces.
7
+
8
+ The package includes type declarations for IDE autocomplete, inline
9
+ documentation, and type checking.
5
10
 
6
11
  ## Requirements
7
12
 
@@ -16,56 +21,271 @@ npm install @cogover/sdk
16
21
 
17
22
  ## Quick start
18
23
 
24
+ This example assumes that the generated `workspace.d.ts` declares the `order`
25
+ Object and the fields used below. See [Workspace types](#workspace-types).
26
+
19
27
  ```typescript
20
- import { createGreeting } from "@cogover/sdk";
28
+ import { defineScript, NotFoundError } from "@cogover/sdk";
21
29
 
22
- const greeting = createGreeting("Cogover");
23
- console.log(greeting); // Hello Cogover
30
+ interface Input { recordId: string }
31
+ interface Output { recordId: string; total: number }
32
+
33
+ export default defineScript<Input, Output>(async ({ input, data, log }) => {
34
+ const orders = data.object("order");
35
+ const order = await orders.records.get(input.recordId, {
36
+ fields: ["subtotal", "tax", "status"],
37
+ });
38
+ if (!order) throw new NotFoundError("order", input.recordId);
39
+
40
+ const total = (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0);
41
+ await orders.records.update(order.id, { status: "processed", total });
42
+ log.info("Order processed", { recordId: order.id, total });
43
+ return { recordId: order.id, total };
44
+ });
24
45
  ```
25
46
 
26
- The SDK uses named exports and currently has no default export.
47
+ `defineScript` parses the input JSON, provides invocation metadata and scoped
48
+ data, schema, logging, state, and lock APIs, waits for the async handler, and
49
+ serializes its result. Cogover authentication credentials are not exposed to
50
+ project code, and Cogover enforces the configured permissions and limits on
51
+ capability calls.
52
+
53
+ ## Current identity and workspace
27
54
 
28
- ## Use in a Cogover handler
55
+ `context.invocation` is an immutable snapshot of the invocation identity and
56
+ current workspace that Cogover already resolved for this execution. The identity
57
+ may represent an authenticated user or a system invocation. Reading it is
58
+ synchronous and does not make a data API request:
29
59
 
30
60
  ```typescript
31
- import { createGreeting } from "@cogover/sdk";
61
+ export default defineScript(({ invocation }) => {
62
+ if (invocation.identity === "system") {
63
+ return { workspaceId: invocation.workspace.id, user: null };
64
+ }
65
+ return {
66
+ workspaceId: invocation.workspace.id,
67
+ workspaceName: invocation.workspace.name,
68
+ accountId: invocation.user.accountId,
69
+ personnelId: invocation.user.membership.personnelId,
70
+ };
71
+ });
72
+ ```
73
+
74
+ The `identity` discriminant narrows `user` to a public `CurrentUser` for user
75
+ invocations and to `null` for system invocations. Only the documented profile,
76
+ membership, locale, and workspace fields are included. Raw authentication data
77
+ and Cogover credentials are never exposed.
78
+
79
+ ## Full HTTP routes and responses
80
+
81
+ ```typescript
82
+ import { createRouter } from "@cogover/sdk";
83
+
84
+ const router = createRouter();
85
+ router.get("/orders/:orderId", ({ request, response }) => response.json({
86
+ orderId: request.params.orderId,
87
+ expand: request.query.expand,
88
+ }));
89
+ router.post<{ description: string }, object>("/orders", ({ request, response }) =>
90
+ response.json({ description: request.body.description }, { status: 201 }));
91
+ router.put("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
92
+ router.patch("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
93
+ router.delete("/orders/:orderId", ({ response }) => response.empty());
94
+ export default router.toHandler();
95
+ ```
96
+
97
+ Routes support GET, POST, PUT, PATCH, and DELETE. `request` exposes `method`, `path`,
98
+ decoded `params`, repeated-value-aware `query`, safe lower-case `headers`, and JSON
99
+ `body`. Authentication headers are never exposed. Plain return values are JSON with
100
+ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide explicit
101
+ status, safe response headers, and text/binary bodies. Missing routes return 404;
102
+ unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
103
+ The complete router contract is included in `docs/en/api-reference.md`.
104
+
105
+ ## Outbound HTTP with `fetch`
106
+
107
+ Cogover provides a Fetch-compatible function for calling an external HTTPS API.
108
+ The request always goes through Cogover's managed network layer; it does not grant
109
+ project code unrestricted network access.
110
+
111
+ ```typescript
112
+ import { defineScript, fetch } from "@cogover/sdk";
32
113
 
33
114
  interface Input {
34
- name: string;
115
+ externalToken: string;
116
+ orderId: string;
35
117
  }
36
118
 
37
- export default function handler(inputJson: string): string {
38
- const input: Input = JSON.parse(inputJson);
119
+ export default defineScript<Input>(async ({ input }) => {
120
+ const response = await fetch("https://api.example.com/v1/orders", {
121
+ method: "POST",
122
+ headers: {
123
+ authorization: `Bearer ${input.externalToken}`,
124
+ "content-type": "application/json",
125
+ },
126
+ body: JSON.stringify({ id: input.orderId }),
127
+ timeoutMs: 5_000,
128
+ });
129
+ return response.json();
130
+ });
131
+ ```
132
+
133
+ V1 supports public HTTPS URLs on port 443 and the methods GET, HEAD, POST, PUT,
134
+ PATCH, and DELETE. Requests and buffered responses have platform limits. Redirects,
135
+ cookie jars, streaming, WebSocket, URL credentials, IP-literal hosts, custom proxy,
136
+ dispatcher, agent, DNS, and TLS settings are not supported. A failed mutating request
137
+ may already have reached the remote API, so use the remote API's idempotency mechanism
138
+ and do not retry blindly.
139
+
140
+ ## Record API
141
+
142
+ An Object client exposes `records.get`, `records.list`, `records.create`,
143
+ `records.update`, `records.batchInsert`, `records.batchUpdate`,
144
+ `records.upsertByUniqueField`, and `records.deleteMany`. List filters are built from typed
145
+ field references, so scripts do not provide transport-specific field metadata or
146
+ response envelopes.
147
+
148
+ Cogover normalizes service values to the declared SDK types: booleans become
149
+ `true`/`false`, and lookup/reference values are reduced to
150
+ `{ id, name, objectSlug }` so nested record fields are not exposed. For writes,
151
+ reference fields accept either a record ID or a `RecordReference`; only the ID is
152
+ sent to the Record API.
39
153
 
40
- return JSON.stringify({
41
- greeting: createGreeting(input.name)
154
+ ```typescript
155
+ import { and, defineScript } from "@cogover/sdk";
156
+
157
+ export default defineScript(async ({ data }) => {
158
+ const orders = data.object("order");
159
+ return orders.records.list({
160
+ where: and(
161
+ orders.fields.status.in(["new", "nurturing"]),
162
+ orders.fields.is_active.eq(true),
163
+ orders.fields.total.gte(1_000_000),
164
+ ),
165
+ orderBy: [orders.fields.updated.desc()],
166
+ limit: 50,
42
167
  });
168
+ });
169
+ ```
170
+
171
+ Batch writes are best-effort per row. Check `result.success` or every entry in
172
+ `result.results`; a successful request envelope does not mean every row succeeded.
173
+ Business upsert accepts one `matchBy` field that must be configured as a single-field
174
+ unique key. It returns `{ id, created }` and requires both create and update permission.
175
+
176
+ ```typescript
177
+ const inserted = await orders.records.batchInsert([
178
+ { name: "Order A", external_id: "EXT-1" },
179
+ { name: "Order B", external_id: "EXT-2" },
180
+ ]);
181
+ const firstInserted = inserted.results[0];
182
+ if (!firstInserted?.success || !firstInserted.id) {
183
+ throw new Error(firstInserted?.msg ?? "Order A could not be created");
43
184
  }
185
+
186
+ const updated = await orders.records.batchUpdate([
187
+ { id: firstInserted.id, fields: { status: "processing" } },
188
+ ]);
189
+ if (!updated.success) throw new Error("The order could not be updated");
190
+
191
+ const upserted = await orders.records.upsertByUniqueField("external_id", {
192
+ external_id: "EXT-1",
193
+ name: "Order A from ERP",
194
+ });
44
195
  ```
45
196
 
46
- A handler must default-export a synchronous function that accepts
47
- `inputJson: string` and returns a JSON string or `null`.
197
+ API failures are unwrapped into `NotFoundError`, `ValidationError`,
198
+ `PermissionDeniedError`, `RateLimitError`, or `CogoverApiError`.
199
+ Unique-key conflicts are returned as `ValidationError` with
200
+ `details.reason === "UNIQUE_KEY_VIOLATION"`, plus the safe `objectSlug` and
201
+ `fieldSlug`; the rejected field value is not echoed in the public error.
48
202
 
49
- ## API
203
+ Uncaught SDK errors return a safe HTTP error response: invalid input and blocked
204
+ outbound requests → 400; state conflicts and lock errors → 409; oversized outbound
205
+ requests → 413; permission denied → 403; not found → 404; unsupported methods →
206
+ 405; rate limits → 429; unavailable state, lock, or outbound HTTP services → 503;
207
+ oversized or failed remote responses → 502; outbound timeouts → 504; and other
208
+ data API failures → 422. The response includes `code`, `msg`, `r` (HTTP status),
209
+ and `writesMayHaveCompleted` when relevant. Earlier writes are not rolled back;
210
+ never retry writes automatically. Unknown script errors and resource-limit
211
+ failures use a generic 422 response.
50
212
 
51
- ### `createGreeting(name)`
213
+ ## Record execution identities
52
214
 
53
- Creates a greeting by adding the `Hello ` prefix to a name.
215
+ By default, `data.object("order")` uses the invocation's identity. Approved scripts
216
+ can explicitly select a personnel identity or system access:
54
217
 
55
218
  ```typescript
56
- function createGreeting(name: string): string;
219
+ const delegatedOrders = data.asUser(personnelId).object("order");
220
+ const record = await delegatedOrders.records.get(recordId, { fields: ["description"] });
221
+ const page = await delegatedOrders.records.list({ fields: ["description"], limit: 20 });
222
+ await data.asUser(personnelId).object("order").records.update(order.id, changes);
223
+ await data.asSystem().object("order").records.update(order.id, changes);
57
224
  ```
58
225
 
59
- Example:
226
+ Both methods return new immutable clients and preserve workspace typing. `asUser`
227
+ accepts a personnel ID (not an account ID) and supports the full record API, including
228
+ batch writes and business upsert. Reads apply that user's permissions and approved field restrictions;
229
+ read access must be approved separately from writes. `asSystem` supports the
230
+ full record API, including in authenticated public scripts, without changing the
231
+ original caller or existing clients.
232
+
233
+ Administrator approval is required for the project version, callers, target users,
234
+ objects, operations, and fields. Unauthorized operations fail without falling back
235
+ to another identity. System access bypasses the caller's record permissions, so
236
+ privileged scripts must validate their business inputs and record scope. These
237
+ methods never accept credentials or a workspace override.
238
+
239
+ ## Project state and distributed locks
240
+
241
+ Use project state for small durable JSON checkpoints and coordination values. State
242
+ is scoped to the workspace and project, survives new project versions, supports TTL
243
+ and compare-and-set, and limits each serialized value to 32 KiB.
60
244
 
61
245
  ```typescript
62
- createGreeting("Cogover"); // "Hello Cogover"
246
+ export default defineScript(async ({ state }) => {
247
+ const sync = state.namespace("inventory-sync");
248
+ const current = await sync.get<{ cursor: string }>("cursor");
249
+ return sync.set("cursor", { cursor: "next-page" }, {
250
+ expectedVersion: current?.version ?? 0,
251
+ ttlSeconds: 3600,
252
+ });
253
+ });
63
254
  ```
64
255
 
256
+ Distributed locks provide project-scoped token leases for short critical sections.
257
+ `withLock` releases in `finally`; manual leases support renew/release and expose a
258
+ fencing token. A lease does not auto-renew and locks do not replace idempotency or
259
+ provide exactly-once execution.
260
+
261
+ ```typescript
262
+ export default defineScript(async ({ locks }) =>
263
+ locks.withLock("INV-1", { namespace: "invoice", waitMs: 500 }, async lease => {
264
+ await processInvoice("INV-1", lease.fencingToken);
265
+ return { processed: true };
266
+ }));
267
+ ```
268
+
269
+ State conflicts throw `StateConflictError`; failed lock acquisition and lost leases
270
+ use `LockUnavailableError` and `LockLostError`.
271
+
272
+ ## Workspace types
273
+
274
+ `WorkspaceObjects` is an open interface augmented by a generated declaration for
275
+ the current Workspace. Generate a declaration from an Object Info JSON response:
276
+
277
+ ```bash
278
+ npx cogover-generate-workspace-types objects.json workspace.d.ts
279
+ ```
280
+
281
+ The declaration makes object slugs, field slugs, value types, and choice option
282
+ slugs available to TypeScript. `schema.object(slug)` is read-only; Object and
283
+ field mutation are intentionally not part of this SDK.
284
+
65
285
  ## TypeScript
66
286
 
67
- Type declarations are included in the package. After installation, IDEs can
68
- resolve `@cogover/sdk` without a separate type package.
287
+ Type declarations are included in the package. Add the generated `workspace.d.ts`
288
+ to the TypeScript project.
69
289
 
70
290
  Recommended `tsconfig.json` options:
71
291
 
@@ -82,6 +302,12 @@ Recommended `tsconfig.json` options:
82
302
  }
83
303
  ```
84
304
 
305
+ ## Additional documentation
306
+
307
+ The installed package includes an English usage guide at
308
+ `docs/en/usage-guide.md` and the complete API reference at
309
+ `docs/en/api-reference.md`.
310
+
85
311
  ## License
86
312
 
87
- [MIT](LICENSE)
313
+ MIT
package/dist/data.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ import type { FieldReferences, FilterExpression, SortExpression } from "./query.js";
2
+ import type { CogoverRecord, CogoverRecordId, BatchUpdateItem, BatchWriteResponse, CreateFields, DeleteResult, RecordPage, UpdateFields, UpsertFields, UpsertResult } from "./records.js";
3
+ import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
4
+ export interface GetRecordOptions<TFields> {
5
+ readonly fields?: readonly StringKeyOf<TFields>[];
6
+ }
7
+ export interface ListOptions<TFields> {
8
+ readonly where?: FilterExpression;
9
+ readonly orderBy?: readonly SortExpression[];
10
+ readonly fields?: readonly StringKeyOf<TFields>[];
11
+ readonly limit?: number;
12
+ readonly cursor?: string;
13
+ }
14
+ export interface RecordWritesApi<TFields> {
15
+ create(fields: CreateFields<TFields>): Promise<CogoverRecordId>;
16
+ update(id: CogoverRecordId, fields: UpdateFields<TFields>): Promise<void>;
17
+ batchInsert(records: readonly CreateFields<TFields>[]): Promise<BatchWriteResponse>;
18
+ batchUpdate(records: readonly BatchUpdateItem<TFields>[]): Promise<BatchWriteResponse>;
19
+ upsertByUniqueField<TMatchBy extends StringKeyOf<TFields>>(matchBy: TMatchBy, fields: UpsertFields<TFields, TMatchBy>): Promise<UpsertResult>;
20
+ deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
21
+ }
22
+ export interface RecordsApi<TFields> extends RecordWritesApi<TFields> {
23
+ get(id: string, options?: GetRecordOptions<TFields>): Promise<CogoverRecord<TFields> | null>;
24
+ list(options?: ListOptions<TFields>): Promise<RecordPage<TFields>>;
25
+ }
26
+ export interface WriteObjectClient<TFields> {
27
+ readonly slug: string;
28
+ readonly fields: FieldReferences<TFields>;
29
+ readonly records: RecordWritesApi<TFields>;
30
+ }
31
+ export interface ObjectClient<TFields> extends WriteObjectClient<TFields> {
32
+ readonly records: RecordsApi<TFields>;
33
+ }
34
+ /** Reads and writes as an approved personnel ID. Authorization is enforced by Cogover. */
35
+ export interface AsUserDataApi<TSchema extends object = EffectiveWorkspaceObjects> {
36
+ object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
37
+ }
38
+ export interface DataApi<TSchema extends object = EffectiveWorkspaceObjects> {
39
+ object<K extends StringKeyOf<TSchema>>(slug: K): ObjectClient<FieldsFor<TSchema, K>>;
40
+ /** New client for reads and writes as an approved personnel ID. */
41
+ asUser(personnelId: string): AsUserDataApi<TSchema>;
42
+ /** New system client, including in public invocations. Requires approval; does not change this client. */
43
+ asSystem(): DataApi<TSchema>;
44
+ }
package/dist/data.js ADDED
@@ -0,0 +1,143 @@
1
+ import { ValidationError } from "./errors.js";
2
+ import { callBridge } from "./internal/bridge.js";
3
+ import { requireFieldSlug, requireFields, requireSlug, requireText } from "./internal/validation.js";
4
+ import { isRecord } from "./internal/values.js";
5
+ import { createFieldReferences } from "./query.js";
6
+ const MAX_BATCH_RECORDS = 200;
7
+ /** @internal */
8
+ export function createDataApi(identity) {
9
+ return Object.freeze({
10
+ object(slug) {
11
+ return createObjectClient(requireSlug(String(slug)), identity);
12
+ },
13
+ asUser(personnelId) {
14
+ const delegated = Object.freeze({ kind: "user", personnelId: requireText(personnelId, "personnelId") });
15
+ return Object.freeze({
16
+ object(slug) {
17
+ return createObjectClient(requireSlug(String(slug)), delegated);
18
+ },
19
+ });
20
+ },
21
+ asSystem() {
22
+ return createDataApi(Object.freeze({ kind: "system" }));
23
+ },
24
+ });
25
+ }
26
+ function createObjectClient(slug, identity) {
27
+ const fields = createFieldReferences();
28
+ const records = Object.freeze({
29
+ async get(id, options) {
30
+ return callBridge("records.get", {
31
+ identity,
32
+ objectSlug: slug,
33
+ id: requireText(id, "record id"),
34
+ fields: options?.fields,
35
+ });
36
+ },
37
+ async list(options) {
38
+ return callBridge("records.list", {
39
+ identity,
40
+ objectSlug: slug,
41
+ where: options?.where,
42
+ orderBy: options?.orderBy,
43
+ fields: options?.fields,
44
+ limit: options?.limit,
45
+ cursor: options?.cursor,
46
+ });
47
+ },
48
+ async create(fieldsToCreate) {
49
+ return callBridge("records.create", {
50
+ identity,
51
+ objectSlug: slug,
52
+ fields: requireFields(fieldsToCreate),
53
+ });
54
+ },
55
+ async update(id, fieldsToUpdate) {
56
+ await callBridge("records.update", {
57
+ identity,
58
+ objectSlug: slug,
59
+ id: requireText(id, "record id"),
60
+ fields: requireFields(fieldsToUpdate),
61
+ });
62
+ },
63
+ async batchInsert(recordsToCreate) {
64
+ const records = requireBatch(recordsToCreate, "batchInsert").map((fields, index) => {
65
+ try {
66
+ return requireFields(fields);
67
+ }
68
+ catch (error) {
69
+ throw indexedValidationError(error, "batchInsert", index);
70
+ }
71
+ });
72
+ return callBridge("records.batchInsert", {
73
+ identity,
74
+ objectSlug: slug,
75
+ records,
76
+ });
77
+ },
78
+ async batchUpdate(recordsToUpdate) {
79
+ const records = requireBatch(recordsToUpdate, "batchUpdate").map((item, index) => {
80
+ if (!isRecord(item)) {
81
+ throw new ValidationError(`batchUpdate record at index ${index} must be an object`);
82
+ }
83
+ try {
84
+ return {
85
+ id: requireText(item.id, `batchUpdate record id at index ${index}`),
86
+ fields: requireFields(item.fields),
87
+ };
88
+ }
89
+ catch (error) {
90
+ throw indexedValidationError(error, "batchUpdate", index);
91
+ }
92
+ });
93
+ return callBridge("records.batchUpdate", {
94
+ identity,
95
+ objectSlug: slug,
96
+ records,
97
+ });
98
+ },
99
+ async upsertByUniqueField(matchBy, fieldsToUpsert) {
100
+ const normalizedMatchBy = requireFieldSlug(matchBy, "matchBy");
101
+ const fields = requireFields(fieldsToUpsert);
102
+ const businessValue = fields[normalizedMatchBy];
103
+ if (!Object.prototype.hasOwnProperty.call(fields, normalizedMatchBy)
104
+ || businessValue === null || businessValue === undefined
105
+ || (typeof businessValue === "string" && businessValue.trim() === "")
106
+ || (Array.isArray(businessValue) && businessValue.length === 0)) {
107
+ throw new ValidationError(`upsertByUniqueField() requires a non-empty '${normalizedMatchBy}' value`);
108
+ }
109
+ return callBridge("records.upsertByUniqueField", {
110
+ identity,
111
+ objectSlug: slug,
112
+ matchBy: normalizedMatchBy,
113
+ fields,
114
+ });
115
+ },
116
+ async deleteMany(ids) {
117
+ if (!Array.isArray(ids) || ids.length === 0) {
118
+ throw new ValidationError("deleteMany() requires at least one record id");
119
+ }
120
+ return callBridge("records.deleteMany", {
121
+ identity,
122
+ objectSlug: slug,
123
+ ids: ids.map((id) => requireText(id, "record id")),
124
+ });
125
+ },
126
+ });
127
+ return Object.freeze({ slug, fields, records });
128
+ }
129
+ function requireBatch(records, operation) {
130
+ if (!Array.isArray(records) || records.length === 0) {
131
+ throw new ValidationError(`${operation}() requires at least one record`);
132
+ }
133
+ if (records.length > MAX_BATCH_RECORDS) {
134
+ throw new ValidationError(`${operation}() supports at most ${MAX_BATCH_RECORDS} records`);
135
+ }
136
+ return records;
137
+ }
138
+ function indexedValidationError(error, operation, index) {
139
+ if (error instanceof ValidationError) {
140
+ return new ValidationError(`${operation} record at index ${index}: ${error.message}`, error.details);
141
+ }
142
+ return new ValidationError(`${operation} record at index ${index} is invalid`);
143
+ }
@@ -0,0 +1,30 @@
1
+ export declare class CogoverApiError extends Error {
2
+ readonly code: string;
3
+ /** Original server result code; undefined for errors without a server response. */
4
+ readonly r: number | undefined;
5
+ readonly details?: unknown;
6
+ constructor(code: string, message: string, details?: unknown);
7
+ }
8
+ export declare class NotFoundError extends CogoverApiError {
9
+ readonly resource: string;
10
+ readonly resourceId: string;
11
+ constructor(resource: string, resourceId: string, message?: string, details?: unknown);
12
+ }
13
+ export declare class ValidationError extends CogoverApiError {
14
+ constructor(message: string, details?: unknown);
15
+ }
16
+ export declare class PermissionDeniedError extends CogoverApiError {
17
+ constructor(message: string, details?: unknown);
18
+ }
19
+ export declare class RateLimitError extends CogoverApiError {
20
+ constructor(message: string, details?: unknown);
21
+ }
22
+ export declare class StateConflictError extends CogoverApiError {
23
+ constructor(message: string, details?: unknown);
24
+ }
25
+ export declare class LockUnavailableError extends CogoverApiError {
26
+ constructor(key: string, message?: string, details?: unknown);
27
+ }
28
+ export declare class LockLostError extends CogoverApiError {
29
+ constructor(message: string, details?: unknown);
30
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,62 @@
1
+ import { isRecord } from "./internal/values.js";
2
+ export class CogoverApiError extends Error {
3
+ code;
4
+ /** Original server result code; undefined for errors without a server response. */
5
+ r;
6
+ details;
7
+ constructor(code, message, details) {
8
+ super(message);
9
+ this.name = "CogoverApiError";
10
+ this.code = code;
11
+ this.r = isRecord(details) && typeof details.r === "number" && Number.isSafeInteger(details.r)
12
+ ? details.r
13
+ : undefined;
14
+ this.details = details;
15
+ }
16
+ }
17
+ export class NotFoundError extends CogoverApiError {
18
+ resource;
19
+ resourceId;
20
+ constructor(resource, resourceId, message, details) {
21
+ super("NOT_FOUND", message ?? `${resource} '${resourceId}' was not found`, { ...(isRecord(details) ? details : {}), resource, resourceId });
22
+ this.name = "NotFoundError";
23
+ this.resource = resource;
24
+ this.resourceId = resourceId;
25
+ }
26
+ }
27
+ export class ValidationError extends CogoverApiError {
28
+ constructor(message, details) {
29
+ super("VALIDATION_ERROR", message, details);
30
+ this.name = "ValidationError";
31
+ }
32
+ }
33
+ export class PermissionDeniedError extends CogoverApiError {
34
+ constructor(message, details) {
35
+ super("PERMISSION_DENIED", message, details);
36
+ this.name = "PermissionDeniedError";
37
+ }
38
+ }
39
+ export class RateLimitError extends CogoverApiError {
40
+ constructor(message, details) {
41
+ super("RATE_LIMITED", message, details);
42
+ this.name = "RateLimitError";
43
+ }
44
+ }
45
+ export class StateConflictError extends CogoverApiError {
46
+ constructor(message, details) {
47
+ super("STATE_CONFLICT", message, details);
48
+ this.name = "StateConflictError";
49
+ }
50
+ }
51
+ export class LockUnavailableError extends CogoverApiError {
52
+ constructor(key, message, details) {
53
+ super("LOCK_NOT_ACQUIRED", message ?? `Lock '${key}' could not be acquired`, details);
54
+ this.name = "LockUnavailableError";
55
+ }
56
+ }
57
+ export class LockLostError extends CogoverApiError {
58
+ constructor(message, details) {
59
+ super("LOCK_LOST", message, details);
60
+ this.name = "LockLostError";
61
+ }
62
+ }
@@ -0,0 +1,28 @@
1
+ export interface CogoverFetchInit {
2
+ readonly method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
3
+ readonly headers?: Readonly<Record<string, string>>;
4
+ readonly body?: string;
5
+ readonly timeoutMs?: number;
6
+ }
7
+ export interface CogoverFetchHeaders {
8
+ get(name: string): string | null;
9
+ has(name: string): boolean;
10
+ entries(): IterableIterator<[string, string]>;
11
+ [Symbol.iterator](): IterableIterator<[string, string]>;
12
+ }
13
+ export interface CogoverFetchResponse {
14
+ readonly ok: boolean;
15
+ readonly status: number;
16
+ readonly statusText: string;
17
+ readonly url: string;
18
+ readonly redirected: false;
19
+ readonly headers: CogoverFetchHeaders;
20
+ readonly bodyUsed: boolean;
21
+ text(): Promise<string>;
22
+ json<T = unknown>(): Promise<T>;
23
+ }
24
+ /** Fetch-compatible API using Cogover's managed network layer. */
25
+ export declare function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
26
+ declare global {
27
+ function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
28
+ }