Deterministic Star-Themed ID Generator – stellar-id

Category: Javascript | October 27, 2026
Authormahirliy55
Last UpdateOctober 27, 2026
LicenseMIT
Tags
Views0 views
Deterministic Star-Themed ID Generator – stellar-id

stellar-id is a JavaScript and TypeScript utility for generating repeatable star-themed identifiers from text. It combines a four-digit hash with a star name and supports custom prefixes, star lists, letter case, and output formats.

Features

  • Three hash algorithms: simple, djb2, and fnv1a.
  • Optional salt and total-length controls.
  • Synchronous and asynchronous generation functions.
  • A local star catalog with distance, magnitude, spectral type, and constellation fields.
  • Batch generation, progress callbacks, and duplicate detection.
  • ID validation, parsing, and cache management utilities.
  • URL construction with QR-image links and optional expiration metadata.

How To Use It

Installation

Install the package in your JavaScript or TypeScript project:

npm install stellar-id

Basic Usage

Pass a nonempty string to generateStellarID(). The default ID uses the STAR-0000-STARNAME structure, with a four-digit hash and one of ten star names. Inputs must contain non-whitespace text and cannot exceed 1,000 characters.

Enforce a unique constraint if you store these IDs as database keys.

import { generateStellarID } from 'stellar-id';
const projectId = generateStellarID('cssscript-project-42');
console.log(projectId);

Customize The Generated ID

Set a custom prefix, select a hash algorithm, or arrange the ID parts with a format string. Custom star names replace the ten default names.

The standard validator rejects outputs with reordered parts, lowercase letters, or a nonstandard hash length.

import { generateStellarID } from 'stellar-id';
const reference = generateStellarID('article-381', {
  prefix: 'DOC',
  hashAlgorithm: 'fnv1a',
  customStarNames: ['VEGA', 'RIGEL', 'SIRIUS'],
  format: '{prefix}-{star}-{hash}',
  case: 'upper',
  enableCache: false
});
console.log(reference);

Generate A Batch With Progress Updates

generateBatchStellarIDs() returns successful IDs, errors, timing fields, and metrics. The optional progress callback runs after each successful generation.

import { generateBatchStellarIDs } from 'stellar-id';
const result = await generateBatchStellarIDs(
  ['project-alpha', 'project-beta', 'project-gamma'],
  { prefix: 'ITEM' },
  ({ current, total, currentId }) => {
    console.log(`${current}/${total}: ${currentId}`);
  }
);
console.log(result.ids);
console.log(result.errors);

Get Star Information

getRealStarDataAsync() reads the bundled star catalog and makes no external astronomy request. The ID generators use ten default star names, independent of the larger catalog, unless you supply customStarNames.

import {
  getRealStarDataAsync,
  getStarInfo,
  getRealStarNames
} from 'stellar-id';
const catalog = await getRealStarDataAsync();
const sirius = getStarInfo('SIRIUS');
const starNames = getRealStarNames();
console.log(catalog.length);
console.log(sirius?.constellation);
console.log(starNames);

Generate A URL And QR Image Link

The URL functions construct links and metadata. They do not host redirects, record analytics events, check passwords, or enforce expiration. Your server must supply those features before the links can function as a short-link service. The password option exposes its value in a URL query string. Requesting the generated QR-image URL sends the encoded link to an external QR service.

import { generateStellarID, generateStellarURL } from 'stellar-id';
const id = generateStellarID('public-project');
const link = await generateStellarURL(id, {
  domain: 'example.com',
  path: 'projects',
  analytics: false
});
console.log(link.shortUrl);
console.log(link.qrCode);

Configuration Options

  • prefix (string, default 'STAR'): Text before the hash. A nonempty value permits letters, numbers, _, and -, with a maximum of 20 characters.
  • length (number, optional): Total output length from 1 to 100. Use an integer. Shorter values truncate the formatted ID; longer values append deterministic characters. This does not change the four-digit hash.
  • useSpecialChars (boolean, default false): Permits punctuation in filler characters when length extends the ID. It does not add punctuation to a standard-length ID.
  • case ('upper' | 'lower' | 'mixed', default 'upper'): Changes output casing. Mixed case converts alternating eligible uppercase letters to lowercase.
  • hashAlgorithm ('simple' | 'djb2' | 'fnv1a', default 'simple'): Chooses a non-cryptographic string hash.
  • customStarNames (string[], optional): Replaces the ten default star names. Supply an array of nonempty strings; an empty array fails validation.
  • format (string, optional): Custom output pattern with {prefix}, {hash}, and {star} placeholders; {input} inserts the first ten input characters. The default is {prefix}-{hash}-{star}.
  • salt (string, optional): Appends extra text to the input before hashing. A nonempty salt can contain at most 100 characters; it is not a secret-key or encryption mechanism.
  • enableCache (boolean, default true): Controls hash caching in generateStellarID().

ID Generation And Utility API

FunctionDescription
generateStellarID(input, options?)Returns a formatted ID string synchronously.
generateStellarIDAsync(input, options?)Returns a Promise<string> with a formatted ID; uses the default star list unless customized and does not update global performance metrics.
generateBatchStellarIDs(inputs, options?, progressCallback?)Generates IDs from string[] and returns a Promise<BatchGenerationResult>. Failed inputs go into errors.
generateValidatedBatchStellarIDs(inputs, options?)Generates a batch, validates the output format, and returns unique IDs plus duplicate and invalid ID arrays.
validateStellarID(id)Checks the uppercase PREFIX-1234-STARNAME pattern; does not verify that an ID was originally issued.
extractStellarIDParts(id)Returns { prefix, hash, starName } or null for an invalid pattern. Avoid hyphens inside a prefix when parsing.
getAvailableStarNames()Returns the ten default generator star names.
getAvailableHashAlgorithms()Returns ['simple', 'djb2', 'fnv1a'].
getRealStarNames()Returns names from the separate local astronomy catalog.
getRealStarDataAsync()Returns a promise for the local array of star records.
getStarInfo(starName)Looks up a catalog entry case-insensitively, or returns null.

A star record contains name: string and optional distance: number (light-years), magnitude: number, spectral_type: string, and constellation: string fields.

The batch result fields are ids: string[], totalTime: number, averageTime: number, errors: { input: string; error: string }[], and performanceMetrics: PerformanceMetrics. The validated batch result contains ids, duplicates, invalid, and validCount. Its invalid array concerns generated IDs that fail format validation, not every rejected input string.

URL API

FunctionDescription
generateStellarURL(stellarId, config?)Returns Promise<URLShortenerResult> with a constructed HTTPS URL.
generateBatchStellarURLs(stellarIds, config?)Returns an array of URL results; invalid entries are skipped with a console warning.
generateBrandedStellarURL(stellarId, brand)Builds a branded URL from brand.name and optional domain data.
generateTemporaryStellarURL(stellarId, expiresIn)Returns a URL result with expiration metadata; expiresIn is a number of days.
generateProtectedStellarURL(stellarId, password)Appends an encoded password query parameter; no access check occurs.
validateStellarURL(url)Checks URL syntax, a hostname containing stellar, and a matching ID in the URL path; it does not authenticate a domain or check link availability.
extractStellarIDFromURL(url)Returns the first path segment matching the standard ID pattern, or null.

Available URLShortenerConfig properties:

  • domain (string, default 'stellar.id'): Hostname used to construct the URL.
  • subdomain (string, optional): Prepends a hostname label before domain.
  • expiresIn (number, default 0): Number of days used to calculate expiresAt; zero omits expiration metadata.
  • password (string, optional): Adds a URL-encoded p query parameter, visible to anyone with the link.
  • analytics (boolean, default true): Generates a trackingId field; it does not collect events.
  • path (string, optional): Inserts a URL segment before the ID.

URLShortenerResult contains originalId: string, shortUrl: string, createdAt: Date, and optional qrCode: string, expiresAt: Date, and trackingId: string. Despite its property name, qrCode contains a URL to a third-party QR-image service rather than an inline image data URL.

generateBrandedStellarURL() takes a brand object with required name: string and optional domain: string, logo: string, and colors: { primary: string; secondary: string }. Only name and domain affect the URL; logo and colors do not change the result. Use a DNS-safe name, since the helper only lowercases text and replaces spaces with hyphens.

Cache And Performance API

ExportDescription
clearStellarIDCaches()Clears internal hash and star caches; returns the number of deleted entries.
getStellarIDCacheStats()Returns hashCacheSize, starNamesCacheSize, totalCacheSize, and maxCacheSize.
getPerformanceMetrics()Returns global generation metrics.
resetPerformanceMetrics()Resets the global metrics.
performanceMonitorShared PerformanceMonitor instance.
PerformanceMonitorExported class for recording generation timing and cache-hit data.

PerformanceMetrics includes generationTime, cacheHitRate, totalGenerations, cacheHits, and cacheMisses, all numbers. BatchProgressCallback receives { current, total, percentage, currentId, completedIds } after a successful generation.

A PerformanceMonitor instance also exposes recordGeneration(time: number, cacheHit: boolean): void, getMetrics(): PerformanceMetrics, and reset(): void.

Alternatives

You Might Be Interested In:


Leave a Reply