@spike-land-ai/shared

v1.0.1

Published

Shared TypeScript types, constants, validations, and utilities for Spike Land's web and mobile applications.

Readme

@spike-land-ai/shared

Shared TypeScript types, constants, validations, and utilities for Spike Land's web and mobile applications.

Overview

This package provides cross-platform code sharing between:

  • Web App (Next.js 16)
  • Mobile App (Expo/React Native)

By extracting common code into this shared package, we ensure type safety and consistent behavior across all platforms.


Installation

This package is published to GitHub Packages under @spike-land-ai/shared.

// In web app or mobile app
import { TOKEN_REGENERATION, User } from "@spike-land-ai/shared";

Exports

Types (/types)

TypeScript interfaces extracted from the Prisma schema:

| Type | Description | | ------------------ | ---------------------------------------- | | User | User profile with role and referral info | | UserTokenBalance | Token balance with regeneration tracking | | TokenTransaction | Token balance change record | | Referral | Referral program tracking | | MerchOrder | Merchandise order details | | Voucher | Promotional voucher |

Enums

// User roles
type UserRole = "USER" | "ADMIN" | "SUPER_ADMIN";

// Job processing status
type JobStatus =
  | "PENDING"
  | "PROCESSING"
  | "COMPLETED"
  | "FAILED"
  | "REFUNDED"
  | "CANCELLED";

// Album privacy settings
type AlbumPrivacy = "PRIVATE" | "UNLISTED" | "PUBLIC";

// Token transaction types
type TokenTransactionType =
  | "EARN_REGENERATION"
  | "EARN_PURCHASE"
  | "EARN_BONUS"
  | "SPEND_ENHANCEMENT"
  | "SPEND_MCP_GENERATION"
  | "REFUND";

Constants (/constants)

Configuration values used across the platform:

Token Regeneration

import { TOKEN_REGENERATION } from "@spike-land-ai/shared";

TOKEN_REGENERATION.TOKENS_PER_REGEN; // 1 token per interval
TOKEN_REGENERATION.REGEN_INTERVAL_MS; // 15 minutes (900,000ms)
TOKEN_REGENERATION.MAX_FREE_TOKENS; // 10 tokens max

Validations (/validations)

Zod schemas for API request/response validation:

import {
  mobileSignInSchema,
  purchaseTokensSchema,
} from "@spike-land-ai/shared";

// Validate token purchase request
const result = purchaseTokensSchema.safeParse({
  amount: 100,
});

Available Schemas

| Schema | Description | | ---------------------- | -------------------------- | | purchaseTokensSchema | Token purchase request | | redeemVoucherSchema | Voucher redemption request | | mobileSignInSchema | Mobile sign-in request |


Utilities (/utils)

Helper functions for common operations:

Token Calculations

import {
  calculateRegeneratedTokens,
  getTimeUntilNextRegen,
} from "@spike-land-ai/shared";

// Calculate tokens regenerated since last update
const regenerated = calculateRegeneratedTokens(
  lastRegenDate,
  currentBalance,
  maxTokens,
);

// Time until next regeneration (ms)
const timeMs = getTimeUntilNextRegen(lastRegenDate);

Formatting

import {
  formatCurrency,
  formatDuration,
  formatFileSize,
  formatRelativeTime,
} from "@spike-land-ai/shared";

formatFileSize(1048576); // "1 MB"
formatDuration(90000); // "1m 30s"
formatRelativeTime(date); // "2h ago"
formatCurrency(9.99, "GBP"); // "£9.99"

Development

Building

cd shared

# Build once
npm run build

# Watch mode for development
npm run dev

Type Checking

npm run typecheck

Linting

npm run lint

Build Output

The package is built with tsup:

| Output | Format | Description | | ----------------- | ---------- | ----------------- | | dist/index.js | CommonJS | Node.js require() | | dist/index.mjs | ESM | ES modules import | | dist/index.d.ts | TypeScript | Type definitions |


Adding New Shared Code

1. Types

Add to src/types/index.ts:

export interface NewType {
  id: string;
  name: string;
}

2. Constants

Add to src/constants/index.ts:

export const NEW_CONSTANT = {
  VALUE_A: 100,
  VALUE_B: 200,
} as const;

3. Validations

Add to src/validations/index.ts:

import { z } from "zod";

export const newRequestSchema = z.object({
  field: z.string().min(1),
});

export type NewRequest = z.infer<typeof newRequestSchema>;

4. Utilities

Add to src/utils/index.ts:

export function newUtility(input: string): string {
  return input.toUpperCase();
}

5. Re-export

Ensure new exports are included in src/index.ts:

export * from "./constants";
export * from "./types";
export * from "./utils";
export * from "./validations";

6. Rebuild

npm run build

Integration

This package is published to GitHub Packages. Add it to consuming packages:

# In package.json of consuming package
dependencies:
  "@spike-land-ai/shared": "^1.0.0"

Changes to this package automatically propagate to:

  • src/ (web app) - after rebuild
  • packages/mobile-app/ - after rebuild

Type Safety Improvements (#797)

Social Platform API Types

The @spike-land-ai/shared/types module provides typed interfaces for all external social platform API responses, improving type safety when parsing rate limits and error responses.

Available Types

import type {
  FacebookErrorResponse,
  LinkedInErrorResponse,
  SocialPlatformErrorResponse,
  TwitterErrorResponse,
} from "@spike-land-ai/shared/types";

| Type | Description | | ----------------------------- | ------------------------------------------- | | TwitterErrorResponse | Twitter/X API error format | | FacebookErrorResponse | Facebook/Instagram Graph API error format | | LinkedInErrorResponse | LinkedIn API error format | | SocialPlatformErrorResponse | Union type for all platform error responses | | FacebookBusinessUsageHeader | Facebook business usage rate limit header | | FacebookAppUsageHeader | Facebook app usage rate limit header | | TwitterRateLimitHeaders | Twitter rate limit headers | | DiscordRateLimitHeaders | Discord rate limit headers |

Type Guards

Use type guards from @spike-land-ai/shared/types to safely validate external API responses:

import {
  isFacebookErrorResponse,
  isLinkedInErrorResponse,
  isSocialPlatformErrorResponse,
  isTwitterErrorResponse,
} from "@spike-land-ai/shared/types";

// Example: Validate Facebook error response
if (isFacebookErrorResponse(apiBody)) {
  // TypeScript now knows apiBody is FacebookErrorResponse
  console.log(apiBody.error?.message);
}

// Example: Generic platform error handling
if (isSocialPlatformErrorResponse(apiBody)) {
  // Handle any platform error
}

Cache Types

Generic cache types with expiry tracking:

import type {
  CacheEntry,
  CacheKey,
  CacheMap,
} from "@spike-land-ai/shared/types";

// Example: Type-safe cache
const cache: CacheMap<MyDataType> = new Map();
cache.set("key", { data: myData, expiry: Date.now() + 5000 });

Health Event Types

Structured types for health monitoring event details:

import type {
  HealthEventDetails,
  RateLimitEventInfo,
  TokenEventInfo,
} from "@spike-land-ai/shared/types";

Related Documentation