@bonnard/sdk 0.1.2

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) 2025-present Bonnard (meal-inc)
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.
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # @bonnard/sdk
2
+
3
+ TypeScript SDK for querying the [Bonnard](https://www.bonnard.dev) semantic layer from any JavaScript or TypeScript application.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @bonnard/sdk
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ### With a publishable key
14
+
15
+ ```typescript
16
+ import { createClient } from '@bonnard/sdk';
17
+
18
+ const bon = createClient({
19
+ apiKey: 'bon_pk_...',
20
+ });
21
+
22
+ const { data } = await bon.query({
23
+ cube: 'orders',
24
+ measures: ['revenue', 'count'],
25
+ dimensions: ['status'],
26
+ });
27
+
28
+ console.log(data);
29
+ // [{ revenue: 45000, count: 120, status: "completed" }, ...]
30
+ ```
31
+
32
+ ### With token exchange (multi-tenant)
33
+
34
+ For B2B apps where each user sees their own data, use a server-side secret key to mint scoped tokens:
35
+
36
+ ```typescript
37
+ // Server: exchange secret key for a scoped JWT
38
+ const res = await fetch('https://app.bonnard.dev/api/sdk/token', {
39
+ method: 'POST',
40
+ headers: {
41
+ Authorization: 'Bearer bon_sk_...',
42
+ 'Content-Type': 'application/json',
43
+ },
44
+ body: JSON.stringify({
45
+ security_context: { tenant_id: 'acme-123' },
46
+ }),
47
+ });
48
+ const { token } = await res.json();
49
+ ```
50
+
51
+ ```typescript
52
+ // Client: use the token callback
53
+ const bon = createClient({
54
+ fetchToken: async () => {
55
+ const res = await fetch('/api/analytics/token');
56
+ const { token } = await res.json();
57
+ return token;
58
+ },
59
+ });
60
+
61
+ const { data } = await bon.query({
62
+ cube: 'orders',
63
+ measures: ['revenue'],
64
+ timeDimension: {
65
+ dimension: 'created_at',
66
+ granularity: 'month',
67
+ dateRange: ['2025-01-01', '2025-12-31'],
68
+ },
69
+ });
70
+ ```
71
+
72
+ Tokens are cached automatically and refreshed 60 seconds before expiry.
73
+
74
+ ## API
75
+
76
+ ### `createClient(config)`
77
+
78
+ | Option | Type | Description |
79
+ |--------|------|-------------|
80
+ | `apiKey` | `string` | Publishable key (`bon_pk_...`). Use one of `apiKey` or `fetchToken`. |
81
+ | `fetchToken` | `() => Promise<string>` | Async callback that returns a JWT. Use for multi-tenant setups. |
82
+ | `baseUrl` | `string` | API base URL (default: `https://app.bonnard.dev`) |
83
+
84
+ ### `client.query(options)`
85
+
86
+ JSON query against the semantic layer.
87
+
88
+ ```typescript
89
+ const { data } = await bon.query({
90
+ cube: 'orders',
91
+ measures: ['revenue', 'count'],
92
+ dimensions: ['product_category'],
93
+ filters: [
94
+ { dimension: 'status', operator: 'equals', values: ['completed'] },
95
+ ],
96
+ timeDimension: {
97
+ dimension: 'created_at',
98
+ granularity: 'month',
99
+ dateRange: ['2025-01-01', '2025-12-31'],
100
+ },
101
+ orderBy: { revenue: 'desc' },
102
+ limit: 100,
103
+ });
104
+ ```
105
+
106
+ ### `client.sql(query)`
107
+
108
+ Raw SQL query using Cube SQL syntax.
109
+
110
+ ```typescript
111
+ const { data } = await bon.sql(
112
+ `SELECT product_category, MEASURE(revenue) FROM orders GROUP BY 1`
113
+ );
114
+ ```
115
+
116
+ ## Links
117
+
118
+ - [Bonnard Docs](https://docs.bonnard.dev)
119
+ - [Getting Started](https://docs.bonnard.dev/docs/getting-started)
120
+ - [Discord](https://discord.com/invite/RQuvjGRz)
121
+
122
+ ## License
123
+
124
+ [MIT](./LICENSE)
125
+
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Bonnard SDK — Client for querying semantic layer
3
+ */
4
+ import type { BonnardConfig, QueryOptions, QueryResult, SqlResult } from './types.js';
5
+ export declare function createClient(config: BonnardConfig): {
6
+ /**
7
+ * Execute a JSON query against the semantic layer
8
+ */
9
+ query<T = Record<string, unknown>>(options: QueryOptions): Promise<QueryResult<T>>;
10
+ /**
11
+ * Execute a SQL query against the semantic layer
12
+ */
13
+ sql<T = Record<string, unknown>>(query: string): Promise<SqlResult<T>>;
14
+ };
package/dist/client.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Bonnard SDK — Client for querying semantic layer
3
+ */
4
+ import { buildCubeQuery, simplifyResult } from './query.js';
5
+ /**
6
+ * Parse JWT expiry from the payload (base64url-decoded middle segment).
7
+ * Returns the `exp` claim as a millisecond timestamp, or 0 if unparseable.
8
+ */
9
+ function parseJwtExpiry(token) {
10
+ try {
11
+ const parts = token.split('.');
12
+ if (parts.length !== 3)
13
+ return 0;
14
+ // base64url → base64 → decode
15
+ const payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
16
+ const json = JSON.parse(atob(payload));
17
+ return typeof json.exp === 'number' ? json.exp * 1000 : 0;
18
+ }
19
+ catch {
20
+ return 0;
21
+ }
22
+ }
23
+ const REFRESH_BUFFER_MS = 60_000; // refresh 60s before expiry
24
+ export function createClient(config) {
25
+ const hasApiKey = !!config.apiKey;
26
+ const hasFetchToken = !!config.fetchToken;
27
+ if (!hasApiKey && !hasFetchToken) {
28
+ throw new Error('BonnardConfig requires either apiKey or fetchToken');
29
+ }
30
+ if (hasApiKey && hasFetchToken) {
31
+ throw new Error('BonnardConfig requires either apiKey or fetchToken, not both');
32
+ }
33
+ const baseUrl = config.baseUrl || 'https://app.bonnard.dev';
34
+ // Token cache for fetchToken mode
35
+ let cachedToken = null;
36
+ let cachedExpiry = 0;
37
+ async function getToken() {
38
+ // Static API key — return directly
39
+ if (config.apiKey) {
40
+ return config.apiKey;
41
+ }
42
+ // Token callback — cache and refresh
43
+ const now = Date.now();
44
+ if (cachedToken && cachedExpiry - REFRESH_BUFFER_MS > now) {
45
+ return cachedToken;
46
+ }
47
+ const token = await config.fetchToken();
48
+ cachedToken = token;
49
+ cachedExpiry = parseJwtExpiry(token);
50
+ return token;
51
+ }
52
+ async function request(endpoint, body) {
53
+ const token = await getToken();
54
+ const res = await fetch(`${baseUrl}${endpoint}`, {
55
+ method: 'POST',
56
+ headers: {
57
+ 'Authorization': `Bearer ${token}`,
58
+ 'Content-Type': 'application/json',
59
+ },
60
+ body: JSON.stringify(body),
61
+ });
62
+ if (!res.ok) {
63
+ const error = await res.json().catch(() => ({ error: res.statusText }));
64
+ throw new Error(error.error || 'Query failed');
65
+ }
66
+ return res.json();
67
+ }
68
+ return {
69
+ /**
70
+ * Execute a JSON query against the semantic layer
71
+ */
72
+ async query(options) {
73
+ const cubeQuery = buildCubeQuery(options);
74
+ const result = await request('/api/cube/query', { query: cubeQuery });
75
+ const simplifiedData = simplifyResult(result.data);
76
+ return { data: simplifiedData, annotation: result.annotation };
77
+ },
78
+ /**
79
+ * Execute a SQL query against the semantic layer
80
+ */
81
+ async sql(query) {
82
+ return request('/api/cube/query', { sql: query });
83
+ },
84
+ };
85
+ }
@@ -0,0 +1,3 @@
1
+ export { createClient } from './client.js';
2
+ export { buildCubeQuery, simplifyResult } from './query.js';
3
+ export type { BonnardConfig, QueryOptions, QueryResult, SqlResult, Filter, TimeDimension, InferQueryResult, } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createClient } from './client.js';
2
+ export { buildCubeQuery, simplifyResult } from './query.js';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Bonnard SDK — Pure query-building functions (zero IO)
3
+ */
4
+ import type { QueryOptions } from './types.js';
5
+ /**
6
+ * Convert SDK QueryOptions into a Cube-native query object.
7
+ * Handles cube-name prefixing for all field references.
8
+ */
9
+ export declare function buildCubeQuery(options: QueryOptions): Record<string, unknown>;
10
+ /**
11
+ * Simplify Cube response keys by removing the cube prefix.
12
+ * e.g. { "orders.revenue": 100 } → { "revenue": 100 }
13
+ */
14
+ export declare function simplifyResult<T = Record<string, unknown>>(data: Record<string, unknown>[]): T[];
package/dist/query.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Bonnard SDK — Pure query-building functions (zero IO)
3
+ */
4
+ /**
5
+ * Convert SDK QueryOptions into a Cube-native query object.
6
+ * Handles cube-name prefixing for all field references.
7
+ */
8
+ export function buildCubeQuery(options) {
9
+ const cubeQuery = {};
10
+ if (options.measures) {
11
+ cubeQuery.measures = options.measures.map(m => m.includes('.') ? m : `${options.cube}.${m}`);
12
+ }
13
+ if (options.dimensions) {
14
+ cubeQuery.dimensions = options.dimensions.map(d => d.includes('.') ? d : `${options.cube}.${d}`);
15
+ }
16
+ if (options.filters) {
17
+ cubeQuery.filters = options.filters.map(f => ({
18
+ dimension: f.dimension.includes('.') ? f.dimension : `${options.cube}.${f.dimension}`,
19
+ operator: f.operator,
20
+ values: f.values,
21
+ }));
22
+ }
23
+ if (options.timeDimension) {
24
+ cubeQuery.timeDimensions = [{
25
+ dimension: options.timeDimension.dimension.includes('.')
26
+ ? options.timeDimension.dimension
27
+ : `${options.cube}.${options.timeDimension.dimension}`,
28
+ granularity: options.timeDimension.granularity,
29
+ dateRange: options.timeDimension.dateRange,
30
+ }];
31
+ }
32
+ if (options.orderBy) {
33
+ cubeQuery.order = Object.entries(options.orderBy).map(([key, dir]) => [
34
+ key.includes('.') ? key : `${options.cube}.${key}`,
35
+ dir,
36
+ ]);
37
+ }
38
+ if (options.limit) {
39
+ cubeQuery.limit = options.limit;
40
+ }
41
+ return cubeQuery;
42
+ }
43
+ /**
44
+ * Simplify Cube response keys by removing the cube prefix.
45
+ * e.g. { "orders.revenue": 100 } → { "revenue": 100 }
46
+ */
47
+ export function simplifyResult(data) {
48
+ return data.map(row => {
49
+ const simplified = {};
50
+ for (const [key, value] of Object.entries(row)) {
51
+ const simpleName = key.includes('.') ? key.split('.').pop() : key;
52
+ simplified[simpleName] = value;
53
+ }
54
+ return simplified;
55
+ });
56
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Bonnard SDK — Shared types
3
+ */
4
+ export interface BonnardConfig {
5
+ apiKey?: string;
6
+ fetchToken?: () => Promise<string>;
7
+ baseUrl?: string;
8
+ }
9
+ export interface QueryOptions {
10
+ cube: string;
11
+ measures?: string[];
12
+ dimensions?: string[];
13
+ filters?: Filter[];
14
+ timeDimension?: TimeDimension;
15
+ orderBy?: Record<string, 'asc' | 'desc'>;
16
+ limit?: number;
17
+ }
18
+ export interface Filter {
19
+ dimension: string;
20
+ operator: 'equals' | 'notEquals' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte';
21
+ values: (string | number)[];
22
+ }
23
+ export interface TimeDimension {
24
+ dimension: string;
25
+ granularity?: 'day' | 'week' | 'month' | 'quarter' | 'year';
26
+ dateRange?: string | [string, string];
27
+ }
28
+ export interface QueryResult<T = Record<string, unknown>> {
29
+ data: T[];
30
+ annotation?: {
31
+ measures: Record<string, {
32
+ title: string;
33
+ type: string;
34
+ }>;
35
+ dimensions: Record<string, {
36
+ title: string;
37
+ type: string;
38
+ }>;
39
+ };
40
+ }
41
+ export interface SqlResult<T = Record<string, unknown>> {
42
+ data: T[];
43
+ schema?: Array<{
44
+ name: string;
45
+ type: string;
46
+ }>;
47
+ }
48
+ /** Type helper for defining cube schemas */
49
+ export type InferQueryResult<C extends string, M extends string[], D extends string[]> = {
50
+ [K in M[number] | D[number]]: K extends M[number] ? number : string;
51
+ };
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Bonnard SDK — Shared types
3
+ */
4
+ export {};
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@bonnard/sdk",
3
+ "version": "0.1.2",
4
+ "description": "Bonnard SDK - query your semantic layer from any JavaScript or TypeScript app",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "dev": "tsc --watch"
20
+ },
21
+ "dependencies": {},
22
+ "devDependencies": {
23
+ "typescript": "^5.3.3"
24
+ },
25
+ "keywords": [
26
+ "bonnard",
27
+ "semantic-layer",
28
+ "analytics",
29
+ "mcp",
30
+ "cube",
31
+ "dashboard",
32
+ "metrics",
33
+ "ai"
34
+ ],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/meal-inc/bonnard-sdk.git"
38
+ },
39
+ "license": "MIT",
40
+ "engines": {
41
+ "node": ">=18.0.0"
42
+ }
43
+ }