@scriptdb/system-modules
v1.1.3
Published
System module resolver for script database
Downloads
168
Readme
@scriptdb/system-modules
System module resolver for the script database, providing built-in modules for creating, updating, removing, and saving code snippets.
Features
- Dynamic module loading: Load system modules at runtime
- Code snippet management: Create, update, remove, and save code snippets
- Module registry: Maintain a registry of all available system modules
- Require-like functionality: Access modules using a require-like API
- Import functionality: Access modules using an import-like API
Installation
bun add @scriptdb/system-modulesQuick Start
import { SystemModuleResolver } from '@scriptdb/system-modules';
// Get the system modules context
const context = await SystemModuleResolver();
// Access the built-in modules
const create = context.create;
const update = context.update;
const remove = context.remove;
const save = context.save;
// Create a new code snippet
create('myDatabase', 'function myFunc() { return "Hello, World!"; }');
// Update an existing function
update('myDatabase', 'myFunc', () => { return "Updated function!"; });
// Save entire code to a database
save('myDatabase', 'export const PI = 3.14159;');
// Remove a function
remove('myDatabase', 'myFunc');API Reference
SystemModuleResolver()
Resolves and loads all system modules, creating a context with built-in modules.
await SystemModuleResolver(): Promise<Record<string, any>>Returns a promise that resolves with a context object containing all system modules.
System Modules
create(dbName, code)
Creates a new code snippet in the specified database file.
create(dbName: string, code: string | Function): voiddbName(string): Name of the database file (without extension)code(string | Function): Code content of the snippet
update(dbName, fnName, code)
Updates an existing code snippet in the specified database file.
update(dbName: string, fnName: string, code: unknown): stringdbName(string): Name of the database filefnName(string): Name of the function to updatecode(unknown): New code content or runtime value
Returns a string indicating the result of the operation.
If the target symbol already exists, update replaces that declaration in place and preserves surrounding exports or type annotations when possible.
remove(dbName, fnName?)
Removes a code snippet from the specified database file.
remove(dbName: string, fnName?: string): string | booleandbName(string): Name of the database filefnName(string, optional): Name of the function to remove. If not provided, removes the entire file.
Returns a string or boolean indicating the result of the operation.
save(dbName, code)
Saves code content to the specified database file, overwriting any existing content.
save(dbName: string, code: unknown): voiddbName(string): Name of the database filecode(unknown): Code content or runtime value to save
Context Methods
require(moduleName)
Loads a system module by name.
context.require(moduleName: string): anymoduleName(string): The name of the module to load
Returns the module's default export if available, otherwise the module itself.
import(moduleName)
Asynchronously loads a system module by name.
context.import(moduleName: string): Promise<{ default: any }>moduleName(string): The name of the module to load
Returns a promise that resolves with an object containing the module's default export.
Examples
Creating and Managing Code Snippets
import { SystemModuleResolver } from '@scriptdb/system-modules';
const context = await SystemModuleResolver();
// Create a new function in a database
context.create('math', `
function add(a: number, b: number): number {
return a + b;
}
`);
// Update an existing function
context.update('math', 'add', (a: number, b: number) => {
console.log(`Adding ${a} and ${b}`);
return a + b;
});
// Add a new function to the same database
context.create('math', `
function multiply(a: number, b: number): number {
return a * b;
}
`);
// Save a complete module
context.save('utils', `
export const formatDate = (date: Date): string => {
return date.toISOString().split('T')[0];
}
export const capitalize = (str: string): string => {
return str.charAt(0).toUpperCase() + str.slice(1);
}
`);Using the Module Context
import { SystemModuleResolver } from '@scriptdb/system-modules';
// Get the system modules context
const context = await SystemModuleResolver();
// Access modules directly
const create = context.create;
const update = context.update;
// Create a new module
create('userManagement', `
class UserManager {
private users: Array<{ id: number; name: string }> = [];
addUser(name: string): void {
const id = this.users.length + 1;
this.users.push({ id, name });
}
getUser(id: number): { id: number; name: string } | undefined {
return this.users.find(user => user.id === id);
}
listUsers(): Array<{ id: number; name: string }> {
return [...this.users];
}
}
export default UserManager;
`);
// Use the require-like functionality
const userModule = context.require('userManagement');
// In this case, userModule will contain the user management codeWorking with Different Module Types
import { SystemModuleResolver } from '@scriptdb/system-modules';
const context = await SystemModuleResolver();
// Create a class-based module
context.create('database', `
class SimpleDatabase {
private data: Record<string, any> = {};
set(key: string, value: any): void {
this.data[key] = value;
}
get(key: string): any {
return this.data[key];
}
has(key: string): boolean {
return key in this.data;
}
delete(key: string): boolean {
if (this.has(key)) {
delete this.data[key];
return true;
}
return false;
}
clear(): void {
this.data = {};
}
}
export default SimpleDatabase;
`);
// Create a functional module
context.create('stringUtils', `
export const reverse = (str: string): string => {
return str.split('').reverse().join('');
};
export const truncate = (str: string, length: number): string => {
return str.length > length ? str.slice(0, length) + '...' : str;
};
export const slugify = (str: string): string => {
return str
.toLowerCase()
.replace(/[^a-z0-9 -]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-');
};
`);
// Update a specific function in a module
context.update('stringUtils', 'reverse', (str: string) => {
return Array.from(str).reverse().join('');
});Managing Database Files
import { SystemModuleResolver } from '@scriptdb/system-modules';
const context = await SystemModuleResolver();
// Create a new database file with multiple functions
context.save('api', `
import { fetch } from 'bun';
// Function to make GET requests
export async function get(url: string): Promise<any> {
const response = await fetch(url);
return await response.json();
}
// Function to make POST requests
export async function post(url: string, data: any): Promise<any> {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return await response.json();
}
// Function to make PUT requests
export async function put(url: string, data: any): Promise<any> {
const response = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return await response.json();
}
// Function to make DELETE requests
export async function del(url: string): Promise<any> {
const response = await fetch(url, {
method: 'DELETE'
});
return await response.json();
}
`);
// Add a new function to the existing database
context.create('api', `
export async function patch(url: string, data: any): Promise<any> {
const response = await fetch(url, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
return await response.json();
}
`);
// Update an existing function
context.update('api', 'get', async (url: string) => {
const response = await fetch(url);
return await response.json();
});
// Remove a specific function
context.remove('api', 'del');
// Remove the entire database file (after creating a backup)
context.remove('api');Error Handling
The System Module Resolver will throw an error if:
- A module is not found when using require() or import()
- There are issues with file operations
import { SystemModuleResolver } from '@scriptdb/system-modules';
try {
const context = await SystemModuleResolver();
try {
const module = context.require('non-existent-module');
} catch (error) {
console.error('Module not found:', error.message);
}
} catch (error) {
console.error('Failed to load system modules:', error.message);
}File Structure
System modules are stored in TypeScript files in the ./databases/system-modules directory:
./databases/system-modules/
├── myDatabase.ts # Database file for code snippets
├── math.ts # Mathematical functions
├── api.ts # API-related functions
└── utils.ts # Utility functionsEach file can contain TypeScript code, including functions, classes, and exports.
Security Considerations
- Validate code content before saving to prevent injection attacks
- Consider implementing a sandboxed environment for executing code snippets
- Limit file system access to prevent unauthorized access to sensitive files
- Regularly backup your databases to prevent data loss
License
MIT
