feat(variables): persist scripted variable changes by default + re-enable disabled scripting APIs (#8315)

* feat(variables): add variable persistence with scripting

feat(collections): implement script-driven update for collection variables, ensuring direct root modification and draft synchronization

feat(collections): enhance script variable management with baseline tracking and draft preservation

* feat(variables): add runtime variable updates and optimize disk writes by implementing dirty flags

fix(collections): handle errors during environment persistence in script execution

feat(collections): implement baseline clearing for script execution and optimize variable update handling

feat(tests): add default persistence tests for environment variables and update runtime variable handling

refactor(collections): streamline variable update handling and improve draft management by removing redundant comments and optimizing code clarity

test(collection-vars): add verification for draft edits and script variable visibility in collection settings UI

refactor(collection-vars): update header value selection logic for improved clarity and accuracy in draft isolation tests

* feat(global-environments): enhance global environment updates to resolve stale active UIDs and improve persistence logic

- Updated the `updateGlobalEnvironments` reducer to handle stale active UIDs by matching against environment names.
- Improved the logic for setting global environments and active UIDs to ensure consistency after disk reloads.
- Removed outdated tests related to persisted values in favor of more relevant assertions for environment variable handling.

* feat(variables): enhance typed value handling and persistence in global and collection environments

- Added tests to infer data types (number, boolean, object) when setting environment and collection variables.
- Updated the logic to preserve existing data types when variables are not modified by scripts.
- Implemented dirty flags to track changes in typed variables, ensuring accurate persistence across sessions.
- Refactored related tests to verify the correct behavior of typed variables in various scenarios.

* refactor(variables): streamline data type inference and enhance deletion methods

- Removed redundant data type inference logic from global and collection variable updates to simplify the codebase.
- Updated deletion methods in the Bru class to use Object.keys for improved resilience against user-defined properties.
- Added tests to ensure deletion methods function correctly even when properties are shadowed.
- Enhanced clarity in draft merge tests by standardizing keyboard shortcuts for selecting all text.

* fix(tests): correct variable naming and improve environment panel interactions

- Updated test cases to reflect the correct variable name 'wasSaved' instead of 'was-saved'.
- Modified environment panel interaction to remove forced click, enhancing test reliability.
- Added a utility function to close the environment panel in safe mode tests for better readability and maintainability.

* feat(runtime): enhance variable management and cleanup logic

- Introduced a new method to clear script-driven variable baselines for collections, ensuring no stale data leaks into new requests.
- Updated the handling of runtime variables in the Bru class to track changes with a new dirty flag, improving state management.
- Refactored the application of script environment variables to prevent direct mutations, ensuring immutability and cleaner state updates.
- Enhanced the response handling in the script runtime to conditionally include runtime variables based on their dirty state.

* feat(variables): improve request handling and state management for collections and environments

- Enhanced event listeners to clear global environment baselines on both 'testrun-started' and 'request-queued' events, preventing stale data issues.
- Updated global environment and collection variable update events to ignore stale updates from superseded requests, ensuring accurate state management.
- Refactored the Bru class to optimize variable management, including checks for existing keys before updates and deletions, improving performance and reliability.
- Introduced request UID tracking to maintain consistency across variable updates during concurrent requests.

* refactor(collections): update action to clear script variable baselines

- Replaced the dispatch of `_clearScriptGlobalEnvBaseline` with `clearScriptVariableBaselines` to improve clarity and maintainability in the Redux action handling for collections.

* feat(environments): introduce getScriptModifiedKeys utility for improved variable management

- Added a new utility function, `getScriptModifiedKeys`, to identify keys modified by scripts relative to a baseline, enhancing the handling of data types during variable updates.
- Updated the application of script environment variables to prevent overwriting user-defined draft changes during no-op writes.
- Refactored related logic in collections and global environments to utilize the new utility, ensuring accurate state management and improved clarity in the Redux slices.

* refactor(global-environments): simplify active UID resolution logic in updateGlobalEnvironments reducer

- Streamlined the logic for resolving the active global environment UID by consolidating conditions into a more concise format.
- Removed outdated comments to enhance code clarity and maintainability.
- Updated tests to ensure accurate resolution of active UIDs based on incoming environment data.

* refactor(tests): remove outdated comments and streamline environment variable row expectations

- Eliminated comments related to state sync and inference issues to enhance code clarity.
- Adjusted expectations for environment variable row rendering in tests, focusing on relevant assertions.

* feat(tests): add comprehensive tests for secret variable persistence in environments

- Introduced new test cases to validate the preservation of secret variables when updated via scripts in both collection and global environments.
- Implemented tests to ensure that secret values are encrypted before storage and can be correctly decrypted for subsequent requests.
- Added fixtures and environment configurations for testing secret variable behavior in both bru and yml formats.
- Enhanced utility functions for managing environment configurations and interactions within the test suite.

* feat(tests): enhance environment variable tests and add global variable persistence

- Updated MultiLineEditor and SingleLineEditor components to include data-testid for secret reveal toggle buttons, improving testability.
- Introduced new tests for global environment variable persistence, ensuring non-secret variables survive app restarts and are correctly interpolated.
- Added fixtures for workspace and collections to support the new global variable tests, enhancing the overall test coverage for environment management.
- Refactored utility functions to streamline interactions with environment variables in tests.

* refactor(collections): optimize environment and collection saving logic

- Simplified the persistence logic for active environments by directly constructing the environment copy, reducing unnecessary cloning.
- Updated the collection saving process to utilize the fresh collection state, ensuring accurate data is saved without drafts.
- Enhanced error handling during the save operations to improve reliability and maintainability.

* feat(tests): implement collection variable persistence tests

- Added multiple test cases to validate the persistence of collection variables across app restarts, including typed values and multiple variable settings.
- Created new fixtures for collection variables to support the tests, ensuring accurate simulation of variable management scenarios.
- Enhanced the existing collection management logic to ensure that variables are correctly set and deleted as per the test requirements.

* feat(tests): add tests for typed global environment variable persistence

- Introduced a new test suite to validate the persistence of typed global environment variables across app restarts, ensuring correct data types are maintained.
- Created a fixture for the test collection to simulate setting global variables with various data types, including number, boolean, object, and string.
- Enhanced the test logic to verify that the environment file reflects the correct state before and after application restarts.

* fix(tests): update request tab close interaction in variable persistence tests

* fix(tests): improve hover interaction for collection actions in runner tests

- Updated the hover logic for revealing collection actions to handle sidebar re-renders more reliably.
- Replaced one-shot hover with a polling mechanism to ensure visibility of actions, enhancing test stability.

* refactor(environments): streamline environment variable handling and remove ephemeral metadata logic

- Simplified the comparison logic for environment variables by removing unnecessary ephemeral metadata handling.
- Updated the saving process to directly use the environment variables without stripping metadata, enhancing clarity and maintainability.
- Removed outdated comments and unused utility functions related to ephemeral variables, improving code cleanliness.

* fix(ipc): update persistActiveEnvironment to handle requestUid for stale updates

- Modified the persistActiveEnvironment function to accept a requestUid parameter, allowing for better management of stale updates.
- Enhanced the logic to prevent disk writes for superseded requests, improving data integrity during environment persistence.

* refactor(bru): remove unused envName variable in deleteAllEnvVars method

- Eliminated the envName variable from the deleteAllEnvVars method, simplifying the logic for deleting environment variables.
- Cleaned up the method by removing unnecessary checks related to the envName, enhancing code clarity and maintainability.

* fix(bru): prevent deletion of internal __name__ variable in deleteEnvVar method

- Added a check in the deleteEnvVar method to silently ignore attempts to delete the internal __name__ variable, preserving its integrity.
- Updated tests to verify that the __name__ variable remains unchanged when deleteEnvVar is called with this key.
- Enhanced runtime tests to ensure compatibility with QuickJS by confirming that environment variables set with persist options are handled correctly.

* feat(tests): add legacy support test for environment variable persistence

- Introduced a new test suite to validate that the legacy argument for setting environment variables with persistence is still functional in version 4.
- Created a fixture to simulate the legacy syntax, ensuring that the variable is correctly persisted on disk without errors.
- Enhanced integration testing to confirm that the legacy behavior aligns with the current implementation, maintaining backward compatibility.

* test(tests): enhance legacy environment variable persistence tests for safe and developer modes

- Updated the test suite for `bru.setEnvVar` to verify that the legacy persist flag is correctly handled in both safe and developer modes.
- Introduced a helper function to streamline the verification process and ensure consistent behavior across different execution contexts.
- Adjusted the test logic to reset the environment state between mode switches, maintaining test integrity.
- Improved hover interaction in multiple persistent variable tests to ensure reliable visibility of actions during execution.

* fix(EnvironmentVariablesTable): correct change detection logic for environment variables

- Updated the logic for determining changes in environment variables to compare active current and saved values instead of previously used variablesToSave and savedValues.
- This change ensures accurate detection of modifications before saving, improving user feedback when no changes are present.

* test(tests): enhance secret variable persistence tests for environment configurations

- Updated the test suites for `bru.setEnvVar` and `bru.setGlobalEnvVar` to include interactions with the secrets tab, ensuring visibility of secret variables during various states of the environment.
- Added checks to confirm that the eye toggle functionality correctly reveals the values of secret variables after setting and overwriting them.
- Improved test coverage for secret variable persistence, validating that the expected values are displayed in both collection and global environment contexts.
This commit is contained in:
sanish chirayath
2026-06-26 23:01:37 +05:30
committed by GitHub
parent 30b4512983
commit 87f74262bb
171 changed files with 7138 additions and 1018 deletions

View File

@@ -1,4 +1,4 @@
const { cloneDeep } = require('lodash');
const { cloneDeep, isEqual } = require('lodash');
const xmlFormat = require('xml-formatter');
const { interpolate: _interpolate } = require('@usebruno/common');
const { createSendRequest } = require('@usebruno/requests').scripting;
@@ -76,8 +76,11 @@ class Bru {
createCookieJar,
getCookiesForUrl
});
// Holds variables that are marked as persistent by scripts
this.persistentEnvVariables = {};
// Dirty flags — set by mutators so runtimes can skip IPC/disk writes for unchanged scopes
this._envDirty = false;
this._globalEnvDirty = false;
this._collVarsDirty = false;
this._runtimeVarsDirty = false;
// Holds credential IDs to be reset after script execution
this.oauth2CredentialsToReset = [];
this.runner = {
@@ -192,7 +195,7 @@ class Bru {
return this.interpolate(this.envVariables[key]);
}
setEnvVar(key, value, options = {}) {
setEnvVar(key, value) {
if (!key) {
throw new Error('Creating a env variable without specifying a name is not allowed.');
}
@@ -203,19 +206,21 @@ class Bru {
);
}
this.envVariables[key] = value;
if (options?.persist) {
this.persistentEnvVariables[key] = value;
} else {
if (this.persistentEnvVariables[key]) {
delete this.persistentEnvVariables[key];
}
// Deep-equal compare so object/array writes that mutate in place
// (e.g. `const c = bru.getEnvVar('cfg'); c.port = 4000; bru.setEnvVar('cfg', c);`)
// still flip the dirty flag — strict `!==` returned false for same-reference writes.
if (!Object.hasOwn(this.envVariables, key) || !isEqual(this.envVariables[key], value)) {
this.envVariables[key] = value;
this._envDirty = true;
}
}
deleteEnvVar(key) {
delete this.envVariables[key];
if (key === '__name__') return;
if (Object.hasOwn(this.envVariables, key)) {
delete this.envVariables[key];
this._envDirty = true;
}
}
getAllEnvVars() {
@@ -225,15 +230,15 @@ class Bru {
}
deleteAllEnvVars() {
const envName = this.envVariables.__name__;
for (let key in this.envVariables) {
if (this.envVariables.hasOwnProperty(key)) {
delete this.envVariables[key];
}
}
if (envName !== undefined) {
this.envVariables.__name__ = envName;
// Iterate via Object.keys (own enumerable) so a user-set `hasOwnProperty` var
// can't shadow Object.prototype.hasOwnProperty and crash the loop.
let removed = false;
for (const key of Object.keys(this.envVariables)) {
if (key === '__name__') continue;
delete this.envVariables[key];
removed = true;
}
if (removed) this._envDirty = true;
}
hasGlobalEnvVar(key) {
@@ -249,28 +254,31 @@ class Bru {
throw new Error('Creating a env variable without specifying a name is not allowed.');
}
this.globalEnvironmentVariables[key] = value;
if (!Object.hasOwn(this.globalEnvironmentVariables, key) || !isEqual(this.globalEnvironmentVariables[key], value)) {
this.globalEnvironmentVariables[key] = value;
this._globalEnvDirty = true;
}
}
// TODO: deleteGlobalEnvVar works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// deleteGlobalEnvVar(key) {
// delete this.globalEnvironmentVariables[key];
// }
deleteGlobalEnvVar(key) {
if (Object.hasOwn(this.globalEnvironmentVariables, key)) {
delete this.globalEnvironmentVariables[key];
this._globalEnvDirty = true;
}
}
getAllGlobalEnvVars() {
return Object.assign({}, this.globalEnvironmentVariables);
}
// TODO: deleteAllGlobalEnvVars works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// deleteAllGlobalEnvVars() {
// for (let key in this.globalEnvironmentVariables) {
// if (this.globalEnvironmentVariables.hasOwnProperty(key)) {
// delete this.globalEnvironmentVariables[key];
// }
// }
// }
deleteAllGlobalEnvVars() {
const keys = Object.keys(this.globalEnvironmentVariables);
if (!keys.length) return;
for (const key of keys) {
delete this.globalEnvironmentVariables[key];
}
this._globalEnvDirty = true;
}
getOauth2CredentialVar(key) {
return this.interpolate(this.oauth2CredentialVariables[key]);
@@ -310,7 +318,10 @@ class Bru {
);
}
this.runtimeVariables[key] = value;
if (!Object.hasOwn(this.runtimeVariables, key) || !isEqual(this.runtimeVariables[key], value)) {
this.runtimeVariables[key] = value;
this._runtimeVarsDirty = true;
}
}
getVar(key) {
@@ -325,15 +336,19 @@ class Bru {
}
deleteVar(key) {
delete this.runtimeVariables[key];
if (Object.hasOwn(this.runtimeVariables, key)) {
delete this.runtimeVariables[key];
this._runtimeVarsDirty = true;
}
}
deleteAllVars() {
for (let key in this.runtimeVariables) {
if (this.runtimeVariables.hasOwnProperty(key)) {
delete this.runtimeVariables[key];
}
const keys = Object.keys(this.runtimeVariables);
if (!keys.length) return;
for (const key of keys) {
delete this.runtimeVariables[key];
}
this._runtimeVarsDirty = true;
}
getAllVars() {
@@ -344,48 +359,47 @@ class Bru {
return this.interpolate(this.collectionVariables[key]);
}
// TODO: setCollectionVar works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// setCollectionVar(key, value) {
// if (!key) {
// throw new Error('Creating a variable without specifying a name is not allowed.');
// }
//
// if (variableNameRegex.test(key) === false) {
// throw new Error(
// `Variable name: "${key}" contains invalid characters!`
// + ' Names must only contain alpha-numeric characters, "-", "_", "."'
// );
// }
//
// this.collectionVariables[key] = value;
// }
setCollectionVar(key, value) {
if (!key) {
throw new Error('Creating a variable without specifying a name is not allowed.');
}
if (variableNameRegex.test(key) === false) {
throw new Error(
`Variable name: "${key}" contains invalid characters!`
+ ' Names must only contain alpha-numeric characters, "-", "_", "."'
);
}
if (!Object.hasOwn(this.collectionVariables, key) || !isEqual(this.collectionVariables[key], value)) {
this.collectionVariables[key] = value;
this._collVarsDirty = true;
}
}
hasCollectionVar(key) {
return Object.hasOwn(this.collectionVariables, key);
}
// TODO: deleteCollectionVar works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// deleteCollectionVar(key) {
// delete this.collectionVariables[key];
// }
deleteCollectionVar(key) {
if (Object.hasOwn(this.collectionVariables, key)) {
delete this.collectionVariables[key];
this._collVarsDirty = true;
}
}
// TODO: deleteAllCollectionVars works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// deleteAllCollectionVars() {
// for (let key in this.collectionVariables) {
// if (this.collectionVariables.hasOwnProperty(key)) {
// delete this.collectionVariables[key];
// }
// }
// }
deleteAllCollectionVars() {
const keys = Object.keys(this.collectionVariables);
if (!keys.length) return;
for (const key of keys) {
delete this.collectionVariables[key];
}
this._collVarsDirty = true;
}
// TODO: getAllCollectionVars works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// getAllCollectionVars() {
// return Object.assign({}, this.collectionVariables);
// }
getAllCollectionVars() {
return Object.assign({}, this.collectionVariables);
}
getFolderVar(key) {
return this.interpolate(this.folderVariables[key]);

View File

@@ -89,10 +89,10 @@ class ScriptRuntime {
// Extracted to avoid duplication across runtime branches
const buildRequestScriptResult = () => ({
request,
envVariables: cleanJson(envVariables),
runtimeVariables: cleanJson(runtimeVariables),
persistentEnvVariables: bru.persistentEnvVariables,
globalEnvironmentVariables: cleanJson(globalEnvironmentVariables),
envVariables: bru._envDirty ? cleanJson(envVariables) : null,
runtimeVariables: bru._runtimeVarsDirty ? cleanJson(runtimeVariables) : null,
collectionVariables: bru._collVarsDirty ? cleanJson(collectionVariables) : null,
globalEnvironmentVariables: bru._globalEnvDirty ? cleanJson(globalEnvironmentVariables) : null,
oauth2CredentialsToReset: bru.oauth2CredentialsToReset,
results: cleanJson(__brunoTestResults.getResults()),
nextRequestName: bru.nextRequest,
@@ -225,10 +225,10 @@ class ScriptRuntime {
// Extracted to avoid duplication across runtime branches
const buildResponseScriptResult = () => ({
response,
envVariables: cleanJson(envVariables),
persistentEnvVariables: cleanJson(bru.persistentEnvVariables),
runtimeVariables: cleanJson(runtimeVariables),
globalEnvironmentVariables: cleanJson(globalEnvironmentVariables),
envVariables: bru._envDirty ? cleanJson(envVariables) : null,
runtimeVariables: bru._runtimeVarsDirty ? cleanJson(runtimeVariables) : null,
collectionVariables: bru._collVarsDirty ? cleanJson(collectionVariables) : null,
globalEnvironmentVariables: bru._globalEnvDirty ? cleanJson(globalEnvironmentVariables) : null,
oauth2CredentialsToReset: bru.oauth2CredentialsToReset,
results: cleanJson(__brunoTestResults.getResults()),
nextRequestName: bru.nextRequest,

View File

@@ -62,9 +62,10 @@ class TestRuntime {
if (!testsFile || !testsFile.length) {
return {
request,
envVariables,
runtimeVariables,
globalEnvironmentVariables,
envVariables: null,
runtimeVariables: null,
collectionVariables: null,
globalEnvironmentVariables: null,
results: __brunoTestResults.getResults(),
nextRequestName: bru.nextRequest
};
@@ -125,10 +126,10 @@ class TestRuntime {
const result = {
request,
envVariables: cleanJson(envVariables),
runtimeVariables: cleanJson(runtimeVariables),
globalEnvironmentVariables: cleanJson(globalEnvironmentVariables),
persistentEnvVariables: cleanJson(bru.persistentEnvVariables),
envVariables: bru._envDirty ? cleanJson(envVariables) : null,
runtimeVariables: bru._runtimeVarsDirty ? cleanJson(runtimeVariables) : null,
collectionVariables: bru._collVarsDirty ? cleanJson(collectionVariables) : null,
globalEnvironmentVariables: bru._globalEnvDirty ? cleanJson(globalEnvironmentVariables) : null,
oauth2CredentialsToReset: bru.oauth2CredentialsToReset,
results: cleanJson(__brunoTestResults.getResults()),
nextRequestName: bru.nextRequest,

View File

@@ -86,10 +86,10 @@ class VarsRuntime {
}
return {
envVariables,
runtimeVariables,
globalEnvironmentVariables: cleanJson(globalEnvironmentVariables),
persistentEnvVariables: cleanJson(bru.persistentEnvVariables),
envVariables: bru._envDirty ? cleanJson(envVariables) : null,
runtimeVariables: bru._runtimeVarsDirty ? cleanJson(runtimeVariables) : null,
collectionVariables: bru._collVarsDirty ? cleanJson(collectionVariables) : null,
globalEnvironmentVariables: bru._globalEnvDirty ? cleanJson(globalEnvironmentVariables) : null,
error
};
}

View File

@@ -54,8 +54,8 @@ const addBruShimToContext = (vm, bru) => {
vm.setProp(bruObject, 'getEnvVar', getEnvVar);
getEnvVar.dispose();
let setEnvVar = vm.newFunction('setEnvVar', function (key, value, options = {}) {
bru.setEnvVar(vm.dump(key), vm.dump(value), vm.dump(options));
let setEnvVar = vm.newFunction('setEnvVar', function (key, value) {
bru.setEnvVar(vm.dump(key), vm.dump(value));
});
vm.setProp(bruObject, 'setEnvVar', setEnvVar);
setEnvVar.dispose();
@@ -102,13 +102,11 @@ const addBruShimToContext = (vm, bru) => {
vm.setProp(bruObject, 'setGlobalEnvVar', setGlobalEnvVar);
setGlobalEnvVar.dispose();
// TODO: deleteGlobalEnvVar works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// let deleteGlobalEnvVar = vm.newFunction('deleteGlobalEnvVar', function (key) {
// bru.deleteGlobalEnvVar(vm.dump(key));
// });
// vm.setProp(bruObject, 'deleteGlobalEnvVar', deleteGlobalEnvVar);
// deleteGlobalEnvVar.dispose();
let deleteGlobalEnvVar = vm.newFunction('deleteGlobalEnvVar', function (key) {
bru.deleteGlobalEnvVar(vm.dump(key));
});
vm.setProp(bruObject, 'deleteGlobalEnvVar', deleteGlobalEnvVar);
deleteGlobalEnvVar.dispose();
let getAllGlobalEnvVars = vm.newFunction('getAllGlobalEnvVars', function () {
return marshallToVm(bru.getAllGlobalEnvVars(), vm);
@@ -122,13 +120,11 @@ const addBruShimToContext = (vm, bru) => {
vm.setProp(bruObject, 'hasGlobalEnvVar', hasGlobalEnvVar);
hasGlobalEnvVar.dispose();
// TODO: deleteAllGlobalEnvVars works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// let deleteAllGlobalEnvVars = vm.newFunction('deleteAllGlobalEnvVars', function () {
// bru.deleteAllGlobalEnvVars();
// });
// vm.setProp(bruObject, 'deleteAllGlobalEnvVars', deleteAllGlobalEnvVars);
// deleteAllGlobalEnvVars.dispose();
let deleteAllGlobalEnvVars = vm.newFunction('deleteAllGlobalEnvVars', function () {
bru.deleteAllGlobalEnvVars();
});
vm.setProp(bruObject, 'deleteAllGlobalEnvVars', deleteAllGlobalEnvVars);
deleteAllGlobalEnvVars.dispose();
let hasVar = vm.newFunction('hasVar', function (key) {
return marshallToVm(bru.hasVar(vm.dump(key)), vm);
@@ -220,13 +216,11 @@ const addBruShimToContext = (vm, bru) => {
vm.setProp(bruObject, 'getCollectionVar', getCollectionVar);
getCollectionVar.dispose();
// TODO: setCollectionVar works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// let setCollectionVar = vm.newFunction('setCollectionVar', function (key, value) {
// bru.setCollectionVar(vm.dump(key), vm.dump(value));
// });
// vm.setProp(bruObject, 'setCollectionVar', setCollectionVar);
// setCollectionVar.dispose();
let setCollectionVar = vm.newFunction('setCollectionVar', function (key, value) {
bru.setCollectionVar(vm.dump(key), vm.dump(value));
});
vm.setProp(bruObject, 'setCollectionVar', setCollectionVar);
setCollectionVar.dispose();
let hasCollectionVar = vm.newFunction('hasCollectionVar', function (key) {
return marshallToVm(bru.hasCollectionVar(vm.dump(key)), vm);
@@ -234,29 +228,23 @@ const addBruShimToContext = (vm, bru) => {
vm.setProp(bruObject, 'hasCollectionVar', hasCollectionVar);
hasCollectionVar.dispose();
// TODO: deleteCollectionVar works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// let deleteCollectionVar = vm.newFunction('deleteCollectionVar', function (key) {
// bru.deleteCollectionVar(vm.dump(key));
// });
// vm.setProp(bruObject, 'deleteCollectionVar', deleteCollectionVar);
// deleteCollectionVar.dispose();
let deleteCollectionVar = vm.newFunction('deleteCollectionVar', function (key) {
bru.deleteCollectionVar(vm.dump(key));
});
vm.setProp(bruObject, 'deleteCollectionVar', deleteCollectionVar);
deleteCollectionVar.dispose();
// TODO: deleteAllCollectionVars works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// let deleteAllCollectionVars = vm.newFunction('deleteAllCollectionVars', function () {
// bru.deleteAllCollectionVars();
// });
// vm.setProp(bruObject, 'deleteAllCollectionVars', deleteAllCollectionVars);
// deleteAllCollectionVars.dispose();
let deleteAllCollectionVars = vm.newFunction('deleteAllCollectionVars', function () {
bru.deleteAllCollectionVars();
});
vm.setProp(bruObject, 'deleteAllCollectionVars', deleteAllCollectionVars);
deleteAllCollectionVars.dispose();
// TODO: getAllCollectionVars works in the request lifecycle but does not update the UI.
// Re-enable once the UI sync issue is resolved.
// let getAllCollectionVars = vm.newFunction('getAllCollectionVars', function () {
// return marshallToVm(bru.getAllCollectionVars(), vm);
// });
// vm.setProp(bruObject, 'getAllCollectionVars', getAllCollectionVars);
// getAllCollectionVars.dispose();
let getAllCollectionVars = vm.newFunction('getAllCollectionVars', function () {
return marshallToVm(bru.getAllCollectionVars(), vm);
});
vm.setProp(bruObject, 'getAllCollectionVars', getAllCollectionVars);
getAllCollectionVars.dispose();
let getTestResults = vm.newFunction('getTestResults', () => {
const promise = vm.newPromise();

View File

@@ -0,0 +1,217 @@
const Bru = require('../src/bru');
describe('Collection Variable APIs', () => {
const makeBru = (collectionVariables = {}) =>
new Bru({
runtime: 'quickjs',
envVariables: {},
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test',
collectionVariables
});
describe('bru.setCollectionVar', () => {
test('sets a new collection variable', () => {
const bru = makeBru();
bru.setCollectionVar('baseUrl', 'https://api.example.com');
expect(bru.collectionVariables.baseUrl).toBe('https://api.example.com');
});
test('overwrites an existing collection variable', () => {
const bru = makeBru({ baseUrl: 'https://old.com' });
bru.setCollectionVar('baseUrl', 'https://new.com');
expect(bru.collectionVariables.baseUrl).toBe('https://new.com');
});
test('allows non-string values', () => {
const bru = makeBru();
bru.setCollectionVar('count', 42);
expect(bru.collectionVariables.count).toBe(42);
bru.setCollectionVar('active', true);
expect(bru.collectionVariables.active).toBe(true);
bru.setCollectionVar('config', { port: 3000 });
expect(bru.collectionVariables.config).toEqual({ port: 3000 });
});
test('throws when key is empty', () => {
const bru = makeBru();
expect(() => bru.setCollectionVar('', 'v')).toThrow(/without specifying a name/);
});
test('throws when key has invalid characters', () => {
const bru = makeBru();
expect(() => bru.setCollectionVar('invalid key', 'v')).toThrow(/contains invalid characters/);
});
test('re-run: setting same key twice does not throw', () => {
const bru = makeBru();
bru.setCollectionVar('key', 'first');
bru.setCollectionVar('key', 'second');
expect(bru.collectionVariables.key).toBe('second');
});
});
describe('bru.setCollectionVar — dirty flag for typed values', () => {
test('setting a number trips the collection-vars dirty flag', () => {
const bru = makeBru();
expect(bru._collVarsDirty).toBe(false);
bru.setCollectionVar('count', 42);
expect(bru._collVarsDirty).toBe(true);
});
test('setting a boolean trips the collection-vars dirty flag', () => {
const bru = makeBru();
bru.setCollectionVar('active', true);
expect(bru._collVarsDirty).toBe(true);
});
test('setting an object trips the collection-vars dirty flag', () => {
const bru = makeBru();
bru.setCollectionVar('config', { port: 3000 });
expect(bru._collVarsDirty).toBe(true);
});
});
describe('bru.setCollectionVar — dirty flag for reference-mutation idiom', () => {
test('the getCollectionVar → mutate → setCollectionVar idiom trips the dirty flag', () => {
const bru = makeBru({ config: { port: 3000 } });
expect(bru._collVarsDirty).toBe(false);
// Real-script idiom: getCollectionVar deep-copies through interpolate's JSON roundtrip,
// so mutating the result leaves the store untouched and the deep-equal guard fires.
const config = bru.getCollectionVar('config');
config.port = 4000;
bru.setCollectionVar('config', config);
expect(bru._collVarsDirty).toBe(true);
expect(bru.collectionVariables.config).toEqual({ port: 4000 });
});
test('re-setting a structurally-equal object value does NOT trip the dirty flag', () => {
const bru = makeBru({ config: { port: 3000 } });
bru.setCollectionVar('config', { port: 3000 });
expect(bru._collVarsDirty).toBe(false);
});
test('re-setting a structurally-equal primitive value does NOT trip the dirty flag', () => {
const bru = makeBru({ token: 'abc' });
bru.setCollectionVar('token', 'abc');
expect(bru._collVarsDirty).toBe(false);
});
});
describe('bru.deleteCollectionVar — dirty flag contract', () => {
test('deleting an existing key trips the collection-vars dirty flag', () => {
const bru = makeBru({ token: 'abc' });
bru.deleteCollectionVar('token');
expect(bru._collVarsDirty).toBe(true);
});
test('deleting a non-existent key leaves the dirty flag clean', () => {
const bru = makeBru();
bru.deleteCollectionVar('missing');
expect(bru._collVarsDirty).toBe(false);
});
});
describe('bru.deleteAllCollectionVars — dirty flag contract', () => {
test('deleting populated scope trips the dirty flag', () => {
const bru = makeBru({ a: '1', b: '2' });
bru.deleteAllCollectionVars();
expect(bru._collVarsDirty).toBe(true);
});
test('calling on empty scope leaves the dirty flag clean', () => {
const bru = makeBru();
bru.deleteAllCollectionVars();
expect(bru._collVarsDirty).toBe(false);
});
});
describe('bru.getCollectionVar', () => {
test('returns the value of an existing variable', () => {
const bru = makeBru({ token: 'abc123' });
expect(bru.getCollectionVar('token')).toBe('abc123');
});
test('returns undefined for a non-existent variable', () => {
const bru = makeBru();
expect(bru.getCollectionVar('missing')).toBeUndefined();
});
});
describe('bru.hasCollectionVar', () => {
test('returns true for an existing variable', () => {
const bru = makeBru({ token: 'abc' });
expect(bru.hasCollectionVar('token')).toBe(true);
});
test('returns false for a non-existent variable', () => {
const bru = makeBru();
expect(bru.hasCollectionVar('missing')).toBe(false);
});
});
describe('bru.deleteCollectionVar', () => {
test('removes an existing variable', () => {
const bru = makeBru({ token: 'abc' });
bru.deleteCollectionVar('token');
expect(bru.collectionVariables.token).toBeUndefined();
expect(bru.hasCollectionVar('token')).toBe(false);
});
test('re-run: deleting a non-existent key is a silent no-op', () => {
const bru = makeBru();
expect(() => bru.deleteCollectionVar('missing')).not.toThrow();
});
test('re-run: deleting an already-deleted key is a silent no-op', () => {
const bru = makeBru({ token: 'abc' });
bru.deleteCollectionVar('token');
expect(() => bru.deleteCollectionVar('token')).not.toThrow();
});
});
describe('bru.deleteAllCollectionVars', () => {
test('removes all collection variables', () => {
const bru = makeBru({ a: '1', b: '2', c: '3' });
bru.deleteAllCollectionVars();
expect(bru.collectionVariables).toEqual({});
});
test('re-run: calling on empty scope is a silent no-op', () => {
const bru = makeBru();
expect(() => bru.deleteAllCollectionVars()).not.toThrow();
expect(bru.collectionVariables).toEqual({});
});
test('re-run: calling twice is a silent no-op', () => {
const bru = makeBru({ a: '1' });
bru.deleteAllCollectionVars();
expect(() => bru.deleteAllCollectionVars()).not.toThrow();
expect(bru.collectionVariables).toEqual({});
});
});
describe('bru.getAllCollectionVars', () => {
test('returns a copy of all collection variables', () => {
const bru = makeBru({ a: '1', b: '2' });
const all = bru.getAllCollectionVars();
expect(all).toEqual({ a: '1', b: '2' });
});
test('returned object is a copy, not a reference', () => {
const bru = makeBru({ a: '1' });
const all = bru.getAllCollectionVars();
all.a = 'mutated';
expect(bru.collectionVariables.a).toBe('1');
});
test('returns empty object when no variables exist', () => {
const bru = makeBru();
expect(bru.getAllCollectionVars()).toEqual({});
});
});
});

View File

@@ -0,0 +1,207 @@
const Bru = require('../src/bru');
describe('Global Environment Variable APIs', () => {
const makeBru = (globalEnvironmentVariables = {}) =>
new Bru({
runtime: 'quickjs',
envVariables: {},
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test',
globalEnvironmentVariables
});
describe('bru.setGlobalEnvVar', () => {
test('sets a new global env variable', () => {
const bru = makeBru();
bru.setGlobalEnvVar('apiKey', 'abc123');
expect(bru.globalEnvironmentVariables.apiKey).toBe('abc123');
});
test('overwrites an existing variable', () => {
const bru = makeBru({ apiKey: 'old' });
bru.setGlobalEnvVar('apiKey', 'new');
expect(bru.globalEnvironmentVariables.apiKey).toBe('new');
});
test('allows non-string values', () => {
const bru = makeBru();
bru.setGlobalEnvVar('count', 42);
expect(bru.globalEnvironmentVariables.count).toBe(42);
bru.setGlobalEnvVar('config', { port: 3000 });
expect(bru.globalEnvironmentVariables.config).toEqual({ port: 3000 });
});
test('throws when key is empty', () => {
const bru = makeBru();
expect(() => bru.setGlobalEnvVar('', 'v')).toThrow(/without specifying a name/);
});
test('re-run: setting same key twice does not throw', () => {
const bru = makeBru();
bru.setGlobalEnvVar('key', 'first');
bru.setGlobalEnvVar('key', 'second');
expect(bru.globalEnvironmentVariables.key).toBe('second');
});
});
describe('bru.setGlobalEnvVar — dirty flag for typed values', () => {
test('setting a number trips the global-env dirty flag', () => {
const bru = makeBru();
expect(bru._globalEnvDirty).toBe(false);
bru.setGlobalEnvVar('count', 42);
expect(bru._globalEnvDirty).toBe(true);
});
test('setting a boolean trips the global-env dirty flag', () => {
const bru = makeBru();
bru.setGlobalEnvVar('active', true);
expect(bru._globalEnvDirty).toBe(true);
});
test('setting an object trips the global-env dirty flag', () => {
const bru = makeBru();
bru.setGlobalEnvVar('config', { port: 3000 });
expect(bru._globalEnvDirty).toBe(true);
});
});
describe('bru.setGlobalEnvVar — dirty flag for reference-mutation idiom', () => {
test('the getGlobalEnvVar → mutate → setGlobalEnvVar idiom trips the dirty flag', () => {
const bru = makeBru({ config: { port: 3000 } });
expect(bru._globalEnvDirty).toBe(false);
// Real-script idiom: getGlobalEnvVar deep-copies through interpolate's JSON roundtrip,
// so mutating the result leaves the store untouched and the deep-equal guard fires.
const config = bru.getGlobalEnvVar('config');
config.port = 4000;
bru.setGlobalEnvVar('config', config);
expect(bru._globalEnvDirty).toBe(true);
expect(bru.globalEnvironmentVariables.config).toEqual({ port: 4000 });
});
test('re-setting a structurally-equal object value does NOT trip the dirty flag', () => {
const bru = makeBru({ config: { port: 3000 } });
bru.setGlobalEnvVar('config', { port: 3000 });
expect(bru._globalEnvDirty).toBe(false);
});
test('re-setting a structurally-equal primitive value does NOT trip the dirty flag', () => {
const bru = makeBru({ token: 'abc' });
bru.setGlobalEnvVar('token', 'abc');
expect(bru._globalEnvDirty).toBe(false);
});
});
describe('bru.deleteGlobalEnvVar — dirty flag contract', () => {
test('deleting an existing key trips the global-env dirty flag', () => {
const bru = makeBru({ token: 'abc' });
bru.deleteGlobalEnvVar('token');
expect(bru._globalEnvDirty).toBe(true);
});
test('deleting a non-existent key leaves the dirty flag clean', () => {
const bru = makeBru();
bru.deleteGlobalEnvVar('missing');
expect(bru._globalEnvDirty).toBe(false);
});
});
describe('bru.deleteAllGlobalEnvVars — dirty flag contract', () => {
test('deleting populated scope trips the dirty flag', () => {
const bru = makeBru({ a: '1', b: '2' });
bru.deleteAllGlobalEnvVars();
expect(bru._globalEnvDirty).toBe(true);
});
test('calling on empty scope leaves the dirty flag clean', () => {
const bru = makeBru();
bru.deleteAllGlobalEnvVars();
expect(bru._globalEnvDirty).toBe(false);
});
});
describe('bru.getGlobalEnvVar', () => {
test('returns value of an existing variable', () => {
const bru = makeBru({ token: 'abc' });
expect(bru.getGlobalEnvVar('token')).toBe('abc');
});
test('returns undefined for non-existent variable', () => {
const bru = makeBru();
expect(bru.getGlobalEnvVar('missing')).toBeUndefined();
});
});
describe('bru.hasGlobalEnvVar', () => {
test('returns true for existing variable', () => {
const bru = makeBru({ token: 'abc' });
expect(bru.hasGlobalEnvVar('token')).toBe(true);
});
test('returns false for non-existent variable', () => {
const bru = makeBru();
expect(bru.hasGlobalEnvVar('missing')).toBe(false);
});
});
describe('bru.deleteGlobalEnvVar', () => {
test('removes an existing variable', () => {
const bru = makeBru({ token: 'abc' });
bru.deleteGlobalEnvVar('token');
expect(bru.globalEnvironmentVariables.token).toBeUndefined();
expect(bru.hasGlobalEnvVar('token')).toBe(false);
});
test('re-run: deleting a non-existent key is a silent no-op', () => {
const bru = makeBru();
expect(() => bru.deleteGlobalEnvVar('missing')).not.toThrow();
});
test('re-run: deleting an already-deleted key is a silent no-op', () => {
const bru = makeBru({ token: 'abc' });
bru.deleteGlobalEnvVar('token');
expect(() => bru.deleteGlobalEnvVar('token')).not.toThrow();
});
});
describe('bru.deleteAllGlobalEnvVars', () => {
test('removes all global env variables', () => {
const bru = makeBru({ a: '1', b: '2', c: '3' });
bru.deleteAllGlobalEnvVars();
expect(bru.globalEnvironmentVariables).toEqual({});
});
test('re-run: calling on empty scope is a silent no-op', () => {
const bru = makeBru();
expect(() => bru.deleteAllGlobalEnvVars()).not.toThrow();
expect(bru.globalEnvironmentVariables).toEqual({});
});
test('re-run: calling twice is a silent no-op', () => {
const bru = makeBru({ a: '1' });
bru.deleteAllGlobalEnvVars();
expect(() => bru.deleteAllGlobalEnvVars()).not.toThrow();
});
});
describe('bru.getAllGlobalEnvVars', () => {
test('returns a copy of all global env variables', () => {
const bru = makeBru({ a: '1', b: '2' });
expect(bru.getAllGlobalEnvVars()).toEqual({ a: '1', b: '2' });
});
test('returned object is a copy, not a reference', () => {
const bru = makeBru({ a: '1' });
const all = bru.getAllGlobalEnvVars();
all.a = 'mutated';
expect(bru.globalEnvironmentVariables.a).toBe('1');
});
test('returns empty object when no variables exist', () => {
const bru = makeBru();
expect(bru.getAllGlobalEnvVars()).toEqual({});
});
});
});

View File

@@ -180,61 +180,121 @@ describe('runtime', () => {
});
});
describe('persistent environment variables validation', () => {
it('should persist non-string values without throwing', async () => {
describe('environment variables from scripts', () => {
it('should allow any value type', async () => {
const script = `
bru.setEnvVar('number', 42, {persist: true});
bru.setEnvVar('isActive', true, {persist: true});
bru.setEnvVar('config', {port: 3000}, {persist: true});
bru.setEnvVar('items', ['item1', 'item2'], {persist: true});
`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.envVariables.number).toBe(42);
expect(result.persistentEnvVariables.number).toBe(42);
expect(result.envVariables.isActive).toBe(true);
expect(result.persistentEnvVariables.isActive).toBe(true);
expect(result.envVariables.config).toEqual({ port: 3000 });
expect(result.persistentEnvVariables.config).toEqual({ port: 3000 });
expect(result.envVariables.items).toEqual(['item1', 'item2']);
expect(result.persistentEnvVariables.items).toEqual(['item1', 'item2']);
});
it('should allow string values when persist is true', async () => {
const script = `bru.setEnvVar('api_key', 'abc123', {persist: true});`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.envVariables.api_key).toBe('abc123');
});
it('should allow non-string values when persist is false', async () => {
const script = `
bru.setEnvVar('number', 42, {persist: false});
bru.setEnvVar('boolean', true, {persist: false});
bru.setEnvVar('object', {key: 'value'}, {persist: false});
bru.setEnvVar('array', [1, 2, 3], {persist: false});
bru.setEnvVar('str', 'hello');
bru.setEnvVar('number', 42);
bru.setEnvVar('boolean', true);
bru.setEnvVar('object', {key: 'value'});
bru.setEnvVar('array', [1, 2, 3]);
`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.envVariables.str).toBe('hello');
expect(result.envVariables.number).toBe(42);
expect(result.envVariables.boolean).toBe(true);
expect(result.envVariables.object).toEqual({ key: 'value' });
expect(result.envVariables.array).toEqual([1, 2, 3]);
});
it('should allow non-string values when persist is not specified', async () => {
const script = `bru.setEnvVar('number', 42);`;
it('should preserve typed values through the QuickJS shim', async () => {
await quickJsLoader();
const script = `
bru.setEnvVar('num', 42);
bru.setEnvVar('bool', true);
bru.setEnvVar('obj', { key: 'value' });
bru.setCollectionVar('collNum', 7);
bru.setGlobalEnvVar('globalBool', false);
`;
const runtime = new ScriptRuntime({ runtime: 'quickjs' });
const onConsoleLog = () => {};
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', onConsoleLog, process.env);
expect(typeof result.envVariables.num).toBe('number');
expect(result.envVariables.num).toBe(42);
expect(typeof result.envVariables.bool).toBe('boolean');
expect(result.envVariables.bool).toBe(true);
expect(typeof result.envVariables.obj).toBe('object');
expect(result.envVariables.obj).toEqual({ key: 'value' });
expect(typeof result.collectionVariables.collNum).toBe('number');
expect(result.collectionVariables.collNum).toBe(7);
expect(typeof result.globalEnvironmentVariables.globalBool).toBe('boolean');
expect(result.globalEnvironmentVariables.globalBool).toBe(false);
});
it('should return null for scopes the script did not touch (dirty-flag gating)', async () => {
const script = `bru.setEnvVar('only_env', 'val');`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.envVariables.number).toBe(42);
expect(result.envVariables).not.toBeNull();
expect(result.envVariables.only_env).toBe('val');
expect(result.collectionVariables).toBeNull();
expect(result.globalEnvironmentVariables).toBeNull();
});
it('should return null for scopes the script did not touch — QuickJS parity', async () => {
await quickJsLoader();
const script = `bru.setEnvVar('only_env', 'val');`;
const runtime = new ScriptRuntime({ runtime: 'quickjs' });
const onConsoleLog = () => {};
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', onConsoleLog, process.env);
expect(result.envVariables).not.toBeNull();
expect(result.envVariables.only_env).toBe('val');
expect(result.collectionVariables).toBeNull();
expect(result.globalEnvironmentVariables).toBeNull();
});
it('should not include persistentEnvVariables in result', async () => {
const script = `bru.setEnvVar('key', 'val');`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result).not.toHaveProperty('persistentEnvVariables');
});
it('should include collectionVariables in result', async () => {
const script = `bru.setCollectionVar('myVar', 'myValue');`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result = await runtime.runRequestScript(script, {}, {}, {}, '.', null, process.env);
expect(result.collectionVariables).toBeDefined();
expect(result.collectionVariables.myVar).toBe('myValue');
});
it('should silently ignore old persist flag as extra argument', async () => {
const scriptTrue = `bru.setEnvVar('key1', 'val1', { persist: true });`;
const scriptFalse = `bru.setEnvVar('key2', 'val2', { persist: false });`;
const runtime = new ScriptRuntime({ runtime: 'nodevm' });
const result1 = await runtime.runRequestScript(scriptTrue, {}, {}, {}, '.', null, process.env);
expect(result1.envVariables.key1).toBe('val1');
const result2 = await runtime.runRequestScript(scriptFalse, {}, {}, {}, '.', null, process.env);
expect(result2.envVariables.key2).toBe('val2');
});
it('should silently ignore old persist flag as extra argument — QuickJS parity', async () => {
await quickJsLoader();
const scriptTrue = `bru.setEnvVar('key1', 'val1', { persist: true });`;
const scriptFalse = `bru.setEnvVar('key2', 'val2', { persist: false });`;
const runtime = new ScriptRuntime({ runtime: 'quickjs' });
const onConsoleLog = () => {};
const result1 = await runtime.runRequestScript(scriptTrue, {}, {}, {}, '.', onConsoleLog, process.env);
expect(result1.envVariables.key1).toBe('val1');
const result2 = await runtime.runRequestScript(scriptFalse, {}, {}, {}, '.', onConsoleLog, process.env);
expect(result2.envVariables.key2).toBe('val2');
});
});

View File

@@ -1,112 +1,220 @@
const Bru = require('../src/bru');
const { valueToString } = require('@usebruno/common/utils');
describe('Bru.setEnvVar', () => {
const makeBru = () =>
new Bru({
const makeBru = () =>
new Bru({
runtime: 'quickjs',
envVariables: {},
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test'
});
describe('bru.setEnvVar', () => {
test('sets envVariables[key] to value', () => {
const bru = makeBru();
bru.setEnvVar('token', 'abc123');
expect(bru.envVariables.token).toBe('abc123');
});
test('allows non-string values', () => {
const bru = makeBru();
bru.setEnvVar('count', 42);
expect(bru.envVariables.count).toBe(42);
bru.setEnvVar('active', true);
expect(bru.envVariables.active).toBe(true);
bru.setEnvVar('config', { port: 3000 });
expect(bru.envVariables.config).toEqual({ port: 3000 });
});
test('overwrites existing value', () => {
const bru = makeBru();
bru.setEnvVar('key', 'old');
bru.setEnvVar('key', 'new');
expect(bru.envVariables.key).toBe('new');
});
test('throws when key is empty', () => {
const bru = makeBru();
expect(() => bru.setEnvVar('', 'v')).toThrow(/without specifying a name/);
});
test('rejects key with invalid characters', () => {
const bru = makeBru();
expect(() => bru.setEnvVar('invalid key', 'v')).toThrow(/contains invalid characters/);
});
});
describe('bru.setEnvVar — dirty flag for typed values', () => {
test('setting a number trips the env dirty flag', () => {
const bru = makeBru();
expect(bru._envDirty).toBe(false);
bru.setEnvVar('count', 42);
expect(bru._envDirty).toBe(true);
});
test('setting a boolean trips the env dirty flag', () => {
const bru = makeBru();
bru.setEnvVar('active', true);
expect(bru._envDirty).toBe(true);
});
test('setting an object trips the env dirty flag', () => {
const bru = makeBru();
bru.setEnvVar('config', { port: 3000 });
expect(bru._envDirty).toBe(true);
});
});
describe('bru.deleteEnvVar', () => {
test('removes an existing variable', () => {
const bru = makeBru();
bru.setEnvVar('token', 'abc');
bru.deleteEnvVar('token');
expect(bru.envVariables.token).toBeUndefined();
});
test('deleting a non-existent key is a silent no-op', () => {
const bru = makeBru();
expect(() => bru.deleteEnvVar('missing')).not.toThrow();
});
test('does not delete the internal __name__ marker', () => {
const bru = new Bru({
runtime: 'quickjs',
envVariables: {},
envVariables: { __name__: 'dev', token: 'abc' },
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test'
});
test('updates envVariables and does not mark persistent when persist=false', () => {
const bru = makeBru();
bru.setEnvVar('non_persist', 'value', { persist: false });
expect(bru.envVariables.non_persist).toBe('value');
expect(bru.persistentEnvVariables.non_persist).toBeUndefined();
});
test('updates envVariables and tracks persistent when persist=true (string only)', () => {
const bru = makeBru();
bru.setEnvVar('persist_me', 'value', { persist: true });
expect(bru.envVariables.persist_me).toBe('value');
expect(bru.persistentEnvVariables.persist_me).toBe('value');
});
test('updates envVariables when options are omitted (defaults to non-persistent)', () => {
const bru = makeBru();
bru.setEnvVar('no_options', 'value');
expect(bru.envVariables.no_options).toBe('value');
expect(bru.persistentEnvVariables.no_options).toBeUndefined();
});
describe('persist=true with non-string values', () => {
test('stores numbers as-is without throwing', () => {
const bru = makeBru();
expect(() => bru.setEnvVar('n', 123, { persist: true })).not.toThrow();
expect(bru.envVariables.n).toBe(123);
expect(bru.persistentEnvVariables.n).toBe(123);
});
test('stores booleans as-is without throwing', () => {
const bru = makeBru();
expect(() => bru.setEnvVar('b', true, { persist: true })).not.toThrow();
expect(bru.persistentEnvVariables.b).toBe(true);
});
test('stores plain objects and arrays by reference without throwing', () => {
const bru = makeBru();
const obj = { a: 1 };
const arr = [1, 2, 3];
bru.setEnvVar('o', obj, { persist: true });
bru.setEnvVar('a', arr, { persist: true });
expect(bru.persistentEnvVariables.o).toBe(obj);
expect(bru.persistentEnvVariables.a).toBe(arr);
});
test('stores functions and symbols without throwing — but they round-trip to "" via valueToString', () => {
const bru = makeBru();
const fn = () => 42;
const sym = Symbol('s');
bru.setEnvVar('fn', fn, { persist: true });
bru.setEnvVar('sym', sym, { persist: true });
// Raw values land in persistentEnvVariables...
expect(bru.persistentEnvVariables.fn).toBe(fn);
expect(bru.persistentEnvVariables.sym).toBe(sym);
// ...but the serializer used by mergeAndPersistEnvironment produces ''
// for both, so the value is silently lost on the next save round-trip.
expect(valueToString(fn)).toBe('');
expect(valueToString(sym)).toBe('');
});
test('stores circular objects without throwing — but they round-trip to "" via valueToString', () => {
const bru = makeBru();
const circular = { a: 1 };
circular.self = circular;
bru.setEnvVar('c', circular, { persist: true });
expect(bru.persistentEnvVariables.c).toBe(circular);
// JSON.stringify throws on circulars; valueToString swallows that and returns ''.
expect(valueToString(circular)).toBe('');
});
});
test('changing existing key to non-persistent removes prior persisted entry', () => {
const bru = makeBru();
bru.setEnvVar('same_key', 'old', { persist: true });
expect(bru.persistentEnvVariables.same_key).toBe('old');
bru.setEnvVar('same_key', 'new');
expect(bru.envVariables.same_key).toBe('new');
expect(bru.persistentEnvVariables.same_key).toBeUndefined();
});
test('changing existing key to persistent updates persisted value', () => {
const bru = makeBru();
bru.setEnvVar('same_key', 'old');
expect(bru.persistentEnvVariables.same_key).toBeUndefined();
bru.setEnvVar('same_key', 'new', { persist: true });
expect(bru.envVariables.same_key).toBe('new');
expect(bru.persistentEnvVariables.same_key).toBe('new');
});
test('validates key name - invalid characters are rejected', () => {
const bru = makeBru();
expect(() => bru.setEnvVar('invalid key', 'v')).toThrow(/contains invalid characters/);
bru.deleteEnvVar('__name__');
expect(bru.envVariables.__name__).toBe('dev');
expect(bru._envDirty).toBe(false);
});
});
describe('bru.setEnvVar — dirty flag for reference-mutation idiom', () => {
test('the getEnvVar → mutate → setEnvVar idiom trips the dirty flag', () => {
const bru = new Bru({
runtime: 'quickjs',
envVariables: { config: { port: 3000 } },
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test'
});
expect(bru._envDirty).toBe(false);
// Real-script idiom: `const c = bru.getEnvVar('config'); c.port = 4000; bru.setEnvVar('config', c);`
// `getEnvVar` deep-copies through interpolate's JSON roundtrip, so mutating the result
// leaves envVariables.config untouched; the deep-equal guard then sees a real change.
// Pre-fix the strict-`!==` guard missed cases where the script structurally rebuilt the value.
const config = bru.getEnvVar('config');
config.port = 4000;
bru.setEnvVar('config', config);
expect(bru._envDirty).toBe(true);
expect(bru.envVariables.config).toEqual({ port: 4000 });
});
test('re-setting a structurally-equal object value does NOT trip the dirty flag', () => {
const bru = new Bru({
runtime: 'quickjs',
envVariables: { config: { port: 3000 } },
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test'
});
bru.setEnvVar('config', { port: 3000 });
expect(bru._envDirty).toBe(false);
});
test('re-setting a structurally-equal primitive value does NOT trip the dirty flag', () => {
const bru = new Bru({
runtime: 'quickjs',
envVariables: { token: 'abc' },
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test'
});
bru.setEnvVar('token', 'abc');
expect(bru._envDirty).toBe(false);
});
});
describe('bru.deleteEnvVar — dirty flag contract', () => {
test('deleting an existing key trips the env dirty flag', () => {
const bru = makeBru();
bru.setEnvVar('token', 'abc');
bru._envDirty = false; // reset post-set
bru.deleteEnvVar('token');
expect(bru._envDirty).toBe(true);
});
test('deleting a non-existent key leaves the dirty flag clean', () => {
const bru = makeBru();
bru.deleteEnvVar('missing');
expect(bru._envDirty).toBe(false);
});
});
describe('bru.deleteAllEnvVars — dirty flag contract', () => {
test('deleting populated env trips the dirty flag', () => {
const bru = new Bru({
runtime: 'quickjs',
envVariables: { a: '1', b: '2' },
runtimeVariables: {},
processEnvVars: {},
collectionPath: '/',
collectionName: 'Test'
});
bru.deleteAllEnvVars();
expect(bru._envDirty).toBe(true);
});
test('calling on empty env leaves the dirty flag clean', () => {
const bru = makeBru();
bru.deleteAllEnvVars();
expect(bru._envDirty).toBe(false);
});
});
describe('bru.deleteAll* methods — resilient to user-shadowed Object.prototype methods', () => {
// Use Object.hasOwn (not the property accessor) to check deletion, since after
// delete the prototype's hasOwnProperty becomes visible again on a plain object.
test('deleteAllEnvVars works when a var named "hasOwnProperty" was set', () => {
const bru = makeBru();
bru.setEnvVar('hasOwnProperty', 'shadow');
bru.setEnvVar('other', 'value');
expect(() => bru.deleteAllEnvVars()).not.toThrow();
expect(Object.hasOwn(bru.envVariables, 'hasOwnProperty')).toBe(false);
expect(Object.hasOwn(bru.envVariables, 'other')).toBe(false);
});
test('deleteAllGlobalEnvVars works when a var named "hasOwnProperty" was set', () => {
const bru = makeBru();
bru.setGlobalEnvVar('hasOwnProperty', 'shadow');
bru.setGlobalEnvVar('other', 'value');
expect(() => bru.deleteAllGlobalEnvVars()).not.toThrow();
expect(Object.hasOwn(bru.globalEnvironmentVariables, 'hasOwnProperty')).toBe(false);
});
test('deleteAllCollectionVars works when a var named "hasOwnProperty" was set', () => {
const bru = makeBru();
bru.setCollectionVar('hasOwnProperty', 'shadow');
bru.setCollectionVar('other', 'value');
expect(() => bru.deleteAllCollectionVars()).not.toThrow();
expect(Object.hasOwn(bru.collectionVariables, 'hasOwnProperty')).toBe(false);
});
test('deleteAllVars works when a runtime var named "hasOwnProperty" was set', () => {
const bru = makeBru();
bru.setVar('hasOwnProperty', 'shadow');
bru.setVar('other', 'value');
expect(() => bru.deleteAllVars()).not.toThrow();
expect(Object.hasOwn(bru.runtimeVariables, 'hasOwnProperty')).toBe(false);
});
});