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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@weweb/backend-core

v0.3.3

Published

Core library for building and serving backend workflows in WeWeb applications

Downloads

89

Readme

WeWeb Backend Core

Core library for building and serving backend workflows in WeWeb applications. This package provides the foundation for creating configurable, secure API endpoints with flexible request handling and integration with external services.

Features

  • API route handling and serving with Hono
  • Dynamic workflow configuration and execution
  • Security configuration with public/private access rules
  • Advanced input validation and mapping
  • Integration with external services via pluggable integrations
  • Error handling and response formatting
  • CORS support
  • SSE streaming support
  • Formula evaluation system

Installation

# npm
npm install @weweb/backend-core

# pnpm
pnpm add @weweb/backend-core

# yarn
yarn add @weweb/backend-core

Basic Usage

import { serve } from '@weweb/backend-core';

// Define your backend configuration
const config = {
  workflows: [
    {
      id: 'hello-workflow',
      name: 'Hello API',
      path: '/hello',
      methods: ['GET'],
      security: {
        accessRule: 'public',
      },
      firstAction: 'hello_action',
      actions: {
        hello_action: {
          id: 'hello_action',
          type: 'action',
          name: 'Say Hello',
          actionId: 'example.say_hello',
          inputMapping: {},
          next: null,
        },
      },
    },
  ],
  integrations: [
    {
      slug: 'example',
      _packageVersion: '1.0.0',
      methods: {
        say_hello: () => {
          return { message: 'Hello from WeWeb Backend!' };
        },
      },
    },
  ],
  production: false,
};

// Start the server
serve(config);
console.log('Server running on http://localhost:8000');

Core Concepts

Backend Configuration

The backend configuration defines the structure for your backend server:

interface BackendConfig {
  workflows: Workflow[]
  integrations: Integration[]
  production: boolean
  rolesConfig?: RolesConfig
  apiKey?: string
  pathPrefix?: string
  corsOptions?: CorsOptions
}

Workflows

Workflows define API endpoints with their HTTP methods, security settings, parameters validation, and actions:

interface Workflow {
  /** Unique identifier for this workflow */
  id: string

  /** Name of the workflow */
  name: string

  /** Metadata for the workflow including path, method and security */
  metadata?: WorkflowMetadata

  /** Parameters for request inputs validation */
  parameters?: Parameter[]

  /** ID of the first action to execute in the workflow */
  firstAction: string

  /** ID of the first action to execute in the error path, or null if not handled */
  firstErrorAction?: string | null

  /** Map of actions keyed by their ID */
  actions: Record<string, WorkflowAction>
}

interface WorkflowMetadata {
  /** URL path for this endpoint (e.g., "/users" or "/products/:id") */
  path?: string

  /** HTTP method this endpoint supports (GET, POST, etc.) */
  method: HttpMethod

  /** Security configuration for this endpoint */
  security?: SecurityConfig
}

interface Parameter {
  /** Type of the parameter */
  type: 'string' | 'number' | 'boolean' | 'object' | 'array'

  /** Name of the parameter */
  name: string

  /** Whether this parameter is required */
  required?: boolean
}

interface SecurityConfig {
  /** Whether the endpoint is public or private */
  accessRule: 'public' | 'private'

  /** List of roles that have access when accessRule is "private" */
  accessRoles?: string[]

  /** How to combine multiple roles: "OR" (any role grants access) or "AND" (all roles required) */
  accessRolesCondition?: 'OR' | 'AND'
}

Integrations

Integrations allow external services to be accessed through defined methods:

interface Integration {
  slug: string
  _packageVersion: string
  methods: {
    [slug: string]: (...args: any[]) => MaybePromise<any>
  }
}

Advanced Features

Input Validation

Define parameters for request validation:

const workflow = {
  // ...
  parameters: [
    {
      type: 'string',
      name: 'name',
      required: true
    },
    {
      type: 'string',
      name: 'email',
      required: true
    }
  ],
  // ...
};

Security Rules

Configure endpoints with public or private access rules:

const workflow = {
  // ...
  metadata: {
    security: {
      accessRule: 'private',
      accessRoles: ['admin', 'editor'],
      accessRolesCondition: 'OR', // User needs to be either admin OR editor
    }
  }
  // ...
};

Multi-action Workflows

Chain multiple actions in a workflow and pass results between them:

const workflow = {
  // ...
  firstAction: 'get_data',
  actions: {
    get_data: {
      id: 'get_data',
      type: 'action',
      name: 'Get Data',
      actionId: 'example.getData',
      inputMapping: {
        id: '$query.id'
      },
      next: 'process_data',
    },
    process_data: {
      id: 'process_data',
      type: 'action',
      name: 'Process Data',
      actionId: 'example.processData',
      inputMapping: {
        data: '$results.get_data'
      },
      next: null,
    },
  },
  // ...
};

SSE Streaming

Stream data to clients using Server-Sent Events by returning an AsyncIterator from your workflow:

// Example of a workflow action that returns an AsyncIterator
const streamingAction = {
  id: 'stream-data',
  type: 'custom-js',
  name: 'Stream Large Dataset',
  inputs: {},
  code: `
    // Define an async generator function
    async function* generateData() {
      for (let i = 0; i < 100; i++) {
        // Simulate processing time
        await new Promise(resolve => setTimeout(resolve, 100));
        yield { index: i, value: Math.random() * 100 };
      }
    }

    // Return the async iterator directly
    return generateData();
  `,
  next: null,
};

Custom CORS Configuration

Configure Cross-Origin Resource Sharing (CORS) options to control which domains can access your API:

const config = {
  // ...other config properties
  corsOptions: {
    // Allow requests only from specific origins
    origin: ['https://app.example.com', 'https://admin.example.com'],

    // Specify allowed HTTP methods
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],

    // Allow specific headers
    allowHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'],

    // Enable credentials (cookies, auth headers)
    credentials: true,

    // Cache preflight requests for 1 hour (in seconds)
    maxAge: 3600,

    // Expose these headers to the browser
    exposeHeaders: ['Content-Length', 'X-Request-Id'],
  }
};

If corsOptions is not provided, a default permissive configuration is used:

  • origin: '*' (allows requests from any domain)
  • Standard HTTP methods
  • Common headers like 'Content-Type' and 'Authorization'

Formula Evaluation

Use formulas to dynamically compute values from request data and previous action results:

const workflow = {
  // ...
  actions: {
    some_action: {
      // ...
      inputMapping: {
        computed: {
          __wwtype: 'f',
          code: 'context.http.query.id + context.http.body.data.value'
        },
        advancedComputed: {
          __wwtype: 'js',
          code: `
            const id = parseInt(context.http.query.id);
            const value = context.http.body.data.value;
            return id + value;
          `
        }
      }
    }
  }
};

Development

Testing

# Run all tests
pnpm test

# Run tests with coverage
pnpm test --coverage

Code Quality

# Format code
pnpm format

# Run linter
pnpm lint

# Check types
pnpm typecheck

# Combined code quality check
pnpm lint && pnpm typecheck

Related Packages

License

MIT