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 🙏

© 2024 – Pkg Stats / Ryan Hefner

ninja-server

v1.1.5

Published

![Image description](src/ninjaServerLogo.svg)

Downloads

25

Readme

Ninja Server

Image description

Install

npm i ninja-server

Run Server

To run and start the server:

npx run

Table of Contents

Introduction

A powerful server for developing and deploying websites.

With this tool you can easily and quickly create your dream website.

One of the standout features is the automatic generation of the server API from functions in the "API" folder. This can help speed up development by reducing the amount of boilerplate code needed to set up the server API. Additionally, the generation of the corresponding "clientAPI" folder can simplify the process of calling the server API from the front-end without having to worry about URL structures.

It also integrate with TypeScript a useful feature, as it provides type checking and improves the overall maintainability of the code.

Finally, the presence of a public folder for static resources and front-end code makes it easy to organize and serve static content.

Features

  • Automatic File-based Routing
    Automatically maps URLs to files in the public folder, simplifying routing without manual configurations.

  • JSX Support
    Allows you to use JSX syntax for building component-based UI, making it easy to integrate React-like workflows.

  • TypeScript Support
    Supports TypeScript files (.ts and .tsx), enabling type-safe development with better code quality and IDE support.

  • Auto Resource Injection
    Automatically includes JavaScript and CSS resources in HTML files, eliminating the need for manual <link> or <script> tags.

  • Dynamic API Generation
    Creates API endpoints automatically from files in the API folder, so server-side logic is neatly organized and accessible.

  • Client-side API Generation
    Generates a client-side API based on the structure of the API folder, allowing easy integration of backend services in front-end code.

  • Live Reloading
    Monitors files for changes and automatically reloads the server, speeding up the development process with live updates.

  • Extendable via Plugins
    Extend and customize the server's behavior using a configuration-based plugin system, allowing easy integration of additional features.

Server Structure

  • Public:
    This folder is used to serve static content and resources that are accessible to the client. All files that the client can view, such as HTML, CSS, JavaScript, images, and other assets, are placed here.

  • API (optional):
    This folder is used to define server-side APIs. The Ninja server automatically generates API routes based on the structure of this folder, allowing you to easily create backend services.

  • Client API:
    Based on the contents of the API folder, this folder is automatically generated inside public folder. It provides client-side access to the APIs defined in the API folder, making it easy to interact with backend functionality from the front end.

Configuration

Note that these folder names can be customized through the configuration file (server.config.js). This file allows you to further configure the server, such as setting the host, port, and other settings. If the configuration file does not exist, it will be automatically generated.

Routing System

The Ninja server is designed to serve static files from a designated folder, typically called public. It features a simple file-based routing system, making it easy to map URLs to files in the directory structure.

The Ninja server's routing system works by mapping the URL paths requested by users directly to the file paths within the public folder.

  1. Public Directory:
    All of your site’s files are placed in a folder named public. This folder acts as the root directory for all static content.

  2. File Path Mapping:
    The URL requested by the user is translated to the corresponding file path in the public folder. For example:

    • A request for http://yourwebsite.com/index.html will look for the file at /public/index.html.
    • A request for http://yourwebsite.com/css/styles.css will look for the file at /public/css/styles.css.
  3. Handling URLs without File Extensions:
    If the user requests a URL without specifying a file extension, the server will attempt to find the appropriate file. For example:

    • A request for http://yourwebsite.com/about could resolve to /public/about.html or /public/about/index.html.

This routing system makes it simple to serve static websites without the need to define individual routes in your code.

JSX Support

The Ninja Server provides robust support for both JSX and TSX, facilitating the creation of reusable components and modular design, which significantly simplifies the process of building webpages.

Expected Structure

JSX and TSX files should export a default function that returns the desired content. The server will execute this function to render the content visually for the client. If a requested file does not contain a default function, the server will throw an error.

Note on Static Content

It’s important to understand that the returned default function is executed only once, meaning it is treated as a static resource.

If your application requires dynamic content, you will need to:

  • Separate the logic from the rendering and fetch data from the API.
  • Utilize JavaScript to manipulate the DOM or update the content as necessary.

TypeScript Configuration for .tsx Files

To enable TypeScript support specifically for .tsx files within the public folder, the Ninja Server automatically generates a tsconfig.json file. This configuration is tailored to support TypeScript in the public folder only, ensuring that it does not interfere with any existing tsconfig.json files in your project.

By following these guidelines, you can take full advantage of JSX and TypeScript to create dynamic and modular web applications effortlessly.

Typescript Configuration for .tsx files inside public folder

It will generate the tsconfig.json file in public to enable the typescript support accordingly and only for public folder so it won't use the project tsconfig if exists.

Automatic Resource Injection

These features helps streamline development by reducing manual work and ensuring that your styles and scripts are automatically linked to their respective HTML files.

Automatic Inject CSS & JS

The Ninja server includes a powerful feature that automatically injects resources such as CSS and JavaScript files into the corresponding HTML files within the same folder.

  1. Folder-based Resource Detection:
    The server scans the folder for any CSS or JavaScript files located alongside the HTML file. It will automatically insert <link> tags for CSS files and <script> tags for JavaScript files directly into the HTML file.

  2. Automatic Injection:

    • If an HTML file (e.g., /public/index.html) is served, the server will search for CSS and JS files within the same folder (e.g., /public/index.css, /public/index.js).
    • The server will then insert appropriate tags inside the <head> or <body> of the HTML file:
      <link rel="stylesheet" href="index.css" />
      <script src="index.js"></script>
  3. No Manual Linking Required:
    This feature eliminates the need to manually include <link> and <script> tags in your HTML files. If CSS or JS files are present in the same directory or imported by within JSX file , the server automatically adds the necessary tags to ensure they are loaded when the HTML page is served.

  4. Flexible and Dynamic:
    This process works for any HTML kind of file like JSX in the public directory. As long as the resources are located in the same folder as the HTML file or it's component required by JSX file, the server will handle the injection for you.

Automatic Node Module Bundling and Script Ordering

The Ninja server also includes a feature that automatically bundles any required Node.js modules within JavaScript files and ensures that scripts are inserted in the correct order in the HTML file.

  1. Node Module Bundling:
    When a JavaScript file served by the Ninja server contains a require statement for a Node.js module, the server will automatically bundle the module into the script. This ensures that the module is included and available for use without needing a separate bundling tool.

    For example, if /public/app.js contains:

    const _ = require("lodash")

    The Ninja server will bundle lodash into the final output when serving app.js.

    <script src="loadash"></script>
  2. Automatic Script Ordering:
    If multiple JavaScript files are detected in the same folder as the HTML file, the server will ensure that they are injected in the correct order into the HTML file. This prevents dependency issues between scripts. For example:

    • Assuming app.js depends on loadash in the HTML file , the server will place <script> tags in the appropriate order:
    <script src="loadash"></script>
    <script src="app.js"></script>
  3. No Manual Bundling Required:
    This feature removes the need to manually bundle JavaScript files or include Node.js modules using third-party bundling tools. The server automatically handles bundling and ensures all scripts are loaded in the correct order.

  4. Efficient and Convenient:
    The bundler is created from scratch to be as fast as possible during development for live changes , by bundling Node.js modules and organizing scripts for you, the server simplifies the development process, especially for projects that involve multiple JavaScript files and dependencies.

Automatic Plugin-based Transpilation and Resource Injection

The Ninja server supports handling files that need to be transpiled into JavaScript or CSS by leveraging plugins, making it easy to work with pre-processor languages such as Sass and Less.

  1. Plugin-based Transpilation:
    The server can handle various types of files processed by plugins. For example, if you're using Sass (.scss) or Less (.less), the server will automatically transpile these files into CSS. The server currently supports the Sass and Less plugins.

  2. Standardized Resource Injection:
    Once the files are transpiled, the server will treat them as standard CSS files. For example, if you have a .scss or .less file, the server will generate a .css file and automatically inject it into the corresponding HTML file. It does this using standard <link> tags, ensuring that the styles are properly loaded:

    <link rel="stylesheet" href="styles.css" />
  3. No More Need to Worry About Including:
    You no longer need to manually link or render these resources in your HTML files. The Ninja server handles everything for you, making sure that transpiled files are properly injected into the HTML in their correct format (".js" , ".css"). This ensures seamless integration and makes development faster and easier.

Adding Plugin

To extend the functionality of the Ninja Server, you can easily add your own plugins by specifying them in the server.config.js file under the plugins array property.

A plugin is an object with the following structure:

type Plugin = {
  rawExtension: string // The original file extension, e.g., ".sass"
  toExtension: string // The target file extension after conversion, e.g., ".css"
  converter: (path: string) => Promise<string> | string // A function that converts or compiles the raw file to the desired output
}

By using plugins, you can integrate support for additional file types or pre-processors (such as SASS or LESS) seamlessly. This flexibility allows you to customize and enhance the server’s behavior to suit your project’s needs, making the process of adding resources both simple and powerful.

API

API Folder

The ninja server scans through the API directory defined in server.config.js and automatically creates URLs based on the folder structure. It processes .ts and .js files within this directory and dynamically maps them to API endpoints.

  • The server inspects all the exported functions within the files and exposes them as API routes.
  • The URL structure is generated by combining the filename and the exported function names, similar to how the routing system works for the public folder.

For example, if the API folder contains a file named users.js and it exports a function called login, the server will automatically generate the following API endpoint:

/users/login

API Parameters & Return Type

Each API function receives exactly one object as its parameter, which contains the data from the request. This object is constructed by parsing the URL query parameters or the POST body, depending on the request type.

  • Request Parsing: The server automatically parses URL queries or POST body data and passes them to the function as a single object argument.
  • Return Type: There are no restrictions on the return type of the API function. You can return any data structure, and the server will handle the response accordingly.
type API_Function = (p: Record<string, any>) => any

This setup makes API development intuitive by automating URL generation and streamlining parameter handling.

API Parameters: __request Property

In cases where developers need to access the raw request details—such as processing headers, checking the HTTP method, or other request-specific information—the __request property is available.

This property provides a direct reference to the request object, with the type IncomingMessage from Node.js. It allows you to handle low-level request operations while still working within the Ninja server's framework.

For example, you can use __request to:

  • Inspect and manipulate HTTP headers.
  • Determine the request method (e.g., GET, POST).
  • Access other request metadata or body content beyond the usual API parameters.

API Response

API functions can return any type and it will be wrapped up by appropriate statusCode and headres . For example on successful execution :

{
  statusCode: 200,
  headers: headers // needed headers for the returned_value type
}

If an error catched during exucting such API, it will also wrap the error in such:

{
  statusCode: 500,
  headers: headers // needed headers for the error type
}

In order to send another statusCode or some headers, currently the only way is to throw an object with statusCode property`. In this case it will assign the givin statusCode and headers to the response.

async function login({usernaem, password}){
  // ...code
  throw {
    statusCode: 400 // any code,
    //headers: {} // optional
    message: "any message"
  }
}

Client-Side API

The Ninja Server automatically generates a client-side API, simplifying frontend development by providing functions that correspond to the server-side API. Instead of manually constructing API requests, you can simply call these functions with the desired parameters.

Each generated function mirrors the API structure and accepts:

  1. Parameters: The data required for the API.
  2. Options (optional): An additional parameter similar to the fetch API’s RequestInit object, allowing further customization of the request (e.g., headers, method, etc.).

TypeScript Support

It is highly recommended to use TypeScript. The Ninja Server intelligently includes type definitions, ensuring that:

  • API calls are type-safe, preventing errors due to incorrect parameter types or values.
  • The development process is streamlined, reducing debugging time and speeding up frontend development.

Example

Here’s an example of a server-side API:

//  api/users.ts
export function login({ username, password }: Omit<User, "auth">): string {
  // Returns a JWT token or throws an error if not found
}
type User = {
  username: string
  password: string
  auth: "admin" | "standard"
}

The automatically generated client-side API would look like this:

//  public/clientApi/users.ts
export const login: (
  { username, password }: Omit<User, "auth">,
  options?: RequestInit
) => Promise<string> = (data, options = {}) => {
  // code
}
type User = {
  username: string
  password: string
  auth: "admin" | "standard"
}

As you can see, the type definitions are carried over to the client-side, ensuring that you know exactly what parameters the function expects. This makes development faster, more reliable, and eliminates the risk of mistyped or invalid data being sent to the API.

Summary

The Ninja Server is designed to streamline the development process for modern web applications by providing a robust and flexible framework. Key features include:

  • Intutive Routing: The server automatically generates routes based on the directory structure within the public folder, allowing for seamless navigation and organization of static content.

  • Auto Resource Injection: Greatly helps streamline development by reducing manual work and the total overhead of view-kind files.

  • Dynamic API Generation: The API folder structure allows for dynamic URL generation based on filenames and exported functions, facilitating easy server-side integration.

  • Client-Side API Generation: APIs are generated automatically for the client-side, simplifying frontend development. Functions mirror server-side APIs and include TypeScript definitions for type safety.

  • JSX Support: Supports both JSX and TSX for building reusable components.

With its focus on modularity, type safety, and ease of use, Ninja Server empowers developers to create efficient, maintainable web applications with minimal overhead. Whether you're building APIs or crafting dynamic components, Ninja Server provides the tools needed to enhance your development workflow.