@cogover/sdk 0.1.1 → 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 +256 -30
  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
@@ -0,0 +1,284 @@
1
+ # Using `@cogover/sdk`
2
+
3
+ ## What is a Custom Backend Module?
4
+
5
+ A **Custom Backend Module** adds server-side business logic to a Cogover
6
+ workspace. Use one to process requests, validate or transform data, automate
7
+ record operations, expose HTTP routes, or integrate Cogover with an external
8
+ service. It is different from a Custom Frontend Module, which implements a user
9
+ interface.
10
+
11
+ Custom Backend Modules are written in TypeScript. `@cogover/sdk` supplies the
12
+ types and APIs for the current invocation, workspace data, schema metadata,
13
+ logging, outbound HTTPS requests, state, and distributed locks. Cogover executes
14
+ the module with the permissions and resource limits configured for the project.
15
+
16
+ A typical development flow is:
17
+
18
+ 1. Create a TypeScript project and install `@cogover/sdk`.
19
+ 2. Generate `workspace.d.ts` so workspace Objects and fields are type-safe.
20
+ 3. Implement and locally type-check the module's default handler.
21
+ 4. Publish the module to Cogover, configure its permissions, and invoke it
22
+ through the intended trigger or HTTP route.
23
+
24
+ ## Installation and type checking
25
+
26
+ ```bash
27
+ npm install @cogover/sdk
28
+ npx tsc --noEmit
29
+ ```
30
+
31
+ Place the generated `workspace.d.ts` declaration alongside the module's source
32
+ and include it in the TypeScript project.
33
+
34
+ ## Quick start
35
+
36
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
37
+ fields used below.
38
+
39
+ ```typescript
40
+ import { defineScript, NotFoundError } from "@cogover/sdk";
41
+
42
+ interface Input { recordId: string }
43
+ interface Output { recordId: string; total: number }
44
+
45
+ export default defineScript<Input, Output>(async ({ input, data, log }) => {
46
+ const orders = data.object("order");
47
+ const order = await orders.records.get(input.recordId, {
48
+ fields: ["subtotal", "tax", "status"],
49
+ });
50
+ if (!order) throw new NotFoundError("order", input.recordId);
51
+
52
+ const total = (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0);
53
+ await orders.records.update(order.id, { status: "processed", total });
54
+ log.info("Order processed", { recordId: order.id, total });
55
+ return { recordId: order.id, total };
56
+ });
57
+ ```
58
+
59
+ Generate `workspace.d.ts` from Object Info metadata and include it in the script's
60
+ TypeScript project. Cogover authentication credentials are not exposed to project
61
+ code. Access to data and external services is governed by the project's configured
62
+ permissions and limits.
63
+
64
+ The runtime applies object/operation/field permissions, capability call and byte
65
+ budgets, and a wall-clock deadline to the complete async handler lifecycle.
66
+
67
+ ## Read the current identity and workspace
68
+
69
+ Use the immutable `invocation` snapshot when business logic needs the user or
70
+ system identity and workspace that Cogover already resolved. This is an in-memory
71
+ read and does not make a data API request:
72
+
73
+ ```typescript
74
+ export default defineScript(({ invocation }) => {
75
+ const {workspace} = invocation;
76
+ if (invocation.identity === "system") {
77
+ return {workspaceId: workspace.id, user: null};
78
+ }
79
+ return {
80
+ workspaceId: workspace.id,
81
+ workspaceName: workspace.name,
82
+ accountId: invocation.user.accountId,
83
+ personnelId: invocation.user.membership.personnelId,
84
+ };
85
+ });
86
+ ```
87
+
88
+ Use the Record API only when you need richer, current Personnel business fields
89
+ such as department, position, manager, or custom fields. The snapshot intentionally
90
+ contains only documented fields and omits credentials and raw authentication data.
91
+
92
+ ## Filter and sort records
93
+
94
+ ```typescript
95
+ import { and, defineScript } from "@cogover/sdk";
96
+
97
+ export default defineScript(async ({ data }) => {
98
+ const orders = data.object("order");
99
+ return orders.records.list({
100
+ where: and(
101
+ orders.fields.status.in(["new", "nurturing"]),
102
+ orders.fields.is_active.eq(true),
103
+ orders.fields.total.gte(1_000_000),
104
+ ),
105
+ orderBy: [orders.fields.updated.desc()],
106
+ limit: 50,
107
+ });
108
+ });
109
+ ```
110
+
111
+ ## Call an external API with `fetch`
112
+
113
+ ```typescript
114
+ import { defineScript, fetch } from "@cogover/sdk";
115
+
116
+ interface Input {
117
+ externalToken: string;
118
+ orderId: string;
119
+ }
120
+
121
+ export default defineScript<Input>(async ({ input }) => {
122
+ const response = await fetch("https://api.example.com/v1/orders", {
123
+ method: "POST",
124
+ headers: {
125
+ authorization: `Bearer ${input.externalToken}`,
126
+ "content-type": "application/json",
127
+ },
128
+ body: JSON.stringify({ id: input.orderId }),
129
+ timeoutMs: 5_000,
130
+ });
131
+ if (!response.ok) return { status: response.status };
132
+ return response.json();
133
+ });
134
+ ```
135
+
136
+ This Fetch-compatible API uses Cogover's managed network layer; it does not provide
137
+ unrestricted Node.js network access. Only public HTTPS URLs on port 443 are supported.
138
+ V1 does not follow redirects, maintain a cookie jar, stream, support WebSocket,
139
+ accept IP-literal/userinfo URLs, or expose proxy, dispatcher, agent, DNS, or TLS
140
+ configuration. Requests and responses are bounded. For remote mutations, use the
141
+ destination API's idempotency mechanism: a timeout or missing response does not
142
+ prove that the remote request was not applied.
143
+
144
+ ## Permissions and limits
145
+
146
+ - Cogover authentication credentials are never exposed to module code. Access is
147
+ limited to the configured Objects, operations, and fields.
148
+ - TypeScript types do not replace runtime validation of business input.
149
+ - Cogover limits capability calls, request and response sizes, and execution time.
150
+ - Do not automatically retry writes after a timeout because the commit outcome may
151
+ be unknown.
152
+
153
+ ## Store small progress with state
154
+
155
+ Use state for synchronization cursors, checkpoints, or small coordination flags
156
+ that must survive multiple executions and deployed project versions. Each value is
157
+ JSON of at most 32 KiB:
158
+
159
+ ```typescript
160
+ export default defineScript(async ({ state }) => {
161
+ const sync = state.namespace("inventory-sync");
162
+ const current = await sync.get<{ cursor: string }>("cursor");
163
+ const nextCursor = await fetchNextPage(current?.value.cursor);
164
+
165
+ const saved = await sync.set("cursor", { cursor: nextCursor }, {
166
+ expectedVersion: current?.version ?? 0,
167
+ ttlSeconds: 86_400,
168
+ });
169
+ return { version: saved.version };
170
+ });
171
+ ```
172
+
173
+ `expectedVersion` prevents overwriting a concurrent change. On
174
+ `StateConflictError`, read again and make a business-level merge/retry decision.
175
+ State is not for secrets or large data and is not transactional with record calls.
176
+
177
+ ## Prevent concurrent work with distributed locks
178
+
179
+ ```typescript
180
+ export default defineScript(async ({ locks }) =>
181
+ locks.withLock("daily-import", { namespace: "inventory", waitMs: 500 }, async lease => {
182
+ await runImport({ fencingToken: lease.fencingToken });
183
+ return { completed: true };
184
+ }));
185
+ ```
186
+
187
+ `withLock` attempts release in `finally`; acquisition failure throws
188
+ `LockUnavailableError`. Leases default to 30 seconds and do not auto-renew. For
189
+ longer work, watch `expiresAt` and call `renew()` before expiry. Use the fencing
190
+ token in downstream systems where possible to reject stale writers. Locks do not
191
+ replace idempotency or provide exactly-once execution.
192
+
193
+ ## Choose the identity for record operations
194
+
195
+ Keep using `data.object("order")` to inherit the caller's identity. When an
196
+ administrator has approved the project and caller for identity selection, use:
197
+
198
+ ```typescript
199
+ const orders = data.object("order");
200
+ const order = await orders.records.get(input.recordId, { fields: ["description"] });
201
+ if (!order) throw new NotFoundError("order", input.recordId);
202
+
203
+ // Choose one operation as required by the business workflow:
204
+ await data.asUser(personnelId).object("order").records.update(order.id, { description: "Delegated update" });
205
+ // Or: await data.asSystem().object("order").records.update(order.id, { description: "System update" });
206
+ ```
207
+
208
+ `asUser` uses a personnel ID and supports both reads and writes. `asSystem` also supports reads and
209
+ can be used in public scripts without changing their authenticated caller. Both
210
+ return new clients, preserve workspace typing, and leave existing clients intact.
211
+
212
+ To read under a selected user, use the same scoped client for `get` and `list`:
213
+
214
+ ```typescript
215
+ const delegatedOrders = data.asUser(personnelId).object("order");
216
+ const record = await delegatedOrders.records.get(input.recordId, { fields: ["description"] });
217
+ const page = await delegatedOrders.records.list({ fields: ["description"], limit: 20 });
218
+ // Fetch another page with the same identity:
219
+ if (page.nextCursor) {
220
+ await delegatedOrders.records.list({ fields: ["description"], limit: 20, cursor: page.nextCursor });
221
+ }
222
+ ```
223
+
224
+ The administrator must approve read access separately from write access. These
225
+ reads apply the selected user's permissions; failures never retry as system.
226
+
227
+ An uncaught permission error returns HTTP 403 with `code: "PERMISSION_DENIED"`.
228
+ `reason: "IDENTITY_NOT_GRANTED"` means the project lacks approval to select that
229
+ identity. Check `writesMayHaveCompleted` before considering a retry: earlier writes
230
+ are not rolled back. See the [error response reference](api-reference.md#errors).
231
+
232
+ Unapproved selections fail; there is no automatic fallback. A project with
233
+ privileged access must validate which records a caller may request it to process;
234
+ being able to see a record is not sufficient business authorization. Never let
235
+ request input grant system privileges. Never place a Cogover API key or
236
+ authentication object in module code, and never log or return credentials for an
237
+ external service. See
238
+ [API reference](api-reference.md#record-execution-identities).
239
+
240
+ ## Recommended TypeScript configuration
241
+
242
+ ```json
243
+ {
244
+ "compilerOptions": {
245
+ "target": "ES2022",
246
+ "module": "ESNext",
247
+ "moduleResolution": "Bundler",
248
+ "strict": true,
249
+ "noEmit": true,
250
+ "skipLibCheck": true
251
+ },
252
+ "include": ["src/**/*.ts", "workspace.d.ts"]
253
+ }
254
+ ```
255
+
256
+ Import from `@cogover/sdk` and project-local source only. Custom Backend Modules
257
+ do not support Node.js built-ins, unapproved packages, URL imports, `require()`, or
258
+ dynamic `import()`.
259
+
260
+ ## Full HTTP routes and responses
261
+
262
+ ```typescript
263
+ import { createRouter } from "@cogover/sdk";
264
+
265
+ const router = createRouter();
266
+ router.get("/orders/:orderId", ({ request, response }) => response.json({
267
+ orderId: request.params.orderId,
268
+ expand: request.query.expand,
269
+ }));
270
+ router.post<{ description: string }, object>("/orders", ({ request, response }) =>
271
+ response.json({ description: request.body.description }, { status: 201 }));
272
+ router.put("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
273
+ router.patch("/orders/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
274
+ router.delete("/orders/:orderId", ({ response }) => response.empty());
275
+ export default router.toHandler();
276
+ ```
277
+
278
+ Routes support GET, POST, PUT, PATCH, and DELETE. `request` exposes `method`, `path`,
279
+ decoded `params`, repeated-value-aware `query`, safe lower-case `headers`, and JSON
280
+ `body`. Authentication headers are never exposed. Plain return values are JSON with
281
+ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide explicit
282
+ status, safe response headers, and text/binary bodies. Missing routes return 404;
283
+ unsupported methods return 405. Existing `defineScript()` projects continue at `/`.
284
+ Validate all business input. See the [router API reference](api-reference.md#http-routers-and-request-context).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.1.1",
4
- "description": "TypeScript SDK for customer code running on Cogover",
3
+ "version": "0.5.0",
4
+ "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "main": "./dist/index.js",
@@ -14,16 +14,24 @@
14
14
  "default": "./dist/index.js"
15
15
  }
16
16
  },
17
+ "bin": {
18
+ "cogover-generate-workspace-types": "scripts/generate-workspace-types.mjs"
19
+ },
17
20
  "files": [
18
21
  "dist",
22
+ "!dist/internal/**/*.d.ts",
23
+ "docs/en",
24
+ "scripts/generate-workspace-types.mjs",
19
25
  "README.md"
20
26
  ],
21
27
  "scripts": {
22
28
  "clean": "node ./scripts/clean.mjs",
23
29
  "build": "npm run clean && tsc -p tsconfig.json && npm run build:runtime",
24
30
  "build:runtime": "node ./scripts/build-runtime-module.mjs",
25
- "typecheck": "tsc -p tsconfig.json --noEmit",
26
- "test": "npm run build && node --test",
31
+ "generate:workspace-types": "node ./scripts/generate-workspace-types.mjs",
32
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json --noEmit",
33
+ "typecheck:dist": "tsc -p tsconfig.dist-test.json --noEmit",
34
+ "test": "npm run build && npm run typecheck:dist && node --test",
27
35
  "check": "npm run typecheck && npm test",
28
36
  "pack:dry-run": "npm pack --dry-run --ignore-scripts",
29
37
  "prepack": "npm run check"
@@ -37,7 +45,11 @@
37
45
  "typescript"
38
46
  ],
39
47
  "license": "MIT",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ },
40
51
  "devDependencies": {
41
- "typescript": "5.9.3"
52
+ "esbuild": "0.28.2",
53
+ "typescript": "7.0.2"
42
54
  }
43
55
  }
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFile, writeFile } from "node:fs/promises";
4
+
5
+ const [inputPath, outputPath] = process.argv.slice(2);
6
+ if (!inputPath || !outputPath) {
7
+ throw new Error("Usage: node generate-workspace-types.mjs <objects.json> <workspace.d.ts>");
8
+ }
9
+
10
+ const document = JSON.parse(await readFile(inputPath, "utf8"));
11
+ const objects = extractObjects(document);
12
+ const declaration = renderDeclaration(objects);
13
+ await writeFile(outputPath, declaration, "utf8");
14
+
15
+ function extractObjects(documentValue) {
16
+ const candidates = [
17
+ documentValue,
18
+ documentValue?.items,
19
+ documentValue?.data?.items,
20
+ documentValue?.data?.rows,
21
+ ];
22
+ const objectsValue = candidates.find(Array.isArray);
23
+ if (!objectsValue) {
24
+ throw new Error("Object metadata must contain an items array");
25
+ }
26
+ return objectsValue;
27
+ }
28
+
29
+ function renderDeclaration(objectsValue) {
30
+ const objectLines = objectsValue
31
+ .filter((object) => typeof object?.slug === "string" && object.slug.length > 0)
32
+ .sort((left, right) => left.slug.localeCompare(right.slug))
33
+ .map(renderObject)
34
+ .join("\n");
35
+
36
+ return `// Generated by @cogover/sdk. Do not edit manually.\n`
37
+ + `import "@cogover/sdk";\n\n`
38
+ + `declare module "@cogover/sdk" {\n`
39
+ + ` interface WorkspaceObjects {\n`
40
+ + objectLines
41
+ + ` }\n`
42
+ + `}\n`;
43
+ }
44
+
45
+ function renderObject(object) {
46
+ const fields = Array.isArray(object.fields) ? object.fields : [];
47
+ const fieldLines = fields
48
+ .filter((field) => typeof field?.slug === "string" && field.slug.length > 0)
49
+ .sort((left, right) => left.slug.localeCompare(right.slug))
50
+ .map((field) => ` ${property(field.slug)}: ${fieldType(field)};\n`)
51
+ .join("");
52
+ return ` ${property(object.slug)}: {\n${fieldLines} };\n`;
53
+ }
54
+
55
+ function fieldType(field) {
56
+ const baseType = baseFieldType(field);
57
+ const nullableType = field.required === true ? baseType : `${baseType} | null`;
58
+ return field.multiple === true && !baseType.endsWith("[]")
59
+ ? `readonly ${parenthesize(baseType)}[]${field.required === true ? "" : " | null"}`
60
+ : nullableType;
61
+ }
62
+
63
+ function baseFieldType(field) {
64
+ switch (field.fieldType) {
65
+ case "short_text":
66
+ case "long_text":
67
+ case "phone":
68
+ case "email":
69
+ case "regex":
70
+ case "auto_number":
71
+ case "date":
72
+ return "string";
73
+ case "boolean":
74
+ return "boolean";
75
+ case "numeric":
76
+ case "decimal":
77
+ case "currency":
78
+ case "percent":
79
+ case "rating":
80
+ case "time":
81
+ case "date_time":
82
+ case "time_duration":
83
+ return "number";
84
+ case "single_choice":
85
+ return optionUnion(field.options);
86
+ case "multi_choices":
87
+ case "label":
88
+ case "cascading":
89
+ return `readonly ${parenthesize(optionUnion(field.options))}[]`;
90
+ case "url":
91
+ return "UrlValue";
92
+ case "file":
93
+ return "FileValue";
94
+ case "lookup_normal":
95
+ case "reference": {
96
+ const objectSlug = referenceObjectSlug(field);
97
+ return objectSlug === null
98
+ ? "RecordReference"
99
+ : `RecordReference<${JSON.stringify(objectSlug)}>`;
100
+ }
101
+ case "date_range":
102
+ return "readonly [string, string]";
103
+ case "date_time_range":
104
+ case "time_range":
105
+ return "readonly [number, number]";
106
+ default:
107
+ return "unknown";
108
+ }
109
+ }
110
+
111
+ function optionUnion(options) {
112
+ const slugs = Array.isArray(options)
113
+ ? options
114
+ .map((option) => option?.slug)
115
+ .filter((slug) => typeof slug === "string" && slug.length > 0)
116
+ : [];
117
+ return slugs.length === 0 ? "string" : slugs.map(JSON.stringify).join(" | ");
118
+ }
119
+
120
+ function referenceObjectSlug(field) {
121
+ const metadata = field.metaData ?? field.meta_data ?? {};
122
+ return metadata.objectSlug
123
+ ?? metadata.object_slug
124
+ ?? metadata.lookupObjectSlug
125
+ ?? metadata.lookup_object_slug
126
+ ?? null;
127
+ }
128
+
129
+ function property(value) {
130
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/u.test(value) ? value : JSON.stringify(value);
131
+ }
132
+
133
+ function parenthesize(value) {
134
+ return value.includes(" | ") ? `(${value})` : value;
135
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEnD"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,8DAA8D;AAC9D,MAAM,UAAU,cAAc,CAAC,IAAY;IACvC,OAAO,SAAS,IAAI,EAAE,CAAC;AAC3B,CAAC"}