@hachej/boring-data-bridge 0.1.60
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 +21 -0
- package/README.md +9 -0
- package/dist/chunk-72EZA7HP.js +6 -0
- package/dist/front/index.d.ts +2 -0
- package/dist/front/index.js +0 -0
- package/dist/server/index.d.ts +27 -0
- package/dist/server/index.js +168 -0
- package/dist/shared/index.d.ts +37 -0
- package/dist/shared/index.js +6 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 boringdata
|
|
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,9 @@
|
|
|
1
|
+
# @hachej/boring-data-bridge
|
|
2
|
+
|
|
3
|
+
Trusted WorkspaceBridge-backed data query plugin. It registers `data.v1.query.run`
|
|
4
|
+
so dashboard/runtime callers can execute either:
|
|
5
|
+
|
|
6
|
+
- `language: "bsl"` — a BSL/Ibis expression string evaluated by BSL `safe_eval`.
|
|
7
|
+
- `language: "sql"` — read-only SQL routed through a host-registered adapter.
|
|
8
|
+
|
|
9
|
+
This package intentionally does not define a separate dashboard JSON-to-BSL query DSL.
|
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { WorkspaceServerPlugin } from '@hachej/boring-workspace/server';
|
|
2
|
+
import { DataBridgeSqlQuery, DataBridgeTableResult } from '../shared/index.js';
|
|
3
|
+
|
|
4
|
+
interface DataBridgeSqlAdapter {
|
|
5
|
+
requiredCapabilities?: string[];
|
|
6
|
+
maxRows?: number;
|
|
7
|
+
execute(args: {
|
|
8
|
+
query: DataBridgeSqlQuery;
|
|
9
|
+
sql: string;
|
|
10
|
+
params?: Record<string, unknown>;
|
|
11
|
+
limit: number;
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}): Promise<DataBridgeTableResult>;
|
|
14
|
+
}
|
|
15
|
+
interface CreateDataBridgeServerPluginOptions {
|
|
16
|
+
workspaceRoot: string;
|
|
17
|
+
bslModelPath?: string;
|
|
18
|
+
bslProfile?: string;
|
|
19
|
+
bslProfileFile?: string;
|
|
20
|
+
sqlAdapters?: Record<string, DataBridgeSqlAdapter>;
|
|
21
|
+
}
|
|
22
|
+
declare function createDataBridgeServerPlugin(options: CreateDataBridgeServerPluginOptions): WorkspaceServerPlugin;
|
|
23
|
+
declare function defaultDataBridgeServerPlugin(_options: unknown, ctx: {
|
|
24
|
+
workspaceRoot: string;
|
|
25
|
+
}): WorkspaceServerPlugin;
|
|
26
|
+
|
|
27
|
+
export { type DataBridgeSqlAdapter, createDataBridgeServerPlugin, defaultDataBridgeServerPlugin as default };
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DATA_BRIDGE_QUERY_RUN_OP
|
|
3
|
+
} from "../chunk-72EZA7HP.js";
|
|
4
|
+
|
|
5
|
+
// src/server/index.ts
|
|
6
|
+
import { spawn } from "child_process";
|
|
7
|
+
import {
|
|
8
|
+
defineServerPlugin,
|
|
9
|
+
defineTrustedDomainBridgeHandler
|
|
10
|
+
} from "@hachej/boring-workspace/server";
|
|
11
|
+
var SQL_DEFAULT_LIMIT = 1e3;
|
|
12
|
+
var SQL_MAX_LIMIT = 5e3;
|
|
13
|
+
var SQL_ALLOWED_FIRST_TOKENS = /* @__PURE__ */ new Set(["SELECT", "WITH", "EXPLAIN", "DESCRIBE", "SHOW", "DESC"]);
|
|
14
|
+
var MULTI_STMT_RE = /;\s*\S/;
|
|
15
|
+
function isRecord(value) {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
function normalizeLimit(value, max = SQL_MAX_LIMIT) {
|
|
19
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
20
|
+
if (!Number.isFinite(n)) return Math.min(SQL_DEFAULT_LIMIT, max);
|
|
21
|
+
return Math.max(1, Math.min(Math.floor(n), max));
|
|
22
|
+
}
|
|
23
|
+
function requireCapabilities(actual, required) {
|
|
24
|
+
const missing = required.find((capability) => !actual.includes(capability));
|
|
25
|
+
if (missing) throw new Error(`Missing required data capability: ${missing}`);
|
|
26
|
+
}
|
|
27
|
+
function normalizeReadOnlySql(sql) {
|
|
28
|
+
const query = sql.trim().replace(/;+$/, "").trim();
|
|
29
|
+
if (!query) throw new Error("SQL query is required");
|
|
30
|
+
const firstToken = query.split(/\s+/)[0]?.toUpperCase() ?? "";
|
|
31
|
+
if (!SQL_ALLOWED_FIRST_TOKENS.has(firstToken)) {
|
|
32
|
+
throw new Error(`Only read-only SQL queries are allowed (${[...SQL_ALLOWED_FIRST_TOKENS].sort().join(", ")})`);
|
|
33
|
+
}
|
|
34
|
+
if (MULTI_STMT_RE.test(query)) throw new Error("Multi-statement SQL queries are not allowed");
|
|
35
|
+
return query;
|
|
36
|
+
}
|
|
37
|
+
function truncateResult(result, limit) {
|
|
38
|
+
if (result.rows.length <= limit) return result;
|
|
39
|
+
return {
|
|
40
|
+
...result,
|
|
41
|
+
rows: result.rows.slice(0, limit),
|
|
42
|
+
rowCount: Math.max(result.rowCount, result.rows.length),
|
|
43
|
+
truncated: true
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
async function runBslQuery(options, input, signal) {
|
|
47
|
+
const modelPath = options.bslModelPath ?? process.env.BORING_BSL_MODEL_PATH ?? process.env.BSL_MODEL_PATH;
|
|
48
|
+
if (!modelPath) throw new Error("BSL adapter is not configured: set BORING_BSL_MODEL_PATH");
|
|
49
|
+
const payload = {
|
|
50
|
+
modelPath,
|
|
51
|
+
profile: options.bslProfile ?? process.env.BORING_BSL_PROFILE,
|
|
52
|
+
profileFile: options.bslProfileFile ?? process.env.BORING_BSL_PROFILE_FILE,
|
|
53
|
+
model: input.query.model,
|
|
54
|
+
query: input.query.query,
|
|
55
|
+
limit: input.query.limit ?? 5e3
|
|
56
|
+
};
|
|
57
|
+
return await runPythonBsl(payload, signal);
|
|
58
|
+
}
|
|
59
|
+
async function runSqlQuery(options, input, capabilities, signal) {
|
|
60
|
+
if (input.query.language !== "sql") throw new Error("SQL adapter requires query.language=sql");
|
|
61
|
+
requireCapabilities(capabilities, ["data:sql-query"]);
|
|
62
|
+
const adapter = options.sqlAdapters?.[input.query.source];
|
|
63
|
+
if (!adapter) throw new Error(`Data bridge SQL source is not configured: ${input.query.source}`);
|
|
64
|
+
requireCapabilities(capabilities, adapter.requiredCapabilities ?? []);
|
|
65
|
+
const maxRows = adapter.maxRows ?? SQL_MAX_LIMIT;
|
|
66
|
+
const limit = normalizeLimit(input.query.limit, maxRows);
|
|
67
|
+
const sql = normalizeReadOnlySql(input.query.sql);
|
|
68
|
+
const result = await adapter.execute({
|
|
69
|
+
query: { ...input.query, sql, limit },
|
|
70
|
+
sql,
|
|
71
|
+
params: input.query.params,
|
|
72
|
+
limit,
|
|
73
|
+
signal
|
|
74
|
+
});
|
|
75
|
+
return { ...truncateResult(result, limit), source: result.source ?? input.query.source };
|
|
76
|
+
}
|
|
77
|
+
async function runPythonBsl(payload, signal) {
|
|
78
|
+
const script = String.raw`
|
|
79
|
+
import json, sys
|
|
80
|
+
from pathlib import Path
|
|
81
|
+
import ibis
|
|
82
|
+
from ibis import _
|
|
83
|
+
from returns.result import Failure, Success
|
|
84
|
+
from boring_semantic_layer import from_yaml
|
|
85
|
+
from boring_semantic_layer.utils import safe_eval
|
|
86
|
+
payload = json.loads(sys.stdin.read())
|
|
87
|
+
query = payload["query"]
|
|
88
|
+
models = from_yaml(Path(payload["modelPath"]), profile=payload.get("profile"), profile_path=payload.get("profileFile"))
|
|
89
|
+
sm = models[payload["model"]]
|
|
90
|
+
evaluated = safe_eval(query, context={**models, "sm": sm, "ibis": ibis, "_": _})
|
|
91
|
+
if isinstance(evaluated, Failure):
|
|
92
|
+
raise evaluated.failure()
|
|
93
|
+
result = evaluated.unwrap() if isinstance(evaluated, Success) else evaluated
|
|
94
|
+
df = result.execute()
|
|
95
|
+
limit = int(payload.get("limit") or 5000)
|
|
96
|
+
rows = json.loads(df.head(limit).to_json(orient="records", date_format="iso"))
|
|
97
|
+
columns = []
|
|
98
|
+
for name in df.columns:
|
|
99
|
+
series = df[name]
|
|
100
|
+
kind = "string"
|
|
101
|
+
if str(series.dtype).startswith("int"):
|
|
102
|
+
kind = "integer"
|
|
103
|
+
elif str(series.dtype).startswith("float") or str(series.dtype).startswith("decimal"):
|
|
104
|
+
kind = "float"
|
|
105
|
+
elif str(series.dtype).startswith("bool"):
|
|
106
|
+
kind = "boolean"
|
|
107
|
+
elif "datetime" in str(series.dtype):
|
|
108
|
+
kind = "datetime"
|
|
109
|
+
columns.append({"name": str(name), "type": kind})
|
|
110
|
+
print(json.dumps({"kind":"data-bridge.table","version":1,"columns":columns,"rows":rows,"rowCount":len(rows),"truncated": len(df) > len(rows), "source":"bsl"}))
|
|
111
|
+
`;
|
|
112
|
+
if (signal?.aborted) throw new Error("BSL query aborted");
|
|
113
|
+
const child = spawn(process.env.BORING_DATA_BRIDGE_PYTHON ?? "python3", ["-c", script], { stdio: ["pipe", "pipe", "pipe"] });
|
|
114
|
+
const abort = () => child.kill("SIGKILL");
|
|
115
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
116
|
+
child.stdin.end(JSON.stringify(payload));
|
|
117
|
+
const [stdout, stderr, code] = await new Promise((resolvePromise) => {
|
|
118
|
+
let out = "";
|
|
119
|
+
let err = "";
|
|
120
|
+
child.stdout.on("data", (chunk) => {
|
|
121
|
+
out += String(chunk);
|
|
122
|
+
});
|
|
123
|
+
child.stderr.on("data", (chunk) => {
|
|
124
|
+
err += String(chunk);
|
|
125
|
+
});
|
|
126
|
+
child.on("close", (exitCode) => resolvePromise([out, err, exitCode]));
|
|
127
|
+
}).finally(() => signal?.removeEventListener("abort", abort));
|
|
128
|
+
if (signal?.aborted) throw new Error("BSL query aborted");
|
|
129
|
+
if (code !== 0) throw new Error(stderr.trim() || `BSL query failed with exit code ${code}`);
|
|
130
|
+
return JSON.parse(stdout);
|
|
131
|
+
}
|
|
132
|
+
function createDataBridgeServerPlugin(options) {
|
|
133
|
+
const queryRun = defineTrustedDomainBridgeHandler({
|
|
134
|
+
op: DATA_BRIDGE_QUERY_RUN_OP,
|
|
135
|
+
version: 1,
|
|
136
|
+
owner: "data-bridge",
|
|
137
|
+
callerClassesAllowed: ["browser", "runtime", "server"],
|
|
138
|
+
requiredCapabilities: ["data:read"],
|
|
139
|
+
inputSchema: { type: "object" },
|
|
140
|
+
maxOutputBytes: 2 * 1024 * 1024,
|
|
141
|
+
timeoutMs: 3e4,
|
|
142
|
+
idempotencyPolicy: "none",
|
|
143
|
+
handler: async ({ input, context, signal }) => {
|
|
144
|
+
if (!isRecord(input) || !isRecord(input.query)) throw new Error("Invalid data bridge query input");
|
|
145
|
+
const typedInput = input;
|
|
146
|
+
if (typedInput.query.language === "sql") {
|
|
147
|
+
return await runSqlQuery(options, typedInput, context.capabilities, signal);
|
|
148
|
+
}
|
|
149
|
+
if (typedInput.query.language !== "bsl") {
|
|
150
|
+
throw new Error("Data bridge query language must be either bsl or sql");
|
|
151
|
+
}
|
|
152
|
+
return await runBslQuery(options, typedInput, signal);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
return defineServerPlugin({
|
|
156
|
+
id: "data-bridge",
|
|
157
|
+
label: "Data Bridge",
|
|
158
|
+
workspaceBridgeHandlers: [queryRun],
|
|
159
|
+
systemPrompt: "Use data.v1.query.run through WorkspaceBridge for dashboard data. Supported query languages are bsl and sql."
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function defaultDataBridgeServerPlugin(_options, ctx) {
|
|
163
|
+
return createDataBridgeServerPlugin({ workspaceRoot: ctx.workspaceRoot });
|
|
164
|
+
}
|
|
165
|
+
export {
|
|
166
|
+
createDataBridgeServerPlugin,
|
|
167
|
+
defaultDataBridgeServerPlugin as default
|
|
168
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
declare const DATA_BRIDGE_QUERY_RUN_OP: "data.v1.query.run";
|
|
2
|
+
type DataBridgeScalarType = "string" | "integer" | "float" | "boolean" | "date" | "datetime" | "json";
|
|
3
|
+
type DataBridgeRole = "dimension" | "measure" | "time" | "unknown";
|
|
4
|
+
interface DataBridgeColumn {
|
|
5
|
+
name: string;
|
|
6
|
+
type: DataBridgeScalarType;
|
|
7
|
+
role?: DataBridgeRole;
|
|
8
|
+
}
|
|
9
|
+
interface DataBridgeBslQuery {
|
|
10
|
+
language: "bsl";
|
|
11
|
+
model: string;
|
|
12
|
+
query: string;
|
|
13
|
+
limit?: number;
|
|
14
|
+
}
|
|
15
|
+
interface DataBridgeSqlQuery {
|
|
16
|
+
language: "sql";
|
|
17
|
+
source: string;
|
|
18
|
+
sql: string;
|
|
19
|
+
params?: Record<string, unknown>;
|
|
20
|
+
limit?: number;
|
|
21
|
+
}
|
|
22
|
+
type DataBridgeQuery = DataBridgeBslQuery | DataBridgeSqlQuery;
|
|
23
|
+
interface DataBridgeQueryRunInput {
|
|
24
|
+
source?: string;
|
|
25
|
+
query: DataBridgeQuery;
|
|
26
|
+
}
|
|
27
|
+
interface DataBridgeTableResult {
|
|
28
|
+
kind: "data-bridge.table";
|
|
29
|
+
version: 1;
|
|
30
|
+
columns: DataBridgeColumn[];
|
|
31
|
+
rows: Record<string, unknown>[];
|
|
32
|
+
rowCount: number;
|
|
33
|
+
truncated?: boolean;
|
|
34
|
+
source?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export { DATA_BRIDGE_QUERY_RUN_OP, type DataBridgeBslQuery, type DataBridgeColumn, type DataBridgeQuery, type DataBridgeQueryRunInput, type DataBridgeRole, type DataBridgeScalarType, type DataBridgeSqlQuery, type DataBridgeTableResult };
|
package/package.json
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@hachej/boring-data-bridge",
|
|
3
|
+
"version": "0.1.60",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"private": false,
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"description": "WorkspaceBridge-backed semantic data adapter plugin for Boring workspace.",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/hachej/boring-ui"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/hachej/boring-ui",
|
|
13
|
+
"boring": {
|
|
14
|
+
"id": "data-bridge",
|
|
15
|
+
"label": "Data Bridge",
|
|
16
|
+
"front": "dist/front/index.js",
|
|
17
|
+
"server": "dist/server/index.js"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/shared/index.d.ts",
|
|
26
|
+
"import": "./dist/shared/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./front": {
|
|
29
|
+
"types": "./dist/front/index.d.ts",
|
|
30
|
+
"import": "./dist/front/index.js"
|
|
31
|
+
},
|
|
32
|
+
"./server": {
|
|
33
|
+
"types": "./dist/server/index.d.ts",
|
|
34
|
+
"import": "./dist/server/index.js"
|
|
35
|
+
},
|
|
36
|
+
"./shared": {
|
|
37
|
+
"types": "./dist/shared/index.d.ts",
|
|
38
|
+
"import": "./dist/shared/index.js"
|
|
39
|
+
},
|
|
40
|
+
"./package.json": "./package.json"
|
|
41
|
+
},
|
|
42
|
+
"sideEffects": false,
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@hachej/boring-workspace": "0.1.60"
|
|
45
|
+
},
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@duckdb/node-api": "1.5.2-r.1",
|
|
48
|
+
"tsup": "^8.4.0",
|
|
49
|
+
"typescript": "~5.9.3",
|
|
50
|
+
"vitest": "^3.2.6",
|
|
51
|
+
"@hachej/boring-workspace": "0.1.60"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "tsup",
|
|
55
|
+
"typecheck": "tsc --noEmit",
|
|
56
|
+
"test": "vitest run --passWithNoTests",
|
|
57
|
+
"lint": "pnpm run typecheck",
|
|
58
|
+
"clean": "rm -rf dist .tsbuildinfo"
|
|
59
|
+
}
|
|
60
|
+
}
|