diff --git a/.claude/skills/front-end-architect/references/code-patterns.md b/.claude/skills/front-end-architect/references/code-patterns.md index 644e124..114b36a 100644 --- a/.claude/skills/front-end-architect/references/code-patterns.md +++ b/.claude/skills/front-end-architect/references/code-patterns.md @@ -152,7 +152,6 @@ This is an excerpt. The real file defines every semantic token the components us ```css @import './theme.css'; -@import './fonts.css'; @import './utilities.css'; @source '../'; ``` diff --git a/.claude/skills/front-end-architect/references/project-structure.md b/.claude/skills/front-end-architect/references/project-structure.md index 32061d9..4d17857 100644 --- a/.claude/skills/front-end-architect/references/project-structure.md +++ b/.claude/skills/front-end-architect/references/project-structure.md @@ -21,7 +21,7 @@ Three folders are named `tools`. Keep them apart: - Root `tools/`: scripts that run in a terminal, in CI, or through Nx (generators, validators). App code never imports them. TypeScript scripts run with jiti. - `packages/tools/`: shared runtime tools that apps and projects import. -- `packages/island/src/tools/`: design-system tools such as `cn`, `cvx`, `icon-sprite-plugin`, and `icon-name-extraction`. +- `packages/island/src/tools/`: design-system tools such as `cn`, `icon-sprite-plugin`, and `icon-name-extraction`. ## App (Next.js) @@ -49,6 +49,7 @@ apps//src/ │ └── templates/ # optional: this route's mobile and desktop templates ├── styles/ │ ├── app.css # Tailwind entry; imports island.css +│ ├── fonts.ts # next/font/local faces from island fonts/, set as CSS variables on │ └── index.ts ├── configs/ │ ├── seo.ts @@ -190,7 +191,7 @@ packages/island/src/ ├── templates/ # like organisms ├── primitives/ # non-visual structural pieces, e.g. portal, error-boundary; like organisms ├── tools/ -│ └── / # e.g. cn, cvx, icon-sprite-plugin, icon-name-extraction +│ └── / # e.g. cn, icon-sprite-plugin, icon-name-extraction │ ├── .ts or .tsx │ ├── types.ts │ ├── constants.ts @@ -198,8 +199,7 @@ packages/island/src/ ├── styles/ │ ├── island.css # entry that apps import into their Tailwind v4 CSS │ ├── theme.css # primitive and semantic tokens -│ ├── utilities.css # custom @utility definitions -│ └── fonts.css # @font-face rules for fonts/ +│ └── utilities.css # custom @utility definitions ├── env/ # island's env: setEnv and getEnv, filled by the app's bootstrap │ ├── env.ts │ ├── types.ts @@ -207,7 +207,7 @@ packages/island/src/ ├── icons/ │ ├── symbol-defs.svg # sprite generated by Icomoon │ └── selection.json # Icomoon snapshot; re-import it into Icomoon to update the set -├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2 +├── fonts/ # every app's fonts, e.g. yekan-bakh-vf.woff2; each app loads them with next/font/local ├── constants.ts # island-level constants ├── index.ts └── server.ts diff --git a/.gitignore b/.gitignore index 2fcb6d6..298ee76 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,59 @@ +# Dependencies +node_modules +.pnpm-store +# Nx .nx/installation .nx/cache .nx/workspace-data .nx/self-healing .nx/migrate-runs .nx/polygraph + +# Claude Code .claude/worktrees .claude/settings.local.json +# Build output +dist +out +out-tsc +tmp +build +*.tsbuildinfo + # Next.js .next -out -node_modules +next-env.d.ts +.vercel + +# Testing +coverage +test-output +.vitest +playwright-report +test-results + +# Env (keep examples committed) +.env +.env.* +!.env.example + +# Logs +*.log +npm-debug.log* +pnpm-debug.log* +yarn-debug.log* +yarn-error.log* + +# OS / editors +.DS_Store +Thumbs.db +*.swp +.idea +.vscode/* +!.vscode/extensions.json +!.vscode/settings.json # graft's local graph cache — regenerable, not committed (run `graft build`). /graft/ diff --git a/apps/bear/src/app/layout.tsx b/apps/bear/src/app/layout.tsx index 9874b55..cd2875d 100644 --- a/apps/bear/src/app/layout.tsx +++ b/apps/bear/src/app/layout.tsx @@ -1,10 +1,15 @@ import type { ReactNode } from 'react'; +import { yekanBakh, yekanBakhLatin } from '../styles'; import '../styles/app.css'; export default function RootLayout({ children }: { children: ReactNode }) { return ( - + {children} ); diff --git a/apps/bear/src/styles/app.css b/apps/bear/src/styles/app.css index f7938bf..48c4f78 100644 --- a/apps/bear/src/styles/app.css +++ b/apps/bear/src/styles/app.css @@ -1,7 +1,6 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @import '@lumina/island/styles/island.css'; -/* Scan workspace sources that this app renders. */ +/* Workspace projects that render UI in this app. island registers itself. */ @source '../../../../platforms/market/src'; -@source '../../../../packages/island/src'; @source '../../../../packages/integrations/src'; diff --git a/apps/bear/src/styles/fonts.ts b/apps/bear/src/styles/fonts.ts new file mode 100644 index 0000000..1b9ac2f --- /dev/null +++ b/apps/bear/src/styles/fonts.ts @@ -0,0 +1,23 @@ +import localFont from 'next/font/local'; + +// Variable fonts from island. next/font self-hosts them, preloads the critical face, +// and adds a size-adjusted fallback so the swap doesn't shift the layout. + +/** Yekan Bakh with Persian digit shapes: every UI text. */ +export const yekanBakh = localFont({ + src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2', + variable: '--font-yekan-bakh', + weight: '100 950', + display: 'swap', + adjustFontFallback: 'Arial', +}); + +/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */ +export const yekanBakhLatin = localFont({ + src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2', + variable: '--font-yekan-bakh-latin', + weight: '100 950', + display: 'swap', + preload: false, + adjustFontFallback: 'Arial', +}); diff --git a/apps/bear/src/styles/index.ts b/apps/bear/src/styles/index.ts new file mode 100644 index 0000000..b0a9521 --- /dev/null +++ b/apps/bear/src/styles/index.ts @@ -0,0 +1 @@ +export { yekanBakh, yekanBakhLatin } from './fonts'; diff --git a/apps/bull/src/app/layout.tsx b/apps/bull/src/app/layout.tsx index 9874b55..cd2875d 100644 --- a/apps/bull/src/app/layout.tsx +++ b/apps/bull/src/app/layout.tsx @@ -1,10 +1,15 @@ import type { ReactNode } from 'react'; +import { yekanBakh, yekanBakhLatin } from '../styles'; import '../styles/app.css'; export default function RootLayout({ children }: { children: ReactNode }) { return ( - + {children} ); diff --git a/apps/bull/src/styles/app.css b/apps/bull/src/styles/app.css index f7938bf..48c4f78 100644 --- a/apps/bull/src/styles/app.css +++ b/apps/bull/src/styles/app.css @@ -1,7 +1,6 @@ -@import 'tailwindcss'; +@import 'tailwindcss' source('../'); @import '@lumina/island/styles/island.css'; -/* Scan workspace sources that this app renders. */ +/* Workspace projects that render UI in this app. island registers itself. */ @source '../../../../platforms/market/src'; -@source '../../../../packages/island/src'; @source '../../../../packages/integrations/src'; diff --git a/apps/bull/src/styles/fonts.ts b/apps/bull/src/styles/fonts.ts new file mode 100644 index 0000000..1b9ac2f --- /dev/null +++ b/apps/bull/src/styles/fonts.ts @@ -0,0 +1,23 @@ +import localFont from 'next/font/local'; + +// Variable fonts from island. next/font self-hosts them, preloads the critical face, +// and adds a size-adjusted fallback so the swap doesn't shift the layout. + +/** Yekan Bakh with Persian digit shapes: every UI text. */ +export const yekanBakh = localFont({ + src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2', + variable: '--font-yekan-bakh', + weight: '100 950', + display: 'swap', + adjustFontFallback: 'Arial', +}); + +/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */ +export const yekanBakhLatin = localFont({ + src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2', + variable: '--font-yekan-bakh-latin', + weight: '100 950', + display: 'swap', + preload: false, + adjustFontFallback: 'Arial', +}); diff --git a/apps/bull/src/styles/index.ts b/apps/bull/src/styles/index.ts new file mode 100644 index 0000000..b0a9521 --- /dev/null +++ b/apps/bull/src/styles/index.ts @@ -0,0 +1 @@ +export { yekanBakh, yekanBakhLatin } from './fonts'; diff --git a/package.json b/package.json index 64f4705..b50a69a 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "eslint": "^9.8.0", + "jiti": "^2.7.0", "nx": "23.2.1", "oxlint": "^1.75.0", "postcss": "^8.5.28", @@ -33,9 +34,14 @@ "typescript-eslint": "^8.58.0" }, "dependencies": { + "@t3-oss/env-core": "^0.13.11", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", "next": "~16.1.6", "react": "^19.0.0", "react-dom": "^19.0.0", - "server-only": "^0.0.1" + "server-only": "^0.0.1", + "tailwind-merge": "^3.7.0", + "valibot": "^1.5.0" } } diff --git a/packages/integrations/tsconfig.lib.json b/packages/integrations/tsconfig.lib.json index c4bc03b..759680d 100644 --- a/packages/integrations/tsconfig.lib.json +++ b/packages/integrations/tsconfig.lib.json @@ -9,7 +9,12 @@ ], "rootDir": "src", "jsx": "react-jsx", - "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo" + "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", + "lib": [ + "es2022", + "dom", + "dom.iterable" + ] }, "exclude": [ "out-tsc", @@ -28,7 +33,12 @@ "eslint.config.cjs", "eslint.config.mjs" ], - "include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"], + "include": [ + "src/**/*.js", + "src/**/*.jsx", + "src/**/*.ts", + "src/**/*.tsx" + ], "references": [ { "path": "../tools/tsconfig.lib.json" diff --git a/packages/island/src/fonts/.gitkeep b/packages/island/src/fonts/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2 b/packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2 new file mode 100644 index 0000000..0df8cbb Binary files /dev/null and b/packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2 differ diff --git a/packages/island/src/fonts/yekan-bakh-vf.woff2 b/packages/island/src/fonts/yekan-bakh-vf.woff2 new file mode 100644 index 0000000..9b2f3a5 Binary files /dev/null and b/packages/island/src/fonts/yekan-bakh-vf.woff2 differ diff --git a/packages/island/src/index.ts b/packages/island/src/index.ts index 2219612..01d304a 100644 --- a/packages/island/src/index.ts +++ b/packages/island/src/index.ts @@ -1,2 +1,2 @@ // Public client-safe API. Re-export each module by name; never `export *`. -export {}; +export { cn } from './tools/cn'; diff --git a/packages/island/src/styles/fonts.css b/packages/island/src/styles/fonts.css deleted file mode 100644 index 30f6960..0000000 --- a/packages/island/src/styles/fonts.css +++ /dev/null @@ -1 +0,0 @@ -/* @font-face rules for files in ../fonts/. */ diff --git a/packages/island/src/styles/island.css b/packages/island/src/styles/island.css index 6674dba..efc92d9 100644 --- a/packages/island/src/styles/island.css +++ b/packages/island/src/styles/island.css @@ -1,4 +1,26 @@ -/* Entry that apps import after `tailwindcss`. Order: tokens, fonts, utilities. */ +/* Entry that apps import after `tailwindcss`. Fonts are loaded by each app with next/font. */ @import './theme.css'; -@import './fonts.css'; @import './utilities.css'; +@source '../'; + +@layer base { + html { + background-color: var(--color-bg-page); + color: var(--color-text-primary); + font-family: var(--font-sans); + /* Every number is tabular: prices, dates, OTP, stats, countdowns. */ + font-variant-numeric: tabular-nums; + -webkit-text-size-adjust: 100%; + } + + @media (prefers-reduced-motion: reduce) { + *, + ::before, + ::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } + } +} diff --git a/packages/island/src/styles/theme.css b/packages/island/src/styles/theme.css index 0a03311..013119a 100644 --- a/packages/island/src/styles/theme.css +++ b/packages/island/src/styles/theme.css @@ -1,3 +1,228 @@ -/* Primitive tokens, then semantic tokens, from the Lumina design system. */ +/* + * Lumina design tokens, generated from the Lumina Design System (tokens.json, v4 Indigo). + * Three layers: primitives (no utilities, so screens can't use them), semantic + * variables that a future theme can switch, and @theme inline utilities. + */ @theme { + /* Drop Tailwind's defaults so only Lumina tokens produce utilities. */ + --color-*: initial; + --font-*: initial; + --text-*: initial; + --radius-*: initial; + --shadow-*: initial; + --breakpoint-*: initial; + --container-*: initial; + + --font-sans: var(--font-yekan-bakh), Tahoma, sans-serif; + /* Latin digits, for شبا and other codes banks print in Latin digits. */ + --font-latin: var(--font-yekan-bakh-latin), Tahoma, sans-serif; + + /* Sizes are the design system's px values ÷ 16, in rem, so text and spacing follow + the reader's browser font size. */ + --text-display: 2rem; + --text-display--line-height: 2.75rem; + --text-display--font-weight: 700; + --text-heading-lg: 1.625rem; + --text-heading-lg--line-height: 2.375rem; + --text-heading-lg--font-weight: 700; + --text-heading-md: 1.3125rem; + --text-heading-md--line-height: 2rem; + --text-heading-md--font-weight: 700; + --text-heading-sm: 1.0625rem; + --text-heading-sm--line-height: 1.75rem; + --text-heading-sm--font-weight: 600; + --text-body-lg: 1.125rem; + --text-body-lg--line-height: 2rem; + --text-body-lg--font-weight: 400; + --text-body-md: 1rem; + --text-body-md--line-height: 1.75rem; + --text-body-md--font-weight: 400; + --text-body-sm: 0.875rem; + --text-body-sm--line-height: 1.5rem; + --text-body-sm--font-weight: 400; + --text-label: 0.875rem; + --text-label--line-height: 1.375rem; + --text-label--font-weight: 600; + --text-caption: 0.8125rem; + --text-caption--line-height: 1.375rem; + --text-caption--font-weight: 400; + --text-micro: 0.6875rem; + --text-micro--line-height: 1.125rem; + --text-micro--font-weight: 500; + + /* 4px grid: space-1 … space-16 map to Tailwind's numeric spacing (p-4 = 1rem = 16px). */ + --spacing: 0.25rem; + --spacing-touch-target: 2.75rem; + --spacing-control-sm: 2.25rem; + --spacing-control-md: 2.75rem; + --spacing-control-lg: 3.25rem; + --spacing-input-height: 3rem; + --container-mobile: 24.375rem; + --container-checkout: 30rem; + --container-form: 35rem; + --container-content: 40rem; + --radius-xs: 4px; + --radius-sm: 6px; + --radius-md: 8px; + --radius-lg: 12px; + --radius-xl: 16px; + --radius-full: 9999px; + --shadow-1: + 0 1px 2px rgba(12, 16, 24, 0.06), 0 1px 3px rgba(12, 16, 24, 0.08); + --shadow-2: + 0 6px 16px -4px rgba(12, 16, 24, 0.14), + 0 2px 4px -2px rgba(12, 16, 24, 0.08); + --shadow-3: + 0 24px 48px -12px rgba(12, 16, 24, 0.28), + 0 8px 16px -8px rgba(12, 16, 24, 0.16); + /* No `tablet` (768px) breakpoint: bull keeps the bottom navigation up to 1024px, + and bear starts at 1024px, so layout never switches below that. */ + --breakpoint-desktop: 1024px; + --breakpoint-wide: 1280px; + --ease-standard: cubic-bezier(0.2, 0, 0, 1); +} + +:root { + /* Primitives: referenced only by the semantic layer below. */ + --indigo-50: #f5f4ff; + --indigo-100: #e9e7ff; + --indigo-200: #d1cdff; + --indigo-300: #aea8ff; + --indigo-400: #827aff; + --indigo-500: #6459ff; + --indigo-600: #533afd; + --indigo-700: #402fcb; + --indigo-800: #30249e; + --indigo-900: #211c6d; + --indigo-950: #1c1e54; + --saffron-50: #fdf8ea; + --saffron-100: #faeecb; + --saffron-300: #edc256; + --saffron-400: #e2a82e; + --saffron-500: #c88a12; + --saffron-600: #a16b0b; + --saffron-700: #7b510c; + --saffron-800: #58390c; + --slate-0: #ffffff; + --slate-25: #fafbfc; + --slate-50: #f4f6f9; + --slate-100: #eceff4; + --slate-150: #e2e7ee; + --slate-200: #d5dce6; + --slate-300: #b9c2cf; + --slate-400: #7d889a; + --slate-500: #6a7586; + --slate-600: #515c6d; + --slate-700: #3a4352; + --slate-800: #262d39; + --slate-900: #151b25; + --green-50: #ecf6ee; + --green-100: #d2ebd7; + --green-300: #6cc985; + --green-500: #2f8f46; + --green-600: #25763a; + --green-700: #1d5e2e; + --red-50: #fcefee; + --red-100: #f7d9d7; + --red-300: #f08a84; + --red-500: #cc3333; + --red-600: #a82a2a; + --red-700: #86221f; + --amber-50: #fff6e3; + --amber-500: #e08c0b; + --amber-600: #b26a06; + --amber-700: #8c5207; + + /* Semantic: what components use. A theme overrides only this block. */ + --bg-page: var(--slate-50); + --surface: var(--slate-0); + --surface-sunken: var(--slate-100); + --surface-hover: var(--slate-25); + --surface-raised: var(--slate-0); + --surface-inverse: var(--slate-900); + --scrim: rgba(12, 16, 24, 0.48); + --lightbox: #000000; + --text-primary: var(--slate-900); + --text-secondary: var(--slate-600); + --text-tertiary: var(--slate-500); + --text-inverse: var(--slate-0); + --text-on-action: #ffffff; + --text-link: var(--indigo-600); + --border-subtle: var(--slate-150); + --border-default: var(--slate-400); + --border-strong: var(--slate-200); + --action-primary: var(--indigo-600); + --action-primary-hover: var(--indigo-700); + --action-primary-subtle: var(--indigo-50); + --action-primary-muted: var(--indigo-100); + --action-primary-text: var(--indigo-700); + --premium: var(--indigo-950); + --premium-on: var(--saffron-300); + --premium-accent: var(--saffron-600); + --premium-subtle: var(--saffron-50); + --premium-text: var(--saffron-700); + --success: var(--green-500); + --success-text: var(--green-600); + --success-subtle: var(--green-50); + --danger: var(--red-500); + --danger-text: var(--red-600); + --danger-solid: var(--red-500); + --danger-subtle: var(--red-50); + --warning: var(--amber-600); + --warning-text: var(--amber-700); + --warning-subtle: var(--amber-50); + --neutral-mark: var(--slate-400); + + --opacity-frozen: 0.4; + --opacity-dimmed: 0.5; + --z-sticky: 10; + --z-menu: 850; + --z-overlay: 900; + --z-toast: 950; + --z-lightbox: 1000; +} + +@theme inline { + --color-bg-page: var(--bg-page); + --color-surface: var(--surface); + --color-surface-sunken: var(--surface-sunken); + --color-surface-hover: var(--surface-hover); + --color-surface-raised: var(--surface-raised); + --color-surface-inverse: var(--surface-inverse); + --color-scrim: var(--scrim); + --color-lightbox: var(--lightbox); + --color-text-primary: var(--text-primary); + --color-text-secondary: var(--text-secondary); + --color-text-tertiary: var(--text-tertiary); + --color-text-inverse: var(--text-inverse); + --color-text-on-action: var(--text-on-action); + --color-text-link: var(--text-link); + --color-border-subtle: var(--border-subtle); + --color-border-default: var(--border-default); + --color-border-strong: var(--border-strong); + --color-action-primary: var(--action-primary); + --color-action-primary-hover: var(--action-primary-hover); + --color-action-primary-subtle: var(--action-primary-subtle); + --color-action-primary-muted: var(--action-primary-muted); + --color-action-primary-text: var(--action-primary-text); + --color-premium: var(--premium); + --color-premium-on: var(--premium-on); + --color-premium-accent: var(--premium-accent); + --color-premium-subtle: var(--premium-subtle); + --color-premium-text: var(--premium-text); + --color-success: var(--success); + --color-success-text: var(--success-text); + --color-success-subtle: var(--success-subtle); + --color-danger: var(--danger); + --color-danger-text: var(--danger-text); + --color-danger-solid: var(--danger-solid); + --color-danger-subtle: var(--danger-subtle); + --color-warning: var(--warning); + --color-warning-text: var(--warning-text); + --color-warning-subtle: var(--warning-subtle); + --color-neutral-mark: var(--neutral-mark); + + /* Inline, so a theme that overrides the semantic layer also recolours the ring. */ + --shadow-focus-ring: + 0 0 0 2px var(--surface), 0 0 0 4px var(--action-primary); } diff --git a/packages/island/src/styles/utilities.css b/packages/island/src/styles/utilities.css index 603c582..c97bc6c 100644 --- a/packages/island/src/styles/utilities.css +++ b/packages/island/src/styles/utilities.css @@ -1 +1,36 @@ -/* Custom @utility definitions. */ +/* Keyboard focus on every control: 2px white gap, then 2px action-primary. */ +@utility focus-ring { + outline: none; + box-shadow: var(--shadow-focus-ring); +} + +/* A control that exists but can't be used now: visible, explains itself on tap or hover. */ +@utility frozen { + opacity: var(--opacity-frozen); + cursor: not-allowed; +} + +/* An unavailable item (a suspended creator); live actions inside stay at full opacity. */ +@utility dimmed { + opacity: var(--opacity-dimmed); +} + +@utility z-sticky { + z-index: var(--z-sticky); +} + +@utility z-menu { + z-index: var(--z-menu); +} + +@utility z-overlay { + z-index: var(--z-overlay); +} + +@utility z-toast { + z-index: var(--z-toast); +} + +@utility z-lightbox { + z-index: var(--z-lightbox); +} diff --git a/packages/island/src/tools/cn/.gitkeep b/packages/island/src/tools/cn/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/tools/cn/cn.ts b/packages/island/src/tools/cn/cn.ts new file mode 100644 index 0000000..157fa89 --- /dev/null +++ b/packages/island/src/tools/cn/cn.ts @@ -0,0 +1,29 @@ +import { clsx, type ClassValue } from 'clsx'; +import { extendTailwindMerge } from 'tailwind-merge'; + +import { + CONTAINERS, + NAMED_SPACING, + SHADOWS, + TEXT_SIZES, + Z_LAYERS, +} from './constants'; + +const twMerge = extendTailwindMerge({ + extend: { + theme: { + text: [...TEXT_SIZES], + shadow: [...SHADOWS], + spacing: [...NAMED_SPACING], + container: [...CONTAINERS], + }, + classGroups: { + z: [{ z: [...Z_LAYERS] }], + }, + }, +}); + +/** Joins class names and resolves Tailwind conflicts, so a caller's class overrides a component's. */ +export function cn(...inputs: ClassValue[]): string { + return twMerge(clsx(inputs)); +} diff --git a/packages/island/src/tools/cn/constants.ts b/packages/island/src/tools/cn/constants.ts new file mode 100644 index 0000000..bd67814 --- /dev/null +++ b/packages/island/src/tools/cn/constants.ts @@ -0,0 +1,35 @@ +/** Font-size tokens from theme.css; tailwind-merge would otherwise read `text-body-sm` as a color. */ +export const TEXT_SIZES = [ + 'display', + 'heading-lg', + 'heading-md', + 'heading-sm', + 'body-lg', + 'body-md', + 'body-sm', + 'label', + 'caption', + 'micro', +] as const; + +export const SHADOWS = ['1', '2', '3', 'focus-ring'] as const; + +export const NAMED_SPACING = [ + 'touch-target', + 'control-sm', + 'control-md', + 'control-lg', + 'input-height', +] as const; + +/** Container widths from theme.css, used as `w-*` and `max-w-*`. */ +export const CONTAINERS = ['mobile', 'checkout', 'form', 'content'] as const; + +/** z-index layers from utilities.css, so `z-overlay` replaces `z-sticky`. */ +export const Z_LAYERS = [ + 'sticky', + 'menu', + 'overlay', + 'toast', + 'lightbox', +] as const; diff --git a/packages/island/src/tools/cn/index.ts b/packages/island/src/tools/cn/index.ts new file mode 100644 index 0000000..414c24d --- /dev/null +++ b/packages/island/src/tools/cn/index.ts @@ -0,0 +1 @@ +export { cn } from './cn'; diff --git a/packages/island/src/tools/cvx/.gitkeep b/packages/island/src/tools/cvx/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/tsconfig.lib.json b/packages/island/tsconfig.lib.json index 766301b..cef0e75 100644 --- a/packages/island/tsconfig.lib.json +++ b/packages/island/tsconfig.lib.json @@ -9,7 +9,12 @@ ], "rootDir": "src", "jsx": "react-jsx", - "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo" + "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", + "lib": [ + "es2022", + "dom", + "dom.iterable" + ] }, "exclude": [ "out-tsc", @@ -28,7 +33,12 @@ "eslint.config.cjs", "eslint.config.mjs" ], - "include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"], + "include": [ + "src/**/*.js", + "src/**/*.jsx", + "src/**/*.ts", + "src/**/*.tsx" + ], "references": [ { "path": "../tools/tsconfig.lib.json" diff --git a/packages/libs/src/cookie/.gitkeep b/packages/libs/src/cookie/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/libs/src/cookie/constants.ts b/packages/libs/src/cookie/constants.ts new file mode 100644 index 0000000..65bbaad --- /dev/null +++ b/packages/libs/src/cookie/constants.ts @@ -0,0 +1,7 @@ +import type { CookieOptions } from './types'; + +export const DEFAULT_COOKIE_OPTIONS: Readonly = Object.freeze({ + path: '/', + sameSite: 'Lax', + secure: true, +}); diff --git a/packages/libs/src/cookie/cookie.ts b/packages/libs/src/cookie/cookie.ts new file mode 100644 index 0000000..0044cff --- /dev/null +++ b/packages/libs/src/cookie/cookie.ts @@ -0,0 +1,83 @@ +import { DEFAULT_COOKIE_OPTIONS } from './constants'; +import type { CookieAdapterAbstraction, CookieOptions } from './types'; + +const SECONDS_PER_DAY = 24 * 60 * 60; + +function assertBrowser(): void { + if (typeof document === 'undefined') { + throw new Error( + 'cookie is browser-only; on the server read cookies with next/headers', + ); + } +} + +function safeDecode(value: string): string { + try { + return decodeURIComponent(value); + } catch { + return value; + } +} + +export class CookieAdapter implements CookieAdapterAbstraction { + #defaults: CookieOptions = {}; + + /** Sets app-wide defaults once, in the client bootstrap. Never touches `document`. */ + configure(defaults: CookieOptions): void { + this.#defaults = { ...defaults }; + } + + get(key: string): string | null { + assertBrowser(); + const prefix = `${encodeURIComponent(key)}=`; + const entry = document.cookie + .split('; ') + .find((part) => part.startsWith(prefix)); + return entry === undefined ? null : safeDecode(entry.slice(prefix.length)); + } + + set(key: string, value: string, options?: CookieOptions): void { + assertBrowser(); + const merged: CookieOptions = { + ...DEFAULT_COOKIE_OPTIONS, + ...this.#defaults, + ...options, + }; + document.cookie = this.#serialize( + key, + encodeURIComponent(value), + merged, + merged.maxAgeDays === undefined + ? undefined + : Math.floor(merged.maxAgeDays * SECONDS_PER_DAY), + ); + } + + remove(key: string, options?: Pick): void { + assertBrowser(); + const merged: CookieOptions = { + ...DEFAULT_COOKIE_OPTIONS, + ...this.#defaults, + ...options, + }; + document.cookie = this.#serialize(key, '', merged, 0); + } + + #serialize( + key: string, + encodedValue: string, + options: CookieOptions, + maxAgeSeconds: number | undefined, + ): string { + const sameSite = options.sameSite ?? 'Lax'; + const parts = [`${encodeURIComponent(key)}=${encodedValue}`]; + parts.push(`path=${options.path ?? '/'}`); + if (options.domain) parts.push(`domain=${options.domain}`); + if (maxAgeSeconds !== undefined) parts.push(`max-age=${maxAgeSeconds}`); + parts.push(`SameSite=${sameSite}`); + if (options.secure !== false || sameSite === 'None') parts.push('Secure'); + return parts.join('; '); + } +} + +export const cookie = new CookieAdapter(); diff --git a/packages/libs/src/cookie/index.ts b/packages/libs/src/cookie/index.ts new file mode 100644 index 0000000..1bce548 --- /dev/null +++ b/packages/libs/src/cookie/index.ts @@ -0,0 +1,3 @@ +export { DEFAULT_COOKIE_OPTIONS } from './constants'; +export { CookieAdapter, cookie } from './cookie'; +export type { CookieAdapterAbstraction, CookieOptions } from './types'; diff --git a/packages/libs/src/cookie/types.ts b/packages/libs/src/cookie/types.ts new file mode 100644 index 0000000..096efaa --- /dev/null +++ b/packages/libs/src/cookie/types.ts @@ -0,0 +1,18 @@ +export interface CookieOptions { + /** Default '/'. */ + path?: string; + /** Default: none (current host only). Set it to share with subdomains, e.g. '.example.com'. */ + domain?: string; + /** Lifetime in days; omit for a session cookie. */ + maxAgeDays?: number; + /** Default 'Lax'. */ + sameSite?: 'Strict' | 'Lax' | 'None'; + /** Default true; forced to true when sameSite is 'None'. */ + secure?: boolean; +} + +export interface CookieAdapterAbstraction { + get(key: string): string | null; + set(key: string, value: string, options?: CookieOptions): void; + remove(key: string, options?: Pick): void; +} diff --git a/packages/libs/src/env/.gitkeep b/packages/libs/src/env/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/libs/src/env/env.client.ts b/packages/libs/src/env/env.client.ts new file mode 100644 index 0000000..6a8454e --- /dev/null +++ b/packages/libs/src/env/env.client.ts @@ -0,0 +1,30 @@ +import { createEnv, type StandardSchemaV1 } from '@t3-oss/env-core'; +import type { ClientEnvOptions, EnvSchema, EnvValues } from './types'; + +export function throwInvalidEnv( + issues: readonly StandardSchemaV1.Issue[], +): never { + const lines = issues.map((issue) => { + const name = issue.path + ?.map((segment) => + String(typeof segment === 'object' ? segment.key : segment), + ) + .join('.'); + return `- ${name ?? 'env'}: ${issue.message}`; + }); + throw new Error(`Invalid environment variables:\n${lines.join('\n')}`); +} + +export function createClientEnv< + const TPrefix extends string, + TSchema extends EnvSchema, +>(options: ClientEnvOptions): EnvValues { + return createEnv({ + clientPrefix: options.prefix, + client: options.schema, + // env-core deletes empty strings from the object it gets, so it gets a copy + runtimeEnvStrict: { ...options.runtimeEnv }, + emptyStringAsUndefined: true, + onValidationError: throwInvalidEnv, + }) as EnvValues; +} diff --git a/packages/libs/src/env/env.server.ts b/packages/libs/src/env/env.server.ts new file mode 100644 index 0000000..9c1787d --- /dev/null +++ b/packages/libs/src/env/env.server.ts @@ -0,0 +1,18 @@ +import 'server-only'; +import { createEnv } from '@t3-oss/env-core'; +import { throwInvalidEnv } from './env.client'; +import type { EnvSchema, EnvValues, ServerEnvOptions } from './types'; + +export function createServerEnv( + options: ServerEnvOptions, +): EnvValues { + return createEnv({ + server: options.schema, + // env-core deletes empty strings from the object it gets, so process.env gets a copy + runtimeEnv: { ...options.runtimeEnv }, + isServer: true, + emptyStringAsUndefined: true, + skipValidation: options.skipValidation ?? false, + onValidationError: throwInvalidEnv, + }) as EnvValues; +} diff --git a/packages/libs/src/env/index.ts b/packages/libs/src/env/index.ts new file mode 100644 index 0000000..07ec9ba --- /dev/null +++ b/packages/libs/src/env/index.ts @@ -0,0 +1,7 @@ +export { createClientEnv } from './env.client'; +export type { + ClientEnvOptions, + EnvSchema, + EnvValues, + ServerEnvOptions, +} from './types'; diff --git a/packages/libs/src/env/server.ts b/packages/libs/src/env/server.ts new file mode 100644 index 0000000..87360a1 --- /dev/null +++ b/packages/libs/src/env/server.ts @@ -0,0 +1,3 @@ +import 'server-only'; + +export { createServerEnv } from './env.server'; diff --git a/packages/libs/src/env/types.ts b/packages/libs/src/env/types.ts new file mode 100644 index 0000000..2a08189 --- /dev/null +++ b/packages/libs/src/env/types.ts @@ -0,0 +1,31 @@ +import type { StandardSchemaDictionary } from '@t3-oss/env-core'; + +/** Variable name → valibot schema. */ +export type EnvSchema = StandardSchemaDictionary; + +export type EnvValues = Readonly< + StandardSchemaDictionary.InferOutput +>; + +export type ClientEnvOptions< + TPrefix extends string, + TSchema extends EnvSchema, +> = { + /** e.g. 'NEXT_PUBLIC_' */ + prefix: TPrefix; + schema: TSchema & { + [TKey in keyof TSchema]: TKey extends `${TPrefix}${string}` + ? TSchema[TKey] + : `${TKey & string} must start with ${TPrefix}`; + }; + /** Every declared variable, each read literally: `NEXT_PUBLIC_X: process.env.NEXT_PUBLIC_X`. */ + runtimeEnv: NoInfer>; +}; + +export type ServerEnvOptions = { + schema: TSchema; + /** process.env */ + runtimeEnv: Record; + /** Only for steps that run without the real env (lint, type-check, image build). */ + skipValidation?: boolean; +}; diff --git a/packages/libs/src/error-handler/.gitkeep b/packages/libs/src/error-handler/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/libs/src/error-handler/constants.ts b/packages/libs/src/error-handler/constants.ts new file mode 100644 index 0000000..7b8881b --- /dev/null +++ b/packages/libs/src/error-handler/constants.ts @@ -0,0 +1,3 @@ +export const NOT_FOUND_STATUSES: readonly number[] = [404, 410]; +export const LIB_MESSAGE_PREFIX = 'errors:'; +export const RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'; diff --git a/packages/libs/src/error-handler/error-handler.ts b/packages/libs/src/error-handler/error-handler.ts new file mode 100644 index 0000000..71387bb --- /dev/null +++ b/packages/libs/src/error-handler/error-handler.ts @@ -0,0 +1,120 @@ +import { isHttpError } from '../http'; +import { + LIB_MESSAGE_PREFIX, + NOT_FOUND_STATUSES, + RETRY_AFTER_HINT_KEY, +} from './constants'; +import type { + ErrorClass, + ErrorContext, + ErrorDescription, + ErrorHandlerConfig, + ReadOutcome, + RetryKind, + TranslateFn, +} from './types'; + +// Startup configuration set by the bootstrap; never errors or anything per request. +let config: ErrorHandlerConfig = {}; + +export function configureErrorHandler(next: ErrorHandlerConfig): void { + config = { ...config, ...next }; +} + +const SILENT: ErrorClass = { + cause: 'network', + read: 'silent', + action: 'silent', + retry: 'none', + report: false, +}; +const LOGIC: ErrorClass = { + cause: 'logic', + read: 'boundary', + action: 'toast', + retry: 'none', + report: true, +}; + +function apiError( + read: ReadOutcome, + retry: RetryKind, + report = false, +): ErrorClass { + return { cause: 'network', read, action: 'toast', retry, report }; +} + +function getDigest(error: unknown): string | undefined { + if (typeof error !== 'object' || error === null || !('digest' in error)) + return undefined; + return typeof error.digest === 'string' ? error.digest : undefined; +} + +// Status first, then code. The first matching row of the classification table wins. +export function classifyError(error: unknown): ErrorClass { + if (!isHttpError(error)) + return getDigest(error) ? apiError('boundary', 'again') : LOGIC; + const { status, code } = error; + if (code === 'ABORTED' || status === 401) return SILENT; + if (status === 403) return apiError('no-access', 'none'); + if (NOT_FOUND_STATUSES.includes(status)) + return apiError('not-found', 'reload'); + if (status === 409) return apiError('boundary', 'reload'); + if (status === 429) return apiError('boundary', 'wait'); + if (status >= 500) return apiError('boundary', 'again', true); + if (status >= 400) return apiError('boundary', 'fix'); + if (code === 'NETWORK_ERROR' || code === 'TIMEOUT') + return apiError('boundary', 'again'); + return LOGIC; +} + +// Only errors:-prefixed strings (the HTTP lib's keys) go through t; server text passes through as is. +export function describeError( + error: unknown, + t: TranslateFn, +): ErrorDescription { + if (!isHttpError(error)) return { referenceId: getDigest(error) }; + const translate = (text?: string) => + text?.startsWith(LIB_MESSAGE_PREFIX) ? t(text) : text; + const isUserFacing = + (error.status >= 400 && error.status < 500) || + error.code === 'NETWORK_ERROR' || + error.code === 'TIMEOUT'; + return { + message: isUserFacing ? translate(error.message) : undefined, + hint: + translate(error.hint) ?? + (error.retryAfter + ? t(RETRY_AFTER_HINT_KEY, { seconds: error.retryAfter }) + : undefined), + referenceId: error.requestId ?? getDigest(error), + }; +} + +// Call once, where the error stops. Never throws. +export function handleError( + error: unknown, + context?: ErrorContext, +): ErrorClass { + const errorClass = classifyError(error); + try { + if (errorClass.report) { + config.report?.({ + ...context, + error, + status: isHttpError(error) ? error.status : undefined, + code: isHttpError(error) ? error.code : undefined, + requestId: isHttpError(error) ? error.requestId : undefined, + digest: getDigest(error), + }); + } + } catch { + // Handling an error must never throw a second one. + } + try { + if (isHttpError(error) && error.status === 403) config.onForbidden?.(); + } catch { + // Handling an error must never throw a second one. + } + return errorClass; +} diff --git a/packages/libs/src/error-handler/index.ts b/packages/libs/src/error-handler/index.ts new file mode 100644 index 0000000..1a50f4d --- /dev/null +++ b/packages/libs/src/error-handler/index.ts @@ -0,0 +1,19 @@ +export { + classifyError, + configureErrorHandler, + describeError, + handleError, +} from './error-handler'; +export type { + ActionOutcome, + ErrorCause, + ErrorClass, + ErrorContext, + ErrorDescription, + ErrorHandlerConfig, + ErrorReport, + ErrorWhere, + ReadOutcome, + RetryKind, + TranslateFn, +} from './types'; diff --git a/packages/libs/src/error-handler/types.ts b/packages/libs/src/error-handler/types.ts new file mode 100644 index 0000000..1fd9712 --- /dev/null +++ b/packages/libs/src/error-handler/types.ts @@ -0,0 +1,49 @@ +export type ErrorCause = 'network' | 'logic'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps +export type ReadOutcome = 'silent' | 'not-found' | 'no-access' | 'boundary'; // what a failed read shows +export type ActionOutcome = 'silent' | 'toast'; // what a failed action shows +export type RetryKind = 'again' | 'wait' | 'reload' | 'fix' | 'none'; + +export interface ErrorClass { + cause: ErrorCause; + read: ReadOutcome; + action: ActionOutcome; + retry: RetryKind; + report: boolean; // true for 5xx and logic errors +} + +export type ErrorWhere = + | 'app' + | 'page' + | 'part' + | 'action' + | 'refetch' + | 'server'; + +export interface ErrorContext { + where: ErrorWhere; // where the error stopped + name?: string; // the part, action, or route, e.g. 'order-invoice'; never personal data +} + +export interface ErrorReport extends Partial { + error: unknown; + status?: number; + code?: string; + requestId?: string; + digest?: string; // Next.js's id for a server error +} + +export interface ErrorHandlerConfig { + report?: (report: ErrorReport) => void; // the error-tracking integration's adapter + onForbidden?: () => void; // runs on every 403 that handleError handles +} + +export type TranslateFn = ( + key: string, + options?: Record, +) => string; // i18next's t fits + +export interface ErrorDescription { + message?: string; // what went wrong, only when the user can understand it + hint?: string; // how to fix it: the guide + referenceId?: string; // requestId, or the server digest +} diff --git a/packages/libs/src/event-emitter/.gitkeep b/packages/libs/src/event-emitter/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/libs/src/event-emitter/event-emitter.ts b/packages/libs/src/event-emitter/event-emitter.ts new file mode 100644 index 0000000..6e32395 --- /dev/null +++ b/packages/libs/src/event-emitter/event-emitter.ts @@ -0,0 +1,35 @@ +import type { EventEmitter, EventName } from './types'; + +type AnyListener = (payload?: unknown) => void; + +const listeners = new Map>(); + +/** The app-wide event bus. Actions emit `.` after they succeed; the AppShell subscribes. */ +export const eventEmitter: EventEmitter = { + on(name, listener) { + let set = listeners.get(name); + if (!set) { + set = new Set(); + listeners.set(name, set); + } + set.add(listener as AnyListener); + return () => eventEmitter.off(name, listener); + }, + + off(name, listener) { + const set = listeners.get(name); + set?.delete(listener as AnyListener); + if (set?.size === 0) listeners.delete(name); + }, + + emit(name, ...args) { + // a snapshot, so listeners that subscribe or unsubscribe during emit don't change this round + for (const listener of Array.from(listeners.get(name) ?? [])) { + try { + listener(args[0]); + } catch (error) { + console.error(`eventEmitter: a "${name}" listener threw`, error); + } + } + }, +}; diff --git a/packages/libs/src/event-emitter/index.ts b/packages/libs/src/event-emitter/index.ts new file mode 100644 index 0000000..2e09116 --- /dev/null +++ b/packages/libs/src/event-emitter/index.ts @@ -0,0 +1,10 @@ +export { eventEmitter } from './event-emitter'; +export type { + EventArgs, + EventEmitter, + EventListener, + EventMap, + EventName, + EventPayload, + Unsubscribe, +} from './types'; diff --git a/packages/libs/src/event-emitter/types.ts b/packages/libs/src/event-emitter/types.ts new file mode 100644 index 0000000..2f8845a --- /dev/null +++ b/packages/libs/src/event-emitter/types.ts @@ -0,0 +1,45 @@ +/** + * Event name → payload type. Empty here; each feature adds its `.` events + * with declaration merging, beside its `AUTH_EVENTS`-style constants: + * + * ```ts + * declare module '@lumina/libs/event-emitter' { + * interface EventMap { + * 'auth.login': { userId: string }; + * 'auth.logout': void; + * } + * } + * ``` + */ +export interface EventMap {} + +export type EventName = keyof EventMap & string; + +export type EventPayload = EventMap[TName]; + +export type EventListener = ( + payload: EventPayload, +) => void; + +/** No payload argument for `void` events. */ +export type EventArgs = [EventPayload] extends [ + void, +] + ? [] + : [payload: EventPayload]; + +export type Unsubscribe = () => void; + +export interface EventEmitter { + /** Subscribes and returns the unsubscribe function. */ + on( + name: TName, + listener: EventListener, + ): Unsubscribe; + off( + name: TName, + listener: EventListener, + ): void; + /** Calls every listener; one that throws is logged and doesn't stop the others. */ + emit(name: TName, ...args: EventArgs): void; +} diff --git a/packages/libs/src/http/.gitkeep b/packages/libs/src/http/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/libs/src/http/body.ts b/packages/libs/src/http/body.ts new file mode 100644 index 0000000..5c8bbfd --- /dev/null +++ b/packages/libs/src/http/body.ts @@ -0,0 +1,151 @@ +import { HEADERS, JSON_CONTENT_TYPE, NULL_BODY_STATUSES } from './constants'; +import type { HttpResponseType, QueryParams, UploadProgress } from './types'; + +const ABSOLUTE_URL = /^[a-z][a-z\d+\-.]*:\/\//i; +const JSON_TYPE = /[/+]json\b/i; + +export function isAbsoluteUrl(url: string): boolean { + return ABSOLUTE_URL.test(url); +} + +// Joins baseUrl and url, then merges params into any query string already in the URL. +export function buildUrl( + baseUrl: string, + url: string, + params?: QueryParams, +): string { + const joined = + isAbsoluteUrl(url) || !url + ? url || baseUrl + : `${baseUrl.replace(/\/+$/, '')}/${url.replace(/^\/+/, '')}`; + if (!params) return joined; + + const hashIndex = joined.indexOf('#'); + const hash = hashIndex === -1 ? '' : joined.slice(hashIndex); + const beforeHash = hashIndex === -1 ? joined : joined.slice(0, hashIndex); + const queryIndex = beforeHash.indexOf('?'); + const path = queryIndex === -1 ? beforeHash : beforeHash.slice(0, queryIndex); + const search = new URLSearchParams( + queryIndex === -1 ? '' : beforeHash.slice(queryIndex + 1), + ); + + for (const [key, value] of Object.entries(params)) { + for (const item of Array.isArray(value) ? value : [value]) { + if (item !== undefined && item !== null) search.append(key, String(item)); + } + } + const query = search.toString(); + return `${path}${query ? `?${query}` : ''}${hash}`; +} + +function isBodyInit(body: unknown): body is BodyInit { + return ( + typeof body === 'string' || + body instanceof FormData || + body instanceof URLSearchParams || + body instanceof Blob || + body instanceof ArrayBuffer || + ArrayBuffer.isView(body) || + (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) + ); +} + +// FormData, URLSearchParams, Blob, File, ArrayBuffer, and strings go as is; anything else as JSON. +export function serializeBody(body: unknown): { + body?: BodyInit; + contentType?: string; +} { + if (body === undefined) return {}; + if (isBodyInit(body)) return { body }; + return { body: JSON.stringify(body), contentType: JSON_CONTENT_TYPE }; +} + +export function toFormData( + input: File | Blob | File[] | FormData, + fieldName: string, + fields?: Record, +): FormData { + if (input instanceof FormData) return input; + const form = new FormData(); + for (const [name, value] of Object.entries(fields ?? {})) + form.append(name, value); + for (const file of Array.isArray(input) ? input : [input]) + form.append(fieldName, file); + return form; +} + +export function toProgress(loaded: number, total: number): UploadProgress { + return { + loaded, + total, + percent: total > 0 ? Math.min(100, Math.round((loaded / total) * 100)) : 0, + }; +} + +async function readBlob( + response: Response, + onProgress?: (progress: UploadProgress) => void, +): Promise { + const total = Number(response.headers.get(HEADERS.contentLength)); + if (!onProgress || !response.body || !total) return response.blob(); + + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let loaded = 0; + onProgress(toProgress(0, total)); + for ( + let chunk = await reader.read(); + !chunk.done; + chunk = await reader.read() + ) { + chunks.push(chunk.value); + loaded += chunk.value.byteLength; + onProgress(toProgress(loaded, total)); + } + return new Blob(chunks, { + type: response.headers.get(HEADERS.contentType) ?? '', + }); +} + +// 'auto': 204, 205, or an empty body is undefined; a JSON content type is parsed; anything else is text. +// Invalid JSON throws a SyntaxError, which the client turns into PARSE_ERROR. +export async function parseBody( + response: Response, + responseType: HttpResponseType, + onProgress?: (progress: UploadProgress) => void, +): Promise { + if (responseType === 'blob') return readBlob(response, onProgress); + if (responseType === 'arrayBuffer') return response.arrayBuffer(); + if (NULL_BODY_STATUSES.includes(response.status)) return undefined; + const text = await response.text(); + if (responseType === 'text') return text; + if (!text) return undefined; + if ( + responseType === 'json' || + JSON_TYPE.test(response.headers.get(HEADERS.contentType) ?? '') + ) { + return JSON.parse(text); + } + return text; +} + +// filename* (RFC 5987) first, then filename. +export function parseContentDisposition( + header: string | null, +): string | undefined { + if (!header) return undefined; + const extended = /filename\*\s*=\s*([^;]+)/i.exec(header); + if (extended) { + const encoded = extended[1] + .trim() + .replace(/^"(.*)"$/, '$1') + .replace(/^[^']*'[^']*'/, ''); + try { + return decodeURIComponent(encoded); + } catch { + return encoded; + } + } + const plain = /filename\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(header); + return plain ? (plain[1] ?? plain[2]).trim() : undefined; +} diff --git a/packages/libs/src/http/constants.ts b/packages/libs/src/http/constants.ts new file mode 100644 index 0000000..7630012 --- /dev/null +++ b/packages/libs/src/http/constants.ts @@ -0,0 +1,63 @@ +import type { HttpMethod, RetryConfig } from './types'; + +export const HTTP_ERROR_CODES = { + NETWORK_ERROR: 'NETWORK_ERROR', + TIMEOUT: 'TIMEOUT', + ABORTED: 'ABORTED', + VALIDATION: 'VALIDATION', + BAD_REQUEST: 'BAD_REQUEST', + UNAUTHORIZED: 'UNAUTHORIZED', + FORBIDDEN: 'FORBIDDEN', + NOT_FOUND: 'NOT_FOUND', + CONFLICT: 'CONFLICT', + RATE_LIMITED: 'RATE_LIMITED', + SERVER_ERROR: 'SERVER_ERROR', + PARSE_ERROR: 'PARSE_ERROR', + INTERCEPTOR_ERROR: 'INTERCEPTOR_ERROR', + UNKNOWN: 'UNKNOWN', +} as const; + +export const HEADERS = { + requestId: 'X-Request-Id', + retryAfter: 'Retry-After', + contentType: 'Content-Type', + contentLength: 'Content-Length', + contentDisposition: 'Content-Disposition', + cookie: 'Cookie', +} as const; + +export const DEFAULT_TIMEOUT = 15_000; +export const SERVER_TIMEOUT = 5_000; +export const SERVER_RETRY_ATTEMPTS = 1; +export const DEFAULT_CREDENTIALS: RequestCredentials = 'include'; + +export const DEFAULT_RETRY: RetryConfig = { + attempts: 2, + methods: ['GET', 'HEAD', 'OPTIONS'], + statuses: [408, 429, 502, 503, 504], + networkErrors: true, + baseDelay: 300, + maxDelay: 5_000, +}; + +// A timeout is retried only on these; the request may have reached the server. +export const IDEMPOTENT_METHODS: readonly HttpMethod[] = [ + 'GET', + 'HEAD', + 'OPTIONS', + 'PUT', + 'DELETE', +]; +export const NO_BODY_METHODS: readonly HttpMethod[] = ['GET', 'HEAD', 'DELETE']; +export const RETRYABLE_CLIENT_STATUSES: readonly number[] = [408, 429]; +export const RETRY_AFTER_STATUSES: readonly number[] = [429, 503]; +export const NULL_BODY_STATUSES: readonly number[] = [101, 204, 205, 304]; + +export const JSON_CONTENT_TYPE = 'application/json'; +export const DEFAULT_UPLOAD_FIELD = 'file'; +export const REFRESH_LOCK_NAME = 'http-refresh'; +export const HTTP_ERROR_BRAND_KEY = 'lumina.http-error'; +export const ERROR_MESSAGE_PREFIX = 'errors:http.'; +export const ERROR_HINT_SUFFIX = '-hint'; +export const NOT_CONFIGURED_MESSAGE = + 'HttpClient is not configured: set baseUrl with http.configure({ baseUrl }) in the app bootstrap before sending requests.'; diff --git a/packages/libs/src/http/http-client.ts b/packages/libs/src/http/http-client.ts new file mode 100644 index 0000000..344cb53 --- /dev/null +++ b/packages/libs/src/http/http-client.ts @@ -0,0 +1,548 @@ +import { + buildUrl, + isAbsoluteUrl, + parseBody, + parseContentDisposition, + serializeBody, + toFormData, +} from './body'; +import { + DEFAULT_CREDENTIALS, + DEFAULT_RETRY, + DEFAULT_TIMEOUT, + DEFAULT_UPLOAD_FIELD, + HEADERS, + NO_BODY_METHODS, + SERVER_RETRY_ATTEMPTS, + SERVER_TIMEOUT, +} from './constants'; +import { + asUnauthorized, + createHttpError, + defaultMapErrorBody, + errorFromResponse, + notConfiguredError, + toHttpError, +} from './http-error'; +import type { HttpError, RequestContext } from './http-error'; +import { InterceptorManager } from './interceptors'; +import { abortable, RefreshCoordinator } from './refresh'; +import { getRetryDelay, shouldRetry, sleep } from './retry'; +import { sendWithXhr } from './upload'; +import type { + DownloadOptions, + DownloadResult, + ErrorInterceptor, + FeatureHttpConfig, + HttpClientConfig, + HttpMethod, + HttpResponse, + HttpResponseType, + RefreshConfig, + RequestArgs, + RequestConfig, + RequestInterceptor, + RequestOptions, + ResponseInterceptor, + RetryConfig, + UploadOptions, + UploadProgress, +} from './types'; +import { createRequestId } from './request-id'; + +type RequestKind = 'request' | 'upload' | 'download' | 'refresh'; + +interface Execution { + kind: RequestKind; + method: HttpMethod; + url: string; + body?: unknown; + options: RequestOptions; + responseType: HttpResponseType; + onProgress?: (progress: UploadProgress) => void; +} + +interface ResolvedConfig { + baseUrl: HttpClientConfig['baseUrl']; + headers: Record; + timeout: number | false; + credentials: RequestCredentials; + retry: RetryConfig | false; + refresh: RefreshConfig | false; + getCookieHeader?: () => string | Promise; + mapErrorBody: NonNullable; +} + +interface AttemptContext { + config: ResolvedConfig; + context: RequestContext; + signal: AbortSignal; // the caller's signal and every abort-all signal; the timeout is added per attempt + timeout: number | false; +} + +type Source = + | { kind: 'root'; config: HttpClientConfig } + | { kind: 'feature'; config: FeatureHttpConfig; parent: HttpClient }; + +const isServer = (): boolean => typeof window === 'undefined'; + +const defaultRetry = (): RetryConfig => + isServer() + ? { ...DEFAULT_RETRY, attempts: SERVER_RETRY_ATTEMPTS } + : DEFAULT_RETRY; + +const isUnauthorized = (error: HttpError): boolean => error.status === 401; + +// Merge field by field; false disables; true keeps the current settings. +function mergeRetry( + base: RetryConfig | false, + next: Partial | boolean | undefined, +): RetryConfig | false { + if (next === undefined) return base; + if (next === false) return false; + return { ...(base || defaultRetry()), ...(next === true ? {} : next) }; +} + +export class HttpClient { + readonly interceptors = { + request: new InterceptorManager<[interceptor: RequestInterceptor]>(), + response: new InterceptorManager< + [onSuccess?: ResponseInterceptor, onError?: ErrorInterceptor] + >(), + }; + + private source: Source; + private readonly refreshCoordinator = new RefreshCoordinator(); + private abortController = new AbortController(); + + constructor(config: HttpClientConfig); + /** @internal Feature clients are made with extend(). */ + constructor(config: FeatureHttpConfig, parent: HttpClient); + constructor( + config: HttpClientConfig | FeatureHttpConfig, + parent?: HttpClient, + ) { + this.source = parent + ? { kind: 'feature', config: config as FeatureHttpConfig, parent } + : { kind: 'root', config: config as HttpClientConfig }; + } + + get(url: string, options?: RequestOptions): Promise { + return this.send('GET', url, undefined, options); + } + + delete(url: string, options?: RequestOptions): Promise { + return this.send('DELETE', url, undefined, options); + } + + post(url: string, body?: unknown, options?: RequestOptions): Promise { + return this.send('POST', url, body, options); + } + + put(url: string, body?: unknown, options?: RequestOptions): Promise { + return this.send('PUT', url, body, options); + } + + patch(url: string, body?: unknown, options?: RequestOptions): Promise { + return this.send('PATCH', url, body, options); + } + + request({ + method, + url, + body, + ...options + }: RequestArgs): Promise> { + return this.execute({ + kind: 'request', + method, + url, + body, + options, + responseType: options.responseType ?? 'auto', + }); + } + + async upload( + url: string, + input: File | Blob | File[] | FormData, + options: UploadOptions = {}, + ): Promise { + const { + method = 'POST', + fieldName = DEFAULT_UPLOAD_FIELD, + fields, + onProgress, + ...rest + } = options; + const response = await this.execute({ + kind: 'upload', + method, + url, + body: toFormData(input, fieldName, fields), + options: rest, + responseType: 'auto', + onProgress, + }); + return response.data; + } + + async download( + url: string, + options: DownloadOptions = {}, + ): Promise { + const { onProgress, ...rest } = options; + const response = await this.execute({ + kind: 'download', + method: 'GET', + url, + options: rest, + responseType: 'blob', + onProgress, + }); + return { + blob: response.data, + fileName: parseContentDisposition( + response.headers.get(HEADERS.contentDisposition), + ), + contentType: response.headers.get(HEADERS.contentType) ?? undefined, + }; + } + + // Root client only, at bootstrap. + configure(config: Partial): void { + if (this.source.kind !== 'root') { + throw new Error( + 'configure() is for the root client only; pass feature settings to extend().', + ); + } + this.source = { + kind: 'root', + config: { ...this.source.config, ...config }, + }; + } + + // A feature client: reads this client's config live, runs its interceptors first, + // and shares its refresh coordinator and abort-all controller. + extend(config: FeatureHttpConfig): HttpClient { + return new HttpClient(config, this); + } + + // Browser only: aborts this client's in-flight requests (on the root, every feature's too). + abortAll(reason?: unknown): void { + if (isServer()) return; + this.abortController.abort(reason); + this.abortController = new AbortController(); + } + + private async send( + method: HttpMethod, + url: string, + body: unknown, + options: RequestOptions = {}, + ): Promise { + const response = await this.request({ ...options, method, url, body }); + return response.data; + } + + private root(): HttpClient { + return this.source.kind === 'root' ? this : this.source.parent.root(); + } + + // Merge order: lib defaults → root config → feature config. Read on every request. + private resolveConfig(): ResolvedConfig { + const { source } = this; + if (source.kind === 'feature') { + const base = source.parent.resolveConfig(); + const { config } = source; + return { + ...base, + baseUrl: config.baseUrl ?? base.baseUrl, + headers: { ...base.headers, ...config.headers }, + timeout: config.timeout ?? base.timeout, + retry: mergeRetry(base.retry, config.retry), + mapErrorBody: config.mapErrorBody ?? base.mapErrorBody, + }; + } + const { config } = source; + const server = isServer(); + return { + baseUrl: config.baseUrl, + headers: config.headers ?? {}, + timeout: config.timeout ?? (server ? SERVER_TIMEOUT : DEFAULT_TIMEOUT), + credentials: config.credentials ?? DEFAULT_CREDENTIALS, + retry: mergeRetry(defaultRetry(), config.retry), + refresh: server ? false : (config.refresh ?? false), + getCookieHeader: config.getCookieHeader, + mapErrorBody: config.mapErrorBody ?? defaultMapErrorBody, + }; + } + + private requestChain(): RequestInterceptor[] { + const own = this.interceptors.request + .list() + .map(([interceptor]) => interceptor); + return this.source.kind === 'root' + ? own + : [...this.source.parent.requestChain(), ...own]; + } + + private responseChain(): [ + onSuccess?: ResponseInterceptor, + onError?: ErrorInterceptor, + ][] { + const own = this.interceptors.response.list(); + return this.source.kind === 'root' + ? own + : [...this.source.parent.responseChain(), ...own]; + } + + private abortSignals(): AbortSignal[] { + const own = this.abortController.signal; + return this.source.kind === 'root' + ? [own] + : [own, ...this.source.parent.abortSignals()]; + } + + private async execute(execution: Execution): Promise> { + const { kind, method, url, options } = execution; + const config = this.resolveConfig(); + const context: RequestContext = { + method, + url, + requestId: createRequestId(), + }; + const signal = AbortSignal.any([ + ...(options.signal ? [options.signal] : []), + ...this.abortSignals(), + ]); + const isFile = kind === 'upload' || kind === 'download'; + const attempt: AttemptContext = { + config, + context, + signal, + timeout: options.timeout ?? (isFile ? false : config.timeout), + }; + + let response: HttpResponse; + try { + response = await this.withRecovery(execution, attempt); + } catch (thrown) { + throw await this.applyErrorInterceptors( + toHttpError(thrown, context, signal), + context, + ); + } + try { + for (const [onSuccess] of this.responseChain()) { + if (onSuccess) response = await onSuccess(response); + } + } catch (cause) { + throw await this.applyErrorInterceptors( + createHttpError('INTERCEPTOR_ERROR', context, cause), + context, + ); + } + return response as HttpResponse; + } + + // Sends attempts until one succeeds, refreshing once on 401 and retrying what may be retried. + private async withRecovery( + execution: Execution, + attempt: AttemptContext, + ): Promise> { + const { kind, method, options } = execution; + const { config, context, signal } = attempt; + const retry = + kind === 'upload' ? false : mergeRetry(config.retry, options.retry); + const optIn = options.retry === true || typeof options.retry === 'object'; + const { refresh } = config; + const coordinator = this.root().refreshCoordinator; + let retries = 0; + let replayed = false; + + for (;;) { + const generation = coordinator.generation; + try { + return await this.attempt(execution, attempt); + } catch (thrown) { + const error = toHttpError(thrown, context, signal); + const wantsRefresh = + refresh && + kind !== 'refresh' && + !options.skipRefresh && + error.code !== 'ABORTED' && + (refresh.shouldRefresh ?? isUnauthorized)(error); + + if (wantsRefresh) { + if (replayed) throw asUnauthorized(error); + replayed = true; + // A request sent before the latest refresh replays without another one. + if (coordinator.generation !== generation) continue; + const refreshed = await abortable( + coordinator.refresh( + () => this.sendRefresh(refresh), + refresh.onFailure, + ), + signal, + ); + if (refreshed) continue; + throw asUnauthorized(error); + } + + if (retry && shouldRetry(error, method, retry, retries, optIn)) { + await sleep(getRetryDelay(error, retry, retries), signal); + retries += 1; + continue; + } + throw error; + } + } + } + + private sendRefresh(refresh: RefreshConfig): Promise> { + return this.root().execute({ + kind: 'refresh', + method: refresh.method ?? 'POST', + url: refresh.endpoint, + options: { skipRefresh: true, retry: false }, + responseType: 'auto', + }); + } + + // One try: request interceptors, serialization, send, normalization, parsing. + private async attempt( + execution: Execution, + attempt: AttemptContext, + ): Promise> { + const { kind, options, responseType, onProgress } = execution; + const { config, context } = attempt; + const timeoutSignal = + attempt.timeout === false + ? undefined + : AbortSignal.timeout(attempt.timeout); + const signal = timeoutSignal + ? AbortSignal.any([attempt.signal, timeoutSignal]) + : attempt.signal; + // Which signal fired decides the code, never the message. + const failure = (cause: unknown) => + createHttpError( + attempt.signal.aborted + ? 'ABORTED' + : timeoutSignal?.aborted + ? 'TIMEOUT' + : 'NETWORK_ERROR', + context, + cause, + ); + + let request: RequestConfig = { + method: execution.method, + url: execution.url, + params: options.params, + body: execution.body, + headers: { + ...config.headers, + ...options.headers, + [HEADERS.requestId]: context.requestId, + }, + }; + try { + for (const intercept of this.requestChain()) + request = await intercept(request); + } catch (cause) { + throw createHttpError('INTERCEPTOR_ERROR', context, cause); + } + + const baseUrl = + typeof config.baseUrl === 'function' ? config.baseUrl() : config.baseUrl; + if (!baseUrl && !isAbsoluteUrl(request.url)) + throw notConfiguredError(context); + + const server = isServer(); + const headers = new Headers(request.headers); + const payload = NO_BODY_METHODS.includes(request.method) + ? {} + : serializeBody(request.body); + if (payload.body instanceof FormData) headers.delete(HEADERS.contentType); + else if (payload.contentType && !headers.has(HEADERS.contentType)) { + headers.set(HEADERS.contentType, payload.contentType); + } + if (server && config.getCookieHeader) { + const cookie = await config.getCookieHeader(); + if (cookie) headers.set(HEADERS.cookie, cookie); + } + const target = buildUrl(baseUrl, request.url, request.params); + + let response: Response; + try { + response = + kind === 'upload' && + typeof XMLHttpRequest !== 'undefined' && + payload.body instanceof FormData + ? await sendWithXhr({ + method: request.method, + url: target, + headers, + body: payload.body, + signal, + withCredentials: config.credentials === 'include', + onProgress, + }) + : await fetch(target, { + ...options.init, + method: request.method, + headers, + body: payload.body, + signal, + ...(server + ? { cache: 'no-store', credentials: undefined } + : { + credentials: + options.init?.credentials ?? config.credentials, + }), + }); + } catch (cause) { + throw failure(cause); + } + + if (!response.ok) + throw await errorFromResponse(response, context, config.mapErrorBody); + + let data: unknown; + try { + data = await parseBody( + response, + responseType, + kind === 'download' ? onProgress : undefined, + ); + } catch (cause) { + throw cause instanceof SyntaxError && !signal.aborted + ? createHttpError('PARSE_ERROR', context, cause) + : failure(cause); + } + return { + data, + status: response.status, + headers: response.headers, + requestId: response.headers.get(HEADERS.requestId) ?? context.requestId, + }; + } + + // onError may change the error but never turns a failure into a success. + private async applyErrorInterceptors( + error: HttpError, + context: RequestContext, + ): Promise { + let current = error; + for (const [, onError] of this.responseChain()) { + if (!onError) continue; + try { + current = await onError(current); + } catch (cause) { + return createHttpError('INTERCEPTOR_ERROR', context, cause); + } + } + return current; + } +} diff --git a/packages/libs/src/http/http-error.ts b/packages/libs/src/http/http-error.ts new file mode 100644 index 0000000..e404b94 --- /dev/null +++ b/packages/libs/src/http/http-error.ts @@ -0,0 +1,230 @@ +import { + ERROR_HINT_SUFFIX, + ERROR_MESSAGE_PREFIX, + HEADERS, + HTTP_ERROR_BRAND_KEY, + NOT_CONFIGURED_MESSAGE, + RETRY_AFTER_STATUSES, +} from './constants'; +import { parseRetryAfter } from './retry'; +import type { HttpErrorCode, HttpErrorShape } from './types'; + +// A brand, not only instanceof: server and client bundles can hold separate copies of the class. +const HTTP_ERROR_BRAND: unique symbol = Symbol.for(HTTP_ERROR_BRAND_KEY); + +export interface RequestContext { + method: string; + url: string; + requestId: string; +} + +export interface HttpErrorInit extends HttpErrorShape { + method: string; + url: string; + cause?: unknown; +} + +export interface HttpErrorJson extends HttpErrorShape { + name: string; + method: string; + url: string; +} + +export class HttpError extends Error implements HttpErrorShape { + readonly [HTTP_ERROR_BRAND] = true; + override name = 'HttpError'; + readonly code: HttpErrorCode | string; + readonly status: number; + readonly fieldErrors?: Record; + readonly hint?: string; + readonly requestId?: string; + readonly retryAfter?: number; + readonly method: string; + readonly url: string; + + constructor(init: HttpErrorInit) { + super(init.message, { cause: init.cause }); + this.code = init.code; + this.status = init.status; + this.fieldErrors = init.fieldErrors; + this.hint = init.hint; + this.requestId = init.requestId; + this.retryAfter = init.retryAfter; + this.method = init.method; + this.url = init.url; + } + + toJSON(): HttpErrorJson { + return { + name: this.name, + code: this.code, + message: this.message, + status: this.status, + fieldErrors: this.fieldErrors, + hint: this.hint, + requestId: this.requestId, + retryAfter: this.retryAfter, + method: this.method, + url: this.url, + }; + } +} + +export function isHttpError(error: unknown): error is HttpError { + return ( + typeof error === 'object' && + error !== null && + (error as { [HTTP_ERROR_BRAND]?: unknown })[HTTP_ERROR_BRAND] === true + ); +} + +function messageKey(code: string): string { + return `${ERROR_MESSAGE_PREFIX}${code + .toLowerCase() + .replace(/_error$/, '') + .replaceAll('_', '-')}`; +} + +// An error the lib creates itself: no response, so status 0 and i18n keys for message and hint. +export function createHttpError( + code: HttpErrorCode, + context: RequestContext, + cause?: unknown, +): HttpError { + const key = messageKey(code); + return new HttpError({ + code, + message: key, + hint: `${key}${ERROR_HINT_SUFFIX}`, + status: 0, + requestId: context.requestId, + method: context.method, + url: context.url, + cause, + }); +} + +export function notConfiguredError(context: RequestContext): HttpError { + return new HttpError({ + ...context, + code: 'UNKNOWN', + message: NOT_CONFIGURED_MESSAGE, + status: 0, + }); +} + +// Anything thrown during a request becomes an HttpError. +export function toHttpError( + thrown: unknown, + context: RequestContext, + signal: AbortSignal, +): HttpError { + if (isHttpError(thrown)) return thrown; + return createHttpError( + signal.aborted ? 'ABORTED' : 'UNKNOWN', + context, + thrown, + ); +} + +export function asUnauthorized(error: HttpError): HttpError { + if (error.code === 'UNAUTHORIZED') return error; + return new HttpError({ + ...error.toJSON(), + code: 'UNAUTHORIZED', + cause: error, + }); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function asString(value: unknown): string | undefined { + return typeof value === 'string' ? value : undefined; +} + +function toFieldErrors(value: unknown): Record | undefined { + if (!isRecord(value)) return undefined; + const entries = Object.entries(value).flatMap(([field, message]) => { + const text: unknown = Array.isArray(message) ? message[0] : message; + return typeof text === 'string' ? [[field, text] as const] : []; + }); + return entries.length > 0 ? Object.fromEntries(entries) : undefined; +} + +// Default back-end error contract: { code, message, hint, fieldErrors | errors }. +export function defaultMapErrorBody(body: unknown): Partial { + if (!isRecord(body)) return {}; + return { + code: asString(body.code), + message: asString(body.message), + hint: asString(body.hint), + fieldErrors: toFieldErrors(body.fieldErrors ?? body.errors), + }; +} + +function codeForStatus(status: number, hasFieldErrors: boolean): HttpErrorCode { + if (status === 400 || status === 422) + return hasFieldErrors ? 'VALIDATION' : 'BAD_REQUEST'; + if (status === 401) return 'UNAUTHORIZED'; + if (status === 403) return 'FORBIDDEN'; + if (status === 404) return 'NOT_FOUND'; + if (status === 409) return 'CONFLICT'; + if (status === 429) return 'RATE_LIMITED'; + if (status >= 500) return 'SERVER_ERROR'; + return 'UNKNOWN'; +} + +async function readErrorBody(response: Response): Promise { + try { + const text = await response.text(); + if (!text) return undefined; + try { + return JSON.parse(text); + } catch { + return text; + } + } catch { + return undefined; + } +} + +export async function errorFromResponse( + response: Response, + context: RequestContext, + mapErrorBody: (body: unknown, response: Response) => Partial, +): Promise { + const body = await readErrorBody(response); + let mapped: Partial = {}; + try { + mapped = mapErrorBody(body, response); + } catch { + // A broken mapper must not hide the HTTP error; fall back to the status. + } + const { status } = response; + const fieldErrors = + mapped.fieldErrors && Object.keys(mapped.fieldErrors).length > 0 + ? mapped.fieldErrors + : undefined; + const statusCode = codeForStatus(status, fieldErrors !== undefined); + return new HttpError({ + code: mapped.code ?? statusCode, + message: mapped.message ?? messageKey(statusCode), + status, + fieldErrors, + hint: mapped.hint, + requestId: + mapped.requestId ?? + response.headers.get(HEADERS.requestId) ?? + context.requestId, + retryAfter: + mapped.retryAfter ?? + (RETRY_AFTER_STATUSES.includes(status) + ? parseRetryAfter(response.headers.get(HEADERS.retryAfter)) + : undefined), + method: context.method, + url: context.url, + cause: body, + }); +} diff --git a/packages/libs/src/http/http.ts b/packages/libs/src/http/http.ts new file mode 100644 index 0000000..8abd209 --- /dev/null +++ b/packages/libs/src/http/http.ts @@ -0,0 +1,10 @@ +import { HttpClient } from './http-client'; +import type { HttpClientConfig } from './types'; + +// An independent client that inherits nothing. Only for third-party APIs that don't use the app's auth. +export function createHttpClient(config: HttpClientConfig): HttpClient { + return new HttpClient(config); +} + +// The root client: retry on with defaults, refresh off. The app's bootstrap sets baseUrl and refresh. +export const http = /* @__PURE__ */ createHttpClient({ baseUrl: '' }); diff --git a/packages/libs/src/http/index.ts b/packages/libs/src/http/index.ts new file mode 100644 index 0000000..b5f73da --- /dev/null +++ b/packages/libs/src/http/index.ts @@ -0,0 +1,27 @@ +export { HTTP_ERROR_CODES } from './constants'; +export { HttpClient } from './http-client'; +export { createHttpClient, http } from './http'; +export { HttpError, isHttpError } from './http-error'; +export type { + DownloadOptions, + DownloadResult, + ErrorInterceptor, + FeatureHttpConfig, + HttpClientConfig, + HttpErrorCode, + HttpErrorShape, + HttpMethod, + HttpResponse, + HttpResponseType, + QueryParams, + QueryValue, + RefreshConfig, + RequestArgs, + RequestConfig, + RequestInterceptor, + RequestOptions, + ResponseInterceptor, + RetryConfig, + UploadOptions, + UploadProgress, +} from './types'; diff --git a/packages/libs/src/http/interceptors.ts b/packages/libs/src/http/interceptors.ts new file mode 100644 index 0000000..616054c --- /dev/null +++ b/packages/libs/src/http/interceptors.ts @@ -0,0 +1,17 @@ +// Holds handlers in registration order. use() returns an eject function. +export class InterceptorManager { + private entries: { handler: Handler }[] = []; + + use(...handler: Handler): () => void { + const entry = { handler }; + // Copy on write, so ejecting while a request iterates the list is safe. + this.entries = [...this.entries, entry]; + return () => { + this.entries = this.entries.filter((item) => item !== entry); + }; + } + + list(): Handler[] { + return this.entries.map((entry) => entry.handler); + } +} diff --git a/packages/libs/src/http/refresh.ts b/packages/libs/src/http/refresh.ts new file mode 100644 index 0000000..6c588f3 --- /dev/null +++ b/packages/libs/src/http/refresh.ts @@ -0,0 +1,63 @@ +import { REFRESH_LOCK_NAME } from './constants'; +import { isHttpError } from './http-error'; + +// One refresh at a time for the root client and every feature client. +export class RefreshCoordinator { + // Incremented on each successful refresh, so a stale 401 replays without refreshing again. + generation = 0; + private pending?: Promise; + + // Resolves true when the refresh succeeded. Joins the refresh in flight, if any. + refresh( + send: () => Promise, + onFailure?: () => void, + ): Promise { + this.pending ??= this.run(send, onFailure).finally(() => { + this.pending = undefined; + }); + return this.pending; + } + + private async run( + send: () => Promise, + onFailure?: () => void, + ): Promise { + try { + await withLock(send); + this.generation += 1; + return true; + } catch (error) { + if (!(isHttpError(error) && error.code === 'ABORTED')) { + try { + onFailure?.(); + } catch { + // A failing callback must not break the waiting requests. + } + } + return false; + } + } +} + +// Two tabs never send the same refresh cookie at once. +function withLock(send: () => Promise): Promise { + if (typeof navigator !== 'undefined' && navigator.locks) { + return navigator.locks.request(REFRESH_LOCK_NAME, send); + } + return send(); +} + +// Waits for a shared promise but rejects with the signal's reason as soon as this caller aborts. +export function abortable( + promise: Promise, + signal: AbortSignal, +): Promise { + if (signal.aborted) return Promise.reject(signal.reason); + return new Promise((resolve, reject) => { + const onAbort = () => reject(signal.reason); + signal.addEventListener('abort', onAbort, { once: true }); + promise + .then(resolve, reject) + .finally(() => signal.removeEventListener('abort', onAbort)); + }); +} diff --git a/packages/libs/src/http/request-id.ts b/packages/libs/src/http/request-id.ts new file mode 100644 index 0000000..41a08be --- /dev/null +++ b/packages/libs/src/http/request-id.ts @@ -0,0 +1,11 @@ +/** + * A random request id. `crypto.randomUUID` exists only in secure contexts (HTTPS, localhost), + * so plain-HTTP origins such as a dev server on a LAN IP fall back to `getRandomValues`. + */ +export function createRequestId(): string { + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID(); + const bytes = crypto.getRandomValues(new Uint8Array(16)); + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join( + '', + ); +} diff --git a/packages/libs/src/http/retry.ts b/packages/libs/src/http/retry.ts new file mode 100644 index 0000000..37bb1b6 --- /dev/null +++ b/packages/libs/src/http/retry.ts @@ -0,0 +1,70 @@ +import { IDEMPOTENT_METHODS, RETRYABLE_CLIENT_STATUSES } from './constants'; +import type { HttpError } from './http-error'; +import type { HttpMethod, RetryConfig } from './types'; + +// optIn: the request set `retry: true` or an object, so its method doesn't have to be in retry.methods. +export function shouldRetry( + error: HttpError, + method: HttpMethod, + retry: RetryConfig, + attempt: number, + optIn: boolean, +): boolean { + if (attempt >= retry.attempts) return false; + if (!optIn && !retry.methods.includes(method)) return false; + if (error.code === 'ABORTED') return false; + if (error.code === 'TIMEOUT') + return retry.networkErrors && IDEMPOTENT_METHODS.includes(method); + if (error.code === 'NETWORK_ERROR') return retry.networkErrors; + if ( + error.status >= 400 && + error.status < 500 && + !RETRYABLE_CLIENT_STATUSES.includes(error.status) + ) { + return false; + } + return retry.statuses.includes(error.status); +} + +// Retry-After wins when present; otherwise exponential backoff with full jitter. +export function getRetryDelay( + error: HttpError, + retry: RetryConfig, + attempt: number, +): number { + if (error.retryAfter !== undefined) + return Math.min(retry.maxDelay, error.retryAfter * 1000); + return ( + Math.random() * Math.min(retry.maxDelay, retry.baseDelay * 2 ** attempt) + ); +} + +// Retry-After is either seconds or an HTTP date; returns seconds. +export function parseRetryAfter(value: string | null): number | undefined { + if (!value) return undefined; + const seconds = Number(value); + if (Number.isFinite(seconds)) return Math.max(0, seconds); + const date = Date.parse(value); + return Number.isNaN(date) + ? undefined + : Math.max(0, Math.ceil((date - Date.now()) / 1000)); +} + +// Rejects with the signal's reason as soon as it aborts. +export function sleep(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(signal.reason); + return; + } + const onAbort = () => { + clearTimeout(timer); + reject(signal.reason); + }; + const timer = setTimeout(() => { + signal.removeEventListener('abort', onAbort); + resolve(); + }, ms); + signal.addEventListener('abort', onAbort, { once: true }); + }); +} diff --git a/packages/libs/src/http/server-http.ts b/packages/libs/src/http/server-http.ts new file mode 100644 index 0000000..b940bc8 --- /dev/null +++ b/packages/libs/src/http/server-http.ts @@ -0,0 +1,11 @@ +import { http } from './http'; +import type { ServerHttpConfig } from './types'; + +// Called once by bootstrap.server.ts. getCookieHeader runs on every server request, +// so each request forwards its own user's cookies; nothing per user is kept in module state. +export function configureServerHttp(config: ServerHttpConfig): void { + http.configure({ + baseUrl: config.baseUrl, + getCookieHeader: config.getCookieHeader, + }); +} diff --git a/packages/libs/src/http/server.ts b/packages/libs/src/http/server.ts new file mode 100644 index 0000000..3a89a77 --- /dev/null +++ b/packages/libs/src/http/server.ts @@ -0,0 +1,4 @@ +import 'server-only'; + +export { configureServerHttp } from './server-http'; +export type { ServerHttpConfig } from './types'; diff --git a/packages/libs/src/http/types.ts b/packages/libs/src/http/types.ts new file mode 100644 index 0000000..0a0d3d5 --- /dev/null +++ b/packages/libs/src/http/types.ts @@ -0,0 +1,149 @@ +import type { HTTP_ERROR_CODES } from './constants'; +import type { HttpError } from './http-error'; + +export type HttpMethod = + | 'GET' + | 'POST' + | 'PUT' + | 'PATCH' + | 'DELETE' + | 'HEAD' + | 'OPTIONS'; + +export type HttpErrorCode = + (typeof HTTP_ERROR_CODES)[keyof typeof HTTP_ERROR_CODES]; + +export type QueryValue = string | number | boolean; + +export type QueryParams = Record< + string, + QueryValue | QueryValue[] | null | undefined +>; + +export type HttpResponseType = + | 'auto' + | 'json' + | 'text' + | 'blob' + | 'arrayBuffer'; + +export interface HttpErrorShape { + code: HttpErrorCode | string; // the server's code wins when the body has one + message: string; + status: number; // 0 when there was no response (network, timeout, abort) + fieldErrors?: Record; // field path → message, e.g. { 'address.city': '...' } + hint?: string; // how the user can fix it + requestId?: string; + retryAfter?: number; // seconds, from Retry-After on 429 and 503 +} + +export interface RetryConfig { + attempts: number; // retries after the first try, default 2 (3 tries at most) + methods: HttpMethod[]; // default ['GET', 'HEAD', 'OPTIONS'] + statuses: number[]; // default [408, 429, 502, 503, 504] + networkErrors: boolean; // default true (no response) + baseDelay: number; // default 300 ms + maxDelay: number; // default 5_000 ms +} + +export interface RefreshConfig { + endpoint: string; // relative to baseUrl or absolute, e.g. '/auth/refresh' + method?: 'POST' | 'GET'; // default 'POST' + shouldRefresh?: (error: HttpError) => boolean; // default: error.status === 401 + onFailure?: () => void; // called once per failed refresh, e.g. emit the logout event +} + +export interface HttpClientConfig { + baseUrl: string | (() => string); // a function is read on each request, so env is never read at module load + headers?: Record; + timeout?: number | false; // ms per attempt, default 15_000 (5_000 on the server) + credentials?: RequestCredentials; // default 'include' (auth is cookie-based) + retry?: Partial | false; // default: enabled with the defaults, merged field by field + refresh?: RefreshConfig | false; // default: false until bootstrap sets it + getCookieHeader?: () => string | Promise; // server only, set through configureServerHttp + mapErrorBody?: (body: unknown, response: Response) => Partial; // adapts the back end's error contract +} + +// What a feature may set in http.extend(). Auth settings are left out, so a feature cannot break them. +export type FeatureHttpConfig = Omit< + Partial, + 'refresh' | 'credentials' | 'getCookieHeader' | 'retry' +> & { + retry?: Partial | false; // merged field by field over the root's retry + refresh?: never; + credentials?: never; + getCookieHeader?: never; +}; + +export interface ServerHttpConfig { + baseUrl: HttpClientConfig['baseUrl']; + getCookieHeader: () => string | Promise; +} + +export interface RequestOptions { + params?: QueryParams; + headers?: Record; + signal?: AbortSignal; + timeout?: number | false; + retry?: Partial | boolean; // false disables; true or an object opts in, whatever the method + skipRefresh?: boolean; // this request never triggers a refresh + responseType?: HttpResponseType; // default 'auto' + init?: Omit; // passthrough, e.g. keepalive or priority +} + +export interface RequestArgs extends RequestOptions { + method: HttpMethod; + url: string; + body?: unknown; +} + +// What request interceptors receive and return. Never mutate it; return a new one. +export interface RequestConfig { + method: HttpMethod; + url: string; + headers: Record; + params?: QueryParams; + body?: unknown; +} + +export interface HttpResponse { + data: T; + status: number; + headers: Headers; + requestId: string; +} + +export type RequestInterceptor = ( + config: RequestConfig, +) => RequestConfig | Promise; + +export type ResponseInterceptor = ( + response: HttpResponse, +) => HttpResponse | Promise>; + +export type ErrorInterceptor = ( + error: HttpError, +) => HttpError | Promise; + +export interface UploadProgress { + loaded: number; + total: number; + percent: number; // integer 0–100 +} + +export interface UploadOptions extends Omit { + method?: 'POST' | 'PUT' | 'PATCH'; // default 'POST' + fieldName?: string; // default 'file', used when input is a File, Blob, or File[] + fields?: Record; // extra form fields sent with the file + onProgress?: (progress: UploadProgress) => void; +} + +export interface DownloadOptions extends Omit { + onProgress?: (progress: UploadProgress) => void; +} + +export interface DownloadResult { + blob: Blob; + fileName?: string; + contentType?: string; +} diff --git a/packages/libs/src/http/upload.ts b/packages/libs/src/http/upload.ts new file mode 100644 index 0000000..5ee3895 --- /dev/null +++ b/packages/libs/src/http/upload.ts @@ -0,0 +1,73 @@ +import { NULL_BODY_STATUSES } from './constants'; +import { toProgress } from './body'; +import type { UploadProgress } from './types'; + +export interface XhrRequest { + method: string; + url: string; + headers: Headers; + body: FormData; + signal: AbortSignal; + withCredentials: boolean; + onProgress?: (progress: UploadProgress) => void; +} + +function toResponse(xhr: XMLHttpRequest): Response { + const headers = new Headers(); + for (const line of xhr + .getAllResponseHeaders() + .trim() + .split(/[\r\n]+/)) { + const index = line.indexOf(':'); + if (index > 0) + headers.append(line.slice(0, index).trim(), line.slice(index + 1).trim()); + } + const body: Blob | null = NULL_BODY_STATUSES.includes(xhr.status) + ? null + : xhr.response; + return new Response(body, { + status: xhr.status, + statusText: xhr.statusText, + headers, + }); +} + +// fetch can't report upload progress, so uploads go through XMLHttpRequest. +// Resolves with a Response so the client parses and normalizes it like any fetch response. +export function sendWithXhr(request: XhrRequest): Promise { + const { signal, onProgress } = request; + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(signal.reason); + return; + } + const xhr = new XMLHttpRequest(); + const onAbort = () => xhr.abort(); + const settle = (finish: () => void) => () => { + signal.removeEventListener('abort', onAbort); + finish(); + }; + + xhr.open(request.method, request.url); + xhr.responseType = 'blob'; + xhr.withCredentials = request.withCredentials; + request.headers.forEach((value, key) => xhr.setRequestHeader(key, value)); + + if (onProgress) { + xhr.upload.onloadstart = (event) => + onProgress(toProgress(0, event.total)); + xhr.upload.onprogress = (event) => { + if (event.lengthComputable) + onProgress(toProgress(event.loaded, event.total)); + }; + xhr.upload.onload = (event) => + onProgress({ loaded: event.loaded, total: event.total, percent: 100 }); + } + + xhr.onload = settle(() => resolve(toResponse(xhr))); + xhr.onerror = settle(() => reject(new TypeError('Network request failed'))); + xhr.onabort = settle(() => reject(signal.reason)); + signal.addEventListener('abort', onAbort, { once: true }); + xhr.send(request.body); + }); +} diff --git a/packages/libs/src/index.ts b/packages/libs/src/index.ts index 2219612..505d3d0 100644 --- a/packages/libs/src/index.ts +++ b/packages/libs/src/index.ts @@ -1,2 +1,76 @@ // Public client-safe API. Re-export each module by name; never `export *`. -export {}; +export { CookieAdapter, DEFAULT_COOKIE_OPTIONS, cookie } from './cookie'; +export type { CookieAdapterAbstraction, CookieOptions } from './cookie'; +export { createClientEnv } from './env'; +export type { + ClientEnvOptions, + EnvSchema, + EnvValues, + ServerEnvOptions, +} from './env'; +export { + classifyError, + configureErrorHandler, + describeError, + handleError, +} from './error-handler'; +export type { + ActionOutcome, + ErrorCause, + ErrorClass, + ErrorContext, + ErrorDescription, + ErrorHandlerConfig, + ErrorReport, + ErrorWhere, + ReadOutcome, + RetryKind, + TranslateFn, +} from './error-handler'; +export { eventEmitter } from './event-emitter'; +export type { + EventArgs, + EventEmitter, + EventListener, + EventMap, + EventName, + EventPayload, + Unsubscribe, +} from './event-emitter'; +export { + HTTP_ERROR_CODES, + HttpClient, + HttpError, + createHttpClient, + http, + isHttpError, +} from './http'; +export type { + DownloadOptions, + DownloadResult, + ErrorInterceptor, + FeatureHttpConfig, + HttpClientConfig, + HttpErrorCode, + HttpErrorShape, + HttpMethod, + HttpResponse, + HttpResponseType, + QueryParams, + QueryValue, + RefreshConfig, + RequestArgs, + RequestConfig, + RequestInterceptor, + RequestOptions, + ResponseInterceptor, + RetryConfig, + UploadOptions, + UploadProgress, +} from './http'; +export { + DEFAULT_STORAGE_PREFIX, + LocalStorageAdapter, + storage, +} from './local-storage'; +export type { LocalStorageOptions } from './local-storage'; diff --git a/packages/libs/src/local-storage/.gitkeep b/packages/libs/src/local-storage/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/libs/src/local-storage/constants.ts b/packages/libs/src/local-storage/constants.ts new file mode 100644 index 0000000..ff65ee9 --- /dev/null +++ b/packages/libs/src/local-storage/constants.ts @@ -0,0 +1,3 @@ +export const DEFAULT_STORAGE_PREFIX = 'app'; + +export const STORAGE_KEY_SEPARATOR = '.'; diff --git a/packages/libs/src/local-storage/index.ts b/packages/libs/src/local-storage/index.ts new file mode 100644 index 0000000..62a6f4c --- /dev/null +++ b/packages/libs/src/local-storage/index.ts @@ -0,0 +1,3 @@ +export { DEFAULT_STORAGE_PREFIX } from './constants'; +export { LocalStorageAdapter, storage } from './local-storage'; +export type { LocalStorageOptions } from './types'; diff --git a/packages/libs/src/local-storage/local-storage.ts b/packages/libs/src/local-storage/local-storage.ts new file mode 100644 index 0000000..c7d3f3b --- /dev/null +++ b/packages/libs/src/local-storage/local-storage.ts @@ -0,0 +1,118 @@ +import { DEFAULT_STORAGE_PREFIX, STORAGE_KEY_SEPARATOR } from './constants'; +import type { LocalStorageOptions } from './types'; + +function assertBrowser(): void { + if (typeof window === 'undefined') { + throw new Error( + 'storage is browser-only; never read it during render or on the server', + ); + } +} + +/** + * Namespaces every key under `.` and absorbs blocked or full storage. + * Has the members of the native `Storage` interface, so it works with zustand's `createJSONStorage`. + */ +export class LocalStorageAdapter { + #options: Required = { + prefix: DEFAULT_STORAGE_PREFIX, + debug: false, + }; + + /** Sets the prefix once, in the client bootstrap. Never touches `window`. */ + configure(options: LocalStorageOptions): void { + this.#options = { debug: false, ...options }; + } + + get length(): number { + return this.#run((native) => this.#ownKeys(native).length, 0); + } + + key(index: number): string | null { + return this.#run((native) => { + const fullKey = this.#ownKeys(native)[index]; + return fullKey === undefined + ? null + : fullKey.slice(this.#namespace().length); + }, null); + } + + getItem(key: string): string | null { + return this.#run((native) => native.getItem(this.#fullKey(key)), null); + } + + setItem(key: string, value: string): void { + this.#run((native) => native.setItem(this.#fullKey(key), value), undefined); + } + + removeItem(key: string): void { + this.#run((native) => native.removeItem(this.#fullKey(key)), undefined); + } + + /** Removes only the keys under this adapter's prefix. */ + clear(): void { + this.#removeStartingWith(this.#namespace()); + } + + /** Removes every key under `.`, e.g. `clearByPrefix('session.')` on logout. */ + clearByPrefix(subPrefix: string): void { + this.#removeStartingWith(this.#fullKey(subPrefix)); + } + + /** Parsed JSON, or null for a missing key or invalid JSON (which is removed). The result is untrusted. */ + getJSON(key: string): T | null { + const raw = this.getItem(key); + if (raw === null) return null; + try { + return JSON.parse(raw) as T; + } catch { + this.removeItem(key); + return null; + } + } + + setJSON(key: string, value: unknown): void { + this.setItem(key, JSON.stringify(value)); + } + + #namespace(): string { + return `${this.#options.prefix}${STORAGE_KEY_SEPARATOR}`; + } + + #fullKey(key: string): string { + return `${this.#namespace()}${key}`; + } + + #ownKeys(native: Storage, startsWith = this.#namespace()): string[] { + const keys: string[] = []; + for (let index = 0; index < native.length; index += 1) { + const fullKey = native.key(index); + if (fullKey?.startsWith(startsWith)) keys.push(fullKey); + } + return keys; + } + + #removeStartingWith(startsWith: string): void { + this.#run((native) => { + // collect first: removing while iterating shifts the indexes + for (const fullKey of this.#ownKeys(native, startsWith)) + native.removeItem(fullKey); + }, undefined); + } + + /** Throws on the server (a programming mistake); returns `fallback` when storage is blocked or full. */ + #run(operation: (native: Storage) => T, fallback: T): T { + assertBrowser(); + try { + // reading window.localStorage itself throws SecurityError when storage is blocked + return operation(window.localStorage); + } catch (error) { + if (this.#options.debug) { + console.warn('storage is unavailable; continuing without it.', error); + } + return fallback; + } + } +} + +export const storage = new LocalStorageAdapter(); diff --git a/packages/libs/src/local-storage/types.ts b/packages/libs/src/local-storage/types.ts new file mode 100644 index 0000000..e6b638a --- /dev/null +++ b/packages/libs/src/local-storage/types.ts @@ -0,0 +1,6 @@ +export interface LocalStorageOptions { + /** The app's namespace, e.g. 'shop'. Default DEFAULT_STORAGE_PREFIX. */ + prefix: string; + /** Log a warning when storage is blocked or full. The app passes true in development. Default false. */ + debug?: boolean; +} diff --git a/packages/libs/src/server.ts b/packages/libs/src/server.ts index 9c66bed..8ad0659 100644 --- a/packages/libs/src/server.ts +++ b/packages/libs/src/server.ts @@ -1,3 +1,6 @@ import 'server-only'; // Public server-only API, exposed as the `/server` subpath. index.ts never imports this file. +export { createServerEnv } from './env/server'; +export { configureServerHttp } from './http/server'; +export type { ServerHttpConfig } from './http/server'; diff --git a/packages/libs/tsconfig.lib.json b/packages/libs/tsconfig.lib.json index 41d5cfc..2d842f2 100644 --- a/packages/libs/tsconfig.lib.json +++ b/packages/libs/tsconfig.lib.json @@ -5,11 +5,19 @@ "outDir": "dist", "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", "emitDeclarationOnly": true, - "forceConsistentCasingInFileNames": true, - "types": ["node"] + "types": [ + "node" + ], + "lib": [ + "es2022", + "dom", + "dom.iterable" + ] }, - "include": ["src/**/*.ts"], + "include": [ + "src/**/*.ts" + ], "references": [ { "path": "../tools/tsconfig.lib.json" diff --git a/packages/tools/src/format/.gitkeep b/packages/tools/src/format/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/tools/src/format/constants.ts b/packages/tools/src/format/constants.ts new file mode 100644 index 0000000..11fb892 --- /dev/null +++ b/packages/tools/src/format/constants.ts @@ -0,0 +1,21 @@ +/** Every date shown in the product is Shamsi in Tehran time, whatever the runtime's time zone. */ +export const TIME_ZONE = 'Asia/Tehran'; + +/** Persian locale with Latin digits: the font draws Persian digit shapes, so text stays searchable and copyable. */ +export const LOCALE = 'fa-IR-u-ca-persian-nu-latn'; + +export const THOUSANDS_SEPARATOR = '٬'; // ٬ +export const DECIMAL_SEPARATOR = '٫'; // ٫ +export const PERCENT_SIGN = '٪'; // ٪ +export const MINUS_SIGN = '−'; // − + +/** Left-to-right isolate, so signs and percents keep their order inside RTL text. */ +export const LTR_ISOLATE_START = '⁦'; +export const LTR_ISOLATE_END = '⁩'; + +export const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹'; +export const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩'; + +export const MINUTE_MS = 60_000; +export const HOUR_MS = 60 * MINUTE_MS; +export const DAY_MS = 24 * HOUR_MS; diff --git a/packages/tools/src/format/format.ts b/packages/tools/src/format/format.ts new file mode 100644 index 0000000..058250c --- /dev/null +++ b/packages/tools/src/format/format.ts @@ -0,0 +1,157 @@ +import { + ARABIC_DIGITS, + DAY_MS, + DECIMAL_SEPARATOR, + HOUR_MS, + LOCALE, + LTR_ISOLATE_END, + LTR_ISOLATE_START, + MINUS_SIGN, + MINUTE_MS, + PERCENT_SIGN, + PERSIAN_DIGITS, + THOUSANDS_SEPARATOR, + TIME_ZONE, +} from './constants'; +import type { DateFormatOptions, DateInput, ShebaFormatOptions } from './types'; + +// Formatters are built once per fixed locale and time zone (flyweight); they never hold per-request data. +const dateFormatter = new Intl.DateTimeFormat(LOCALE, { + timeZone: TIME_ZONE, + day: 'numeric', + month: 'long', + year: 'numeric', +}); +const dateTimeFormatter = new Intl.DateTimeFormat(LOCALE, { + timeZone: TIME_ZONE, + day: 'numeric', + month: 'long', + year: 'numeric', + hour: '2-digit', + minute: '2-digit', + hourCycle: 'h23', +}); +const relativeFormatter = new Intl.RelativeTimeFormat(LOCALE, { + numeric: 'auto', +}); +const numberFormatters = new Map(); + +function numberFormatter(decimals: number): Intl.NumberFormat { + let formatter = numberFormatters.get(decimals); + if (!formatter) { + formatter = new Intl.NumberFormat('en-US', { + minimumFractionDigits: decimals, + maximumFractionDigits: decimals, + }); + numberFormatters.set(decimals, formatter); + } + return formatter; +} + +function persianSeparators(value: string): string { + return value.replace(/[,.]/g, (char) => + char === ',' ? THOUSANDS_SEPARATOR : DECIMAL_SEPARATOR, + ); +} + +function toDate(value: DateInput): Date { + return value instanceof Date ? value : new Date(value); +} + +/** Wraps text in an LTR isolate so signs, percents and codes keep their order inside RTL copy. */ +export function iso(value: string): string { + return `${LTR_ISOLATE_START}${value}${LTR_ISOLATE_END}`; +} + +/** Converts Persian and Arabic digits to Latin ones; use it on every input before validation. */ +export function latinDigits(value: string): string { + return value.replace(/[۰-۹٠-٩]/g, (digit) => { + const persian = PERSIAN_DIGITS.indexOf(digit); + return String(persian === -1 ? ARABIC_DIGITS.indexOf(digit) : persian); + }); +} + +/** `1234567.8` → `1٬234٬567٫8`. The font draws the digits in Persian. */ +export function number(value: number, decimals = 0): string { + return persianSeparators( + numberFormatter(decimals).format(Math.abs(value)), + ).replace(/^/, value < 0 ? MINUS_SIGN : ''); +} + +/** A price keeps the decimals it has: `1.092` → `1٫092`. */ +export function price(value: number): string { + const decimals = Math.min(value.toString().split('.')[1]?.length ?? 0, 8); + return number(value, decimals); +} + +/** Always shows `+` or `−`, inside an LTR isolate: `−120٬000`. */ +export function signed(value: number, decimals = 0): string { + const sign = value > 0 ? '+' : value < 0 ? MINUS_SIGN : ''; + return iso(`${sign}${number(Math.abs(value), decimals)}`); +} + +/** `62.86` → `62٫9٪`. The value is already a percentage, not a fraction. */ +export function percent(value: number, decimals = 1): string { + return `${number(value, decimals)}${PERCENT_SIGN}`; +} + +/** `4` → `+4٫0٪` inside an LTR isolate. */ +export function signedPercent(value: number, decimals = 1): string { + const sign = value > 0 ? '+' : value < 0 ? MINUS_SIGN : ''; + return iso(`${sign}${number(Math.abs(value), decimals)}${PERCENT_SIGN}`); +} + +/** `1 : 2٫8` inside an LTR isolate. */ +export function ratio(a: number, b: number, decimals = 1): string { + return iso(`${number(a)} : ${number(b, decimals)}`); +} + +/** Shamsi date in Tehran time: `15 خرداد 1404، ساعت 14:30`, or `15 خرداد 1404` with `{ time: false }`. */ +export function date( + value: DateInput, + { time = true }: DateFormatOptions = {}, +): string { + const at = toDate(value); + if (!time) return dateFormatter.format(at); + + // CLDR joins date and time with « ساعت »; the product style adds the Persian comma before it. + const parts = dateTimeFormatter.formatToParts(at); + const hourIndex = parts.findIndex((part) => part.type === 'hour'); + const datePart = parts + .slice(0, hourIndex - 1) + .map((part) => part.value) + .join(''); + const joiner = parts[hourIndex - 1]?.value.trim() ?? ''; + const timePart = parts + .slice(hourIndex) + .map((part) => part.value) + .join(''); + return `${datePart}، ${joiner} ${timePart}`; +} + +/** `5 دقیقه پیش`, `2 ساعت پیش`, `دیروز`; older than a day → `date()`. */ +export function relative( + value: DateInput, + now: DateInput = Date.now(), +): string { + const at = toDate(value); + const diff = toDate(now).getTime() - at.getTime(); + if (diff < MINUTE_MS) return relativeFormatter.format(0, 'second'); + if (diff < HOUR_MS) + return relativeFormatter.format(-Math.floor(diff / MINUTE_MS), 'minute'); + if (diff < DAY_MS) + return relativeFormatter.format(-Math.floor(diff / HOUR_MS), 'hour'); + if (diff < 2 * DAY_MS) return relativeFormatter.format(-1, 'day'); + return date(at); +} + +/** `IR620120000000101234567890` → `IR62 0120 0000 0010 1234 5678 90`. */ +export function sheba( + value: string, + { prefix = true }: ShebaFormatOptions = {}, +): string { + const digits = latinDigits(value).replace(/^IR/i, '').replace(/\D/g, ''); + const grouped = + (prefix ? `IR${digits}` : digits).match(/.{1,4}/g)?.join(' ') ?? ''; + return grouped; +} diff --git a/packages/tools/src/format/index.ts b/packages/tools/src/format/index.ts new file mode 100644 index 0000000..e4916bd --- /dev/null +++ b/packages/tools/src/format/index.ts @@ -0,0 +1,15 @@ +export { + date, + iso, + latinDigits, + number, + percent, + price, + ratio, + relative, + sheba, + signed, + signedPercent, +} from './format'; +export { LOCALE, TIME_ZONE } from './constants'; +export type { DateFormatOptions, DateInput, ShebaFormatOptions } from './types'; diff --git a/packages/tools/src/format/types.ts b/packages/tools/src/format/types.ts new file mode 100644 index 0000000..4271649 --- /dev/null +++ b/packages/tools/src/format/types.ts @@ -0,0 +1,11 @@ +export type DateInput = string | number | Date; + +export type DateFormatOptions = { + /** Include the time («ساعت ۱۴:۳۰»). Default `true`. */ + time?: boolean; +}; + +export type ShebaFormatOptions = { + /** Include the leading `IR`. Default `true`; pass `false` for the field after its fixed prefix. */ + prefix?: boolean; +}; diff --git a/packages/tools/src/index.ts b/packages/tools/src/index.ts index 2219612..0ac5df2 100644 --- a/packages/tools/src/index.ts +++ b/packages/tools/src/index.ts @@ -1,2 +1,20 @@ -// Public client-safe API. Re-export each module by name; never `export *`. -export {}; +export { + date, + iso, + latinDigits, + LOCALE, + number, + percent, + price, + ratio, + relative, + sheba, + signed, + signedPercent, + TIME_ZONE, +} from './format'; +export type { + DateFormatOptions, + DateInput, + ShebaFormatOptions, +} from './format'; diff --git a/packages/tools/tsconfig.lib.json b/packages/tools/tsconfig.lib.json index 9b52337..74d8927 100644 --- a/packages/tools/tsconfig.lib.json +++ b/packages/tools/tsconfig.lib.json @@ -5,10 +5,18 @@ "outDir": "dist", "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", "emitDeclarationOnly": true, - "forceConsistentCasingInFileNames": true, - "types": ["node"] + "types": [ + "node" + ], + "lib": [ + "es2022", + "dom", + "dom.iterable" + ] }, - "include": ["src/**/*.ts"], + "include": [ + "src/**/*.ts" + ], "references": [] } diff --git a/platforms/market/tsconfig.lib.json b/platforms/market/tsconfig.lib.json index 64944f6..6b58672 100644 --- a/platforms/market/tsconfig.lib.json +++ b/platforms/market/tsconfig.lib.json @@ -9,7 +9,12 @@ ], "rootDir": "src", "jsx": "react-jsx", - "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo" + "tsBuildInfoFile": "dist/tsconfig.lib.tsbuildinfo", + "lib": [ + "es2022", + "dom", + "dom.iterable" + ] }, "exclude": [ "out-tsc", @@ -28,7 +33,12 @@ "eslint.config.cjs", "eslint.config.mjs" ], - "include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"], + "include": [ + "src/**/*.js", + "src/**/*.jsx", + "src/**/*.ts", + "src/**/*.tsx" + ], "references": [ { "path": "../../packages/tools/tsconfig.lib.json" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dcbe4bb..568a5dc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,15 @@ importers: .: dependencies: + '@t3-oss/env-core': + specifier: ^0.13.11 + version: 0.13.11(typescript@6.0.3)(valibot@1.5.0(typescript@6.0.3)) + class-variance-authority: + specifier: ^0.7.1 + version: 0.7.1 + clsx: + specifier: ^2.1.1 + version: 2.1.1 next: specifier: ~16.1.6 version: 16.1.7(@babel/core@7.29.7(supports-color@7.2.0))(babel-plugin-macros@3.1.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -20,6 +29,12 @@ importers: server-only: specifier: ^0.0.1 version: 0.0.1 + tailwind-merge: + specifier: ^3.7.0 + version: 3.7.0 + valibot: + specifier: ^1.5.0 + version: 1.5.0(typescript@6.0.3) devDependencies: '@babel/core': specifier: ^7.14.5 @@ -72,6 +87,9 @@ importers: eslint: specifier: ^9.8.0 version: 9.39.5(jiti@2.7.0)(supports-color@7.2.0) + jiti: + specifier: ^2.7.0 + version: 2.7.0 nx: specifier: 23.2.1 version: 23.2.1(@swc-node/register@1.11.1(@swc/core@1.15.47(@swc/helpers@0.5.23))(@swc/types@0.1.28)(supports-color@7.2.0)(typescript@6.0.3))(@swc/core@1.15.47(@swc/helpers@0.5.23)) @@ -2023,6 +2041,23 @@ packages: '@swc/types@0.1.28': resolution: {integrity: sha512-V6Mnml8v09QALx6K0elJ7o9K/MkVDtW3t6L+7Ou/JcWtb3xwId2AH4FeOceySd2JaO87IMw4+6vSZxLm34LPbw==} + '@t3-oss/env-core@0.13.11': + resolution: {integrity: sha512-sM7GYY+KL7H/Hl0BE0inWfk3nRHZOLhmVn7sHGxaZt9FAR6KqREXAE+6TqKfiavfXmpRxO/OZ2QgKRd+oiBYRQ==} + peerDependencies: + arktype: ^2.1.0 + typescript: '>=5.0.0' + valibot: ^1.0.0-beta.7 || ^1.0.0 + zod: ^3.24.0 || ^4.0.0 + peerDependenciesMeta: + arktype: + optional: true + typescript: + optional: true + valibot: + optional: true + zod: + optional: true + '@tailwindcss/node@4.3.3': resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==} @@ -2512,6 +2547,9 @@ packages: resolution: {integrity: sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==} engines: {node: '>=6.0'} + class-variance-authority@0.7.1: + resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} + cli-cursor@3.1.0: resolution: {integrity: sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==} engines: {node: '>=8'} @@ -2535,6 +2573,10 @@ packages: resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==} engines: {node: '>=0.8'} + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} @@ -3972,6 +4014,9 @@ packages: resolution: {integrity: sha512-0OJWD12D7XX3KUg1DYkMaTTjSTo2k/mhIYI3HlBlceXSMcJhW/1qO735fPKS5prcyjvn57Ub151vvASYXpQrEw==} engines: {node: '>=18'} + tailwind-merge@3.7.0: + resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==} + tailwindcss@4.3.3: resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==} @@ -4095,6 +4140,14 @@ packages: util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + valibot@1.5.0: + resolution: {integrity: sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==} + peerDependencies: + typescript: '>=5' + peerDependenciesMeta: + typescript: + optional: true + vite@8.3.2: resolution: {integrity: sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w==} engines: {node: ^20.19.0 || >=22.12.0} @@ -6095,6 +6148,11 @@ snapshots: dependencies: '@swc/counter': 0.1.3 + '@t3-oss/env-core@0.13.11(typescript@6.0.3)(valibot@1.5.0(typescript@6.0.3))': + optionalDependencies: + typescript: 6.0.3 + valibot: 1.5.0(typescript@6.0.3) + '@tailwindcss/node@4.3.3': dependencies: '@jridgewell/remapping': 2.3.5 @@ -6689,6 +6747,10 @@ snapshots: chrome-trace-event@1.0.4: {} + class-variance-authority@0.7.1: + dependencies: + clsx: 2.1.1 + cli-cursor@3.1.0: dependencies: restore-cursor: 3.1.0 @@ -6711,6 +6773,8 @@ snapshots: clone@1.0.4: {} + clsx@2.1.1: {} + color-convert@2.0.1: dependencies: color-name: 1.1.4 @@ -8240,6 +8304,8 @@ snapshots: system-architecture@1.0.0: {} + tailwind-merge@3.7.0: {} + tailwindcss@4.3.3: {} tapable@2.3.3: {} @@ -8364,6 +8430,10 @@ snapshots: util-deprecate@1.0.2: {} + valibot@1.5.0(typescript@6.0.3): + optionalDependencies: + typescript: 6.0.3 + vite@8.3.2(@types/node@22.20.4)(jiti@2.7.0)(terser@5.51.2)(yaml@2.9.0): dependencies: lightningcss: 1.33.0