Repository navigation
feat(db): sqlite as a re-usable SDK for secondary queries - #8533
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds the ChangesSQLite package and integration
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Renderer
participant SQLiteProvider
participant Electron
participant SQLite
participant QueryClient
Renderer->>SQLiteProvider: run SQLite query or mutation
SQLiteProvider->>Electron: invoke SQLite IPC request
Electron->>SQLite: execute prepared statement
SQLite-->>Electron: result and mutation tables
Electron-->>SQLiteProvider: result or mutation event
SQLiteProvider->>QueryClient: invalidate affected queries
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
c030fee to
171222c
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (5)
packages/bruno-sqlite/package.json (2)
44-47: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse version ranges for peer dependencies instead of exact pins.
Exact versions (
"19.0.0","5.101.1") mean consumers with[email protected]or@tanstack/[email protected]will see peer dependency warnings. Use caret ranges to allow compatible patch/minor versions.♻️ Proposed fix
"peerDependencies": { - "`@tanstack/react-query`": "5.101.1", - "react": "19.0.0" + "`@tanstack/react-query`": "^5.101.1", + "react": "^19.0.0" },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/package.json` around lines 44 - 47, Update the peerDependencies entries for `@tanstack/react-query` and react to caret version ranges, allowing compatible patch and minor releases while preserving their current major-version compatibility.
66-66: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUnused devDependency:
rollup-plugin-peer-deps-external.This plugin is declared in
devDependenciesbut never imported inrollup.config.js— externals are specified manually vianodeExternalandwebExternalarrays. Consider removing it to keep the dependency list clean.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/package.json` at line 66, Remove the unused rollup-plugin-peer-deps-external entry from the package’s devDependencies, since rollup.config.js uses the nodeExternal and webExternal arrays instead and does not import the plugin.packages/bruno-sqlite/scripts/lib/sources.ts (1)
5-6: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse an ESM import for
node-sql-parser. The package ships type declarations, soimport { Parser } from 'node-sql-parser';keepsParsertyped instead of falling back toanythroughrequire.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/lib/sources.ts` around lines 5 - 6, Replace the CommonJS require for node-sql-parser with a typed ESM import of Parser, while preserving the existing sqlParser initialization and usage.packages/bruno-sqlite/src/node/index.ts (1)
24-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
db._dbis accessed from outside theDBclass, breaking encapsulation.The underscore-prefixed
_dbconvention signals an internal field.createDatabasereaches into it twice — for the openness check and to pass the rawDatabaseSynctoStatements. Expose a public getter (e.g.,db.getDatabase()ordb.isOpen) onDBso callers don't depend on internals.♻️ Suggested public API on DB
export const createDatabase = (path: string, options: CreateDatabaseOptions = {}) => { const { onMutation, ...dbOptions } = options const db = new DB(path, migrations, dbOptions) - if (db._db === undefined) { + if (!db.isOpen()) { throw new Error("Failed to open the database.") } - const statements = new Statements(db._db, onMutation) + const statements = new Statements(db.getDatabase(), onMutation) return { db, statements } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/src/node/index.ts` around lines 24 - 27, Update the DB class to expose a public accessor for its underlying database state, then modify createDatabase to use that accessor for both the open check and Statements construction instead of referencing db._db directly. Preserve the existing failure behavior when no database is available.packages/bruno-sqlite/src/node/statements.ts (1)
27-27: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winUnsafe cast from
Record<string, unknown>toRecord<string, SupportedValueType>.
SQLiteParamsisRecord<string, unknown>, but this cast assumes all values conform toSupportedValueTypewithout any runtime check. Invalid types will surface as opaque SQLite errors rather than a clear validation message. Consider adding a lightweight type guard or at minimum documenting the expected value types at the IPC boundary.♻️ Suggested validation
const args = params as Record<string, SupportedValueType> +for (const [key, value] of Object.entries(args)) { + if (value !== null && typeof value !== 'number' && typeof value !== 'bigint' && typeof value !== 'string' && !(value instanceof Uint8Array)) { + throw new TypeError(`Invalid parameter type for "${key}": expected null, number, bigint, string, or Uint8Array`) + } +} switch (def.type) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/src/node/statements.ts` at line 27, Replace the unsafe cast assigned to args with validation that each SQLiteParams value is a SupportedValueType before passing it to the statement execution path. Add a lightweight type guard near the parameter handling logic, reject invalid values with a clear validation error, and preserve the existing behavior for valid parameters.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-sqlite/jest.config.js`:
- Around line 3-11: Update the Jest configuration’s transform pattern,
moduleFileExtensions, testMatch, and collectCoverageFrom entries to include .tsx
alongside .js and .ts, so TSX source files such as src/web/provider.tsx are
transformed, resolved, matched, and covered.
In `@packages/bruno-sqlite/package.json`:
- Line 59: Update the `@types/react` dependency in the package configuration to
the React 19-compatible version matching the declared react 19.0.0 peer and dev
dependencies, replacing the current 18.3.18 pin while preserving the existing
dependency structure.
In `@packages/bruno-sqlite/scripts/lib/sources.ts`:
- Around line 39-40: Update the marker detection in the migration parsing logic
using the visible upIdx and downIdx findIndex expressions so it matches only
standalone UP and DOWN markers, not longer words such as UPDATE or DOWNLOAD.
Preserve case-insensitive behavior provided by commentBody and ensure
surrounding marker text or whitespace is handled according to the existing
comment format.
In `@packages/bruno-sqlite/src/node/db.ts`:
- Around line 19-22: Update the DB constructor around DatabaseSync
initialization and _runMigrations so any migration failure closes the newly
created database before rethrowing the original error. Preserve successful
construction and existing migration behavior, ensuring cleanup occurs when no DB
instance can be returned.
In `@packages/bruno-sqlite/src/node/statements.ts`:
- Around line 28-38: Add a default branch to the switch in execute that throws
an error for unsupported def.type values, ensuring invalid statement types
cannot silently return undefined while preserving the existing exec, one, and
many behavior.
---
Nitpick comments:
In `@packages/bruno-sqlite/package.json`:
- Around line 44-47: Update the peerDependencies entries for
`@tanstack/react-query` and react to caret version ranges, allowing compatible
patch and minor releases while preserving their current major-version
compatibility.
- Line 66: Remove the unused rollup-plugin-peer-deps-external entry from the
package’s devDependencies, since rollup.config.js uses the nodeExternal and
webExternal arrays instead and does not import the plugin.
In `@packages/bruno-sqlite/scripts/lib/sources.ts`:
- Around line 5-6: Replace the CommonJS require for node-sql-parser with a typed
ESM import of Parser, while preserving the existing sqlParser initialization and
usage.
In `@packages/bruno-sqlite/src/node/index.ts`:
- Around line 24-27: Update the DB class to expose a public accessor for its
underlying database state, then modify createDatabase to use that accessor for
both the open check and Statements construction instead of referencing db._db
directly. Preserve the existing failure behavior when no database is available.
In `@packages/bruno-sqlite/src/node/statements.ts`:
- Line 27: Replace the unsafe cast assigned to args with validation that each
SQLiteParams value is a SupportedValueType before passing it to the statement
execution path. Add a lightweight type guard near the parameter handling logic,
reject invalid values with a clear validation error, and preserve the existing
behavior for valid parameters.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 53e9b4e6-40c1-4a6e-80be-593662caa6f9
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (35)
package.jsonpackages/bruno-app/package.jsonpackages/bruno-app/src/pages/Main.jspackages/bruno-electron/package.jsonpackages/bruno-electron/src/index.jspackages/bruno-electron/src/ipc/sqlite.jspackages/bruno-sqlite/.gitignorepackages/bruno-sqlite/LICENSE.mdpackages/bruno-sqlite/README.mdpackages/bruno-sqlite/babel.config.jspackages/bruno-sqlite/jest.config.jspackages/bruno-sqlite/package.jsonpackages/bruno-sqlite/rollup.config.jspackages/bruno-sqlite/scripts/generate-artifacts.tspackages/bruno-sqlite/scripts/lib/sources.tspackages/bruno-sqlite/scripts/new-migration.tspackages/bruno-sqlite/scripts/tsconfig.jsonpackages/bruno-sqlite/scripts/verify-migrations.tspackages/bruno-sqlite/src/node/db.tspackages/bruno-sqlite/src/node/index.tspackages/bruno-sqlite/src/node/ipc.tspackages/bruno-sqlite/src/node/statements.tspackages/bruno-sqlite/src/shared/index.tspackages/bruno-sqlite/src/shared/ipc.tspackages/bruno-sqlite/src/shared/types.tspackages/bruno-sqlite/src/web/index.tspackages/bruno-sqlite/src/web/provider.tsxpackages/bruno-sqlite/src/web/tables.tspackages/bruno-sqlite/src/web/use-sqlite.tspackages/bruno-sqlite/tests/node/migrations.spec.tspackages/bruno-sqlite/tests/node/statements.spec.tspackages/bruno-sqlite/tests/web/invalidation.spec.tspackages/bruno-sqlite/tests/web/tables.spec.tspackages/bruno-sqlite/tsconfig.jsonscripts/setup.js
171222c to
7c2dc95
Compare
There was a problem hiding this comment.
Actionable comments posted: 13
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-electron/src/ipc/sqlite.js`:
- Around line 14-16: Update the onMutation handler to verify the BrowserWindow
is not destroyed before calling webContents.send on SQLITE_MUTATION_CHANNEL.
Preserve the existing optional window/webContents checks and skip sending when
the window has been destroyed.
In `@packages/bruno-sqlite/.env.example`:
- Line 1: Update the DB_PATH example in the environment configuration to use a
platform-neutral placeholder such as path-to-database.sqlite instead of a
Unix-style absolute path, and add a brief note that users must replace it with
their environment-specific database path.
In `@packages/bruno-sqlite/package.json`:
- Line 59: Regenerate the package lockfile after adding "`@types/react`": "19.0.0"
in package.json, ensuring the resolved dependency and integrity metadata are
recorded so npm ci can install cleanly.
In `@packages/bruno-sqlite/scripts/lib/sources.ts`:
- Around line 1-35: Apply the repository style throughout the shown code:
replace double-quoted strings with single quotes, terminate statements with
semicolons, and wrap all arrow-function parameters in parentheses, including
callbacks in extractTables and commentBody. Simplify extractTables by returning
the mapped list directly instead of wrapping the .map result in Array.from.
- Around line 116-129: Update loadStatements and its surrounding code to use
single-quoted string literals and terminate statements with semicolons,
preserving the existing duplicate-name validation and sorted return behavior.
- Around line 65-83: Update walkSql and the SQLC constants to follow the coding
guidelines: use single-quoted strings, add semicolons to statements, and wrap
the entry parameter in parentheses for the arrow callback. Preserve the existing
traversal and annotation behavior.
- Around line 108-114: Update the affected code in the source parsing function
to follow the project’s formatting guidelines: use single-quoted string literals
and terminate statements with semicolons, including the surrounding statements
in the function such as current.body.push(line), flush(), and return defs.
- Around line 37-63: Update parseMigration and loadMigrations to follow the
project formatting conventions: use single-quoted strings, terminate statements
with semicolons, and parenthesize all arrow-function parameters. In
loadMigrations, replace entry.parentPath with MIGRATIONS_DIR when calling
parseMigration to support Node versions where Dirent.parentPath is unavailable.
In `@packages/bruno-sqlite/scripts/new-migration.ts`:
- Around line 20-35: Update the promptName function to use single quotes for all
string literals and add semicolons to terminate statements, including the
readline setup, prompt text, empty-name initialization, error message, return,
and cleanup statements.
- Around line 37-62: Update main and its migration-file filtering to follow the
repository style: use single quotes, terminate statements with semicolons, wrap
the file arrow-function parameter in parentheses, and replace the loose
extension comparison with strict equality. Call getEmptyFileTemplate without the
unnecessary fileName argument.
- Around line 1-18: Update the migration script’s string literals to use single
quotes consistently and add semicolons to terminated statements, including
imports, constants, function returns, and the generated migration template while
preserving its output.
In `@packages/bruno-sqlite/scripts/verify-migrations.ts`:
- Around line 4-21: Update the shown verify-migrations.ts code to consistently
use single-quoted strings and terminate statements with semicolons, including
imports, declarations, conditionals, and error-handling statements in main.
- Around line 23-47: Update the VACUUM INTO construction in main to escape every
single quote in backupPath as two single quotes before interpolating it into
SQL, preserving valid operation for paths such as O'Connor. Also format the
surrounding migration-verification block with single-quoted JavaScript strings
and semicolon-terminated statements, including the existing cleanup calls.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 48da734b-d546-4d42-acde-2b001b4d40b4
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (36)
package.jsonpackages/bruno-app/package.jsonpackages/bruno-app/src/pages/Main.jspackages/bruno-electron/package.jsonpackages/bruno-electron/src/index.jspackages/bruno-electron/src/ipc/sqlite.jspackages/bruno-sqlite/.env.examplepackages/bruno-sqlite/.gitignorepackages/bruno-sqlite/LICENSE.mdpackages/bruno-sqlite/README.mdpackages/bruno-sqlite/babel.config.jspackages/bruno-sqlite/jest.config.jspackages/bruno-sqlite/package.jsonpackages/bruno-sqlite/rollup.config.jspackages/bruno-sqlite/scripts/generate-artifacts.tspackages/bruno-sqlite/scripts/lib/sources.tspackages/bruno-sqlite/scripts/new-migration.tspackages/bruno-sqlite/scripts/tsconfig.jsonpackages/bruno-sqlite/scripts/verify-migrations.tspackages/bruno-sqlite/src/node/db.tspackages/bruno-sqlite/src/node/index.tspackages/bruno-sqlite/src/node/ipc.tspackages/bruno-sqlite/src/node/statements.tspackages/bruno-sqlite/src/shared/index.tspackages/bruno-sqlite/src/shared/ipc.tspackages/bruno-sqlite/src/shared/types.tspackages/bruno-sqlite/src/web/index.tspackages/bruno-sqlite/src/web/provider.tsxpackages/bruno-sqlite/src/web/tables.tspackages/bruno-sqlite/src/web/use-sqlite.tspackages/bruno-sqlite/tests/node/migrations.spec.tspackages/bruno-sqlite/tests/node/statements.spec.tspackages/bruno-sqlite/tests/web/invalidation.spec.tspackages/bruno-sqlite/tests/web/tables.spec.tspackages/bruno-sqlite/tsconfig.jsonscripts/setup.js
🚧 Files skipped from review as they are similar to previous changes (24)
- packages/bruno-sqlite/scripts/tsconfig.json
- packages/bruno-sqlite/tests/web/tables.spec.ts
- packages/bruno-sqlite/LICENSE.md
- packages/bruno-sqlite/babel.config.js
- packages/bruno-sqlite/src/shared/types.ts
- packages/bruno-sqlite/src/web/index.ts
- packages/bruno-sqlite/src/node/ipc.ts
- packages/bruno-sqlite/.gitignore
- packages/bruno-sqlite/jest.config.js
- packages/bruno-sqlite/src/shared/ipc.ts
- packages/bruno-sqlite/src/node/index.ts
- packages/bruno-sqlite/src/web/tables.ts
- packages/bruno-app/src/pages/Main.js
- packages/bruno-sqlite/tsconfig.json
- packages/bruno-sqlite/rollup.config.js
- packages/bruno-electron/package.json
- packages/bruno-sqlite/src/shared/index.ts
- packages/bruno-sqlite/tests/node/statements.spec.ts
- packages/bruno-sqlite/src/web/use-sqlite.ts
- package.json
- packages/bruno-sqlite/src/node/statements.ts
- packages/bruno-sqlite/tests/node/migrations.spec.ts
- packages/bruno-sqlite/src/web/provider.tsx
- packages/bruno-sqlite/tests/web/invalidation.spec.ts
75513d3 to
2aefc46
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (10)
packages/bruno-sqlite/scripts/verify-migrations.ts (2)
1-21: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes and semicolons.
As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes" and "Terminate statements with semicolons."
♻️ Proposed refactor
-import { DB } from "../src/node/db" -import type { Migration } from "../src/shared/types" -import { loadMigrations } from "./lib/sources" -import { DatabaseSync } from 'node:sqlite' -import os from 'node:os' -import fs from 'node:fs' -import path from 'node:path' +import { DB } from '../src/node/db'; +import type { Migration } from '../src/shared/types'; +import { loadMigrations } from './lib/sources'; +import { DatabaseSync } from 'node:sqlite'; +import os from 'node:os'; +import fs from 'node:fs'; +import path from 'node:path'; const main = () => { const dbPath = process.env.DB_PATH; - if (dbPath === undefined || dbPath.trim().length === 0) throw new Error('undefined environment variable DB_PATH. create a .env file.') - if (!path.isAbsolute(dbPath)) throw new Error('non absolute DB_PATH. provide an absolute path') + if (dbPath === undefined || dbPath.trim().length === 0) throw new Error('undefined environment variable DB_PATH. create a .env file.'); + if (!path.isAbsolute(dbPath)) throw new Error('non absolute DB_PATH. provide an absolute path'); - let migrations: Migration[] + let migrations: Migration[]; try { - migrations = loadMigrations() + migrations = loadMigrations(); } catch (err) { - console.error(`Failed to load migrations: ${(err as Error).message}`) - process.exit(1) + console.error(`Failed to load migrations: ${(err as Error).message}`); + process.exit(1); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/verify-migrations.ts` around lines 1 - 21, Update the imports and statements in main and the surrounding migration-loading code to consistently use single-quoted strings and terminate statements with semicolons, without changing behavior.Source: Coding guidelines
23-47: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winEscape single quotes in the database path for SQLite compatibility.
The string interpolation for
VACUUM INTO '${backupPath}'can produce an invalid SQL command if theos.tmpdir()path contains a single quote. This occasionally happens in Windows environments (e.g., if a user's name isO'Connor). Escaping the'characters as''fixes this.Additionally, let's fix up the formatting to adhere to coding guidelines (single quotes and semicolons) and swap out the optional chaining
?.close()for a strict check to comply with the TS optional chaining rule. As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes", "Terminate statements with semicolons", and "Avoid optional chaining unless the null case is handled immediately; otherwise narrow the type or fix it."🐛 Proposed fix
if (migrations.length === 0) { - console.log("No migrations to verify.") - return + console.log('No migrations to verify.'); + return; } let dbHandle, backupHandle, tempDir; try { - tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bruno-sqlite-backup-')) - const backupPath = path.join(tempDir, 'bruno_backup.db') - dbHandle = new DatabaseSync(dbPath) - dbHandle.exec(`VACUUM INTO '${backupPath}'`) - backupHandle = new DB(backupPath, migrations) + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bruno-sqlite-backup-')); + const backupPath = path.join(tempDir, 'bruno_backup.db'); + dbHandle = new DatabaseSync(dbPath); + dbHandle.exec(`VACUUM INTO '${backupPath.replace(/'/g, "''")}'`); + backupHandle = new DB(backupPath, migrations); } catch (err) { - console.error(`Migration verification failed: ${(err as Error).stack}`) - process.exitCode = 1 - return + console.error(`Migration verification failed: ${(err as Error).stack}`); + process.exitCode = 1; + return; } finally { - dbHandle?.close() - backupHandle?.close(); - if (tempDir) fs.rmSync(tempDir, {recursive: true, force: true}) + if (dbHandle) dbHandle.close(); + if (backupHandle) backupHandle.close(); + if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true }); } - console.log(`Verified ${migrations.length} migration(s): all statements applied cleanly.`) -} + console.log(`Verified ${migrations.length} migration(s): all statements applied cleanly.`); +}; -main() +main();🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/verify-migrations.ts` around lines 23 - 47, Update the VACUUM INTO SQL construction in main to escape every single quote in backupPath by doubling it before interpolation. Also normalize the shown block to single-quoted strings and semicolon-terminated statements, and replace both optional-chaining close calls with explicit null checks before invoking close.Source: Coding guidelines
packages/bruno-sqlite/scripts/new-migration.ts (3)
20-35: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes and semicolons.
As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes" and "Terminate statements with semicolons."
♻️ Proposed refactor
const promptName = async (): Promise<string> => { - const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) + const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); try { - let name = "" + let name = ''; while (!name) { - const answer = await rl.question("Migration name: ") - name = answer.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") + const answer = await rl.question('Migration name: '); + name = answer.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, ''); if (!name) { - console.error(`Invalid migration name: "${answer.trim()}". Use letters, numbers, and underscores.`) + console.error(`Invalid migration name: "${answer.trim()}". Use letters, numbers, and underscores.`); } } - return name + return name; } finally { - rl.close() + rl.close(); } -} +};🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/new-migration.ts` around lines 20 - 35, Update promptName and its surrounding code to use single-quoted string literals and terminate statements with semicolons, including the readline prompt, empty string, error message, and return/cleanup statements.Source: Coding guidelines
1-18: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes and semicolons.
As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes" and "Terminate statements with semicolons."
♻️ Proposed refactor
-import path from "path" -import fs from "fs" -import readline from "readline/promises" +import path from 'path'; +import fs from 'fs'; +import readline from 'readline/promises'; -const MIGRATIONS_DIR = path.join(process.cwd(), 'migrations'); -const PREFIX_LENGTH = 7 +const MIGRATIONS_DIR = path.join(process.cwd(), 'migrations'); +const PREFIX_LENGTH = 7; const getEmptyFileTemplate = (): string => { return ` export const up = (): string => { // Return the SQL that applies this migration return ''; -} +}; export const down = (): string => { // Return the SQL that reverts this migration return ''; -} +}; ` -} +};🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/new-migration.ts` around lines 1 - 18, Update the shown migration script to use single quotes consistently for string literals and add semicolons to all statements, including imports, constants, returns, and declarations in getEmptyFileTemplate.Source: Coding guidelines
37-62: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes, semicolons, and arrow functions.
In addition to styling guidelines,
getEmptyFileTemplate()does not accept any arguments, so passingfileNameto it is unnecessary. A strict equality check (===) is also preferred.As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes", "Terminate statements with semicolons", and "Always use parentheses around arrow-function parameters."
♻️ Proposed refactor
const main = async () => { - const name = await promptName() + const name = await promptName(); - fs.mkdirSync(MIGRATIONS_DIR, {recursive: true}) + fs.mkdirSync(MIGRATIONS_DIR, { recursive: true }); - let files = fs.readdirSync(MIGRATIONS_DIR, {withFileTypes: true}) - files = files.filter(file => path.extname(file.name) == '.ts') - files.sort((a, b) => a.name.localeCompare(b.name)) + let files = fs.readdirSync(MIGRATIONS_DIR, { withFileTypes: true }); + files = files.filter((file) => path.extname(file.name) === '.ts'); + files.sort((a, b) => a.name.localeCompare(b.name)); - const last = files.pop() + const last = files.pop(); - let sequence = 0 + let sequence = 0; if (last !== undefined) { - sequence = Number(last.name.slice(0, PREFIX_LENGTH)) + sequence = Number(last.name.slice(0, PREFIX_LENGTH)); } const newSequence = sequence + 1; - const prefix = newSequence.toString().padStart(PREFIX_LENGTH, "0") - const fileName = `${prefix}_${name}.ts` - const filePath = path.join(MIGRATIONS_DIR, fileName) + const prefix = newSequence.toString().padStart(PREFIX_LENGTH, '0'); + const fileName = `${prefix}_${name}.ts`; + const filePath = path.join(MIGRATIONS_DIR, fileName); - fs.writeFileSync(filePath, getEmptyFileTemplate(fileName)) - console.log(`Created ${path.relative(process.cwd(), filePath)}`) -} + fs.writeFileSync(filePath, getEmptyFileTemplate()); + console.log(`Created ${path.relative(process.cwd(), filePath)}`); +}; -main() +main();🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/new-migration.ts` around lines 37 - 62, Update main and its nearby expressions to follow the project’s quote, semicolon, and arrow-parameter conventions: use single quotes, terminate statements with semicolons, parenthesize the file parameter in the filter callback, and replace the extname comparison with strict equality. Since getEmptyFileTemplate accepts no arguments, call it without fileName while preserving the existing migration file creation flow.Source: Coding guidelines
packages/bruno-sqlite/scripts/lib/sources.ts (5)
37-63: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueAlign with formatting guidelines and improve Node compatibility.
Besides applying the formatting guidelines, let's replace
entry.parentPathwith the globally availableMIGRATIONS_DIR. TheparentPathproperty was only added tofs.Direntin Node.js 20.12.0 and 21.2.0, so this prevents runtime crashes in slightly older environments.As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes", "Terminate statements with semicolons", and "Always use parentheses around arrow-function parameters."
♻️ Proposed refactor
const parseMigration = (parentPath: string, name: string): Migration => { - const filePath = path.join(parentPath, name) - const { up, down } = require(filePath) - if (up === undefined || down === undefined) throw new Error(`Migration ${name} should export up and down methods`) + const filePath = path.join(parentPath, name); + const { up, down } = require(filePath); + if (up === undefined || down === undefined) throw new Error(`Migration ${name} should export up and down methods`); const upStatement = typeof up === 'function' ? up() : up; const downStatement = typeof down === 'function' ? down() : down; - if (typeof upStatement !== 'string') throw new Error('up should be a string or a function returning a string') - if (typeof downStatement !== 'string') throw new Error('down should be a string or a function returning a string') + if (typeof upStatement !== 'string') throw new Error('up should be a string or a function returning a string'); + if (typeof downStatement !== 'string') throw new Error('down should be a string or a function returning a string'); return { sequence: parseSequence(name), - name: path.basename(name, ".ts"), + name: path.basename(name, '.ts'), up: upStatement, down: downStatement - } -} + }; +}; export const loadMigrations = (): Migration[] => { - if (!fs.existsSync(MIGRATIONS_DIR)) return [] + if (!fs.existsSync(MIGRATIONS_DIR)) return []; return fs .readdirSync(MIGRATIONS_DIR, { withFileTypes: true }) - .filter(entry => entry.isFile() && path.extname(entry.name) === ".ts") - .map(entry => parseMigration(entry.parentPath, entry.name)) - .sort((a, b) => a.sequence - b.sequence) -} + .filter((entry) => entry.isFile() && path.extname(entry.name) === '.ts') + .map((entry) => parseMigration(MIGRATIONS_DIR, entry.name)) + .sort((a, b) => a.sequence - b.sequence); +};🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/lib/sources.ts` around lines 37 - 63, Update loadMigrations to pass MIGRATIONS_DIR to parseMigration instead of entry.parentPath for compatibility with older Node.js versions. Apply the repository formatting rules throughout the shown code: use single-quoted strings, terminate statements with semicolons, and wrap single arrow-function parameters in parentheses.Source: Coding guidelines
85-114: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes and semicolons.
As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes" and "Terminate statements with semicolons."
♻️ Proposed refactor
-const parseStatementFile = (relative: string, content: string): StatementDef[] => { - const defs: StatementDef[] = [] - let current: { name: string; type: StatementType; body: string[] } | null = null +const parseStatementFile = (relative: string, content: string): StatementDef[] => { + const defs: StatementDef[] = []; + let current: { name: string; type: StatementType; body: string[] } | null = null; const flush = () => { - if (current === null) return - const sql = current.body.join("\n").trim() - if (sql === "") { + if (current === null) return; + const sql = current.body.join('\n').trim(); + if (sql === '') { throw new Error(`Statement "${current.name}" in ${relative} has no SQL body.`) } - defs.push({ name: current.name, type: current.type, sql, tables: extractTables(sql) }) - } + defs.push({ name: current.name, type: current.type, sql, tables: extractTables(sql) }); + }; - content.split("\n").forEach((line) => { + content.split('\n').forEach((line) => { const match = line.match(SQLC_NAME_ANNOTATION) if (match) { - flush() - const [, name, command] = match - const type = SQLC_COMMAND_TYPES[command.toLowerCase()] + flush(); + const [, name, command] = match; + const type = SQLC_COMMAND_TYPES[command.toLowerCase()]; if (type === undefined) { throw new Error(`Statement "${name}" in ${relative} uses unsupported command ":${command}". Use :one, :many, or :exec.`) } - current = { name, type, body: [] } + current = { name, type, body: [] }; } else if (current !== null) { - current.body.push(line) + current.body.push(line); } - }) - flush() - return defs -} + }); + flush(); + return defs; +};🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/lib/sources.ts` around lines 85 - 114, Update parseStatementFile and its nearby statements to use single-quoted string literals and terminate statements with semicolons, while preserving the existing parsing and error-handling behavior.Source: Coding guidelines
65-83: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes, semicolons, and arrow functions.
As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes", "Terminate statements with semicolons", and "Always use parentheses around arrow-function parameters."
♻️ Proposed refactor
const walkSql = (dir: string): string[] => { - return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => { - const full = path.join(dir, entry.name) - if (entry.isDirectory()) return walkSql(full) - return entry.isFile() && entry.name.endsWith(".sql") ? [full] : [] - }) -} + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return walkSql(full); + return entry.isFile() && entry.name.endsWith('.sql') ? [full] : []; + }); +}; // sqlc-style query annotation: `-- name: <Name> :one|:many|:exec` -const SQLC_NAME_ANNOTATION = /^--\s*name:\s*(\S+)\s+:(\w+)\s*$/ +const SQLC_NAME_ANNOTATION = /^--\s*name:\s*(\S+)\s+:(\w+)\s*$/; const SQLC_COMMAND_TYPES: Record<string, StatementType> = { - one: "one", - many: "many", - exec: "exec", - execrows: "exec", - execresult: "exec", - execlastid: "exec" -} + one: 'one', + many: 'many', + exec: 'exec', + execrows: 'exec', + execresult: 'exec', + execlastid: 'exec' +};🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/lib/sources.ts` around lines 65 - 83, The SQL source helpers and constants in walkSql, SQLC_NAME_ANNOTATION, and SQLC_COMMAND_TYPES do not follow the project’s formatting conventions. Update this code to use single-quoted strings, semicolons for statement termination, and parentheses around the arrow-function parameter, without changing its behavior.Source: Coding guidelines
1-35: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes, semicolons, and arrow functions.
To ensure consistency with the repository's styling guidelines, let's switch to single quotes, terminate our statements with semicolons, and ensure arrow function parameters are wrapped in parentheses. The
Array.fromwrapper around a.mapresult is also redundant and can be simplified.As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes", "Terminate statements with semicolons", and "Always use parentheses around arrow-function parameters."
♻️ Proposed refactor
-import * as path from "path" -import * as fs from "fs" -import type { Migration, StatementDef, StatementType } from "../../src/shared/types" +import * as path from 'path'; +import * as fs from 'fs'; +import type { Migration, StatementDef, StatementType } from '../../src/shared/types'; -const { Parser } = require("node-sql-parser") -const sqlParser = new Parser() +const { Parser } = require('node-sql-parser'); +const sqlParser = new Parser(); const extractTables = (sql: string): string[] => { try { - let list: string[] = sqlParser.tableList(sql, { database: "Sqlite" }) + const list: string[] = sqlParser.tableList(sql, { database: 'Sqlite' }); // This is in the form of statement::db::table, hence the second index access - return Array.from(list.map(entry => entry.split("::")[2])) + return list.map((entry) => entry.split('::')[2]); } catch { - return [] + return []; } -} +}; -const ROOT_DIR = process.cwd() -const MIGRATIONS_DIR = path.join(ROOT_DIR, "migrations") -const STATEMENTS_DIR = path.join(ROOT_DIR, "statements") +const ROOT_DIR = process.cwd(); +const MIGRATIONS_DIR = path.join(ROOT_DIR, 'migrations'); +const STATEMENTS_DIR = path.join(ROOT_DIR, 'statements'); const parseSequence = (fileName: string): number => { - const prefix = fileName.split("_")[0] - const sequence = Number(prefix) - if (prefix === "" || Number.isNaN(sequence)) { - throw new Error(`Migration "${fileName}" is missing a numeric sequence prefix.`) + const prefix = fileName.split('_')[0]; + const sequence = Number(prefix); + if (prefix === '' || Number.isNaN(sequence)) { + throw new Error(`Migration "${fileName}" is missing a numeric sequence prefix.`); } - return sequence -} + return sequence; +}; const commentBody = (line: string): string => { - const trimmed = line.trim() - if (!trimmed.startsWith("--")) return "" - return trimmed.slice(2).trim().toUpperCase() -} + const trimmed = line.trim(); + if (!trimmed.startsWith('--')) return ''; + return trimmed.slice(2).trim().toUpperCase(); +};🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/lib/sources.ts` around lines 1 - 35, Apply the repository style in sources.ts: change string literals to single quotes, terminate statements with semicolons, and wrap all arrow-function parameters in parentheses. In extractTables, remove the redundant Array.from wrapper while preserving the existing map result and table extraction behavior.Source: Coding guidelines
116-129: 📐 Maintainability & Code Quality | 🟠 Major | 💤 Low valueApply coding guidelines for quotes and semicolons.
As per coding guidelines: "Use single-quoted strings, except JSX/TSX attributes" and "Terminate statements with semicolons."
♻️ Proposed refactor
export const loadStatements = (): StatementDef[] => { - if (!fs.existsSync(STATEMENTS_DIR)) return [] + if (!fs.existsSync(STATEMENTS_DIR)) return []; const defs = walkSql(STATEMENTS_DIR).flatMap((full) => - parseStatementFile(path.relative(STATEMENTS_DIR, full), fs.readFileSync(full, "utf8")) - ) - const seen = new Set<string>() + parseStatementFile(path.relative(STATEMENTS_DIR, full), fs.readFileSync(full, 'utf8')) + ); + const seen = new Set<string>(); for (const def of defs) { if (seen.has(def.name)) { - throw new Error(`Duplicate statement name "${def.name}".`) + throw new Error(`Duplicate statement name "${def.name}".`); } - seen.add(def.name) + seen.add(def.name); } - return defs.sort((a, b) => a.name.localeCompare(b.name)) -} + return defs.sort((a, b) => a.name.localeCompare(b.name)); +};🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/lib/sources.ts` around lines 116 - 129, Update loadStatements and its surrounding code to use single-quoted string literals and terminate statements with semicolons, including the duplicate-name error message, while preserving the existing loading, validation, and sorting behavior.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@packages/bruno-sqlite/scripts/lib/sources.ts`:
- Around line 37-63: Update loadMigrations to pass MIGRATIONS_DIR to
parseMigration instead of entry.parentPath for compatibility with older Node.js
versions. Apply the repository formatting rules throughout the shown code: use
single-quoted strings, terminate statements with semicolons, and wrap single
arrow-function parameters in parentheses.
- Around line 85-114: Update parseStatementFile and its nearby statements to use
single-quoted string literals and terminate statements with semicolons, while
preserving the existing parsing and error-handling behavior.
- Around line 65-83: The SQL source helpers and constants in walkSql,
SQLC_NAME_ANNOTATION, and SQLC_COMMAND_TYPES do not follow the project’s
formatting conventions. Update this code to use single-quoted strings,
semicolons for statement termination, and parentheses around the arrow-function
parameter, without changing its behavior.
- Around line 1-35: Apply the repository style in sources.ts: change string
literals to single quotes, terminate statements with semicolons, and wrap all
arrow-function parameters in parentheses. In extractTables, remove the redundant
Array.from wrapper while preserving the existing map result and table extraction
behavior.
- Around line 116-129: Update loadStatements and its surrounding code to use
single-quoted string literals and terminate statements with semicolons,
including the duplicate-name error message, while preserving the existing
loading, validation, and sorting behavior.
In `@packages/bruno-sqlite/scripts/new-migration.ts`:
- Around line 20-35: Update promptName and its surrounding code to use
single-quoted string literals and terminate statements with semicolons,
including the readline prompt, empty string, error message, and return/cleanup
statements.
- Around line 1-18: Update the shown migration script to use single quotes
consistently for string literals and add semicolons to all statements, including
imports, constants, returns, and declarations in getEmptyFileTemplate.
- Around line 37-62: Update main and its nearby expressions to follow the
project’s quote, semicolon, and arrow-parameter conventions: use single quotes,
terminate statements with semicolons, parenthesize the file parameter in the
filter callback, and replace the extname comparison with strict equality. Since
getEmptyFileTemplate accepts no arguments, call it without fileName while
preserving the existing migration file creation flow.
In `@packages/bruno-sqlite/scripts/verify-migrations.ts`:
- Around line 1-21: Update the imports and statements in main and the
surrounding migration-loading code to consistently use single-quoted strings and
terminate statements with semicolons, without changing behavior.
- Around line 23-47: Update the VACUUM INTO SQL construction in main to escape
every single quote in backupPath by doubling it before interpolation. Also
normalize the shown block to single-quoted strings and semicolon-terminated
statements, and replace both optional-chaining close calls with explicit null
checks before invoking close.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 48cfb4bf-a36e-4721-b6be-902282f439b4
⛔ Files ignored due to path filters (1)
package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (36)
package.jsonpackages/bruno-app/package.jsonpackages/bruno-app/src/pages/Main.jspackages/bruno-electron/package.jsonpackages/bruno-electron/src/index.jspackages/bruno-electron/src/ipc/sqlite.jspackages/bruno-sqlite/.env.examplepackages/bruno-sqlite/.gitignorepackages/bruno-sqlite/LICENSE.mdpackages/bruno-sqlite/README.mdpackages/bruno-sqlite/babel.config.jspackages/bruno-sqlite/jest.config.jspackages/bruno-sqlite/package.jsonpackages/bruno-sqlite/rollup.config.jspackages/bruno-sqlite/scripts/generate-artifacts.tspackages/bruno-sqlite/scripts/lib/sources.tspackages/bruno-sqlite/scripts/new-migration.tspackages/bruno-sqlite/scripts/tsconfig.jsonpackages/bruno-sqlite/scripts/verify-migrations.tspackages/bruno-sqlite/src/node/db.tspackages/bruno-sqlite/src/node/index.tspackages/bruno-sqlite/src/node/ipc.tspackages/bruno-sqlite/src/node/statements.tspackages/bruno-sqlite/src/shared/index.tspackages/bruno-sqlite/src/shared/ipc.tspackages/bruno-sqlite/src/shared/types.tspackages/bruno-sqlite/src/web/index.tspackages/bruno-sqlite/src/web/provider.tsxpackages/bruno-sqlite/src/web/tables.tspackages/bruno-sqlite/src/web/use-sqlite.tspackages/bruno-sqlite/tests/node/migrations.spec.tspackages/bruno-sqlite/tests/node/statements.spec.tspackages/bruno-sqlite/tests/web/invalidation.spec.tspackages/bruno-sqlite/tests/web/tables.spec.tspackages/bruno-sqlite/tsconfig.jsonscripts/setup.js
🚧 Files skipped from review as they are similar to previous changes (27)
- packages/bruno-sqlite/babel.config.js
- packages/bruno-sqlite/.gitignore
- packages/bruno-sqlite/.env.example
- packages/bruno-sqlite/src/shared/types.ts
- packages/bruno-sqlite/scripts/tsconfig.json
- packages/bruno-sqlite/src/shared/index.ts
- packages/bruno-sqlite/tests/web/tables.spec.ts
- packages/bruno-sqlite/package.json
- packages/bruno-sqlite/rollup.config.js
- packages/bruno-sqlite/jest.config.js
- packages/bruno-sqlite/tests/node/migrations.spec.ts
- packages/bruno-sqlite/src/web/tables.ts
- packages/bruno-app/package.json
- packages/bruno-sqlite/src/node/ipc.ts
- packages/bruno-app/src/pages/Main.js
- packages/bruno-sqlite/src/web/provider.tsx
- packages/bruno-electron/package.json
- packages/bruno-sqlite/tsconfig.json
- packages/bruno-sqlite/src/node/index.ts
- packages/bruno-sqlite/src/web/index.ts
- packages/bruno-sqlite/tests/web/invalidation.spec.ts
- packages/bruno-sqlite/src/shared/ipc.ts
- packages/bruno-sqlite/tests/node/statements.spec.ts
- packages/bruno-sqlite/src/node/statements.ts
- packages/bruno-sqlite/src/web/use-sqlite.ts
- packages/bruno-electron/src/index.js
- packages/bruno-electron/src/ipc/sqlite.js
There was a problem hiding this comment.
♻️ Duplicate comments (1)
packages/bruno-sqlite/scripts/new-migration.ts (1)
25-26: 📐 Maintainability & Code Quality | 🟡 Minor | 💤 Low valueUse single quotes for string literals.
As per the coding guidelines, use single-quoted strings.
♻️ Proposed fix
- const answer = await rl.question("Migration name: "); - name = answer.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, ""); + const answer = await rl.question('Migration name: '); + name = answer.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/new-migration.ts` around lines 25 - 26, Update the string literals in the migration-name prompt and normalization logic within the migration creation flow to use single quotes instead of double quotes, without changing the existing behavior.Source: Coding guidelines
🧹 Nitpick comments (3)
packages/bruno-sqlite/tests/node/vacuum.spec.ts (2)
33-33: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse single-quoted strings.
As per coding guidelines, use single quotes instead of template literals for simple strings.
♻️ Proposed fix
- expect(backupPath).toContain(`'`); + expect(backupPath).toContain('\'');🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/tests/node/vacuum.spec.ts` at line 33, Update the expectation in the vacuum test to use a single-quoted string instead of a template literal for the simple apostrophe value, preserving the existing assertion behavior.Source: Coding guidelines
8-22: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse single-quoted strings.
As per coding guidelines, use single quotes for strings that do not require interpolation.
♻️ Proposed fix
it('single-quotes the backup path', () => { - expect(vacuumIntoStatement('/tmp/backup.db')).toBe(`VACUUM INTO '/tmp/backup.db'`); + expect(vacuumIntoStatement('/tmp/backup.db')).toBe('VACUUM INTO \'/tmp/backup.db\''); }); it('escapes single quotes in the path by doubling them', () => { - expect(vacuumIntoStatement(`/tmp/O'Connor/backup.db`)).toBe(`VACUUM INTO '/tmp/O''Connor/backup.db'`); - expect(vacuumIntoStatement(`/tmp/a'b'c.db`)).toBe(`VACUUM INTO '/tmp/a''b''c.db'`); + expect(vacuumIntoStatement('/tmp/O\'Connor/backup.db')).toBe('VACUUM INTO \'/tmp/O\'\'Connor/backup.db\''); + expect(vacuumIntoStatement('/tmp/a\'b\'c.db')).toBe('VACUUM INTO \'/tmp/a\'\'b\'\'c.db\''); }); describe('executed against a real database', () => { let dir: string; beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), `bruno-sqlite-o'connor-`)); + dir = mkdtempSync(join(tmpdir(), 'bruno-sqlite-o\'connor-')); });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/tests/node/vacuum.spec.ts` around lines 8 - 22, Update the new test descriptions and string literals in the vacuumIntoStatement tests to use single-quoted strings wherever interpolation is not required, while retaining template literals only for interpolated expected paths.Source: Coding guidelines
packages/bruno-sqlite/scripts/lib/sql.ts (1)
1-4: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse single-quoted strings.
As per coding guidelines, use single-quoted strings instead of template literals when there is no interpolation.
♻️ Proposed fix
export const vacuumIntoStatement = (backupPath: string): string => { - const escaped = backupPath.replace(/'/g, `''`); + const escaped = backupPath.replace(/'/g, '\'\''); return `VACUUM INTO '${escaped}'`; };🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-sqlite/scripts/lib/sql.ts` around lines 1 - 4, Update vacuumIntoStatement to use single-quoted string literals for the static replacement string and SQL prefix/suffix where no interpolation is needed, while preserving the existing backupPath escaping and generated VACUUM INTO statement.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@packages/bruno-sqlite/scripts/new-migration.ts`:
- Around line 25-26: Update the string literals in the migration-name prompt and
normalization logic within the migration creation flow to use single quotes
instead of double quotes, without changing the existing behavior.
---
Nitpick comments:
In `@packages/bruno-sqlite/scripts/lib/sql.ts`:
- Around line 1-4: Update vacuumIntoStatement to use single-quoted string
literals for the static replacement string and SQL prefix/suffix where no
interpolation is needed, while preserving the existing backupPath escaping and
generated VACUUM INTO statement.
In `@packages/bruno-sqlite/tests/node/vacuum.spec.ts`:
- Line 33: Update the expectation in the vacuum test to use a single-quoted
string instead of a template literal for the simple apostrophe value, preserving
the existing assertion behavior.
- Around line 8-22: Update the new test descriptions and string literals in the
vacuumIntoStatement tests to use single-quoted strings wherever interpolation is
not required, while retaining template literals only for interpolated expected
paths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 0d934c2e-f328-42cf-9ccd-3e1a82f203e7
📒 Files selected for processing (4)
packages/bruno-sqlite/scripts/lib/sql.tspackages/bruno-sqlite/scripts/new-migration.tspackages/bruno-sqlite/scripts/verify-migrations.tspackages/bruno-sqlite/tests/node/vacuum.spec.ts
6cfa3a5 to
1380a17
Compare
…xec types Split _runMigrations into _rollbackObsolete/_applyPending helpers and add migration-runner tests (apply, idempotent, drift, rollback). Rename StatementType from run/get/all to exec/one/many so the internal type matches the sqlc query annotations directly, dropping the translation layer. Also drop the unused @tanstack/react-query dep from bruno-app (used via @usebruno/sqlite), fix the electron mount shutdown call, and minor cleanup.
…h exports up and down statements. This is to avoid the parsing issue we might face with handling SQL files
… within the Statements class to handle upsupported def.type
…anup the DB handle
… .env file. The script now creates a backup of the original DB in a temp dir and tries to apply the migration on the copy. This is to avoid the shitty migration -> delete db -> run migrations cycle
Extract the statement builder into scripts/lib/sql.ts and cover it with a test that executes VACUUM against a real DB using a path containing a single quote.
bruno-sqlite's package.json pinned @types/[email protected] while the lockfile already resolved 18.3.18, so npm installed a nested 19.0.0 copy whose ReactNode admits bigint. QueryClientProvider resolves the root 18.3.18 (no bigint), so passing children across the two type sets failed the declaration build. Pin to 18.3.18 to match the lockfile and the version the rest of the workspace (incl. bruno-app) resolves.
Lets main-process modules reach the prepared statements handle to run queries directly, without going through the renderer IPC round-trip.
Co-authored-by: Sid <[email protected]>
The .nvmrc pins Node 22.12.0, where node:sqlite is only reachable behind the flag, so jest and migration:verify could not load it. Electron bundles Node 22.19.0, where the module is unflagged and the flag is a no-op.
67d4510 to
85aedc2
Compare
* fix(ws): keep body-mode dropdown above collapsed sticky headers (#8622) * fix(ws): keep body-mode dropdown above collapsed sticky headers * fix * add: test * rm: only * improvement * fix(app): point generated docs to api-docs CDN path (#8633) * test(sidebar): move sidebar locators to a dedicated file (#8634) Co-authored-by: Bijin A B <[email protected]> * fix(ai): align AI buttons to primary color and refine copy (#8627) * fix(ai): align AI buttons to primary color and refine copy * fix: test --------- Co-authored-by: naman-bruno <[email protected]> * improve: test file arrangement * fix(new-app): prevented validation error on blur and dialog layout shift (#8624) * add: unit test * feat(proxy-settings): show "last refreshed" timestamp on System Proxy panel (#8640) * refactor: improve Wysiwyg editor toolbar interactions, add delete table option * refactor: update documentation code block background theme colors * reconciled autocomplete suggestions against typed prefix to stop dupes + invalid res (#8621) * fix(ai): scope autocomplete API hints by scriptType so pre-request never suggests res * fix(ai): de-duplicated typed token in autocomplete + unify suggestion sanitization * resolved the coderabit review. * fix(ai): reconciled autocomplete suggestions against typed prefix to stop dupes + invalid res * fix(ws): keep selection on current message when deleting another (#8643) * Generate documentation modal text and style changes (#8644) * fix(ui): visual improvements for tables in FileBody and EnvironmentVarsTable (#8632) * fix(StyledWrapper): improve table header styling and add ellipsis for overflow text * fix(FileBody): add truncation to 'Selected' column for better overflow handling * fix: ui improvements for descriptions and tables * fix(EnvironmentVariablesTable): improve formatting and overflow handling in EnvVarValueCell * fix(EnvironmentVariablesTable): add testId to SecretEyeButton for better testing support * chore(claude): add .claude config into the repo (#8648) * fix(app): resolve collection level variables in bru.ctx and add app logs to console (#8650) * fix(app): resolve collection level variables in bru.ctx.variables * fix(app): log bru.ctx.log output into app console * refactor(app): integrate Portal component and enhance form submission (#8645) * chore(mount): route request entries through buildRequestNode in buildTree (#8658) * Update CODEOWNERS (#8666) * refactor: replace DocsLinkModal with contextual DocsLinkPopover and update toolbar link handling * test(environments): env tab eye icon (#8655) * fix(interpolation): add interpolation for akamai-auth (#8631) * fix: show correct New Request shortcut in response placeholder (#8116) * refactor: redesign documentation editor table styles, update mode switch UI * fix(ai): respected the redact-secret-variables toggle for name-pattern variables (#8657) * fix(app): chevron positioning and selector width (#8669) * refactor: extract richtext editor test utility and modularize test suites * fix(ai): improve script types and clarify res restrictions in pre scripts (#8678) * Update beta features section in preferences (#8642) * Refine bug report issue template UI * Rename config.yaml to config.yml * Update FeatureRequest.yaml * chore(ui-component)/added radio group component with storybook and updated the preset component * added storybook docs * added tests for radio group * fix(environments): keep secret values on the secret row when a variable shares its name (#8679) * fix(environments): keep secret values on the secret row when a variable shares its name * rm: comment * fix * fix(mount): redact large text blocks so big .bru files parse fast (#8660) Large .bru files (>=512KB) were fed whole to the ohm parser on mount, which is slow and memory-heavy. Add a redaction pass that splits the flat text blocks (bodies, scripts, tests, docs) out of the file, parses the small remaining skeleton, and re-attaches the extracted content. - redactLargeBruTextBlocks: replaces each top-level text block's content with a content-hash token, returning a skeleton + the extracted values - restoreRedactedBlocks: re-attaches values wherever the tokens land in the parsed object - parse-file uses this for request, collection and folder .bru above the size threshold - values are extracted to be byte-identical to a normal parse (leading blank lines, CRLF terminator and 2-space outdent all handled), proven by round-trip tests that deep-equal against a normal parse * added stories for ui components * feat(mount): follow symlinks when walking collections (#8649) * feat(mount): follow symlinks when walking collections Resolve symbolic-link entries during the mountv2 walk so symlinked request files and directories are classified and listed like their real counterparts. Broken links are skipped. Adds an e2e spec covering symlinked file and directory entries across both formats and with the file cache off and on. * test(mount): use waitForReadyPage and closeElectronApp helpers in symlink spec * fix(mount): guard against directory-symlink cycles when walking A directory symlink that resolves to an ancestor (or itself) previously re-entered the same subtree until the walk exhausted the stack. Track canonical directory paths and skip any directory already visited, so a cyclic link is walked at most once. Extends the symlink e2e spec with an ancestor-pointing link, asserting the mounted tree stays bounded (file-cache path). * removed preset component * fix(size/S):Minor bug fix in the version edit popup for the new version input box (#8672) * Minor bug fix for the version edit popup * Fix unit test case failing issue * added segment group component with stories and tests * revert presets to not use segment group * added theme selector * added readme for storybook * feat(ai): implement immediate security settings save (#8685) * feat(ai): implement immediate security settings save * Update packages/bruno-app/src/components/Preferences/AI/index.js * refactor: migrate editor components to RichTextEditor, and adjust ModeSwitch UI styles * refactor: rename Docs-prefixed editor extensions to Editor * refactor: rename Wysiwyg references to Rich Text * enabled code in storybook and updated Radio and Segmented control API to accept list * refactor: remove code-block test file * removed box shadow * refactor: rename docs CSS classes to editor prefix for consistency * fix(snapshot): environment loss of some workspaces (#8686) * fix: draft attempt 1 * fix(snapshot): enhance active workspace collection handling in SnapshotManager * fix(snapshot): refactor collection lookup assignments for improved readability * fix(snapshot): simplify collection lookup assignments for clarity and maintainability * fix(snapshot): improve handling of workspace-scoped collection lookups and ensure distinct entries based on active workspace preferences * fix: coderabbit comments * added a box shadow on active item * updated shadow to lighter version * improved readme file * added test and stories for toggle switch * added post css loader so Storybook can compile the app's Tailwind CSS * added dropdown stories and test * feat(ai): enhance app handling in AiChatSidebar (#8697) * fix: size of cancel button (#8692) Co-authored-by: shubh-bruno <[email protected]> * task (migration) : hiding migration options and the respective test (#8690) * fix(ui): SensitiveFieldWarning tooltip position (#8698) * feat(ai): add request handling to ai chatbar (#8700) * feat(ai): add request handling to ai chatbar * fix: test * Added changelog for v4 (#8677) * Added changelog for v4 * updated images to use s3 links * Updated url for images * Added version for docs urls * Reverted version change Co-authored-by: Bijin A B <[email protected]> * Updated the YAML migration text --------- Co-authored-by: Bijin A B <[email protected]> * fix(keybindings): new request in active tab based on active collection (#8703) * Added beta flag for AI (#8706) * chore(coderabbit)/adds coderabbit instructions for adding new file as ts/tsx in bruno app (#8717) * fix(devtools): prevent console panel from bleeding over modals (#8716) * feat(web-buidler): remote artifact builder plugin (#8718) * basic plugin * Apply suggestion from @sid-bruno * fix(settings): Enable App toggle for GQL requests (#8723) * fix(converters): add missing auth mappings on postman export, add additional parameters mapping on postman import (#8494) * fix(import): add Oauth fallback for grant authorization code, parse additional parameters. * feat(import): support NTLM auth import from postman. #BRU-3114 * feat(export): support collection level auth. support awsv4, digest, ntlm, oauth1 and oauth2 auth types. fix bearer type return structure. * test(import): add NTLM, Additional parameters tests. * fix(export): add 'in' key for 'apiKey' auth type * test(export): add test cases for bruno to postman Auth flow. * fix (export): add folder level auth in export and use ensureString for string attributes * fix(import): add missing placement default and remove grant-type redundant logic * fix: revert missed grantType variable * test(export): add auth undefined assertion (code rabbit review) * fix: use common string util method for fallback * added stories and tests for Help component * fix(mountv2): give duplicate-named env variables distinct uids (#8730) * refactor(tests): update data type assertions to use data-selected-type attribute for consistency (#8731) * added stories and tests for accordian * fix(secrets): environment table (#8733) * fix(secrets): environment table * fix: removed useeffect * added introduction md file * test(converters): add round trip tests for Postman <-> Bruno converters (#8534) * test(export): add round trip tests for Postman <-> Bruno converter * fix(export): add unique key for paths to handle duplicates, fix postman collections to handle more code coverage * fix(conveters): add diff enum for reusability * fix: add enum for auth types * fix: CJS to ESM imports * fix: update readme info for round trip * added outlined version for segmented control * updated icons * removed dropdown * chore(eslint): adds eslint config warnings for unused-vars, debuggers, duplicate-imports (#8505) * feat(tests): enhance Playwright configuration for sharded CI runs (#8742) * refactor(ui): extract richtext editor utilities to utils folder * refactor(ui): move useLinkHandlers to utils folder * refactor(ui): extract richtext editor components to components folder * refactor(ui): refactor RichTextEditor toolbar state into custom hooks * test(e2e): fix richtext editor locators and handle new button components * fix(tests-macos): update branch filters for workflow triggers to support release branches (#8752) * fix: encode url for url without protocol (#8756) * fix(cookies): toggle raw mode state in ModifyCookieModal (#8755) * refactor: reorganize RichTextEditor hooks * feat(ai): add focus for prompt input after AI response completion (#8747) * fix(security): overflow on chip list styling (#8748) * feat(converters): add support for script execution flow in yml configuration (#8745) * chore: remove accidentally added non-bruno-app files * feat(collections): open multiple collections from a monorepo (#8724) * feat(collections): open multiple collections at once * refactor(collections): rename open-collection IPC channels * test(collections): e2e coverage for open collection picker and selection modal * refactor(collections): 'no collections found' toast message * fix(collections): import hydrateCollectionWithUiStateSnapshot in workspaces actions * fix(collections): default to no selection and surface open failures * feat(collections): prevent duplicate open collection toasts * fix(collections): update auto close condition for selection modal * test(collections): open collection selection selectors moved to page module * test(collections): match open collection rows by exact title * Merge branch 'main' into feat/open-multiple-collections * fix(workspaces): switch to default workspace on close so header shows correct name (#8425) * fix(workspaces): switch to default workspace on close so header shows correct name * Added the test spec related review. * added e2e test for closing workspace returns to default * added e2e test for closing workspace returns to default * added e2e test for closing workspace returns to default * test(workspaces): used stable test ids for workspace switcher and actions in close-workspace e2e * refactor(ai): update API key handling in openai comp providers (#8749) * refactor(ai): update API key handling in openai comp providers * fix * refactor: simplify rich text editor link management with unified ToolHint components and improved URL validation logic * chore(pr-decription)/updated pr description (#8786) * removed unused stories * removed radio group * chore(eslint)/disable autofix for const (#8760) * chore(eslint)/disable autofix for const * added a config * Apply suggestion from @sid-bruno Co-authored-by: Sid <[email protected]> * Apply suggestion from @sid-bruno Co-authored-by: Sid <[email protected]> * Apply suggestion from @sid-bruno Co-authored-by: Sid <[email protected]> * Apply suggestion from @sid-bruno Co-authored-by: Sid <[email protected]> * lint fix * added inline check * removed comment --------- Co-authored-by: Sid <[email protected]> * updated segment control design * fix: decouple task lists from mixed-content lists and improve markdown serialization for block elements * Fix: binary body lost on importing from postman (#8729) * fix/3118 - Postman Import: Binary Body Type Silently Lost * fix/3118 - Postman Import: Binary Body Type Silently Lost * fix/3118 - Postman Import: Binary Body Type Silently Lost * fix/Added indentation * Import binary body mode * handling else if * Handling example with binary body * file body mode * Add tests for importing Postman binary body requests * Enhance Postman binary body import by inferring content type from file extensions and adding tests for various file types * Add mime-types as an external dependency and implement test for .bin file content type resolution in Postman to Bruno conversion * fix: import statements * fix: e2e tests * refactor: improve test structure and assertions for Postman binary body import --------- Co-authored-by: rajashreehj-bruno <[email protected]> * style: update documentation edit toggle button size to sm * updated outlined styles * style: update inline code and block styling with transparent backgrounds, borders, and light-mode adjustments * fix(timeout): allow inherit request timeout for yaml requests (#8746) * fix(timeout): allow inherit request timeout for yaml requests * fix: add test.step for timeout * fix(timeout): normalize resolveTimeoutSetting to reject non-finite/negative timeouts * style: update code and block border radius to use base theme radius * fix(environment): auto save on env table removing some characters (#8732) * fix(environment)/auto save on env table * moved autosave tests * added locators * added test for multi line * updated name * feat(code-mirror-search): add replace and replace-all with search position, debouncing and tests (#8715) * feat(environment): add default env to presets (#8612) * fix: Folder Sequencing When we try to move any folder at the bottom of the folders list (#8722) * fix: Folder Sequencing When we try to move any folder at the bottom of the folders list * fix(bruno-app): use path-segment ancestry for folder drop checks to avoid sibling-prefix false positives * fix(bruno-app): allow folder to be reordered to bottom via dropType edge zones (BRU-1112) * ci: re-run benchmark check (flaky perf gate) * docs(bruno-app): updated stale dropType comments to above/below terminology * Added the fix for bru.runner.stopExecution() while running collection run from tests (#8720) * Added the fix for bru.runner.stopExecution() while running collection run from tests * resolved the code review for coderabbit * fix * feat(collections): add description text to open collection selection modal (#8793) * fix(ws): remove auto-reconnect in websockets (#8605) * feat: add preserve scripts option for Postman import/export (#8726) * feat(import): add preserve scripts option for Postman import/export * test(import): add postman preserve scripts coverage * fix(import): align preserve scripts option place and color * fix(import): address coderabbit comments * test(import): assert export scripts and centralize import locators * fix(export): validate empty filename, dismiss dialogs between tests * refactor(import): use options object for convertCollection config params * refactor(import): remove redundant check from importPostmanV2CollectionItem * Added the ignore for the collection nested folders (#8725) * Added the ignore for the collection nested folders * Removed the unignored functionality for Collection folder for now * require path boundary in folder ignore matching to prevent prefix and empty-pattern over-matching * fix(collection): deep-cloned bruno config before transform so ignore/update never mutated the object returned to redux * resolved the coderebbit review comments * fix:env configure remains visible (#8530) Co-authored-by: Adwait Aayush <[email protected]> * fix:url truncates in docs (#8468) * fix:url truncates in docs * refactor:added unit testcases made functions modular * Keep the default selected as none in the environments (#8785) * feat(request): warn when binary body file is missing on disk (#8753) * fix/request - Binary body type - show warning on file not exists in system * Made filename extraction OS-agnostic. * Use theme tokens for warning colors in this styled-component block. * Refactor FilePickerEditor to use useMissingFileCheck hook for file existence validation and improve warning display. Introduced new hook for checking missing files and updated tests to reflect changes in file picker behavior. * Enhance FilePickerEditor: Update title handling for single/multiple filenames and improve warning tooltip layout with icon integration. Adjust StyledWrapper to utilize theme-based border radius for consistency. --------- Co-authored-by: rajashreehj-bruno <[email protected]> * updated test ids * added dev tag so stories shows in docs only * added disabled * fix: failing test case fix (#8801) * feat(db): sqlite as a re-usable SDK for secondary queries (#8533) * chore: PR checklist update (#8806) * fix: avoid network probe in PAC myIpAddress (#8588) * fix * Fix/collection runner loader issue (#8783) * fix(runner): Collection Runner - Loader still keeps running even after Cancelling the execution * added a test id for the action buttons * removed onborading section * updated bg of segment control * added disabled color * fix(bruno-response): normalize response header name lookup to be case-insensitive (#8461) * fix(bruno-response): normalize header name lookup to be case-insensitive * fix(bruno-response): handle non-string header names in getHeader method * chore: resolve GitHub review conversations * fix(dev-tools): console and network filter dropdown position to top if no space (#8713) * fix(dev-tools): console and network filter dropdown scroll * fix(ws-replace)/add height for ws msgs to fix search overlap * fixed the accordion's isSearchOpen goes stale on collapse * fix(workspace): notify about collections that fail to open in Workspa… (#8719) * fix(workspace): notify about collections that fail to open in Workspace Home * Resolved the coderabbit comments * test(workspace): added e2e coverage for collections that fail to open * resolved the code rabit comments * refactor(ui): changed data-testid prop on StatusBadge for consistency * fix(workspace): exclude failed-to-open collections when reopening on config update * test(workspace): added the switch-time aggregated toast for unopenable collections * test(workspace): guard that config updates don't reopen failed-to-open collections * feat(snapshot):persisting sidebar state in the snapshot (#8328) * chore: new folder shortcut (#8805) * refactor(ai): moved AI Assist from floating overlay into request pane and collection/folder settings tab bars (#8693) * refactor(ai): moved AI Assist from floating overlay into request pane and collection/folder settings tab bars * test(ai): added e2e coverage for AI Assist tab-bar placement across request pane, collection and folder settings * test(ai): added e2e coverage for AI Assist tab-bar placement across request pane and settings * test(ai): extended AI Assist tab-bar placement coverage to graphql, grpc, websocket, app tab and default script sub-tab * scoped AI Assist placement assertions to the tab bar and added a settings tab bar test id * feat(auth-headers):handling authorization header leaks to third party servers on redirect (#8380) * feat: add forwardAuthorizationOnRedirect setting to allow stripping sensitive headers on cross-origin redirects * feat: add forwardAuthorizationOnRedirect to opencollection types * fix: restore missing forwardAuthorizationHeader config lines in runners and filestore * feat: apply secure forwardAuthorizationHeader default to Insomnia and OpenAPI imports * refactor: remove stale module augmentations for GraphQL and HTTP request settings * refactor: centralize default HTTP request settings and improve test step organization * chore: update @opencollection/types to version 0.10.0 across packages * fix: handle cross-origin redirect auth stripping, and optimize Redux settings initialization * refactor: fix formatting in collection schemas * chore: remove unused data-testid from Settings toggle * refactor: simplify forwardAuthorizationHeader serialization logic with nullish coalescing * refactor: migrate redirect auth strip E2E tests to use common locators utility * refactor: use toBool helper in bruToJson * feat: update forwardAuthorizationHeader to respect Postman protocol profile behavior * refactor: move DEFAULT_HTTP_ITEM_SETTINGS to bruno-common and update UI layout and redirection logic * refactor: introduce type conversion helpers to simplify HTTP request setting parsing * tests: support Postman protocolProfileBehavior for authorization header forwarding * feat: add test ID to forward auth toggle * feat: enable URL encoding by default in request settings * refactor: centralize isSameOrigin utility and simplify GraphQL settings conversion logic * refactor: replace manual type checks with toBool and toNumber helpers in collection converters * refactor: migrate request settings test locators to page object model * chore: set default encodeUrl to false and add line breaks for utils * test: add regression tests for encode URL setting default behavior * refactor: migrate encode-url-default-behaviour tests to use pageWithUserData fixture * updated discable dtext opacity * fix(node-vm): resolve npm modules from additionalContextRoots via native walk-up (#8538) * fix: resolve npm modules from additionalContextRoots node_modules in NodeVM When shared script folders configured via additionalContextRoots have their own node_modules, the NodeVM runtime now searches those directories for npm packages instead of only checking the collection and Bruno paths. * fix(node-vm): enhance npm module resolution security by restricting access to ancestor node_modules Added a new function to compare resolved npm module paths against allowed roots, ensuring that modules from ancestor directories outside the configured additionalContextRoots are not accessible. Updated the loadNpmModule function to utilize this security check during module resolution. Added tests to verify that ancestor node_modules cannot be accessed when not explicitly allowed. * feat(tests): add integration tests for additionalContextRoots npm module resolution Introduced a comprehensive set of integration tests to validate the resolution of npm modules from additionalContextRoots in the CLI. The tests ensure that shared libraries are correctly resolved, ancestor node_modules are inaccessible, and that collections can successfully utilize shared scripts. Additionally, created fixture files to support the testing environment, including workspace configurations and sample scripts for both collections A and B. * chore(tests): update .gitignore to track specific node_modules for e2e tests Modified .gitignore to include tracking for node_modules in test fixtures, ensuring that fake npm packages are available for end-to-end tests. Added new files for 'forbidden-lib' and 'signature-utils' to support testing scenarios. * test(node-vm): add test for resolving npm modules via symlink in additionalContextRoots Implemented a new test to verify that npm modules can be resolved correctly when additionalContextRoots points to a symlink. The test ensures that the symlinked library is accessible and that the context variable is set appropriately, enhancing the coverage for npm module resolution scenarios. * feat(node-vm): enhance npm module resolution with additional context roots Added support for resolving npm modules from additional context roots, including symlinked modules. Introduced new functions to validate module paths against allowed roots, ensuring security and proper resolution of transitive dependencies. Updated the loadNpmModule and createNpmModuleRequire functions to incorporate these changes, improving the flexibility and reliability of module loading in the NodeVM context. * feat(node-vm): improve npm module resolution for linked packages Enhanced the module resolution logic to allow internal relative requires within npm-linked packages, even when their physical location is outside declared allowed roots. Introduced a new function to find the closest package root, ensuring that internal dependencies can be resolved correctly. Updated tests to validate this behavior, confirming that the system handles linked packages as expected. * feat(node-vm): support subpath imports for npm-linked packages Enhanced the module resolution logic to allow subpath imports from npm-linked packages, ensuring that imports like `require('linked-pkg/utils')` are correctly resolved. Updated the `isModuleLinkedFromAllowedRoot` function to utilize bare-name lookup for improved accuracy. Added tests to validate this new behavior, confirming that subpath imports function as expected in the NodeVM context. * refactor(tests): remove forbidden-lib tests and update integration scenarios Eliminated tests related to the forbidden-lib package to streamline the test suite, ensuring that ancestor node_modules are not resolvable. Updated integration tests for additionalContextRoots to reflect changes in request counts and improved clarity in test descriptions. Adjusted workspace configurations to enhance overall test coverage and maintainability. * refactor(cjs-loader): simplify module resolution documentation Updated comments in the cjs-loader.js file to clarify the module resolution order, removing redundant explanations while maintaining essential details. This change enhances the readability and understanding of the module loading process in the NodeVM context. * refactor(cjs-loader): improve comments and clarify module resolution logic Updated comments in cjs-loader.js to enhance clarity regarding module resolution, specifically indicating fallback behavior when modules are not found in the collection. Adjusted the path used in createNpmModuleRequire for improved accuracy in module loading. * feat(tests): add additional-context-root-lib and update workflows Introduced the additional-context-root-lib package with its dependencies and updated relevant workflows to install this new library. Adjusted the CLI test and flaky test detector workflows to include installation steps for the additional-context-root-lib, ensuring proper setup for testing scenarios. * refactor(tests): update npm module resolution test for additionalContextRoots Revised the test case to ensure that requiring an npm package from a sibling additionalContextRoot fails as expected. Updated the test description for clarity and adjusted the script to reflect the intended behavior of module resolution, emphasizing the limitations of cross-root discovery in the NodeVM context. * refactor(tests): clean up comments in node-vm sandbox tests * refactor(tests): update fixture URLs in additional-context-roots tests Modified the URLs in the .bru fixture files to point to the local testbench server instead of an external service. This change ensures consistent test behavior and eliminates reliance on external resources during testing. * refactor(tests): enhance node-vm sandbox tests with symlink support Introduced a symlink support check in the node-vm sandbox tests to conditionally skip tests on Windows where symlink creation is restricted. Refactored the test setup to utilize a new `makePkg` function for creating package directories and files, improving code readability and maintainability. Updated relevant tests to leverage this new structure, ensuring consistent behavior across different environments. * refactor(setup): preserve specific node_modules during cleanup Added a mechanism to preserve certain `node_modules` directories during the cleanup process in the setup script. This change ensures that fixture data remains intact for testing, specifically for directories related to additional context roots. --------- Co-authored-by: lohit-bruno <[email protected]> * feat(cli): add --global-env-var to override global environment variables at runtime (#8620) * feat(cli): add support for overriding global environment variables with --global-env-var option - Introduced the --global-env-var option to allow users to overwrite global environment variables during command execution. - Updated the command handler to validate and process global environment variable overrides. - Enhanced the persistence logic to ensure that global environment variable overrides are handled correctly without leaking into the global environment file. - Added tests to verify the correct behavior of global environment variable persistence. * test(cli): enhance integration tests for global env var overrides - Added checks to ensure that runtime overrides do not persist to the global environment file. - Updated fixture scripts to reflect the expected behavior of global environment variable persistence. - Improved the substitution logic for dynamic URLs in test fixtures to ensure accurate testing of overrides. * refactor(tests): streamline CLI test arguments and error handling - Refactored CLI test cases to use a consistent argument array for command execution. - Improved error handling by consolidating error message construction for better readability. - Ensured that the tests maintain clarity while verifying global environment variable overrides. * fix: remove global env file check for global overrides * refactor(persist-variables): enhance global environment variable handling - Introduced a new `globalOverrides` option to manage global environment variable overrides more effectively. - Updated logic to ensure that both local and global overrides are correctly applied and do not persist unintended values to the global environment file. - Improved comments for clarity on the behavior of global environment variable persistence. * fix: address review comments * fix: address review comments * removed chnages which were out of scope * remove unused no-global-env fixture * refactor(tests): update integration tests for global env var overrides - Removed outdated fixture files related to global environment variable overrides. - Enhanced the test setup to dynamically create necessary workspace and collection structures. - Improved clarity in test descriptions and logic for validating that transient overrides do not persist to the global environment file. * refactor(tests): simplify global env var test setup * refactor(tests): remove outdated test for global env var persistence * feat: add markdown mode to documentation editor and upgrade rich text editor extensions * Fix: added actions for post reposne vars in yml (#8815) * feat: introduce DocsEditor component and useDocsEditingState hook to support rich text editing in collection documentation * fix: add dynamic font size adjustment for CodeMirror info display (#8817) * fix: add dynamic font size adjustment for CodeMirror info display * test: implement comprehensive E2E test suite and resolve rich text editor formatting issues * feat(envs): adding search filter to environment selector dropdown (#8277) * feat: adding search filter to environment selector dropdown * fix: making the search input sticky * test: updating tests into individual tests for environment selector search * fix: avioding searchinput refocus if already focussed * tests: ensuring dropdown open for tests and adding first printable key test * refactor: replace inline search logic with reusable SearchInput component in EnvironmentSelector * refactor: standardize environment selector locators and test actions for improved search functionality testing * test: update environment search casing, improve tab state handling in actions * refactor: decouple and centralize collection header locators and utility functions into dedicated module * refactor: migrate environment selector locators to a dedicated utilities file and update collection header references * refactor: consolidate collection header locators and update environment selector test utilities * test: add and implement closeEnvironmentSelector utility to clean up environment selector state in tests * refactor: simplify environment selector lifecycle management by centralizing open/close logic in test hooks * refactor: lift search state to environment selector and clear input on close * test: refactor EnvironmentListContent unit tests to use a wrapper component for state management and update clear button selector * fix(locators): reverting environment selector locator reference * refactor: clear search input when switching environment tabs and ensure persistent visibility of configure button * test: add global environments data and verify search functionality in environment selector --------- Co-authored-by: sachin-thakur-bruno <[email protected]> * feat(client certs): add global client certs and allow disabling individual client certs. (#8751) * feat: add client certificates to global preferences * feat(client certificates): apply global client certs on requests, allow disabling individual certs at global and collection level * fix: create list group component. modify client certificate UI to match new mockup. * test(client certs): setup client certs test suite and add CLI test cases for client certs * test(client certs): add E2E cases for collection and global client certs * fix: fix code review comments from claude * fix: count test failures using filter to remove duplicate counting. * fix: minor UI fixes to support storybook * fix: remove duplicated onboarding config from test preferences.json * fix: use testIds on test and ws responses for better test reachability. use the new test-ids on locators * fix: coderabbit fixes * fix: fix lint issues * fix: review comment changes for test cases * fix: add timeout for the fixture setup * fix: add break for grpcCurl to match first case * test: prevent stale response reads in client-cert e2e specs * fix: add separate fixture for sandbox modes in WSS to prevent stale close connection message * fix: add regex matching for ws assertions to reduce flakiness * fix: fix list group "add button"'s icon alignment * fix: add save button to collection client certificates * test: add collection client certificate precedence test case * feat(presets)/updated the requests to use segmented control (#8816) * feat(presets)/updated the requests to use segmented control * updated icons * yml migration rework (#8795) * feat: extend markdown linkify support for relative assets in rich text editor * feat: add color-scheme support for task list items in editor styles * refactor: updating file/folder structure for docs editor files * refactor: encapsulate DocsAction styling in a new StyledWrapper component * refactor: update richtext editor tests to import utilities from actions instead of utils * fix:cmd+w now works for transient tabs (#8429) * fix:cmd+w now works for transient tabs * test: verify URL is preserved after saving and closing a transient tab * test: use centralized page locators and test.step in the transient close spec * refactor: branch on transient at the save dispatch site * refactor:use if/else branches in onSaveAndClose --------- Co-authored-by: Adwait Aayush <[email protected]> * Fix: Description missing for the import export yml for the environments (#8822) * Fix: Description not there in the import export yml for the environments * Comments addressed * Comments addressed * security(ipc): confine renderer file writes to known collections (#8274) * fix(openapi):strip trailing dots from operation names on import (#8812) * fix(openapi):strip trailing dots from operation names on import * fix(openapi): strip trailing dots from environment names on import --------- Co-authored-by: Adwait Aayush <[email protected]> * feat(rich-text-editor)/scroll persist * fix:populate collection & folder docs on OpenAPI/swagger imports (#8803) * fix:populate collection & folder docs on OpenAPI/swagger imports * fix(openapi): coerce spec descriptions to strings before use * test(openapi): extract findRequestByName/findFolderByName into shared helper * fix:guard against object names --------- Co-authored-by: Adwait Aayush <[email protected]> * fix(generate-code): generate code for url interpolation (#7308) * fix(presets)/ux fixes for dropdown and icon spacing (#8827) * fix ux * updated padding * fix(secrets): block duplicate secret names to prevent value loss (#8750) * refactor: migrate documentation edit toggle to use test ID instead of class selector * refactor: migrate collection and folder documentation edit toggle to shared DocsAction component * chore: enhance claude rules & skills * feat: support drag-and-drop and alphabetical sorting for variables (#8603) * test: update doc toggle locators to use test-ids * Mock Server Implementation (#8734) * reported how many collections failed to open on workspace load (#8831) * reported how many collections failed to open on workspace load * Added the failed collection in the overview list of collections in the workspace * test: fix the draft indicator tests for collection client certs (#8824) * fix(generate-code): encode a literal colon in the path when the toggl… (#8834) * fix(e2e): Playwright failures from mock server and lazy mount (#8835) * fix: green Linux Playwright failures from mock server and lazy mount Unscoped Create clicks collided with the new mock-server button, and sidebar-created examples open in edit mode so view-mode title asserts were stale. Cross-format drops into unmounted workspace collections also failed path confinement; mount on drop and treat last-opened collections as known roots. * Update packages/bruno-electron/src/ipc/collection.js * refactor: simplify collection path retrieval in findCollectionPathByItemPath function * test: update method search test to use test-id for environment selection * fix: simplify watcher management in CollectionWatcher class * feat(presets)/updated presets design (#8828) * feat(presets)/updated presets design * fixed text * updated the text * removed styles * ci: move all linux to self hosted (#8791) * feat(docs): syntax highlighting for code blocks in rich text docs (#8670) * feat(presets)/updated dropdown with menu dropdown and label weight ux changes (#8841) * feat(presets)/updated dropdown with menu dropdown and label weight ux changes * removed the comment * used button for dropdown trigger * feat(tests): enhance CodeEditor and EditorCodeBlock tests with additional mocks and configurations (#8858) * fix:sorting now works for secrets tab (#8871) * fix(mount): hydrate websocket message uids in the cached mount path (#8862) WS message expand/collapse is keyed by the message uid, so a message without one cannot be opened at all — the toggle bails on a falsy uid and every row renders with the same undefined React key. The v1 mount path hydrated request.body.ws (via hydrateRequestWithUuid), but mount v2's uid list omitted it. With File Cache enabled the tree is built from the cache on cold start, so every WS message arrived with no uid and its body could not be expanded. It only reproduced after a restart because live edits during a session still flow through the collection watcher's v1 hydration. Since v2 seeds uids deterministically from the file path, expanded-message state now also survives a restart instead of resetting. * fix:keep sort column header from shifting when the arrow appears (#8833) * fix:keep sort column header from shifting when the arrow appears --------- Co-authored-by: Sid <[email protected]> * fix:change-version modal ui (#8735) * fix:change-version modal ui * feat: add migrate-to-YML pill to collection header (#8882) * fix(mock-server): bring the UI in line with the rest of Bruno (#8880) * fix(mock-server): bring the UI in line with the rest of Bruno * fix --------- Co-authored-by: Utkarsh <[email protected]> * fix(ws): disable message queuing when in intermediate connection states (#8879) * feat: add disabled state to SendButton based on connection status * Update packages/bruno-app/src/components/RequestPane/WsQueryUrl/index.js Co-authored-by: Chirag Chandrashekhar <[email protected]> * fix: update WebSocket connection handling and improve run button behavior --------- Co-authored-by: Chirag Chandrashekhar <[email protected]> * fix(proxy): update timestamp label format (#8870) * fix(proxy): update timestamp label format and enhance timestamp utility function * fix(tests): update timestamp regex to match AM/PM format in system proxy tests * fix(timestamp): enhance formatProxyTimestamp function to replace non-breaking spaces and update regex for system proxy timestamp * fix: persist additional request values in preferences general tab save (#8823) * fix (transient-request): unable to create transient request when preset is websocket (#8889) * fix(transient): updated the websocket type key from websocket to ws to match the key coming from presets * test(transient): added tests, locators, and actions to validate the default request type of transient request when a preset is selected * refactor(import): imported the REQUEST_TYPE (aliased) from common utils and removed unused imports * fixes: OpenAPI Spec Viewer: throws resolver errors for `$ref` schemas (#8892) * fix(app): global environment variables for apps (#8900) * feat(mock-server): enhance MockResponseRequestPane with method selection and other minor tweaks (#8885) * fix(auth): stop AWS V4 auth headers from leaking on cross-origin redirects (#8893) * fix: strip AWS Signature V4 headers on cross-origin redirects when authorization forwarding is disabled * fix: prevent AWS SigV4 header leakage on cross-origin redirects by isolating signature removal from authorization header forwarding * refactor: update formatting of AWS SigV4 redirect comment block for readability * refactor: simplify response text extraction in redirect authentication tests using innerText * fix(editor): allow app keybindings if that keybindings is not present in rich text editor (#8894) * fix(doc-editor)/key bindings for doc editor * fix(mock-server): improve mock response name validation (#8908) * feat(migrate): enhance migration modal to handle collection drafts (#8899) * fix(codemirror-search)/keybinding for focusing search and replace inside the search container (#8895) * fix(sidebar): prevent drag divider from disappearing on zoom-out (#8266) * fix(sidebar): prevent drag divider from disappearing on zoom-out * fix(sidebar): keep resize divider visible across tabs and zoom levels * refactor: remove AI documentation assistant and related context payload generation from documentation components (#8921) * fix(editor)/add guessed language in language dropdown picket (#8925) * fix(editor): tab indentation on code blocks (#8926) * fix(git): use removePath for failed-clone cleanup ipc/git.js imported removeDirectory from utils/filesystem, which only exports removePath. On a failed clone the cleanup branch threw "TypeError: removeDirectory is not a function", replacing the rejection and hiding why the clone actually failed. removePath removes recursively, which is the semantics this call wanted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore: restore upstream code the fork had stripped These files carried no RestWolf feature - the earlier squash-sync had rolled back upstream improvements, and the merge preserved those rollbacks because upstream's later edits did not textually conflict. - CreateCollection / CreateWorkspace: name trimming and validation messages - ExampleTab: exampleIndex lookup, matching the accessor restored in tabs.js and the snapshot serializer - insomnia converter specs, request-pane-interactivity, create-collection and create-workspace e2e specs Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore: restore remaining upstream code stripped by the fork Same pattern as the previous commit, found by diffing the merged tree against upstream/main for net deletions: - RequestTabPanel / ExampleItem: exampleIndex plumbing - insomnia-to-bruno: empty-mimeType text body handling, covered by the insomnia specs restored earlier (now passing) Remaining divergence from upstream is fork features and branding only: Azure Vault, saved auth modes, tab retention, theme colours, RestWolf branding, auto-updater, PostHog removal, and trimmed docs. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(git): add Git UI tab and branch chip Upstream ships the git engine in bruno-electron/src/utils/git.js but wires only clone to IPC, so none of it is reachable from the app. This registers the rest and adds the UI. IPC (ipc/git.js): status, init, stage, unstage, discard, commit, file diff, fetch, pull, push. Each mutating handler returns the recomputed panel state so the renderer never has to re-query. UI: a Git UI tab (left panel with commit box and changed-file list, right pane with fetch/pull/push and ahead-behind), opened from a branch chip in the collection toolbar. Both read shared state via the useGitStatus hook. Two quirks in the existing utils this works around: - pullGitChanges rejects unless given an explicit merge strategy - getUnstagedFileDiff matches absolute paths, while git status reports repo-relative ones Verified against a real repository: status, branch, remote and diffs; plus a full init/stage/commit/edit/diff/discard round trip on a scratch repo. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(theme): move accent colour into the Appearance dropdown The fork repurposed ColorPicker to take value/label/onReset for the accent colour, but the merge restored upstream's per-environment call sites, which pass a `color` prop that component no longer reads. Both environment panels therefore rendered the accent picker and edited the app accent. Removes the picker from both environment panels and from the Themes preferences pane, and puts it in the Appearance dropdown behind the palette button in the status bar, where it edits the accent for whichever theme is on screen. feat(git): branch switching in the Git UI Adds a renderer:git-checkout handler and a branch switcher in the panel footer. A checkout that would overwrite local edits is left to fail, and git's own message is shown in the panel - matching how VS Code reports it - rather than being forced or auto-stashed. Verified: create-and-switch, clean switch, and a dirty switch refused with "Your local changes to the following files would be overwritten by checkout", with the edit left intact. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(theme): keep the accent picker inside the Appearance menu .theme-menu had a fixed 325px height, so the accent row rendered past the bottom edge and overlapped the status bar. min-height lets the menu grow while keeping its size steady when the theme lists are short. The swatch's own dropdown is absolutely positioned below its trigger, which falls off-screen for a menu anchored to the status bar, so it is flipped to open upward within this section. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore: remove screenshot committed by mistake Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(git): pass remote and branch to push and pull pushGitChanges looks the branch up by name (branchSummary.branches[remoteBranch]) and rejects with "Branch undefined does not exist" when it isn't supplied, so Push failed from the panel. Both handlers now default the remote to origin and resolve the current branch. Verified against a local bare remote: commit leaves ahead=1, push clears it, a remote commit shows behind=1 after fetch, and pull brings it down. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(git): sync button and visible feedback for git operations Git operations succeed silently, so a push that worked and a push that failed looked identical - the error banner only rendered inside the sidebar's Changes section, which is collapsible and sits away from the buttons. Every operation now reports through a toast, and the error banner also shows next to the fetch/pull/push controls. Adds a Sync button that pulls before pushing, matching VS Code's ordering so a diverged branch does not hit a non-fast-forward rejection. Its label states what will move: "Sync 2 down, 1 up", "Push 3 commits", "Pull 1 commit", or "Sync Changes" when level. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(secrets): secret managers with ordered vault tiers Replaces the single enable-and-configure Azure vault in General preferences with a Secrets Manager section modelled on how Bruno configures providers: add a provider, pick Azure Key Vault, enter connection details, test the connection. Providers are listed in precedence order. Environments gain an ordered list of vault secret names on the Secrets tab, matching the vault-teller tier layout (tenant, cluster, global). Resolution is first-match-wins per key, so the most specific tier sits at the top - the same precedence as vault-teller's tenant ?? cluster ?? global. Fetching shows what each tier actually contributed: a source dropdown switches between the merged view and any single secret, and keys claimed by a higher tier are struck through with the winner named, so a shadowed value is visible rather than looking ignored. Credentials are now encrypted at rest via the existing safeStorage-backed helpers instead of sitting in plain text in preferences.json, and the client secret is never sent to the renderer. The ordered secret names persist as a VAULT_SECRETS environment variable so they travel with the collection in git; the previous VAULT_SECRET is still read so existing environments keep working. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(secrets): make the vault panel reachable in global environments The panel was passed as renderExtraButtonContent, which the table renders inline beside Save and Reset, so a block-level panel with tables was crushed into that row. It is now a sibling of the table inside a scrolling column, since neither the environment content area nor the table wrapper scrolls - without that, a fetched result pushed the table's Save button out of reach. The resolved table is capped and scrolls on its own, and the panel header carrying Apply is sticky so it stays available while reading a long tier. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(secrets): pin each vault secret to a provider Each entry on the environment's Secrets tab now carries a vault dropdown, so a tier can name which provider serves it rather than relying on lookup order. "Any vault" keeps the previous behaviour of trying each configured provider in turn. A pinned vault is honoured or reported: an unknown vault name, or a secret missing from the pinned vault, is surfaced as an error instead of falling back to another provider, which would otherwise hand back a different environment's values under the same key. The choice persists by vault name rather than local id so it still resolves for a teammate whose provider has a different id. Entries serialise as "<vault>:<secret>" in VAULT_SECRETS, with bare names still accepted. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * style(secrets): fix operator indentation in the resolver Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(secrets): clear all vault secrets from an environment Reset reverts the table to the saved environment, so once fetched secrets have been saved there is nothing for it to undo and it appears to do nothing. Removing them meant deleting each row by hand. Adds a Clear secrets action beside Apply, giving the bulk add a matching bulk removal. It drops the rows from the table only, so the environment still has to be saved and a mis-click is undone by Reset. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore(release): bump RestWolf to 4.0.0 Major bump for the upstream v3-to-v4 merge and the features built on it: Git UI, secret managers with ordered vault tiers, and the accent colour move. Version lives only in packages/bruno-electron/package.json - electron-builder reads it for artifact names, and scripts/release.js bumps it from there. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Pooja <[email protected]> Co-authored-by: Sundram <[email protected]> Co-authored-by: Bijin A B <[email protected]> Co-authored-by: gopu-bruno <[email protected]> Co-authored-by: naman-bruno <[email protected]> Co-authored-by: ravindra-bruno <[email protected]> Co-authored-by: Abhishek Patil <[email protected]> Co-authored-by: Gopi-bruno <[email protected]> Co-authored-by: sachin-bruno <[email protected]> Co-authored-by: Sid <[email protected]> Co-authored-by: Chirag Chandrashekhar <[email protected]> Co-authored-by: shubh-bruno <[email protected]> Co-authored-by: Jiawen Geng <[email protected]> Co-authored-by: anusree-bruno <[email protected]> Co-authored-by: Rohan-Bruno <[email protected]> Co-authored-by: sachin-thakur-bruno <[email protected]> Co-authored-by: Ryan <[email protected]> Co-authored-by: shubh-bruno <[email protected]> Co-authored-by: Utkarsh <[email protected]> Co-authored-by: morsh-bruno <[email protected]> Co-authored-by: sanish chirayath <[email protected]> Co-authored-by: rajashreehj-bruno <[email protected]> Co-authored-by: adwait-bruno <[email protected]> Co-authored-by: Adwait Aayush <[email protected]> Co-authored-by: Rayan Salhab <[email protected]> Co-authored-by: sharan-bruno <[email protected]> Co-authored-by: lohit-bruno <[email protected]> Co-authored-by: arpit-bruno <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Description
BRU-3411
Adds
@usebruno/sqlite, a reusable SQLite SDK for secondary/derived data (network history, timelines, caches, and other non-collection state) that keeps SQL out of the renderer and gives the app a typed, cached data layer.What it provides
@usebruno/sqlitepackage with two entry points:@usebruno/sqlite(/node) — main process. Owns the DB (built-innode:sqlite), runs migrations, and executes statements.@usebruno/sqlite/web— renderer.SQLiteProvider+useSqliteQuery/useSqliteMutationReact Query hooks that call statements over IPC. SQL never ships to the renderer..tsfiles exportingup/down. They apply automatically in order on open, support downgrade rollback via DB-storeddownstatements, and are content-hashed into a_migrationstable so an already-applied migration can't be silently modified.-- name: X :one|:many|:exec), compiled at build time into a typed registry. Params are object-only (named@parambinding).{ name, tables }over a single IPC channel; the renderer invalidates any read query whose tables intersect the changed set, so main- and renderer-initiated writes both refresh live queries (across windows).npm run migration:verifyreplays every migration against a throwawayVACUUM INTOcopy of a real database (set viaDB_PATH), exercising them over real data without touching the source DB.Wiring
bruno-electron: registers SQLite IPC on startup and closes the DB gracefully on quit.bruno-app: wrapped in<SQLiteProvider>over the existingipcRendererbridge.Tests: migration runner (apply, idempotent, drift detection, rollback), statement execution, VACUUM statement construction, and React Query invalidation behavior.
Contribution Checklist:
Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.
Publishing to New Package Managers
Please see here for more information.
Summary by CodeRabbit
@usebruno/sqlitepackage and wired it into the desktop app with main-process IPC support and renderer integration.