Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8bf4bf547 | |||
| 9b93c4a4d9 | |||
| ca14c5f51d | |||
| 1979e0e16c | |||
| 9102c6698a | |||
| b15fc993f2 | |||
| 6cc8833b2a | |||
| fc76b862ad | |||
| 787e791aba | |||
| 96188c8cda | |||
| 781f571474 |
@@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
description: Ban dynamic import() in production code — use static imports instead
|
||||||
|
globs: packages/*/src/**/*.ts
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# No Dynamic Import in Production Code
|
||||||
|
|
||||||
|
## Rule
|
||||||
|
|
||||||
|
Do NOT use `await import()` or dynamic `import()` expressions in production source code.
|
||||||
|
Always use static top-level `import` statements.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
- Static imports enable tree-shaking and bundler optimizations
|
||||||
|
- They make dependencies explicit and discoverable at a glance
|
||||||
|
- Dynamic imports of Node built-ins or project modules add unnecessary async overhead
|
||||||
|
|
||||||
|
## Exceptions (must include a comment explaining why)
|
||||||
|
|
||||||
|
1. **`sense-runtime.ts`** — loads user-authored sense modules whose paths are only known at runtime
|
||||||
|
2. **`workflow-worker.ts`** — loads user-authored workflow modules whose paths are only known at runtime
|
||||||
|
|
||||||
|
When suppressing, add a comment directly above:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Dynamic import required: user module path resolved at runtime
|
||||||
|
const mod = await import(senseIndexPath);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Test Files
|
||||||
|
|
||||||
|
Test files (`__tests__/**`) are exempt — dynamic import after `vi.mock()` is standard vitest practice.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@uncaged/nerve-cli",
|
"name": "@uncaged/nerve-cli",
|
||||||
"version": "0.1.7",
|
"version": "0.1.8",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
"nerve": "dist/cli.js"
|
"nerve": "dist/cli.js"
|
||||||
@@ -20,12 +20,13 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@uncaged/nerve-core": "workspace:*",
|
"@uncaged/nerve-core": "workspace:*",
|
||||||
"citty": "^0.1.6"
|
"citty": "^0.1.6",
|
||||||
|
"sql.js": "^1.14.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@uncaged/nerve-daemon": "workspace:*",
|
|
||||||
"@types/better-sqlite3": "^7.6.13",
|
"@types/better-sqlite3": "^7.6.13",
|
||||||
"@types/node": "^22.0.0",
|
"@types/node": "^22.0.0",
|
||||||
|
"@uncaged/nerve-daemon": "workspace:*",
|
||||||
"vitest": "^4.1.5"
|
"vitest": "^4.1.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
/**
|
||||||
|
* Tests for sense SQLite helpers used by `nerve sense schema` / `nerve sense query`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import initSqlJs, { type Database } from "sql.js";
|
||||||
|
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
assertSenseDbExists,
|
||||||
|
collectColumnKeys,
|
||||||
|
defaultPreviewSql,
|
||||||
|
formatRowsAsAlignedTable,
|
||||||
|
listTableSqlStatements,
|
||||||
|
parseSenseQueryArgs,
|
||||||
|
pickDefaultPreviewTable,
|
||||||
|
queryAsObjects,
|
||||||
|
senseDbPath,
|
||||||
|
} from "../sense-sqlite.js";
|
||||||
|
|
||||||
|
let SQL: Awaited<ReturnType<typeof initSqlJs>>;
|
||||||
|
let tmpDir: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
SQL = await initSqlJs();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tmpDir = join(
|
||||||
|
tmpdir(),
|
||||||
|
`nerve-sense-sqlite-${Date.now()}-${Math.random().toString(16).slice(2)}`,
|
||||||
|
);
|
||||||
|
mkdirSync(join(tmpDir, "data", "senses"), { recursive: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
rmSync(tmpDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Helper: create a SQLite db file with the given setup SQL. */
|
||||||
|
function createDb(name: string, setupSql: string): void {
|
||||||
|
const db = new SQL.Database();
|
||||||
|
db.run(setupSql);
|
||||||
|
const data = db.export();
|
||||||
|
db.close();
|
||||||
|
writeFileSync(join(tmpDir, "data", "senses", `${name}.db`), Buffer.from(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Helper: open an in-memory db with setup SQL for unit tests. */
|
||||||
|
function memDb(setupSql?: string): Database {
|
||||||
|
const db = new SQL.Database();
|
||||||
|
if (setupSql) db.run(setupSql);
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("senseDbPath", () => {
|
||||||
|
it("points at data/senses/<name>.db under the given root", () => {
|
||||||
|
expect(senseDbPath("/root", "cpu-usage")).toBe(join("/root", "data", "senses", "cpu-usage.db"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("assertSenseDbExists", () => {
|
||||||
|
it("throws when the file is missing", () => {
|
||||||
|
expect(() => assertSenseDbExists(tmpDir, "nope")).toThrow(/No database at/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the path when the file exists", () => {
|
||||||
|
createDb("x", "SELECT 1");
|
||||||
|
expect(assertSenseDbExists(tmpDir, "x")).toBe(join(tmpDir, "data", "senses", "x.db"));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("listTableSqlStatements", () => {
|
||||||
|
it("returns CREATE statements ordered by tbl_name", () => {
|
||||||
|
const db = memDb("CREATE TABLE zebra (id INTEGER); CREATE TABLE alpha (id INTEGER);");
|
||||||
|
const stmts = listTableSqlStatements(db);
|
||||||
|
db.close();
|
||||||
|
expect(stmts).toHaveLength(2);
|
||||||
|
expect(stmts[0]).toMatch(/^CREATE TABLE alpha/i);
|
||||||
|
expect(stmts[1]).toMatch(/^CREATE TABLE zebra/i);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("pickDefaultPreviewTable", () => {
|
||||||
|
it("prefers non-_migrations tables when both exist", () => {
|
||||||
|
const db = memDb(
|
||||||
|
`CREATE TABLE _migrations (name TEXT PRIMARY KEY);
|
||||||
|
CREATE TABLE readings (id INTEGER);`,
|
||||||
|
);
|
||||||
|
expect(pickDefaultPreviewTable(db)).toBe("readings");
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses _migrations when it is the only table", () => {
|
||||||
|
const db = memDb("CREATE TABLE _migrations (name TEXT PRIMARY KEY);");
|
||||||
|
expect(pickDefaultPreviewTable(db)).toBe("_migrations");
|
||||||
|
db.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("defaultPreviewSql", () => {
|
||||||
|
it("quotes identifiers for SQL safety", () => {
|
||||||
|
expect(defaultPreviewSql(`weird"name`)).toContain(`weird""name`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("parseSenseQueryArgs", () => {
|
||||||
|
it("parses sense name only", () => {
|
||||||
|
expect(parseSenseQueryArgs(["cpu"])).toEqual({ name: "cpu", sql: undefined });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("strips --json", () => {
|
||||||
|
expect(parseSenseQueryArgs(["cpu", "--json"])).toEqual({ name: "cpu", sql: undefined });
|
||||||
|
expect(parseSenseQueryArgs(["--json", "cpu"])).toEqual({ name: "cpu", sql: undefined });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("joins remaining tokens into SQL", () => {
|
||||||
|
expect(parseSenseQueryArgs(["cpu", "SELECT", "1"])).toEqual({ name: "cpu", sql: "SELECT 1" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws when name is missing", () => {
|
||||||
|
expect(() => parseSenseQueryArgs(["--json"])).toThrow(/Missing sense name/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("formatRowsAsAlignedTable", () => {
|
||||||
|
it("shows empty marker for no rows", () => {
|
||||||
|
expect(formatRowsAsAlignedTable([])).toContain("(0 rows)");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("aligns columns from row data", () => {
|
||||||
|
const out = formatRowsAsAlignedTable([
|
||||||
|
{ a: 1, b: "x" },
|
||||||
|
{ a: 22, b: "yy" },
|
||||||
|
]);
|
||||||
|
expect(out).toContain("a");
|
||||||
|
expect(out).toContain("b");
|
||||||
|
expect(out).toContain("22");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("collectColumnKeys", () => {
|
||||||
|
it("preserves key order from first row then appends new keys", () => {
|
||||||
|
expect(
|
||||||
|
collectColumnKeys([
|
||||||
|
{ z: 1, a: 2 },
|
||||||
|
{ a: 3, b: 4 },
|
||||||
|
]),
|
||||||
|
).toEqual(["z", "a", "b"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("queryAsObjects", () => {
|
||||||
|
it("converts columnar sql.js results to row objects", () => {
|
||||||
|
const db = memDb("CREATE TABLE t (x INTEGER, y TEXT); INSERT INTO t VALUES (1, 'a'), (2, 'b');");
|
||||||
|
const rows = queryAsObjects(db, "SELECT * FROM t ORDER BY x");
|
||||||
|
db.close();
|
||||||
|
expect(rows).toEqual([
|
||||||
|
{ x: 1, y: "a" },
|
||||||
|
{ x: 2, y: "b" },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("readonly query integration", () => {
|
||||||
|
it("runs default preview SQL on a real db file", () => {
|
||||||
|
createDb("demo", "CREATE TABLE items (id INTEGER PRIMARY KEY, v TEXT); INSERT INTO items (v) VALUES ('a'), ('b');");
|
||||||
|
|
||||||
|
const buffer = require("node:fs").readFileSync(join(tmpDir, "data", "senses", "demo.db"));
|
||||||
|
const db = new SQL.Database(buffer);
|
||||||
|
const table = pickDefaultPreviewTable(db);
|
||||||
|
expect(table).toBe("items");
|
||||||
|
if (table === null) throw new Error("expected items table");
|
||||||
|
const sql = defaultPreviewSql(table);
|
||||||
|
const rows = queryAsObjects(db, sql);
|
||||||
|
db.close();
|
||||||
|
expect(rows.length).toBeGreaterThanOrEqual(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
|
import { spawn, execFile } from "node:child_process";
|
||||||
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
|
import { promisify } from "node:util";
|
||||||
|
|
||||||
import { defineCommand } from "citty";
|
import { defineCommand } from "citty";
|
||||||
|
|
||||||
@@ -42,6 +44,8 @@ const GITIGNORE = `data/
|
|||||||
node_modules/
|
node_modules/
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
const CPU_SCHEMA_TS = `import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
const CPU_SCHEMA_TS = `import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||||
|
|
||||||
export const cpuUsage = sqliteTable("cpu_usage", {
|
export const cpuUsage = sqliteTable("cpu_usage", {
|
||||||
@@ -90,7 +94,6 @@ function writeFile(filePath: string, content: string): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function runCommand(cmd: string, args: string[], cwd: string): Promise<void> {
|
async function runCommand(cmd: string, args: string[], cwd: string): Promise<void> {
|
||||||
const { spawn } = await import("node:child_process");
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
await new Promise<void>((resolve, reject) => {
|
||||||
const child = spawn(cmd, args, { cwd, stdio: "inherit" });
|
const child = spawn(cmd, args, { cwd, stdio: "inherit" });
|
||||||
child.on("close", (code) => {
|
child.on("close", (code) => {
|
||||||
@@ -102,10 +105,6 @@ async function runCommand(cmd: string, args: string[], cwd: string): Promise<voi
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function detectPackageManager(): Promise<{ cmd: string; installArgs: string[] }> {
|
async function detectPackageManager(): Promise<{ cmd: string; installArgs: string[] }> {
|
||||||
const { execFile } = await import("node:child_process");
|
|
||||||
const { promisify } = await import("node:util");
|
|
||||||
const execFileAsync = promisify(execFile);
|
|
||||||
|
|
||||||
for (const pm of ["pnpm", "yarn", "npm"]) {
|
for (const pm of ["pnpm", "yarn", "npm"]) {
|
||||||
try {
|
try {
|
||||||
await execFileAsync(pm, ["--version"]);
|
await execFileAsync(pm, ["--version"]);
|
||||||
@@ -223,9 +222,6 @@ async function tryRequireSqlite(nerveRoot: string): Promise<boolean> {
|
|||||||
try {
|
try {
|
||||||
const modulePath = join(nerveRoot, "node_modules", "better-sqlite3");
|
const modulePath = join(nerveRoot, "node_modules", "better-sqlite3");
|
||||||
// Use a child process to test if the native module loads
|
// Use a child process to test if the native module loads
|
||||||
const { execFile } = await import("node:child_process");
|
|
||||||
const { promisify } = await import("node:util");
|
|
||||||
const execFileAsync = promisify(execFile);
|
|
||||||
await execFileAsync("node", ["-e", `require(${JSON.stringify(modulePath)})`], {
|
await execFileAsync("node", ["-e", `require(${JSON.stringify(modulePath)})`], {
|
||||||
cwd: nerveRoot,
|
cwd: nerveRoot,
|
||||||
timeout: 10_000,
|
timeout: 10_000,
|
||||||
|
|||||||
@@ -5,6 +5,16 @@ import { type SenseInfo, parseNerveConfig } from "@uncaged/nerve-core";
|
|||||||
import { defineCommand } from "citty";
|
import { defineCommand } from "citty";
|
||||||
|
|
||||||
import { listSensesViaDaemon, triggerSenseViaDaemon } from "../daemon-client.js";
|
import { listSensesViaDaemon, triggerSenseViaDaemon } from "../daemon-client.js";
|
||||||
|
import {
|
||||||
|
assertSenseDbExists,
|
||||||
|
defaultPreviewSql,
|
||||||
|
formatRowsAsAlignedTable,
|
||||||
|
listTableSqlStatements,
|
||||||
|
openSenseDb,
|
||||||
|
parseSenseQueryArgs,
|
||||||
|
pickDefaultPreviewTable,
|
||||||
|
queryAsObjects,
|
||||||
|
} from "../sense-sqlite.js";
|
||||||
import { getNerveRoot, getSocketPath, isRunning } from "../workspace.js";
|
import { getNerveRoot, getSocketPath, isRunning } from "../workspace.js";
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -139,6 +149,115 @@ const senseTriggerCommand = defineCommand({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// nerve sense schema <name>
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const senseSchemaCommand = defineCommand({
|
||||||
|
meta: {
|
||||||
|
name: "schema",
|
||||||
|
description: "Print CREATE TABLE statements from a sense SQLite database",
|
||||||
|
},
|
||||||
|
args: {
|
||||||
|
name: {
|
||||||
|
type: "positional",
|
||||||
|
description: "Sense name (data/senses/<name>.db under the nerve workspace)",
|
||||||
|
},
|
||||||
|
json: {
|
||||||
|
type: "boolean",
|
||||||
|
description: "Print JSON array of CREATE TABLE SQL strings",
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async run({ args }) {
|
||||||
|
const nerveRoot = getNerveRoot();
|
||||||
|
let db: ReturnType<Awaited<ReturnType<typeof import("sql.js")>>["Database"]> | undefined;
|
||||||
|
try {
|
||||||
|
db = await openSenseDb(nerveRoot, args.name);
|
||||||
|
const statements = listTableSqlStatements(db);
|
||||||
|
if (args.json) {
|
||||||
|
process.stdout.write(`${JSON.stringify(statements, null, 2)}\n`);
|
||||||
|
} else if (statements.length === 0) {
|
||||||
|
process.stdout.write("(no tables)\n");
|
||||||
|
} else {
|
||||||
|
for (const sql of statements) {
|
||||||
|
process.stdout.write(`${sql};\n\n`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
process.stderr.write(`❌ ${msg}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
} finally {
|
||||||
|
db?.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// nerve sense query <name> [sql...]
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const senseQueryCommand = defineCommand({
|
||||||
|
meta: {
|
||||||
|
name: "query",
|
||||||
|
description:
|
||||||
|
"Run a read-only SQL query against a sense database (default: last 10 rows of the first data table). Pass optional SQL after the sense name; multiple words are joined.",
|
||||||
|
},
|
||||||
|
args: {
|
||||||
|
name: {
|
||||||
|
type: "positional",
|
||||||
|
description: "Sense name (data/senses/<name>.db under the nerve workspace)",
|
||||||
|
},
|
||||||
|
json: {
|
||||||
|
type: "boolean",
|
||||||
|
description: "Print result rows as JSON",
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
async run({ args, rawArgs }) {
|
||||||
|
const nerveRoot = getNerveRoot();
|
||||||
|
let db: ReturnType<Awaited<ReturnType<typeof import("sql.js")>>["Database"]> | undefined;
|
||||||
|
try {
|
||||||
|
let parsed: { name: string; sql: string | undefined };
|
||||||
|
try {
|
||||||
|
parsed = parseSenseQueryArgs(rawArgs);
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
process.stderr.write(`❌ ${msg}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
db = await openSenseDb(nerveRoot, args.name);
|
||||||
|
|
||||||
|
let sql = parsed.sql?.trim();
|
||||||
|
if (!sql) {
|
||||||
|
const table = pickDefaultPreviewTable(db);
|
||||||
|
if (table === null) {
|
||||||
|
process.stderr.write("❌ No tables found in database.\n");
|
||||||
|
process.exit(1);
|
||||||
|
} else {
|
||||||
|
sql = defaultPreviewSql(table);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = queryAsObjects(db, sql);
|
||||||
|
|
||||||
|
if (args.json) {
|
||||||
|
process.stdout.write(`${JSON.stringify(rows, null, 2)}\n`);
|
||||||
|
} else {
|
||||||
|
process.stdout.write(formatRowsAsAlignedTable(rows));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
process.stderr.write(`❌ ${msg}\n`);
|
||||||
|
process.exit(1);
|
||||||
|
} finally {
|
||||||
|
db?.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// nerve sense (parent command)
|
// nerve sense (parent command)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -151,5 +270,7 @@ export const senseCommand = defineCommand({
|
|||||||
subCommands: {
|
subCommands: {
|
||||||
list: senseListCommand,
|
list: senseListCommand,
|
||||||
trigger: senseTriggerCommand,
|
trigger: senseTriggerCommand,
|
||||||
|
schema: senseSchemaCommand,
|
||||||
|
query: senseQueryCommand,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { spawn } from "node:child_process";
|
||||||
import { createWriteStream, existsSync } from "node:fs";
|
import { createWriteStream, existsSync } from "node:fs";
|
||||||
import { mkdir } from "node:fs/promises";
|
import { mkdir } from "node:fs/promises";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
@@ -8,6 +9,7 @@ import { defineCommand } from "citty";
|
|||||||
import {
|
import {
|
||||||
getLogPath,
|
getLogPath,
|
||||||
getNerveRoot,
|
getNerveRoot,
|
||||||
|
getSocketPath,
|
||||||
isRunning,
|
isRunning,
|
||||||
readPidFile,
|
readPidFile,
|
||||||
removePidFile,
|
removePidFile,
|
||||||
@@ -64,7 +66,6 @@ async function runDaemon(nerveRoot: string): Promise<void> {
|
|||||||
const logPath = getLogPath();
|
const logPath = getLogPath();
|
||||||
await mkdir(join(nerveRoot, "logs"), { recursive: true });
|
await mkdir(join(nerveRoot, "logs"), { recursive: true });
|
||||||
|
|
||||||
const { spawn } = await import("node:child_process");
|
|
||||||
const logStream = createWriteStream(logPath, { flags: "a" });
|
const logStream = createWriteStream(logPath, { flags: "a" });
|
||||||
await new Promise<void>((resolve) => {
|
await new Promise<void>((resolve) => {
|
||||||
if (logStream.pending) logStream.once("open", () => resolve());
|
if (logStream.pending) logStream.once("open", () => resolve());
|
||||||
@@ -90,7 +91,6 @@ async function runDaemon(nerveRoot: string): Promise<void> {
|
|||||||
|
|
||||||
writePidFile(pid);
|
writePidFile(pid);
|
||||||
|
|
||||||
const { getSocketPath } = await import("../workspace.js");
|
|
||||||
const ready = await waitForSocket(getSocketPath(), 5000);
|
const ready = await waitForSocket(getSocketPath(), 5000);
|
||||||
|
|
||||||
if (!ready || !isRunning()) {
|
if (!ready || !isRunning()) {
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import initSqlJs, { type Database } from "sql.js";
|
||||||
|
|
||||||
|
// ── WASM singleton ──────────────────────────────────────────────────────────
|
||||||
|
let _SQL: Awaited<ReturnType<typeof initSqlJs>> | null = null;
|
||||||
|
|
||||||
|
async function getSQL() {
|
||||||
|
if (!_SQL) {
|
||||||
|
_SQL = await initSqlJs();
|
||||||
|
}
|
||||||
|
return _SQL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Open a sense SQLite database (readonly, loaded into memory via sql.js). */
|
||||||
|
export async function openSenseDb(nerveRoot: string, senseName: string): Promise<Database> {
|
||||||
|
const path = assertSenseDbExists(nerveRoot, senseName);
|
||||||
|
const SQL = await getSQL();
|
||||||
|
const buffer = readFileSync(path);
|
||||||
|
return new SQL.Database(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** SQLite path for a sense under the nerve workspace root. */
|
||||||
|
export function senseDbPath(nerveRoot: string, senseName: string): string {
|
||||||
|
return join(nerveRoot, "data", "senses", `${senseName}.db`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assertSenseDbExists(nerveRoot: string, senseName: string): string {
|
||||||
|
const path = senseDbPath(nerveRoot, senseName);
|
||||||
|
if (!existsSync(path)) {
|
||||||
|
throw new Error(`No database at ${path}`);
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `SELECT sql FROM sqlite_master WHERE type='table'` (non-null sql only). */
|
||||||
|
export function listTableSqlStatements(db: Database): string[] {
|
||||||
|
const results = db.exec(
|
||||||
|
`SELECT sql FROM sqlite_master WHERE type = 'table' AND sql IS NOT NULL ORDER BY tbl_name`,
|
||||||
|
);
|
||||||
|
if (results.length === 0) return [];
|
||||||
|
return results[0].values.map((row) => row[0] as string);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Table used for `nerve sense query <name>` with no SQL.
|
||||||
|
* Prefers real data tables over `_migrations`, then lexicographic by name.
|
||||||
|
*/
|
||||||
|
export function pickDefaultPreviewTable(db: Database): string | null {
|
||||||
|
const results = db.exec(
|
||||||
|
`SELECT name FROM sqlite_master
|
||||||
|
WHERE type = 'table' AND sql IS NOT NULL
|
||||||
|
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'
|
||||||
|
ORDER BY
|
||||||
|
CASE WHEN name = '_migrations' THEN 1 ELSE 0 END,
|
||||||
|
name
|
||||||
|
LIMIT 1`,
|
||||||
|
);
|
||||||
|
if (results.length === 0 || results[0].values.length === 0) return null;
|
||||||
|
return results[0].values[0][0] as string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function defaultPreviewSql(table: string): string {
|
||||||
|
return `SELECT * FROM "${table.replace(/"/g, '""')}" ORDER BY rowid DESC LIMIT 10`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse sense name and optional SQL from subcommand raw argv (flags stripped). */
|
||||||
|
export function parseSenseQueryArgs(rawArgs: string[]): { name: string; sql: string | undefined } {
|
||||||
|
const pos: string[] = [];
|
||||||
|
for (let i = 0; i < rawArgs.length; i++) {
|
||||||
|
const a = rawArgs[i];
|
||||||
|
if (a === "--json" || a === "--no-json") continue;
|
||||||
|
if (a.startsWith("-")) {
|
||||||
|
const eq = a.indexOf("=");
|
||||||
|
if (eq === -1 && i + 1 < rawArgs.length && !rawArgs[i + 1].startsWith("-")) {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
pos.push(a);
|
||||||
|
}
|
||||||
|
if (pos.length < 1) {
|
||||||
|
throw new Error("Missing sense name");
|
||||||
|
}
|
||||||
|
const name = pos[0];
|
||||||
|
const sql = pos.length > 1 ? pos.slice(1).join(" ") : undefined;
|
||||||
|
return { name, sql };
|
||||||
|
}
|
||||||
|
|
||||||
|
function stringifyCell(value: unknown): string {
|
||||||
|
if (value === null || value === undefined) return "";
|
||||||
|
if (typeof value === "bigint") return value.toString();
|
||||||
|
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||||||
|
if (typeof value === "string") return value;
|
||||||
|
if (value instanceof Uint8Array) return Buffer.from(value).toString("hex");
|
||||||
|
try {
|
||||||
|
return JSON.stringify(value);
|
||||||
|
} catch {
|
||||||
|
return String(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Collect column keys in stable order (first row keys, then any extras). */
|
||||||
|
export function collectColumnKeys(rows: Record<string, unknown>[]): string[] {
|
||||||
|
const keys: string[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const row of rows) {
|
||||||
|
for (const k of Object.keys(row)) {
|
||||||
|
if (!seen.has(k)) {
|
||||||
|
seen.add(k);
|
||||||
|
keys.push(k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_CELL = 64;
|
||||||
|
|
||||||
|
function truncate(s: string): string {
|
||||||
|
if (s.length <= MAX_CELL) return s;
|
||||||
|
return `${s.slice(0, MAX_CELL - 1)}…`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plain aligned table for terminal output. */
|
||||||
|
export function formatRowsAsAlignedTable(rows: Record<string, unknown>[]): string {
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return "(0 rows)\n";
|
||||||
|
}
|
||||||
|
const cols = collectColumnKeys(rows);
|
||||||
|
const cells = rows.map((row) => cols.map((c) => truncate(stringifyCell(row[c]))));
|
||||||
|
const widths = cols.map((c, j) => Math.max(c.length, ...cells.map((r) => r[j].length)));
|
||||||
|
const sep = widths.map((w) => "-".repeat(w)).join("-+-");
|
||||||
|
const header = cols.map((c, j) => c.padEnd(widths[j])).join(" | ");
|
||||||
|
const body = cells.map((r) => r.map((cell, j) => cell.padEnd(widths[j])).join(" | ")).join("\n");
|
||||||
|
return `${header}\n${sep}\n${body}\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a SQL query via sql.js and return rows as key-value objects.
|
||||||
|
* sql.js returns columnar data; this converts to the familiar row format.
|
||||||
|
*/
|
||||||
|
export function queryAsObjects(db: Database, sql: string): Record<string, unknown>[] {
|
||||||
|
const results = db.exec(sql);
|
||||||
|
if (results.length === 0) return [];
|
||||||
|
const { columns, values } = results[0];
|
||||||
|
return values.map((row) => {
|
||||||
|
const obj: Record<string, unknown> = {};
|
||||||
|
for (let i = 0; i < columns.length; i++) {
|
||||||
|
obj[columns[i]] = row[i];
|
||||||
|
}
|
||||||
|
return obj;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -9,5 +9,5 @@ export default defineConfig({
|
|||||||
js: "#!/usr/bin/env node",
|
js: "#!/usr/bin/env node",
|
||||||
},
|
},
|
||||||
/** Daemon is loaded from workspace node_modules at runtime — never bundle it. */
|
/** Daemon is loaded from workspace node_modules at runtime — never bundle it. */
|
||||||
external: ["@uncaged/nerve-daemon"],
|
external: ["@uncaged/nerve-daemon", "sql.js"],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -173,6 +173,7 @@ export async function loadComputeFn(senseIndexPath: string): Promise<Result<Comp
|
|||||||
let mod: unknown;
|
let mod: unknown;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Dynamic import required: user-authored sense module, path resolved at runtime
|
||||||
mod = await import(senseIndexPath);
|
mod = await import(senseIndexPath);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = e instanceof Error ? e.message : String(e);
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
|||||||
@@ -198,6 +198,7 @@ async function loadWorkflowDefinition(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dynamic import required: user-authored workflow module, path resolved at runtime
|
||||||
const mod = await import(indexPath);
|
const mod = await import(indexPath);
|
||||||
const def: unknown = mod.default ?? mod;
|
const def: unknown = mod.default ?? mod;
|
||||||
|
|
||||||
|
|||||||
Generated
+11
-2
@@ -26,6 +26,9 @@ importers:
|
|||||||
citty:
|
citty:
|
||||||
specifier: ^0.1.6
|
specifier: ^0.1.6
|
||||||
version: 0.1.6
|
version: 0.1.6
|
||||||
|
sql.js:
|
||||||
|
specifier: ^1.14.1
|
||||||
|
version: 1.14.1
|
||||||
devDependencies:
|
devDependencies:
|
||||||
'@types/better-sqlite3':
|
'@types/better-sqlite3':
|
||||||
specifier: ^7.6.13
|
specifier: ^7.6.13
|
||||||
@@ -60,7 +63,7 @@ importers:
|
|||||||
version: 11.10.0
|
version: 11.10.0
|
||||||
drizzle-orm:
|
drizzle-orm:
|
||||||
specifier: ^0.43.1
|
specifier: ^0.43.1
|
||||||
version: 0.43.1(@types/better-sqlite3@7.6.13)(better-sqlite3@11.10.0)
|
version: 0.43.1(@types/better-sqlite3@7.6.13)(better-sqlite3@11.10.0)(sql.js@1.14.1)
|
||||||
yaml:
|
yaml:
|
||||||
specifier: ^2.8.3
|
specifier: ^2.8.3
|
||||||
version: 2.8.3
|
version: 2.8.3
|
||||||
@@ -1071,6 +1074,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
|
resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
|
||||||
engines: {node: '>= 12'}
|
engines: {node: '>= 12'}
|
||||||
|
|
||||||
|
sql.js@1.14.1:
|
||||||
|
resolution: {integrity: sha512-gcj8zBWU5cFsi9WUP+4bFNXAyF1iRpA3LLyS/DP5xlrNzGmPIizUeBggKa8DbDwdqaKwUcTEnChtd2grWo/x/A==}
|
||||||
|
|
||||||
stackback@0.0.2:
|
stackback@0.0.2:
|
||||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||||
|
|
||||||
@@ -1692,10 +1698,11 @@ snapshots:
|
|||||||
|
|
||||||
detect-libc@2.1.2: {}
|
detect-libc@2.1.2: {}
|
||||||
|
|
||||||
drizzle-orm@0.43.1(@types/better-sqlite3@7.6.13)(better-sqlite3@11.10.0):
|
drizzle-orm@0.43.1(@types/better-sqlite3@7.6.13)(better-sqlite3@11.10.0)(sql.js@1.14.1):
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/better-sqlite3': 7.6.13
|
'@types/better-sqlite3': 7.6.13
|
||||||
better-sqlite3: 11.10.0
|
better-sqlite3: 11.10.0
|
||||||
|
sql.js: 1.14.1
|
||||||
|
|
||||||
end-of-stream@1.4.5:
|
end-of-stream@1.4.5:
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -1997,6 +2004,8 @@ snapshots:
|
|||||||
|
|
||||||
source-map@0.7.6: {}
|
source-map@0.7.6: {}
|
||||||
|
|
||||||
|
sql.js@1.14.1: {}
|
||||||
|
|
||||||
stackback@0.0.2: {}
|
stackback@0.0.2: {}
|
||||||
|
|
||||||
std-env@4.1.0: {}
|
std-env@4.1.0: {}
|
||||||
|
|||||||
Reference in New Issue
Block a user