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

@urlspec/builder

v0.3.1

Published

Programmatic API to build URLSpec files

Readme

@urlspec/builder

Programmatic API for building URLSpec files

npm version License: MIT

Overview

@urlspec/builder provides a fluent, programmatic API for generating .urlspec files in TypeScript. Instead of writing URLSpec syntax manually, you can build URLSpec documents using a chainable API, making it ideal for code generation tools, dynamic specification generation, and migration scripts.

Features

  • Fluent API: Chain method calls for readable code
  • Type-Safe: Full TypeScript support with type checking
  • AST Generation: Built on top of @urlspec/language
  • File Output: Write directly to .urlspec files
  • Dynamic Generation: Generate specifications programmatically (e.g., from loops, API schemas)

Installation

# npm
npm install @urlspec/builder

# yarn
yarn add @urlspec/builder

# pnpm
pnpm add @urlspec/builder

Quick Start

import { URLSpec } from '@urlspec/builder';

const spec = new URLSpec();

spec.addParamType('sortOrder', ['recent', 'popular', 'trending']);
spec.addParamType('jobStatus', ['active', 'closed', 'draft']);

spec.addGlobalParam({
  name: 'utm_source',
  type: 'string',
  optional: true,
});

spec.addPage({
  name: 'list',
  path: '/jobs',
  parameters: [
    { name: 'category', type: 'string', optional: true },
    { name: 'sort', type: 'sortOrder' },
  ],
});

spec.addPage({
  name: 'detail',
  path: '/jobs/:job_id',
  parameters: [
    { name: 'job_id', type: 'string' },
    { name: 'preview', type: ['true', 'false'], optional: true },
    { name: 'status', type: 'jobStatus', optional: true },
  ],
});

// Output to string
console.log(spec.toString());

// Write to file
await spec.writeFile('./jobs.urlspec');

Output:

param sortOrder = "recent" | "popular" | "trending";
param jobStatus = "active" | "closed" | "draft";

global {
  utm_source?: string;
}

page list = /jobs {
  category?: string;
  sort: sortOrder;
}

page detail = /jobs/:job_id {
  job_id: string;
  preview?: "true" | "false";
  status?: jobStatus;
}

API Reference

URLSpec

Main builder class for constructing URLSpec documents.

Constructor

const spec = new URLSpec();

Methods

addParamType(name: string, type: ParamType): void

Add a reusable parameter type definition.

// Primitive type
spec.addParamType('status', 'string');

// String literal
spec.addParamType('role', 'admin');

// Union of string literals
spec.addParamType('sort', ['asc', 'desc']);
spec.addParamType('priority', ['low', 'medium', 'high']);

// Reference to another param type (define that type first)
spec.addParamType('userSort', 'sort');

ParamType Definition:

type ParamType = 'string' | string | string[];
addGlobalParam(param: ParameterDefinition): void

Add a global parameter that applies to all pages.

spec.addGlobalParam({
  name: 'utm_source',
  type: 'string',
  optional: true,
});

spec.addGlobalParam({
  name: 'debug',
  type: ['true', 'false'],
  optional: true,
});
addPage(page: PageDefinition): void

Add a page definition.

spec.addPage({
  name: 'user_profile',
  path: '/users/:user_id',
  parameters: [
    { name: 'user_id', type: 'string' },
    { name: 'tab', type: ['posts', 'likes', 'comments'], optional: true },
  ],
});

PageDefinition Interface:

interface PageDefinition {
  name: string;
  path: string;
  parameters?: ParameterDefinition[];
  comment?: string; // Not yet implemented
}

ParameterDefinition Interface:

interface ParameterDefinition {
  name: string;
  type: ParamType;
  optional?: boolean;
}
toAST(): URLSpecDocument

Build and return the Langium AST document.

const ast = spec.toAST();
console.log(ast.pages);
toString(): string

Convert the spec to formatted .urlspec text.

const urlspecText = spec.toString();
console.log(urlspecText);
writeFile(path: string): Promise<void>

Write the spec to a file.

await spec.writeFile('./output/api.urlspec');

Usage Examples

Basic Example

import { URLSpec } from '@urlspec/builder';

const spec = new URLSpec();


spec.addPage({
  name: 'home',
  path: '/',
});

spec.addPage({
  name: 'article',
  path: '/articles/:article_id',
  parameters: [
    { name: 'article_id', type: 'string' },
  ],
});

console.log(spec.toString());

Dynamic Page Generation

Generate multiple similar pages programmatically:

import { URLSpec } from '@urlspec/builder';

const spec = new URLSpec();

// Define available statuses
const statuses = ['pending', 'approved', 'rejected', 'archived'];

// Generate a page for each status
for (const status of statuses) {
  spec.addPage({
    name: `${status}_jobs`,
    path: `/jobs/${status}`,
    parameters: [
      { name: 'page', type: 'string', optional: true },
      { name: 'limit', type: 'string', optional: true },
    ],
  });
}

await spec.writeFile('./jobs.urlspec');

Type Reference Example

import { URLSpec } from '@urlspec/builder';

const spec = new URLSpec();

// Define reusable types
spec.addParamType('category', ['electronics', 'clothing', 'food', 'books']);
spec.addParamType('sortBy', ['price', 'popularity', 'newest']);
spec.addParamType('sortOrder', ['asc', 'desc']);

// Use type references in pages
spec.addPage({
  name: 'products',
  path: '/products',
  parameters: [
    { name: 'cat', type: 'category', optional: true },
    { name: 'sort', type: 'sortBy', optional: true },
    { name: 'order', type: 'sortOrder', optional: true },
  ],
});

spec.addPage({
  name: 'search',
  path: '/search',
  parameters: [
    { name: 'q', type: 'string' },
    { name: 'category', type: 'category', optional: true },
  ],
});

console.log(spec.toString());

Global Parameters Example

import { URLSpec } from '@urlspec/builder';

const spec = new URLSpec();

// Add global tracking parameters
spec.addGlobalParam({
  name: 'utm_source',
  type: 'string',
  optional: true,
});

spec.addGlobalParam({
  name: 'utm_campaign',
  type: 'string',
  optional: true,
});

spec.addGlobalParam({
  name: 'utm_medium',
  type: ['email', 'social', 'cpc', 'banner'],
  optional: true,
});

// These pages will inherit global parameters
spec.addPage({
  name: 'landing',
  path: '/landing',
});

spec.addPage({
  name: 'signup',
  path: '/signup',
  parameters: [
    { name: 'plan', type: ['free', 'pro', 'enterprise'] },
  ],
});

await spec.writeFile('./analytics.urlspec');

Converting from OpenAPI/Swagger

import { URLSpec } from '@urlspec/builder';

// Hypothetical OpenAPI schema
const openAPISchema = {
  basePath: 'https://api.example.com',
  paths: {
    '/users': {
      get: {
        parameters: [
          { name: 'page', type: 'integer' },
          { name: 'limit', type: 'integer' },
        ],
      },
    },
    '/users/{userId}': {
      get: {
        parameters: [
          { name: 'userId', in: 'path', type: 'string' },
        ],
      },
    },
  },
};

// Convert to URLSpec
const spec = new URLSpec();

for (const [path, methods] of Object.entries(openAPISchema.paths)) {
  const getMethod = methods.get;
  if (getMethod) {
    const name = path.replace(/\//g, '_').replace(/[{}]/g, '');
    const urlspecPath = path.replace(/{(\w+)}/g, ':$1');

    spec.addPage({
      name,
      path: urlspecPath,
      parameters: getMethod.parameters.map(p => ({
        name: p.name,
        type: 'string', // All types are string in URLSpec
        optional: p.in !== 'path',
      })),
    });
  }
}

console.log(spec.toString());

Migration from Legacy URL Definitions

import { URLSpec } from '@urlspec/builder';

// Legacy route definitions
const legacyRoutes = [
  { name: 'home', path: '/' },
  { name: 'about', path: '/about' },
  { name: 'contact', path: '/contact' },
  { name: 'product', path: '/products/:id', params: ['id'] },
];

// Convert to URLSpec
const spec = new URLSpec();

for (const route of legacyRoutes) {
  spec.addPage({
    name: route.name,
    path: route.path,
    parameters: route.params?.map(param => ({
      name: param,
      type: 'string',
    })),
  });
}

await spec.writeFile('./website.urlspec');

Advanced Usage

Working with AST

import { URLSpec } from '@urlspec/builder';

const spec = new URLSpec();
spec.addPage({ name: 'home', path: '/' });

// Get the AST
const ast = spec.toAST();

// Access AST properties
console.log(ast.$type); // "URLSpecModel"
console.log(ast.pages.length); // 1

// Use with @urlspec/language functions
import { print } from '@urlspec/language';

const doc = {
  parseResult: { value: ast },
} as any;

console.log(print(doc));

Low-Level AST Creation

For advanced use cases, you can use the exported AST builder functions directly:

import {
  createURLSpecDocument,
  createPageDeclaration,
  createParameterDeclaration,
  createStringType,
  createStringLiteralType,
  createUnionType,
} from '@urlspec/builder';

const ast = createURLSpecDocument({
  // Namespace removed from URLSpec
  pages: [
    createPageDeclaration(
      'users',
      '/users',
      [
        createParameterDeclaration('sort', createStringLiteralType('name'), true),
      ]
    ),
  ],
});

Type Exports

The package exports all necessary TypeScript types:

import type {
  URLSpec,
  ParamType,
  ParameterDefinition,
  PageDefinition,
  // Langium AST types
  URLSpecDocument,
  PageDeclaration,
  ParameterDeclaration,
  Type,
  // ... and more
} from '@urlspec/builder';

Error Handling

import { URLSpec } from '@urlspec/builder';

const spec = new URLSpec();

// Add at least one page
spec.addPage({
  name: 'home',
  path: '/',
});

const ast = spec.toAST(); // Valid URLSpec document
console.log(ast.pages.length); // 1

Use Cases

1. Code Generation Tools

Generate URLSpec files from database schemas, GraphQL schemas, or API documentation.

2. Testing

Programmatically create URLSpec documents for testing parsers and validators.

3. Migration Scripts

Convert legacy routing configurations to URLSpec format.

4. Dynamic Specifications

Generate specs based on runtime configuration or environment variables.

5. API Documentation

Automatically generate URLSpec files from your API implementation.

Development

Building

yarn build

Testing

# Run tests
yarn test

# Watch mode
yarn test:watch

Related Packages

Contributing

Contributions are welcome! Please see the root repository README for contribution guidelines.

Resources

License

MIT License - see LICENSE for details