npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@scriptdb/system-modules

v1.1.2

Published

System module resolver for script database

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-modules

Quick 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): void
  • dbName (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: string | Function): string
  • dbName (string): Name of the database file
  • fnName (string): Name of the function to update
  • code (string | Function): New code content

Returns a string indicating the result of the operation.

remove(dbName, fnName?)

Removes a code snippet from the specified database file.

remove(dbName: string, fnName?: string): string | boolean
  • dbName (string): Name of the database file
  • fnName (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: string | Function | any): void
  • dbName (string): Name of the database file
  • code (string | Function | any): Code content to save

Context Methods

require(moduleName)

Loads a system module by name.

context.require(moduleName: string): any
  • moduleName (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 code

Working 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 functions

Each 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