@synap-core/sdk 0.2.0 → 1.0.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 (47) hide show
  1. package/README.md +40 -140
  2. package/dist/index.cjs +115 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +80 -0
  5. package/dist/index.d.ts +72 -47
  6. package/dist/index.js +80 -47
  7. package/dist/index.js.map +1 -1
  8. package/package.json +28 -24
  9. package/src/client.ts +193 -0
  10. package/src/index.ts +2 -0
  11. package/dist/client.d.ts +0 -105
  12. package/dist/client.d.ts.map +0 -1
  13. package/dist/client.js +0 -95
  14. package/dist/client.js.map +0 -1
  15. package/dist/index.d.ts.map +0 -1
  16. package/dist/resources/entities.d.ts +0 -90
  17. package/dist/resources/entities.d.ts.map +0 -1
  18. package/dist/resources/entities.js +0 -126
  19. package/dist/resources/entities.js.map +0 -1
  20. package/dist/resources/events.d.ts +0 -51
  21. package/dist/resources/events.d.ts.map +0 -1
  22. package/dist/resources/events.js +0 -92
  23. package/dist/resources/events.js.map +0 -1
  24. package/dist/resources/preferences.d.ts +0 -24
  25. package/dist/resources/preferences.d.ts.map +0 -1
  26. package/dist/resources/preferences.js +0 -30
  27. package/dist/resources/preferences.js.map +0 -1
  28. package/dist/resources/relations.d.ts +0 -71
  29. package/dist/resources/relations.d.ts.map +0 -1
  30. package/dist/resources/relations.js +0 -121
  31. package/dist/resources/relations.js.map +0 -1
  32. package/dist/resources/views.d.ts +0 -43
  33. package/dist/resources/views.d.ts.map +0 -1
  34. package/dist/resources/views.js +0 -54
  35. package/dist/resources/views.js.map +0 -1
  36. package/dist/resources/workspaces.d.ts +0 -50
  37. package/dist/resources/workspaces.d.ts.map +0 -1
  38. package/dist/resources/workspaces.js +0 -66
  39. package/dist/resources/workspaces.js.map +0 -1
  40. package/dist/types/events.d.ts +0 -24
  41. package/dist/types/events.d.ts.map +0 -1
  42. package/dist/types/events.js +0 -5
  43. package/dist/types/events.js.map +0 -1
  44. package/dist/types/relations.d.ts +0 -26
  45. package/dist/types/relations.d.ts.map +0 -1
  46. package/dist/types/relations.js +0 -5
  47. package/dist/types/relations.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,48 +1,81 @@
1
- /**
2
- * @synap/sdk - High-Level SDK for Synap
3
- *
4
- * Event-sourced personal data platform SDK with type-safe APIs.
5
- *
6
- * @example
7
- * ```typescript
8
- * import { SynapSDK } from '@synap/sdk';
9
- *
10
- * const synap = new SynapSDK({
11
- * url: 'https://api.synap.app',
12
- * apiKey: 'your-api-key',
13
- * realtime: {
14
- * userId: 'user-123',
15
- * userName: 'Alice',
16
- * },
17
- * });
18
- *
19
- * // Create entity (event-sourced)
20
- * const task = await synap.entities.create({
21
- * type: 'task',
22
- * title: 'Call Marie',
23
- * metadata: { dueDate: '2024-12-20', priority: 'high' }
24
- * });
25
- *
26
- * // Create workspace
27
- * const workspace = await synap.workspaces.create({ name: 'Team' });
28
- *
29
- * // Create whiteboard
30
- * const board = await synap.views.create({
31
- * type: 'whiteboard',
32
- * name: 'Brainstorm',
33
- * workspaceId: workspace.id,
34
- * });
35
- *
36
- * // Real-time collaboration
37
- * synap.realtime?.connectPresence(board.id);
38
- * const ydoc = synap.realtime?.connectYjs(board.id);
39
- * ```
40
- */
41
- export { SynapSDK } from './client.js';
42
- export { EntitiesAPI } from './resources/entities.js';
43
- export { RelationsAPI } from './resources/relations.js';
44
- export { EventsAPI } from './resources/events.js';
45
- export { WorkspacesAPI } from './resources/workspaces.js';
46
- export { ViewsAPI } from './resources/views.js';
47
- export { PreferencesAPI } from './resources/preferences.js';
1
+ // src/client.ts
2
+ import {
3
+ createTRPCClient,
4
+ httpBatchLink
5
+ } from "@trpc/client";
6
+ import superjson from "superjson";
7
+ function createSynapClient(options) {
8
+ const { podUrl, apiKey, workspaceId, extraHeaders, onAuthError } = options;
9
+ const url = `${podUrl.replace(/\/$/, "")}/trpc`;
10
+ const baseFetch = (input, init) => fetch(input, { ...init, credentials: "include" });
11
+ const wrappedFetch = onAuthError ? async (input, init) => {
12
+ const response = await baseFetch(input, init);
13
+ if (response.ok) return response;
14
+ const cloned = response.clone();
15
+ let body = "";
16
+ try {
17
+ body = await cloned.text();
18
+ } catch {
19
+ body = "";
20
+ }
21
+ let isTrpcFormat = false;
22
+ try {
23
+ isTrpcFormat = Array.isArray(JSON.parse(body));
24
+ } catch {
25
+ isTrpcFormat = false;
26
+ }
27
+ if (isTrpcFormat) return response;
28
+ const parsedMessage = (() => {
29
+ try {
30
+ const parsed = JSON.parse(body);
31
+ return parsed.error ?? parsed.message ?? null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ })();
36
+ const message = response.status === 401 ? "Session expired. Please sign in again." : `Request failed (${response.status}).`;
37
+ if (response.status === 401) {
38
+ onAuthError({ status: 401, message });
39
+ }
40
+ const trpcError = [
41
+ {
42
+ error: {
43
+ message,
44
+ code: response.status === 401 ? -32001 : -32e3,
45
+ data: {
46
+ code: response.status === 401 ? "UNAUTHORIZED" : "INTERNAL_SERVER_ERROR",
47
+ httpStatus: response.status,
48
+ // Server-supplied detail — untrusted; consumers must escape it
49
+ // before rendering (never inject as HTML).
50
+ detail: parsedMessage ?? void 0
51
+ }
52
+ }
53
+ }
54
+ ];
55
+ return new Response(JSON.stringify(trpcError), {
56
+ status: response.status,
57
+ headers: { "content-type": "application/json" }
58
+ });
59
+ } : baseFetch;
60
+ return createTRPCClient({
61
+ links: [
62
+ httpBatchLink({
63
+ url,
64
+ transformer: superjson,
65
+ fetch: wrappedFetch,
66
+ headers: () => ({
67
+ // Session token mode (Kratos, preferred for non-browser clients)
68
+ ...options.sessionToken ? { "x-session-token": options.sessionToken } : {},
69
+ // API key mode (Bearer, for legacy SDK usage)
70
+ ...apiKey && !options.sessionToken ? { Authorization: `Bearer ${apiKey}` } : {},
71
+ ...workspaceId ? { "x-workspace-id": workspaceId } : {},
72
+ ...extraHeaders
73
+ })
74
+ })
75
+ ]
76
+ });
77
+ }
78
+ export {
79
+ createSynapClient
80
+ };
48
81
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,QAAQ,EAAuB,MAAM,aAAa,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC"}
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["/**\n * @synap-core/sdk — Type-safe tRPC client for Synap data pods.\n *\n * Usage:\n * ```typescript\n * import { createSynapClient } from \"@synap-core/sdk\";\n *\n * const synap = createSynapClient({\n * podUrl: \"https://pod.example.com\",\n * apiKey: \"sk_live_...\",\n * workspaceId: \"ws_...\",\n * });\n *\n * // Fully typed — autocomplete works on all 47+ routers\n * const entities = await synap.entities.list.query({ limit: 20 });\n * const workspace = await synap.workspaces.get.query();\n * ```\n */\n\nimport {\n createTRPCClient,\n httpBatchLink,\n type CreateTRPCClient,\n} from \"@trpc/client\";\nimport superjson from \"superjson\";\nimport type { AppRouter } from \"@synap-core/api-types\";\n\nexport interface SynapClientOptions {\n /**\n * Base URL of the data pod (no trailing slash, no `/trpc` suffix).\n * @example \"https://pod.example.com\"\n */\n podUrl: string;\n\n /**\n * Ory Kratos session token (for example, from the Pod's\n * `/api/federation/exchange` endpoint).\n * Sent as `X-Session-Token` header — preferred for non-browser clients\n * like extensions, CLI tools, and mobile apps.\n * @example \"oathkeeper_token_...\"\n */\n sessionToken?: string;\n\n /**\n * API key for authentication (Bearer token).\n * Generate one in your workspace developer settings.\n * If omitted, the client falls back to cookie-based Kratos session auth.\n * @example \"sk_live_abc123...\"\n */\n apiKey?: string;\n\n /**\n * Workspace ID to scope all requests to.\n * Pass empty string for procedures that don't require workspace context\n * (e.g. workspaces.list, which is protectedProcedure only).\n * @example \"ws_01jk...\"\n */\n workspaceId: string;\n\n /**\n * Additional headers to include in every request.\n */\n extraHeaders?: Record<string, string>;\n\n /**\n * Called when the pod returns a `401 Unauthorized` (expired/invalid session\n * or API key). The app should sign out and re-authenticate (re-handshake).\n *\n * The pod's auth middleware can reply with a plain-JSON body\n * (`{\"error\":\"Invalid session\"}`) that is NOT in tRPC batch format and would\n * otherwise crash the superjson transformer; when an `onAuthError` handler is\n * provided the client rewrites such responses into a well-formed tRPC error so\n * the query rejects gracefully instead of throwing a parse error.\n */\n onAuthError?: (error: { status: number; message: string }) => void;\n}\n\n/**\n * Creates a fully-typed tRPC client connected to a Synap data pod.\n *\n * All 47+ tRPC routers are available with full TypeScript autocomplete\n * and compile-time safety. Auth is handled via Bearer token + workspace header.\n */\nexport function createSynapClient(\n options: SynapClientOptions,\n): CreateTRPCClient<AppRouter> {\n const { podUrl, apiKey, workspaceId, extraHeaders, onAuthError } = options;\n\n const url = `${podUrl.replace(/\\/$/, \"\")}/trpc`;\n\n // Base fetch: always include credentials so session cookies are sent in\n // cookie-auth mode. When apiKey is present, the Bearer token takes precedence\n // on the pod.\n const baseFetch: typeof fetch = (input, init) =>\n fetch(input, { ...init, credentials: \"include\" });\n\n // When an onAuthError handler is provided, wrap fetch to catch 401 (and other\n // non-tRPC error) responses. The pod's auth middleware replies with a plain\n // JSON body that is not a tRPC batch array; left untouched it crashes the\n // superjson transformer. We notify the handler and rewrite the body into a\n // valid tRPC error envelope so the query rejects cleanly.\n const wrappedFetch: typeof fetch = onAuthError\n ? async (input, init) => {\n const response = await baseFetch(input, init);\n if (response.ok) return response;\n\n const cloned = response.clone();\n let body = \"\";\n try {\n body = await cloned.text();\n } catch {\n body = \"\";\n }\n\n let isTrpcFormat = false;\n try {\n isTrpcFormat = Array.isArray(JSON.parse(body));\n } catch {\n isTrpcFormat = false;\n }\n if (isTrpcFormat) return response;\n\n const parsedMessage = (() => {\n try {\n const parsed = JSON.parse(body) as {\n error?: string;\n message?: string;\n };\n return parsed.error ?? parsed.message ?? null;\n } catch {\n return null;\n }\n })();\n // Never forward a server-controlled string as user-facing copy — map by\n // status. The raw server detail is preserved (untrusted) on `data.detail`.\n const message =\n response.status === 401\n ? \"Session expired. Please sign in again.\"\n : `Request failed (${response.status}).`;\n\n if (response.status === 401) {\n onAuthError({ status: 401, message });\n }\n\n const trpcError = [\n {\n error: {\n message,\n code: response.status === 401 ? -32001 : -32000,\n data: {\n code:\n response.status === 401\n ? \"UNAUTHORIZED\"\n : \"INTERNAL_SERVER_ERROR\",\n httpStatus: response.status,\n // Server-supplied detail — untrusted; consumers must escape it\n // before rendering (never inject as HTML).\n detail: parsedMessage ?? undefined,\n },\n\n },\n },\n ];\n return new Response(JSON.stringify(trpcError), {\n status: response.status,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n : baseFetch;\n\n return createTRPCClient<AppRouter>({\n links: [\n httpBatchLink({\n url,\n transformer: superjson,\n fetch: wrappedFetch,\n headers: () => ({\n // Session token mode (Kratos, preferred for non-browser clients)\n ...(options.sessionToken ? { \"x-session-token\": options.sessionToken } : {}),\n // API key mode (Bearer, for legacy SDK usage)\n ...(apiKey && !options.sessionToken ? { Authorization: `Bearer ${apiKey}` } : {}),\n ...(workspaceId ? { \"x-workspace-id\": workspaceId } : {}),\n ...extraHeaders,\n }),\n }),\n ],\n });\n}\n\nexport type SynapClient = ReturnType<typeof createSynapClient>;\n\n// Re-export type helpers so consumers don't need @trpc/server\nexport type { AppRouter };\n"],"mappings":";AAmBA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,OAAO,eAAe;AA2Df,SAAS,kBACd,SAC6B;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AAG;AAAA,MAC7C,QAAQ,SAAS;AAAA,MACjB,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAChD,CAAC;AAAA,EACH,IACA;AAEJ,SAAO,iBAA4B;AAAA,IACjC,OAAO;AAAA,MACL,cAAc;AAAA,QACZ;AAAA,QACA,aAAa;AAAA,QACb,OAAO;AAAA,QACP,SAAS,OAAO;AAAA;AAAA,UAEd,GAAI,QAAQ,eAAe,EAAE,mBAAmB,QAAQ,aAAa,IAAI,CAAC;AAAA;AAAA,UAE1E,GAAI,UAAU,CAAC,QAAQ,eAAe,EAAE,eAAe,UAAU,MAAM,GAAG,IAAI,CAAC;AAAA,UAC/E,GAAI,cAAc,EAAE,kBAAkB,YAAY,IAAI,CAAC;AAAA,UACvD,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,12 +1,9 @@
1
1
  {
2
2
  "name": "@synap-core/sdk",
3
- "version": "0.2.0",
4
- "publishConfig": {
5
- "access": "public"
6
- },
7
- "description": "High-level SDK for Synap - Event-sourced personal data platform",
3
+ "version": "1.0.0",
4
+ "description": "Type-safe tRPC client SDK for Synap data pods",
8
5
  "type": "module",
9
- "main": "./dist/index.js",
6
+ "main": "./dist/index.cjs",
10
7
  "module": "./dist/index.js",
11
8
  "types": "./dist/index.d.ts",
12
9
  "exports": {
@@ -16,37 +13,44 @@
16
13
  "require": "./dist/index.cjs"
17
14
  }
18
15
  },
16
+ "files": [
17
+ "dist",
18
+ "src"
19
+ ],
19
20
  "keywords": [
20
21
  "synap",
21
22
  "sdk",
22
- "event-sourcing",
23
- "personal-data",
24
- "knowledge-graph"
23
+ "trpc",
24
+ "data-pod"
25
25
  ],
26
- "author": "Synap Team",
27
- "license": "AGPL-3.0",
28
26
  "dependencies": {
29
- "@synap-core/client": "^0.1.0",
30
- "@synap-core/types": "^0.1.0"
27
+ "@synap-core/api-types": "^1.23.3",
28
+ "@trpc/client": "^11.10.0",
29
+ "superjson": "^2.2.6"
31
30
  },
32
31
  "devDependencies": {
33
- "@types/node": "^20.10.0",
34
- "typescript": "^5.3.3"
32
+ "tsup": "^8.3.5",
33
+ "typescript": "^5.7.3"
34
+ },
35
+ "peerDependencies": {
36
+ "@trpc/server": "^11.0.0"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "@trpc/server": {
40
+ "optional": true
41
+ }
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
35
45
  },
36
- "files": [
37
- "dist",
38
- "README.md"
39
- ],
40
46
  "repository": {
41
47
  "type": "git",
42
- "url": "https://github.com/synap-core/synap-backend",
48
+ "url": "https://github.com/synap/synap-app.git",
43
49
  "directory": "packages/sdk"
44
50
  },
45
- "homepage": "https://github.com/synap-core/synap-backend#readme",
51
+ "license": "MIT",
46
52
  "scripts": {
47
- "build": "tsc -p tsconfig.json",
48
- "dev": "tsc -p tsconfig.json --watch",
49
- "clean": "rm -rf dist",
53
+ "build": "tsup",
50
54
  "typecheck": "tsc --noEmit"
51
55
  }
52
56
  }
package/src/client.ts ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * @synap-core/sdk — Type-safe tRPC client for Synap data pods.
3
+ *
4
+ * Usage:
5
+ * ```typescript
6
+ * import { createSynapClient } from "@synap-core/sdk";
7
+ *
8
+ * const synap = createSynapClient({
9
+ * podUrl: "https://pod.example.com",
10
+ * apiKey: "sk_live_...",
11
+ * workspaceId: "ws_...",
12
+ * });
13
+ *
14
+ * // Fully typed — autocomplete works on all 47+ routers
15
+ * const entities = await synap.entities.list.query({ limit: 20 });
16
+ * const workspace = await synap.workspaces.get.query();
17
+ * ```
18
+ */
19
+
20
+ import {
21
+ createTRPCClient,
22
+ httpBatchLink,
23
+ type CreateTRPCClient,
24
+ } from "@trpc/client";
25
+ import superjson from "superjson";
26
+ import type { AppRouter } from "@synap-core/api-types";
27
+
28
+ export interface SynapClientOptions {
29
+ /**
30
+ * Base URL of the data pod (no trailing slash, no `/trpc` suffix).
31
+ * @example "https://pod.example.com"
32
+ */
33
+ podUrl: string;
34
+
35
+ /**
36
+ * Ory Kratos session token (for example, from the Pod's
37
+ * `/api/federation/exchange` endpoint).
38
+ * Sent as `X-Session-Token` header — preferred for non-browser clients
39
+ * like extensions, CLI tools, and mobile apps.
40
+ * @example "oathkeeper_token_..."
41
+ */
42
+ sessionToken?: string;
43
+
44
+ /**
45
+ * API key for authentication (Bearer token).
46
+ * Generate one in your workspace developer settings.
47
+ * If omitted, the client falls back to cookie-based Kratos session auth.
48
+ * @example "sk_live_abc123..."
49
+ */
50
+ apiKey?: string;
51
+
52
+ /**
53
+ * Workspace ID to scope all requests to.
54
+ * Pass empty string for procedures that don't require workspace context
55
+ * (e.g. workspaces.list, which is protectedProcedure only).
56
+ * @example "ws_01jk..."
57
+ */
58
+ workspaceId: string;
59
+
60
+ /**
61
+ * Additional headers to include in every request.
62
+ */
63
+ extraHeaders?: Record<string, string>;
64
+
65
+ /**
66
+ * Called when the pod returns a `401 Unauthorized` (expired/invalid session
67
+ * or API key). The app should sign out and re-authenticate (re-handshake).
68
+ *
69
+ * The pod's auth middleware can reply with a plain-JSON body
70
+ * (`{"error":"Invalid session"}`) that is NOT in tRPC batch format and would
71
+ * otherwise crash the superjson transformer; when an `onAuthError` handler is
72
+ * provided the client rewrites such responses into a well-formed tRPC error so
73
+ * the query rejects gracefully instead of throwing a parse error.
74
+ */
75
+ onAuthError?: (error: { status: number; message: string }) => void;
76
+ }
77
+
78
+ /**
79
+ * Creates a fully-typed tRPC client connected to a Synap data pod.
80
+ *
81
+ * All 47+ tRPC routers are available with full TypeScript autocomplete
82
+ * and compile-time safety. Auth is handled via Bearer token + workspace header.
83
+ */
84
+ export function createSynapClient(
85
+ options: SynapClientOptions,
86
+ ): CreateTRPCClient<AppRouter> {
87
+ const { podUrl, apiKey, workspaceId, extraHeaders, onAuthError } = options;
88
+
89
+ const url = `${podUrl.replace(/\/$/, "")}/trpc`;
90
+
91
+ // Base fetch: always include credentials so session cookies are sent in
92
+ // cookie-auth mode. When apiKey is present, the Bearer token takes precedence
93
+ // on the pod.
94
+ const baseFetch: typeof fetch = (input, init) =>
95
+ fetch(input, { ...init, credentials: "include" });
96
+
97
+ // When an onAuthError handler is provided, wrap fetch to catch 401 (and other
98
+ // non-tRPC error) responses. The pod's auth middleware replies with a plain
99
+ // JSON body that is not a tRPC batch array; left untouched it crashes the
100
+ // superjson transformer. We notify the handler and rewrite the body into a
101
+ // valid tRPC error envelope so the query rejects cleanly.
102
+ const wrappedFetch: typeof fetch = onAuthError
103
+ ? async (input, init) => {
104
+ const response = await baseFetch(input, init);
105
+ if (response.ok) return response;
106
+
107
+ const cloned = response.clone();
108
+ let body = "";
109
+ try {
110
+ body = await cloned.text();
111
+ } catch {
112
+ body = "";
113
+ }
114
+
115
+ let isTrpcFormat = false;
116
+ try {
117
+ isTrpcFormat = Array.isArray(JSON.parse(body));
118
+ } catch {
119
+ isTrpcFormat = false;
120
+ }
121
+ if (isTrpcFormat) return response;
122
+
123
+ const parsedMessage = (() => {
124
+ try {
125
+ const parsed = JSON.parse(body) as {
126
+ error?: string;
127
+ message?: string;
128
+ };
129
+ return parsed.error ?? parsed.message ?? null;
130
+ } catch {
131
+ return null;
132
+ }
133
+ })();
134
+ // Never forward a server-controlled string as user-facing copy — map by
135
+ // status. The raw server detail is preserved (untrusted) on `data.detail`.
136
+ const message =
137
+ response.status === 401
138
+ ? "Session expired. Please sign in again."
139
+ : `Request failed (${response.status}).`;
140
+
141
+ if (response.status === 401) {
142
+ onAuthError({ status: 401, message });
143
+ }
144
+
145
+ const trpcError = [
146
+ {
147
+ error: {
148
+ message,
149
+ code: response.status === 401 ? -32001 : -32000,
150
+ data: {
151
+ code:
152
+ response.status === 401
153
+ ? "UNAUTHORIZED"
154
+ : "INTERNAL_SERVER_ERROR",
155
+ httpStatus: response.status,
156
+ // Server-supplied detail — untrusted; consumers must escape it
157
+ // before rendering (never inject as HTML).
158
+ detail: parsedMessage ?? undefined,
159
+ },
160
+
161
+ },
162
+ },
163
+ ];
164
+ return new Response(JSON.stringify(trpcError), {
165
+ status: response.status,
166
+ headers: { "content-type": "application/json" },
167
+ });
168
+ }
169
+ : baseFetch;
170
+
171
+ return createTRPCClient<AppRouter>({
172
+ links: [
173
+ httpBatchLink({
174
+ url,
175
+ transformer: superjson,
176
+ fetch: wrappedFetch,
177
+ headers: () => ({
178
+ // Session token mode (Kratos, preferred for non-browser clients)
179
+ ...(options.sessionToken ? { "x-session-token": options.sessionToken } : {}),
180
+ // API key mode (Bearer, for legacy SDK usage)
181
+ ...(apiKey && !options.sessionToken ? { Authorization: `Bearer ${apiKey}` } : {}),
182
+ ...(workspaceId ? { "x-workspace-id": workspaceId } : {}),
183
+ ...extraHeaders,
184
+ }),
185
+ }),
186
+ ],
187
+ });
188
+ }
189
+
190
+ export type SynapClient = ReturnType<typeof createSynapClient>;
191
+
192
+ // Re-export type helpers so consumers don't need @trpc/server
193
+ export type { AppRouter };
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { createSynapClient } from "./client";
2
+ export type { SynapClient, SynapClientOptions, AppRouter } from "./client";
package/dist/client.d.ts DELETED
@@ -1,105 +0,0 @@
1
- /**
2
- * SynapSDK - Main SDK Client
3
- *
4
- * Provides high-level APIs for interacting with Synap Data Pod.
5
- * All mutations go through event sourcing, all queries are direct reads.
6
- */
7
- import { type SynapClient as ClientType } from '@synap-core/client';
8
- import { EntitiesAPI } from './resources/entities.js';
9
- import { RelationsAPI } from './resources/relations.js';
10
- import { EventsAPI } from './resources/events.js';
11
- import { WorkspacesAPI } from './resources/workspaces.js';
12
- import { ViewsAPI } from './resources/views.js';
13
- import { PreferencesAPI } from './resources/preferences.js';
14
- /**
15
- * SDK Configuration
16
- */
17
- export interface SynapSDKConfig {
18
- /**
19
- * Base URL for the Synap API
20
- * @example 'https://api.synap.app' or 'http://localhost:3000'
21
- */
22
- url: string;
23
- /**
24
- * API key or authentication token
25
- * Either provide apiKey OR headers function
26
- */
27
- apiKey?: string;
28
- /**
29
- * Custom headers function for dynamic authentication
30
- * @example () => ({ Authorization: `Bearer ${getToken()}` })
31
- */
32
- headers?: () => Record<string, string> | Promise<Record<string, string>>;
33
- /**
34
- * Custom fetch implementation (for React Native, etc.)
35
- */
36
- fetch?: typeof globalThis.fetch;
37
- /**
38
- * Real-time configuration (optional)
39
- */
40
- realtime?: {
41
- userId: string;
42
- userName: string;
43
- };
44
- }
45
- /**
46
- * Synap SDK - High-Level Client
47
- *
48
- * @example
49
- * ```typescript
50
- * const synap = new SynapSDK({
51
- * url: 'https://api.synap.app',
52
- * apiKey: 'sk_...',
53
- * realtime: {
54
- * userId: 'user-123',
55
- * userName: 'Alice',
56
- * },
57
- * });
58
- *
59
- * // Use resource APIs
60
- * const task = await synap.entities.create({ type: 'task', title: 'Call Marie' });
61
- * await synap.relations.create(task.id, personId, 'assigned_to');
62
- * const history = await synap.events.getHistory(task.id);
63
- *
64
- * // Workspaces
65
- * const workspace = await synap.workspaces.create({ name: 'Team Workspace' });
66
- *
67
- * // Views
68
- * const whiteboard = await synap.views.create({
69
- * type: 'whiteboard',
70
- * name: 'Brainstorm',
71
- * workspaceId: workspace.id
72
- * });
73
- *
74
- * // Real-time collaboration
75
- * synap.realtime?.connectPresence(whiteboard.id);
76
- * const ydoc = synap.realtime?.connectYjs(whiteboard.id);
77
- * ```
78
- */
79
- export declare class SynapSDK {
80
- /** Internal client */
81
- private readonly _client;
82
- /** Entities API - Generic entity operations */
83
- readonly entities: EntitiesAPI;
84
- /** Relations API - Relationship management */
85
- readonly relations: RelationsAPI;
86
- /** Events API - Event history and replay */
87
- readonly events: EventsAPI;
88
- /** Workspaces API - Multi-user workspace management (V3.0) */
89
- readonly workspaces: WorkspacesAPI;
90
- /** Views API - Whiteboards, timelines, kanban boards (V3.0) */
91
- readonly views: ViewsAPI;
92
- /** Preferences API - User preferences (V3.0) */
93
- readonly preferences: PreferencesAPI;
94
- constructor(config: SynapSDKConfig);
95
- /**
96
- * Get direct access to underlying client
97
- * Use this for advanced operations not covered by SDK APIs
98
- */
99
- get client(): ClientType;
100
- /**
101
- * Get real-time client for WebSocket features
102
- */
103
- get realtime(): import("@synap-core/client").RealtimeClient | null;
104
- }
105
- //# sourceMappingURL=client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAqB,KAAK,WAAW,IAAI,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAEzE;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAEhC;;OAEG;IACH,QAAQ,CAAC,EAAE;QACT,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;KAClB,CAAC;CACH;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,qBAAa,QAAQ;IACnB,sBAAsB;IACtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAa;IAErC,+CAA+C;IAC/C,SAAgB,QAAQ,EAAE,WAAW,CAAC;IAEtC,8CAA8C;IAC9C,SAAgB,SAAS,EAAE,YAAY,CAAC;IAExC,4CAA4C;IAC5C,SAAgB,MAAM,EAAE,SAAS,CAAC;IAElC,8DAA8D;IAC9D,SAAgB,UAAU,EAAE,aAAa,CAAC;IAE1C,+DAA+D;IAC/D,SAAgB,KAAK,EAAE,QAAQ,CAAC;IAEhC,gDAAgD;IAChD,SAAgB,WAAW,EAAE,cAAc,CAAC;gBAEhC,MAAM,EAAE,cAAc;IAoBlC;;;OAGG;IACH,IAAI,MAAM,IAAI,UAAU,CAEvB;IAED;;OAEG;IACH,IAAI,QAAQ,uDAEX;CACF"}
package/dist/client.js DELETED
@@ -1,95 +0,0 @@
1
- /**
2
- * SynapSDK - Main SDK Client
3
- *
4
- * Provides high-level APIs for interacting with Synap Data Pod.
5
- * All mutations go through event sourcing, all queries are direct reads.
6
- */
7
- import { createSynapClient } from '@synap-core/client';
8
- import { EntitiesAPI } from './resources/entities.js';
9
- import { RelationsAPI } from './resources/relations.js';
10
- import { EventsAPI } from './resources/events.js';
11
- import { WorkspacesAPI } from './resources/workspaces.js';
12
- import { ViewsAPI } from './resources/views.js';
13
- import { PreferencesAPI } from './resources/preferences.js';
14
- /**
15
- * Synap SDK - High-Level Client
16
- *
17
- * @example
18
- * ```typescript
19
- * const synap = new SynapSDK({
20
- * url: 'https://api.synap.app',
21
- * apiKey: 'sk_...',
22
- * realtime: {
23
- * userId: 'user-123',
24
- * userName: 'Alice',
25
- * },
26
- * });
27
- *
28
- * // Use resource APIs
29
- * const task = await synap.entities.create({ type: 'task', title: 'Call Marie' });
30
- * await synap.relations.create(task.id, personId, 'assigned_to');
31
- * const history = await synap.events.getHistory(task.id);
32
- *
33
- * // Workspaces
34
- * const workspace = await synap.workspaces.create({ name: 'Team Workspace' });
35
- *
36
- * // Views
37
- * const whiteboard = await synap.views.create({
38
- * type: 'whiteboard',
39
- * name: 'Brainstorm',
40
- * workspaceId: workspace.id
41
- * });
42
- *
43
- * // Real-time collaboration
44
- * synap.realtime?.connectPresence(whiteboard.id);
45
- * const ydoc = synap.realtime?.connectYjs(whiteboard.id);
46
- * ```
47
- */
48
- export class SynapSDK {
49
- /** Internal client */
50
- _client;
51
- /** Entities API - Generic entity operations */
52
- entities;
53
- /** Relations API - Relationship management */
54
- relations;
55
- /** Events API - Event history and replay */
56
- events;
57
- /** Workspaces API - Multi-user workspace management (V3.0) */
58
- workspaces;
59
- /** Views API - Whiteboards, timelines, kanban boards (V3.0) */
60
- views;
61
- /** Preferences API - User preferences (V3.0) */
62
- preferences;
63
- constructor(config) {
64
- // Create underlying client
65
- this._client = createSynapClient({
66
- url: config.url,
67
- headers: config.apiKey
68
- ? { Authorization: `Bearer ${config.apiKey}` }
69
- : config.headers,
70
- fetch: config.fetch,
71
- realtime: config.realtime,
72
- });
73
- // Initialize resource APIs
74
- this.entities = new EntitiesAPI(this._client);
75
- this.relations = new RelationsAPI(this._client);
76
- this.events = new EventsAPI(this._client);
77
- this.workspaces = new WorkspacesAPI(this._client);
78
- this.views = new ViewsAPI(this._client);
79
- this.preferences = new PreferencesAPI(this._client);
80
- }
81
- /**
82
- * Get direct access to underlying client
83
- * Use this for advanced operations not covered by SDK APIs
84
- */
85
- get client() {
86
- return this._client;
87
- }
88
- /**
89
- * Get real-time client for WebSocket features
90
- */
91
- get realtime() {
92
- return this._client.realtime;
93
- }
94
- }
95
- //# sourceMappingURL=client.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,iBAAiB,EAAkC,MAAM,oBAAoB,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,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