feat(market): app foundation, session handling and feature data layer

Foundation
- AppShell: query client, i18n, connection bar (NetworkBoundary), toast region,
  and reactions to sign-in and sign-out
- error boundaries: ErrorFallback, PartBoundary (catchError), StatusEmptyState,
  readOnServer
- typed ROUTES, platform env (API origin, support config), Persian locales
  (common, errors) with typed i18next keys
- mapApiErrorBody adapts the gateway's error envelope; shared utils for E.164
  phones, API URLs and field-error renames
- session: refreshSessionInProxy renews an expired cookie session before render
- guards: requireAccount, redirectIfSignedIn, requireRole

Data layer (entities, repositories with mappers, query keys, server caches)
- auth (with login, logout and registration actions), profile, channel, follow,
  notification, post, prediction, feed, pricing, checkout, subscription,
  transaction, overview, finance
- shared domain enums live in shared/constants

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Amiram_se 2026-10-04 21:33:07 +04:00
parent cd082e5ed9
commit a483fc0767
290 changed files with 6345 additions and 7 deletions

View File

@ -12,6 +12,7 @@
"./features/*/caches": "./src/features/*/caches/server.ts",
"./features/*": "./src/features/*/index.ts",
"./stores/*": "./src/stores/*/index.ts",
"./env": "./src/env/index.ts",
"./shared/locales/*": "./src/shared/locales/*",
"./shared/*": "./src/shared/*/index.ts",
"./package.json": "./package.json"

View File

@ -0,0 +1,28 @@
'use client';
import { Toaster } from '@lumina/island/molecules/toast';
import { QueryClientProvider } from '@tanstack/react-query';
import { I18nextProvider } from 'react-i18next';
import { NetworkBoundary } from './components/NetworkBoundary';
import { useSessionEvents } from './hooks/use-session-events';
import type { AppShellProps } from './types';
/**
* The provider shell shared by bull and bear: the query client, i18n, the connection bar, the
* one toast region, and the reactions to sign-in and sign-out. The app's root client component renders it after running the client
* bootstrap.
*/
export function AppShell({ queryClient, i18n, children }: AppShellProps) {
useSessionEvents(queryClient);
return (
<QueryClientProvider client={queryClient}>
<I18nextProvider i18n={i18n}>
<NetworkBoundary />
{children}
<Toaster label={i18n.t('toaster')} dir={i18n.dir()} />
</I18nextProvider>
</QueryClientProvider>
);
}

View File

@ -0,0 +1,72 @@
'use client';
import { useOnline } from '@lumina/island/hooks/use-online';
import { NetworkStatus } from '@lumina/island/molecules/network-status';
import { useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import {
startTransition,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { NETWORK_COPY, ONLINE_NOTICE_MS } from '../constants';
import type { ReconnectPhase } from '../types';
/**
* The network boundary: owns the connection bar for the whole app. Offline, it says so and the
* page stays readable. When the device comes back it refreshes the route and the queries once
* («در حال اتصال دوباره…»), then confirms for 3 seconds. It never re-submits anything.
*/
export function NetworkBoundary() {
const { t } = useTranslation();
const router = useRouter();
const queryClient = useQueryClient();
const isOnline = useOnline();
const [phase, setPhase] = useState<ReconnectPhase>('idle');
const noticeTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
// Started by the `online` event or the retry button.
const reconnect = useCallback(() => {
clearTimeout(noticeTimer.current);
setPhase('reconnecting');
startTransition(() => router.refresh());
void queryClient.invalidateQueries().finally(() => {
setPhase('online');
noticeTimer.current = setTimeout(
() => setPhase('idle'),
ONLINE_NOTICE_MS,
);
});
}, [router, queryClient]);
useEffect(() => {
window.addEventListener('online', reconnect);
return () => window.removeEventListener('online', reconnect);
}, [reconnect]);
useEffect(() => () => clearTimeout(noticeTimer.current), []);
const status = isOnline ? (phase === 'idle' ? null : phase) : 'offline';
if (!status) return null;
const copy = NETWORK_COPY[status];
return (
<NetworkStatus
status={status}
title={t(copy.title)}
description={copy.description && t(copy.description)}
onRetry={
status === 'offline'
? () => {
if (navigator.onLine) reconnect();
}
: undefined
}
retryLabel={t('network.retry')}
/>
);
}

View File

@ -0,0 +1,21 @@
import type { NetworkState } from '@lumina/island/molecules/network-status';
/** How long «دوباره آنلاین شدید» stays before the bar leaves. */
export const ONLINE_NOTICE_MS = 3000;
/** Each bar's copy under `common:network`. */
export const NETWORK_COPY = {
offline: {
title: 'network.offline',
description: 'network.offline-description',
},
reconnecting: { title: 'network.reconnecting', description: undefined },
online: {
title: 'network.online',
description: 'network.online-description',
},
slow: { title: 'network.slow', description: 'network.slow-description' },
} as const satisfies Record<
NetworkState,
{ title: string; description: string | undefined }
>;

View File

@ -0,0 +1,28 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import type { QueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { AUTH_EVENTS } from '../../../features/auth';
/**
* Keeps the page in step with the session. Signing in or up re-renders the server components for
* the new account; signing out, or a refresh that failed, drops every cached query (they belonged
* to the old account) and re-renders as a guest.
*/
export function useSessionEvents(queryClient: QueryClient): void {
const router = useRouter();
useEffect(() => {
const refresh = () => router.refresh();
const unsubscribers = [
eventEmitter.on(AUTH_EVENTS.login, refresh),
eventEmitter.on(AUTH_EVENTS.register, refresh),
eventEmitter.on(AUTH_EVENTS.logout, () => {
queryClient.clear();
router.refresh();
}),
];
return () => unsubscribers.forEach((unsubscribe) => unsubscribe());
}, [router, queryClient]);
}

View File

@ -0,0 +1,2 @@
export { AppShell } from './AppShell';
export type { AppShellProps } from './types';

View File

@ -0,0 +1,14 @@
import type { QueryClient } from '@tanstack/react-query';
import type { i18n } from 'i18next';
import type { ReactNode } from 'react';
export type AppShellProps = {
/** The app's query client: one per server request, one shared in the browser. */
queryClient: QueryClient;
/** The app's i18n instance, initialised with the platform's resources. */
i18n: i18n;
children: ReactNode;
};
/** The connection bar's moment after the device comes back: refreshing, then confirmed. */
export type ReconnectPhase = 'idle' | 'reconnecting' | 'online';

View File

@ -0,0 +1,67 @@
'use client';
import { ErrorState } from '@lumina/island/molecules/error-state';
import {
classifyError,
describeError,
handleError,
} from '@lumina/libs/error-handler';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StatusEmptyState } from '../status-empty-state';
import type { ErrorFallbackProps } from './types';
import { errorKind } from './utils';
/**
* What every boundary renders. A silent error (aborted, or a 401 already redirecting) shows
* nothing; a 404 or 403 read shows its empty state; anything else shows ErrorState with Try again
* for a network cause or Reload page for a bug, and the reference ID. It reports the error once,
* and a page or app fallback moves focus to its heading.
*/
export function ErrorFallback({
error,
size,
name,
onRetry,
}: ErrorFallbackProps) {
const { t } = useTranslation('errors');
const headingRef = useRef<HTMLHeadingElement>(null);
const { read, cause } = classifyError(error);
useEffect(() => {
handleError(error, { where: size, name });
if (size !== 'part') headingRef.current?.focus();
}, [error, size, name]);
if (read === 'silent') return null;
if (read !== 'boundary') {
return (
<StatusEmptyState
variant={read}
size={size === 'part' ? 'part' : 'page'}
headingRef={headingRef}
/>
);
}
const kind = errorKind(error);
// Only the reference ID is read here, so no copy goes through a translator.
const { referenceId } = describeError(error, (key) => key);
const isBug = cause === 'logic';
return (
<ErrorState
kind={kind}
size={size === 'part' ? 'section' : 'page'}
headingRef={headingRef}
title={t(`fallback.${kind}.title`)}
description={t(`fallback.${kind}.description`)}
// A bug won't go away on retry: reload the page instead.
onRetry={isBug ? () => window.location.reload() : onRetry}
retryLabel={isBug ? t('fallback.reload') : t('fallback.retry')}
digest={referenceId}
digestLabel={t('fallback.reference')}
/>
);
}

View File

@ -0,0 +1,6 @@
export { ErrorFallback } from './ErrorFallback';
export type {
ErrorFallbackProps,
ErrorFallbackSize,
FallbackKind,
} from './types';

View File

@ -0,0 +1,19 @@
import type { ErrorKind } from '@lumina/island/molecules/error-state';
/** The ErrorState kinds a boundary can show; each has its copy under `errors:fallback`. */
export type FallbackKind = Exclude<
ErrorKind,
'not-found' | 'forbidden' | 'session'
>;
export type ErrorFallbackSize = 'app' | 'page' | 'part';
export type ErrorFallbackProps = {
error: unknown;
/** app: global-error. page: a route group's error.tsx. part: a PartBoundary. */
size: ErrorFallbackSize;
/** The part or route, for the error report; never personal data. */
name?: string;
/** Try again: resets the failed queries, then the boundary. */
onRetry?: () => void;
};

View File

@ -0,0 +1,20 @@
import { isHttpError } from '@lumina/libs/http';
import type { FallbackKind } from './types';
/**
* Which ErrorState a boundary shows, as the DS classifies it: offline when the device is, the
* HTTP lib's network and timeout codes, server for a 5xx or a server error's digest, else error.
* 404, 403 and 401 never get here: they are empty states or silent.
*/
export function errorKind(error: unknown): FallbackKind {
if (typeof navigator !== 'undefined' && !navigator.onLine) return 'offline';
if (isHttpError(error)) {
if (error.code === 'NETWORK_ERROR') return 'network';
if (error.code === 'TIMEOUT') return 'timeout';
return error.status >= 500 ? 'server' : 'error';
}
return typeof error === 'object' && error !== null && 'digest' in error
? 'server'
: 'error';
}

View File

@ -0,0 +1,13 @@
export { ErrorFallback } from './error-fallback';
export type {
ErrorFallbackProps,
ErrorFallbackSize,
FallbackKind,
} from './error-fallback';
export { PartBoundary } from './part-boundary';
export type { PartBoundaryProps } from './part-boundary';
export { StatusEmptyState } from './status-empty-state';
export type {
StatusEmptyStateProps,
StatusVariant,
} from './status-empty-state';

View File

@ -0,0 +1,38 @@
'use client';
import { useQueryErrorResetBoundary } from '@tanstack/react-query';
import { catchError } from 'next/error';
import type { ErrorInfo } from 'next/error';
import { ErrorFallback } from '../error-fallback';
import type { PartBoundaryProps } from './types';
function PartFallback(
{ name }: PartBoundaryProps,
{ error, retry, reset }: ErrorInfo,
) {
const queryErrors = useQueryErrorResetBoundary();
// A digest means the part failed on the server: retry renders it there again.
const isServerError =
typeof error === 'object' && error !== null && 'digest' in error;
return (
<ErrorFallback
error={error}
size="part"
name={name}
onRetry={() => {
queryErrors.reset();
if (isServerError) retry();
else reset();
}}
/>
);
}
/**
* The part-size boundary (EB-S) around every part that loads on its own, outside its Suspense, so
* the fallback replaces the skeleton and the part together. Next.js's catchError lets notFound()
* and redirect() through and clears itself on navigation.
*/
export const PartBoundary = catchError(PartFallback);

View File

@ -0,0 +1,2 @@
export { PartBoundary } from './PartBoundary';
export type { PartBoundaryProps } from './types';

View File

@ -0,0 +1,4 @@
export type PartBoundaryProps = {
/** The part, for the error report: «creator-stats», «feed». Never personal data. */
name: string;
};

View File

@ -0,0 +1,32 @@
import 'server-only';
import { classifyError } from '@lumina/libs/error-handler';
import { isHttpError } from '@lumina/libs/http';
import { redirect } from 'next/navigation';
import { loginRoute } from '../../navigation';
import type { ReadOnServerOptions, ServerRead } from './types';
/**
* Every server read of a page or a server part goes through it. A Server Component error reaches
* the browser with only its digest, so the expected answers are classified here: 404 and 410 are
* `not-found`, 403 `no-access`, 401 redirects to login with `returnTo`, and the rest is rethrown
* to the nearest boundary.
*/
export async function readOnServer<T>(
read: () => Promise<T>,
{ returnTo }: ReadOnServerOptions = {},
): Promise<ServerRead<T>> {
try {
return { status: 'ok', data: await read() };
} catch (error) {
const outcome = classifyError(error).read;
if (outcome === 'not-found' || outcome === 'no-access') {
return { status: outcome };
}
if (returnTo && isHttpError(error) && error.status === 401) {
redirect(loginRoute(returnTo));
}
throw error;
}
}

View File

@ -0,0 +1,4 @@
import 'server-only';
export { readOnServer } from './read-on-server';
export type { ReadOnServerOptions, ServerRead } from './types';

View File

@ -0,0 +1,9 @@
/** A server read's outcome: its data, or the empty state a 404, 410 or 403 answer shows. */
export type ServerRead<T> =
| { status: 'ok'; data: T }
| { status: 'not-found' | 'no-access' };
export type ReadOnServerOptions = {
/** The page's own path: a 401 redirects to login and comes back here. */
returnTo?: string;
};

View File

@ -0,0 +1,4 @@
import 'server-only';
export { readOnServer } from './read-on-server/server';
export type { ReadOnServerOptions, ServerRead } from './read-on-server/server';

View File

@ -0,0 +1,37 @@
'use client';
import { Button } from '@lumina/island/atoms/button';
import { ErrorState } from '@lumina/island/molecules/error-state';
import { useTranslation } from 'react-i18next';
import { ROUTES } from '../../navigation';
import { STATUS_KINDS } from './constants';
import type { StatusEmptyStateProps } from './types';
/**
* What a read that answered 404, 410 or 403 shows: not an alarm, no retry. At page size it adds the
* way home. A client component, so server pages and parts can render it too.
*/
export function StatusEmptyState({
variant,
size,
headingRef,
}: StatusEmptyStateProps) {
const { t } = useTranslation('errors');
return (
<ErrorState
kind={STATUS_KINDS[variant]}
size={size === 'page' ? 'page' : 'section'}
headingRef={headingRef}
title={t(`empty.${variant}.title`)}
description={t(`empty.${variant}.description`)}
>
{size === 'page' && (
<Button variant="secondary" href={ROUTES.home}>
{t('empty.home')}
</Button>
)}
</ErrorState>
);
}

View File

@ -0,0 +1,9 @@
import type { ErrorKind } from '@lumina/island/molecules/error-state';
import type { StatusVariant } from './types';
/** The DS draws a missing or forbidden read as ErrorState's calm not-found and forbidden kinds. */
export const STATUS_KINDS: Record<StatusVariant, ErrorKind> = {
'not-found': 'not-found',
'no-access': 'forbidden',
};

View File

@ -0,0 +1,2 @@
export { StatusEmptyState } from './StatusEmptyState';
export type { StatusEmptyStateProps, StatusVariant } from './types';

View File

@ -0,0 +1,12 @@
import type { Ref } from 'react';
export type StatusVariant = 'not-found' | 'no-access';
export type StatusEmptyStateProps = {
/** not-found: a 404 or 410 read. no-access: a 403 read. */
variant: StatusVariant;
/** page: a route, with a way home. part: one part of a page. */
size: 'page' | 'part';
/** A page fallback focuses its heading. */
headingRef?: Ref<HTMLHeadingElement>;
};

View File

@ -0,0 +1,27 @@
import 'server-only';
import { redirect } from 'next/navigation';
import { getSessionAccount } from '../../../features/auth/caches/server';
import type { AccountPayload } from '../../../features/auth';
import { loginRoute, ROUTES } from '../../navigation';
import type { RequireAccountOptions } from './types';
/**
* For pages that need a signed-in visitor: the account, or a redirect to login that comes back to
* `returnTo`. proxy.ts has already refreshed an expired session, so `null` here means a guest.
*/
export async function requireAccount({
returnTo,
}: RequireAccountOptions): Promise<AccountPayload> {
const account = await getSessionAccount();
if (!account) redirect(loginRoute(returnTo));
return account;
}
/** For login and registration: a signed-in visitor goes straight to `to` (home by default). */
export async function redirectIfSignedIn(
to: string = ROUTES.home,
): Promise<void> {
if (await getSessionAccount()) redirect(to);
}

View File

@ -0,0 +1,4 @@
import 'server-only';
export { redirectIfSignedIn, requireAccount } from './auth-guard';
export type { RequireAccountOptions } from './types';

View File

@ -0,0 +1,4 @@
export type RequireAccountOptions = {
/** The page's own path: login sends the visitor back here afterwards. */
returnTo: string;
};

View File

@ -0,0 +1,19 @@
import 'server-only';
import { requireAccount } from '../auth-guard/server';
import type { RequireRoleOptions, RoleCheck } from './types';
/**
* For pages of one role (the creator dashboard, the investor's subscriptions). A guest is sent to
* login; the other role gets `no-access`, which the page renders as its page-size
* StatusEmptyState (a 403, never a redirect loop).
*/
export async function requireRole({
role,
returnTo,
}: RequireRoleOptions): Promise<RoleCheck> {
const account = await requireAccount({ returnTo });
return account.role === role
? { status: 'ok', account }
: { status: 'no-access' };
}

View File

@ -0,0 +1,4 @@
import 'server-only';
export { requireRole } from './role-guard';
export type { RequireRoleOptions, RoleCheck } from './types';

View File

@ -0,0 +1,12 @@
import type { AccountPayload, UserRole } from '../../../features/auth';
export type RequireRoleOptions = {
role: UserRole;
/** The page's own path, for the login redirect. */
returnTo: string;
};
/** The account when it has the role, `no-access` when it is the other role. */
export type RoleCheck =
| { status: 'ok'; account: AccountPayload }
| { status: 'no-access' };

View File

@ -0,0 +1,2 @@
export { mapApiErrorBody } from './map-error-body';
export type { ApiErrorEnvelope } from './types';

View File

@ -0,0 +1,45 @@
import type { HttpErrorShape } from '@lumina/libs/http';
import type { ApiErrorEnvelope } from './types';
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/** `{ field: ['first message', …] }` → `{ field: 'first message' }`. */
function toFieldErrors(
value: Record<string, unknown>,
): Record<string, string> | undefined {
const entries = Object.entries(value).flatMap(([field, messages]) => {
const message: unknown = Array.isArray(messages) ? messages[0] : messages;
return typeof message === 'string' ? [[field, message] as const] : [];
});
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
}
/**
* Adapts the gateway's error contract to `HttpError`. Two shapes arrive:
* - the envelope `{ statusCode, error, message, details }`, where `message` is the server's text
* (already translated), a list, or a field map;
* - a bare field map `{ phone_number: ['…'] }` from DTO validation.
* Field names stay the server's; each repository's mappers rename them to its `*Args` names.
* `details` (a changed price, a frozen unfollow) passes through for the action that handles it.
*/
export function mapApiErrorBody(body: unknown): Partial<HttpErrorShape> {
if (!isRecord(body)) return {};
if (typeof body.statusCode !== 'number') {
return { fieldErrors: toFieldErrors(body) };
}
const { message, details } = body as ApiErrorEnvelope;
const retryAfter = details?.retryAfterSeconds;
return {
message: Array.isArray(message)
? message[0]
: typeof message === 'string'
? message
: undefined,
fieldErrors: isRecord(message) ? toFieldErrors(message) : undefined,
retryAfter: typeof retryAfter === 'number' ? retryAfter : undefined,
details: isRecord(details) ? details : undefined,
};
}

View File

@ -0,0 +1,10 @@
/**
* The gateway's error envelope (`RpcToHttpFilter`). `message` is a string, or a field → messages
* map for validation errors; OTP blocks add `details.retryAfterSeconds`.
*/
export type ApiErrorEnvelope = {
statusCode: number;
error?: string;
message?: string | string[] | Record<string, string | string[]>;
details?: { retryAfterSeconds?: number; [key: string]: unknown } | null;
};

View File

@ -0,0 +1,2 @@
/** The public channel URL prefix; next.config rewrites `/@username` onto `channels/[username]`. */
export const CHANNEL_PREFIX = '/@';

View File

@ -0,0 +1,2 @@
export { CHANNEL_PREFIX } from './constants';
export { loginRoute, ROUTES } from './navigation';

View File

@ -0,0 +1,40 @@
import { CHANNEL_PREFIX } from './constants';
const channel = (username: string) =>
`${CHANNEL_PREFIX}${encodeURIComponent(username)}`;
/** Every route path in bull and bear, which share one URL tree. Build links only from here. */
export const ROUTES = {
home: '/',
login: '/auth/login',
account: '/account',
channel,
post: (username: string, id: string) =>
`${channel(username)}/posts/${encodeURIComponent(id)}`,
trackRecord: (username: string) => `${channel(username)}/track-record`,
checkout: (username: string) => `/checkout/${encodeURIComponent(username)}`,
paymentReturn: '/payment/return',
composePost: '/compose/post',
composePrediction: '/compose/prediction',
dashboard: {
subscriptions: '/dashboard/subscriptions',
transactions: '/dashboard/transactions',
following: '/dashboard/following',
pricing: '/dashboard/pricing',
ledger: '/dashboard/finance/ledger',
sheba: '/dashboard/finance/sheba',
},
onboarding: {
creatorIdentity: '/onboarding/creator-identity',
creatorProfile: '/onboarding/creator-profile',
investorProfile: '/onboarding/investor-profile',
},
terms: '/terms/subscription',
} as const;
/** `/auth/login?redirect=…`: auth returns to the page that asked for it. */
export function loginRoute(returnTo?: string): string {
return returnTo
? `${ROUTES.login}?redirect=${encodeURIComponent(returnTo)}`
: ROUTES.login;
}

View File

@ -0,0 +1,11 @@
/** The gateway's HttpOnly session cookies; JavaScript never reads their values. */
export const SESSION_COOKIES = {
access: 'access_token',
refresh: 'refresh_token',
} as const;
/** Rotates the session from the refresh cookie; relative to the API base URL (`…/v1`). */
export const SESSION_REFRESH_ENDPOINT = '/auth/refresh';
/** A refresh before rendering must never hold the page up for long. */
export const PROXY_REFRESH_TIMEOUT_MS = 3000;

View File

@ -0,0 +1 @@
export { SESSION_COOKIES, SESSION_REFRESH_ENDPOINT } from './constants';

View File

@ -0,0 +1,77 @@
import { createHttpClient } from '@lumina/libs/http';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import {
PROXY_REFRESH_TIMEOUT_MS,
SESSION_COOKIES,
SESSION_REFRESH_ENDPOINT,
} from './constants';
import type { ProxySessionOptions, RefreshResponseDto } from './types';
/** `name=value; Path=/; …` → [name, value]. */
function cookiePair(setCookie: string): [string, string] | undefined {
const pair = setCookie.split(';', 1)[0] ?? '';
const index = pair.indexOf('=');
return index > 0 ? [pair.slice(0, index), pair.slice(index + 1)] : undefined;
}
/** Copies the gateway's Set-Cookie headers to the browser's response. */
function forwardCookies(
response: NextResponse,
setCookies: string[],
): NextResponse {
for (const setCookie of setCookies)
response.headers.append('set-cookie', setCookie);
return response;
}
/**
* Refreshes an expired session before the page renders, so server components never render a
* signed-in visitor as a guest. It runs only when the access cookie is gone (it lives 15 minutes)
* and the refresh cookie is still there. The new cookies go to the browser, and into this
* request's Cookie header so this render's API calls already use them.
*
* A superseded refresh (a tab refreshed at the same moment) changes nothing. On any failure the
* page renders as a guest and the cookies stay as they are: the browser's next API call refreshes
* against the gateway itself, which clears a dead session's cookies on its own domain. Never
* throws: rendering goes on either way.
*/
export async function refreshSessionInProxy(
request: NextRequest,
{ apiUrl }: ProxySessionOptions,
): Promise<NextResponse> {
const refreshToken = request.cookies.get(SESSION_COOKIES.refresh)?.value;
if (!refreshToken || request.cookies.has(SESSION_COOKIES.access)) {
return NextResponse.next();
}
// A client of its own: the proxy runs before any bootstrap has configured the root client.
const client = createHttpClient({
baseUrl: apiUrl,
retry: false,
timeout: PROXY_REFRESH_TIMEOUT_MS,
});
try {
const response = await client.request<RefreshResponseDto>({
method: 'POST',
url: SESSION_REFRESH_ENDPOINT,
headers: {
cookie: `${SESSION_COOKIES.refresh}=${refreshToken}`,
'user-agent': request.headers.get('user-agent') ?? '',
},
skipRefresh: true,
});
const setCookies = response.headers.getSetCookie();
for (const setCookie of setCookies) {
const pair = cookiePair(setCookie);
if (pair) request.cookies.set(pair[0], pair[1]);
}
return forwardCookies(
NextResponse.next({ request: { headers: request.headers } }),
setCookies,
);
} catch {
return NextResponse.next();
}
}

View File

@ -0,0 +1,4 @@
import 'server-only';
export { refreshSessionInProxy } from './refresh-in-proxy';
export type { ProxySessionOptions } from './types';

View File

@ -0,0 +1,7 @@
export type ProxySessionOptions = {
/** The API base URL as the server reaches it, with the version: `http://gateway:3000/v1`. */
apiUrl: string;
};
/** `POST /auth/refresh` body: the user after a rotation, or `superseded` when another refresh won. */
export type RefreshResponseDto = { superseded: true } | { user: unknown };

18
platforms/market/src/env/env.ts vendored Normal file
View File

@ -0,0 +1,18 @@
import type { MarketEnv } from './types';
let marketEnv: MarketEnv | undefined;
/** Called by each app bootstrap, on the server and in the browser. Idempotent. */
export function setEnv(env: MarketEnv): void {
marketEnv = env;
}
/** Read inside functions, never at module top level: bootstrap may not have run yet. */
export function getEnv(): Readonly<MarketEnv> {
if (!marketEnv) {
throw new Error(
'market env is not set. The app bootstrap must call setEnv from @lumina/market/env first.',
);
}
return marketEnv;
}

2
platforms/market/src/env/index.ts vendored Normal file
View File

@ -0,0 +1,2 @@
export { getEnv, setEnv } from './env';
export type { MarketEnv } from './types';

12
platforms/market/src/env/types.ts vendored Normal file
View File

@ -0,0 +1,12 @@
/** The platform's own settings, named for what they are, not for the variables behind them. */
export type MarketEnv = {
/**
* The API's public origin (`https://api.lumina.ir`), for what the browser loads straight from it:
* post media, avatars and uploads (`/files/*` sits outside `/v1`).
*/
apiOrigin: string;
/** Support chat handles and hours: config values, never hard-coded in a component. */
baleHandle: string;
telegramHandle: string;
supportHours: string;
};

View File

@ -0,0 +1,20 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type { SessionPayload, VerifyOtpArgs } from '../../repositories/auth';
/** Verifies the login code; the gateway sets the session cookies. Emits `auth.login`. */
export async function login(
args: VerifyOtpArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<SessionPayload> {
const session = await authRepository.verifyLoginOtp(args);
if (emit) {
eventEmitter.emit(AUTH_EVENTS.login, {
userId: session.account.id,
role: session.account.role,
});
}
return session;
}

View File

@ -0,0 +1 @@
export { login } from './actions';

View File

@ -0,0 +1,13 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
/** Revokes the session and clears its cookies. Emits `auth.logout`. */
export async function logout({
emit = true,
}: { emit?: boolean } = {}): Promise<'ok'> {
await authRepository.logout();
if (emit) eventEmitter.emit(AUTH_EVENTS.logout, { reason: 'signed-out' });
return 'ok';
}

View File

@ -0,0 +1 @@
export { logout } from './actions';

View File

@ -0,0 +1,23 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type {
CreatorRegisteredPayload,
RegisterCreatorArgs,
} from '../../repositories/auth';
/** Creates a creator account with lite KYC and signs it in. Emits `auth.register`. */
export async function registerCreator(
args: RegisterCreatorArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<CreatorRegisteredPayload> {
const registration = await authRepository.registerCreator(args);
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {
userId: registration.account.id,
role: registration.account.role,
});
}
return registration;
}

View File

@ -0,0 +1 @@
export { registerCreator } from './actions';

View File

@ -0,0 +1,23 @@
import { eventEmitter } from '@lumina/libs/event-emitter';
import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth';
import type {
RegisterInvestorArgs,
SessionPayload,
} from '../../repositories/auth';
/** Creates an investor account and signs it in. Emits `auth.register`. */
export async function registerInvestor(
args: RegisterInvestorArgs,
{ emit = true }: { emit?: boolean } = {},
): Promise<SessionPayload> {
const session = await authRepository.registerInvestor(args);
if (emit) {
eventEmitter.emit(AUTH_EVENTS.register, {
userId: session.account.id,
role: session.account.role,
});
}
return session;
}

View File

@ -0,0 +1 @@
export { registerInvestor } from './actions';

View File

@ -0,0 +1,3 @@
import 'server-only';
export { getSessionAccount } from './session-account';

View File

@ -0,0 +1,22 @@
import 'server-only';
import { isHttpError } from '@lumina/libs/http';
import { cache } from 'react';
import { accountRepository } from '../repositories/account';
import type { AccountPayload } from '../repositories/account';
/**
* The signed-in account for this request, or `null` for a guest. One request per render however
* many server components ask; the cookies are forwarded by the server HTTP configuration.
*/
export const getSessionAccount = cache(
async (): Promise<AccountPayload | null> => {
try {
return await accountRepository.getCurrent();
} catch (error) {
if (isHttpError(error) && error.status === 401) return null;
throw error;
}
},
);

View File

@ -0,0 +1,6 @@
/** Events auth actions emit when they succeed; the AppShell reacts to them. */
export const AUTH_EVENTS = {
login: 'auth.login',
register: 'auth.register',
logout: 'auth.logout',
} as const;

View File

@ -0,0 +1 @@
export type { UserEntity, UserRole, UserStatus } from './types';

View File

@ -0,0 +1,17 @@
/** The two account roles. Creators are «تحلیلگر» in every UI string, investors «سرمایه‌گذار». */
export type UserRole = 'investor' | 'creator';
export type UserStatus = 'active' | 'suspended';
/** user-service's public projection of an account (`toPublicUser`). */
export type UserEntity = {
id: string;
phone_number: string;
firstName?: string;
lastName?: string;
email?: string | null;
username: string;
role: UserRole;
phone_verified: boolean;
status: UserStatus;
};

View File

@ -0,0 +1,3 @@
import { http } from '@lumina/libs/http';
export const authHttp = http.extend({});

View File

@ -0,0 +1,22 @@
import './types';
export { login } from './actions/login';
export { logout } from './actions/logout';
export { registerCreator } from './actions/register-creator';
export { registerInvestor } from './actions/register-investor';
export { AUTH_EVENTS } from './constants';
export type { UserRole, UserStatus } from './entities/user';
export { accountKeys, accountRepository } from './repositories/account';
export type { AccountPayload, UpdateAccountArgs } from './repositories/account';
export { AUTH_ENDPOINTS, authRepository } from './repositories/auth';
export type {
CreatorRegisteredPayload,
OtpSentPayload,
RegisterCreatorArgs,
RegisterInvestorArgs,
RegistrationVerifiedPayload,
SendOtpArgs,
SessionPayload,
VerifyOtpArgs,
} from './repositories/auth';
export type { LogoutReason } from './types';

View File

@ -0,0 +1,28 @@
import { authHttp } from '../../http';
import { ACCOUNT_ENDPOINT } from './constants';
import { toAccountPayload, toUpdateAccountDto } from './mappers';
import type {
AccountPayload,
AccountResponseDto,
UpdateAccountArgs,
} from './types';
/** The signed-in account (`/users/profile`), any role. 401 without a session. */
export const accountRepository = {
async getCurrent({
signal,
}: { signal?: AbortSignal } = {}): Promise<AccountPayload> {
const response = await authHttp.get<AccountResponseDto>(ACCOUNT_ENDPOINT, {
signal,
});
return toAccountPayload(response);
},
async update(args: UpdateAccountArgs): Promise<AccountPayload> {
const response = await authHttp.patch<AccountResponseDto>(
ACCOUNT_ENDPOINT,
toUpdateAccountDto(args),
);
return toAccountPayload(response);
},
};

View File

@ -0,0 +1,6 @@
export const ACCOUNT_ENDPOINT = '/users/profile';
export const accountKeys = {
all: ['auth', 'account'] as const,
current: () => [...accountKeys.all, 'current'] as const,
};

View File

@ -0,0 +1,3 @@
export { accountRepository } from './account';
export { accountKeys } from './constants';
export type { AccountPayload, UpdateAccountArgs } from './types';

View File

@ -0,0 +1,28 @@
import type {
AccountPayload,
AccountResponseDto,
UpdateAccountArgs,
UpdateAccountDto,
} from './types';
export function toAccountPayload(dto: AccountResponseDto): AccountPayload {
return {
id: dto.id,
phone: dto.phone_number,
firstName: dto.firstName ?? '',
lastName: dto.lastName ?? '',
email: dto.email ?? null,
username: dto.username,
role: dto.role,
phoneVerified: dto.phone_verified,
status: dto.status,
};
}
export function toUpdateAccountDto(args: UpdateAccountArgs): UpdateAccountDto {
return {
firstName: args.firstName?.trim(),
lastName: args.lastName?.trim(),
email: args.email?.trim().toLowerCase() || undefined,
};
}

View File

@ -0,0 +1,24 @@
import type { UserEntity, UserRole, UserStatus } from '../../entities/user';
/** The signed-in account, as apps and stores use it. */
export type AccountPayload = {
id: string;
phone: string;
firstName: string;
lastName: string;
email: string | null;
username: string;
role: UserRole;
phoneVerified: boolean;
status: UserStatus;
};
export type AccountResponseDto = UserEntity;
export type UpdateAccountArgs = {
firstName?: string;
lastName?: string;
email?: string;
};
export type UpdateAccountDto = UpdateAccountArgs;

View File

@ -0,0 +1,131 @@
import { renameFieldErrors } from '../../../../shared/utils';
import { authHttp } from '../../http';
import { AUTH_ENDPOINTS, AUTH_FIELD_NAMES } from './constants';
import {
toCreatorRegisteredPayload,
toOtpSentPayload,
toPhoneDto,
toRegisterCreatorFormData,
toRegisterInvestorDto,
toRegistrationVerifiedPayload,
toSessionPayload,
toVerifyOtpDto,
} from './mappers';
import type {
CreatorRegisteredPayload,
CreatorRegisteredResponseDto,
OtpSentPayload,
OtpSentResponseDto,
RegisterCreatorArgs,
RegisterInvestorArgs,
RegistrationVerifiedPayload,
RegistrationVerifiedResponseDto,
SendOtpArgs,
SessionPayload,
SessionResponseDto,
VerifyOtpArgs,
} from './types';
/**
* Passwordless phone auth. Every request sends `skipRefresh`: these run without a session, and the
* API answers a wrong code with 400 and field errors, so a 401 here never means "refresh". A
* successful sign-in or registration sets the HttpOnly session cookies; the body is the account.
*/
async function send<T>(request: () => Promise<T>): Promise<T> {
try {
return await request();
} catch (error) {
throw renameFieldErrors(error, AUTH_FIELD_NAMES);
}
}
export const authRepository = {
async sendRegistrationOtp(args: SendOtpArgs): Promise<OtpSentPayload> {
const response = await send(() =>
authHttp.post<OtpSentResponseDto>(
AUTH_ENDPOINTS.sendRegistrationOtp,
toPhoneDto(args),
{ skipRefresh: true },
),
);
return toOtpSentPayload(response);
},
async verifyRegistrationOtp(
args: VerifyOtpArgs,
): Promise<RegistrationVerifiedPayload> {
const response = await send(() =>
authHttp.post<RegistrationVerifiedResponseDto>(
AUTH_ENDPOINTS.verifyRegistrationOtp,
toVerifyOtpDto(args),
{ skipRefresh: true },
),
);
return toRegistrationVerifiedPayload(response);
},
/** Registration or login code again; the server keeps its 60-second cooldown. */
async resendOtp(args: SendOtpArgs): Promise<OtpSentPayload> {
const response = await send(() =>
authHttp.post<OtpSentResponseDto>(
AUTH_ENDPOINTS.resendOtp,
toPhoneDto(args),
{ skipRefresh: true },
),
);
return toOtpSentPayload(response);
},
async registerInvestor(args: RegisterInvestorArgs): Promise<SessionPayload> {
const response = await send(() =>
authHttp.post<SessionResponseDto>(
AUTH_ENDPOINTS.registerInvestor,
toRegisterInvestorDto(args),
{ skipRefresh: true },
),
);
return toSessionPayload(response);
},
async registerCreator(
args: RegisterCreatorArgs,
): Promise<CreatorRegisteredPayload> {
const response = await send(() =>
authHttp.upload<CreatorRegisteredResponseDto>(
AUTH_ENDPOINTS.registerCreator,
toRegisterCreatorFormData(args),
{ skipRefresh: true },
),
);
return toCreatorRegisteredPayload(response);
},
async requestLoginOtp(args: SendOtpArgs): Promise<OtpSentPayload> {
const response = await send(() =>
authHttp.post<OtpSentResponseDto>(
AUTH_ENDPOINTS.requestLoginOtp,
toPhoneDto(args),
{ skipRefresh: true },
),
);
return toOtpSentPayload(response);
},
async verifyLoginOtp(args: VerifyOtpArgs): Promise<SessionPayload> {
const response = await send(() =>
authHttp.post<SessionResponseDto>(
AUTH_ENDPOINTS.verifyLoginOtp,
toVerifyOtpDto(args),
{ skipRefresh: true },
),
);
return toSessionPayload(response);
},
/** Revokes the session and clears its cookies; succeeds even without one. */
async logout(): Promise<void> {
await authHttp.post(AUTH_ENDPOINTS.logout, undefined, {
skipRefresh: true,
});
},
};

View File

@ -0,0 +1,16 @@
export const AUTH_ENDPOINTS = {
sendRegistrationOtp: '/auth/send-otp',
verifyRegistrationOtp: '/auth/verify-registration-otp',
resendOtp: '/auth/resend-otp',
registerInvestor: '/auth/register/investor',
registerCreator: '/auth/register/creator',
requestLoginOtp: '/auth/login',
verifyLoginOtp: '/auth/login/verify',
logout: '/auth/logout',
} as const;
/** Server field names → `*Args` names, so form errors land under the right field. */
export const AUTH_FIELD_NAMES = {
phone_number: 'phone',
otp: 'code',
} as const;

View File

@ -0,0 +1,12 @@
export { authRepository } from './auth';
export { AUTH_ENDPOINTS } from './constants';
export type {
CreatorRegisteredPayload,
OtpSentPayload,
RegisterCreatorArgs,
RegisterInvestorArgs,
RegistrationVerifiedPayload,
SendOtpArgs,
SessionPayload,
VerifyOtpArgs,
} from './types';

View File

@ -0,0 +1,79 @@
import { toE164Mobile } from '../../../../shared/utils';
import { toAccountPayload } from '../account/mappers';
import type {
CreatorRegisteredPayload,
CreatorRegisteredResponseDto,
OtpSentPayload,
OtpSentResponseDto,
PhoneDto,
RegisterCreatorArgs,
RegisterInvestorArgs,
RegisterInvestorDto,
RegistrationVerifiedPayload,
RegistrationVerifiedResponseDto,
SendOtpArgs,
SessionPayload,
SessionResponseDto,
VerifyOtpArgs,
VerifyOtpDto,
} from './types';
export function toPhoneDto(args: SendOtpArgs): PhoneDto {
return { phone_number: toE164Mobile(args.phone) };
}
export function toVerifyOtpDto(args: VerifyOtpArgs): VerifyOtpDto {
return { phone_number: toE164Mobile(args.phone), otp: args.code };
}
export function toRegisterInvestorDto(
args: RegisterInvestorArgs,
): RegisterInvestorDto {
return {
phone_number: toE164Mobile(args.phone),
registrationToken: args.registrationToken,
username: args.username.trim(),
firstName: args.firstName.trim(),
lastName: args.lastName.trim(),
};
}
/** Creator registration is multipart: text fields plus the two national ID images. */
export function toRegisterCreatorFormData(args: RegisterCreatorArgs): FormData {
const form = new FormData();
const fields = {
...toRegisterInvestorDto(args),
displayName: args.displayName.trim(),
nationalIdNumber: args.nationalIdNumber.trim(),
};
for (const [name, value] of Object.entries(fields)) form.append(name, value);
form.append('nationalIdFrontImage', args.nationalIdFrontImage);
form.append('nationalIdBackImage', args.nationalIdBackImage);
return form;
}
export function toOtpSentPayload(dto: OtpSentResponseDto): OtpSentPayload {
return { expiresInSeconds: dto.expiresInSeconds };
}
export function toRegistrationVerifiedPayload(
dto: RegistrationVerifiedResponseDto,
): RegistrationVerifiedPayload {
return {
registrationToken: dto.registrationToken,
expiresInSeconds: dto.expiresInSeconds,
};
}
export function toSessionPayload(dto: SessionResponseDto): SessionPayload {
return { account: toAccountPayload(dto.user) };
}
export function toCreatorRegisteredPayload(
dto: CreatorRegisteredResponseDto,
): CreatorRegisteredPayload {
return {
account: toAccountPayload(dto.account),
profileSetupRequired: dto.onboarding.profileSetupRequired,
};
}

View File

@ -0,0 +1,60 @@
import type { UserEntity, UserRole } from '../../entities/user';
import type { AccountPayload } from '../account';
// Phone numbers are typed in any digits and form; mappers send E.164.
export type SendOtpArgs = { phone: string };
export type PhoneDto = { phone_number: string };
export type OtpSentResponseDto = { sent: true; expiresInSeconds: number };
/** A code was sent; it works for this many seconds. */
export type OtpSentPayload = { expiresInSeconds: number };
export type VerifyOtpArgs = { phone: string; code: string };
export type VerifyOtpDto = { phone_number: string; otp: string };
export type RegistrationVerifiedResponseDto = {
verified: true;
registrationToken: string;
expiresInSeconds: number;
};
/** The phone is proven; the token finishes registration within its lifetime (15 minutes). */
export type RegistrationVerifiedPayload = {
registrationToken: string;
expiresInSeconds: number;
};
export type RegisterInvestorArgs = {
phone: string;
registrationToken: string;
username: string;
firstName: string;
lastName: string;
};
export type RegisterInvestorDto = {
phone_number: string;
registrationToken: string;
username: string;
firstName: string;
lastName: string;
};
export type RegisterCreatorArgs = RegisterInvestorArgs & {
displayName: string;
nationalIdNumber: string;
nationalIdFrontImage: File;
nationalIdBackImage: File;
};
/** Sign-in and registration set the HttpOnly session cookies; the body carries the account. */
export type SessionResponseDto = { user: UserEntity; userType: UserRole };
export type SessionPayload = { account: AccountPayload };
export type CreatorRegisteredResponseDto = {
account: UserEntity;
onboarding: { nextStep: string; profileSetupRequired: boolean };
};
export type CreatorRegisteredPayload = {
account: AccountPayload;
/** The public profile (display name, markets) must be completed before publishing. */
profileSetupRequired: boolean;
};

View File

@ -0,0 +1,12 @@
import type { UserRole } from './entities/user';
/** Why the session ended: the user signed out, or the refresh token was dead. */
export type LogoutReason = 'signed-out' | 'session-ended';
declare module '@lumina/libs/event-emitter' {
interface EventMap {
'auth.login': { userId: string; role: UserRole };
'auth.register': { userId: string; role: UserRole };
'auth.logout': { reason: LogoutReason };
}
}

View File

@ -0,0 +1,12 @@
import 'server-only';
import { cache } from 'react';
import { channelRepository } from '../repositories/channel';
import type { PublicCreatorPayload } from '../repositories/channel';
/** An approved creator's public profile, once per render per id. 404 reaches the caller. */
export const getPublicCreator = cache(
(creatorId: string): Promise<PublicCreatorPayload> =>
channelRepository.getCreator({ creatorId }),
);

View File

@ -0,0 +1,12 @@
import 'server-only';
import { cache } from 'react';
import { channelRepository } from '../repositories/channel';
import type { PublicTierPayload } from '../repositories/channel';
/** A creator's active tiers, once per render per id; the channel and checkout share it. */
export const getPublicTiers = cache(
(creatorId: string): Promise<PublicTierPayload[]> =>
channelRepository.listTiers({ creatorId }),
);

View File

@ -0,0 +1,4 @@
import 'server-only';
export { getPublicCreator } from './public-creator';
export { getPublicTiers } from './public-tiers';

View File

@ -0,0 +1 @@
export type { PublicCreatorEntity } from './types';

View File

@ -0,0 +1,17 @@
import type { Market, TradingStyle } from '../../../profile';
/**
* trader-service's public projection of an approved creator (`toPublicProfile`). `id` is the
* profile id, `userId` the creator's account id. Unset fields are left out of the JSON.
*/
export type PublicCreatorEntity = {
id: string;
userId: string;
username: string;
displayName?: string;
bio?: string | null;
avatar?: string | null;
socialLinks?: { label: string; url: string; _id?: string }[];
tradingStyle?: TradingStyle | null;
markets?: Market[];
};

View File

@ -0,0 +1 @@
export type { PublicTierEntity } from './types';

View File

@ -0,0 +1,44 @@
import type {
BillingPeriod,
CompareSource,
} from '../../../../shared/constants';
/**
* subscription-service's public tier (`toCheckoutTier` over `PricingService.toPublicDisplay`). The
* channel tiers, the checkout screen, the renewal preview and the creator dashboard all send it.
*/
export type PublicTierEntity = {
id: string;
traderId: string;
/** The Persian period label by default (legacy tiers could name themselves). */
name: string;
billingPeriod: BillingPeriod;
labelFa: string;
/** Standing price in Rial. */
price: number;
/** Standing price in Rial, despite the name. */
price_monthly: number;
/** Live total in Toman: the promotional price while a promotion runs, else the standing one. */
priceToman: number | null;
standingPriceToman: number | null;
perMonthToman: number | null;
compareAtToman: number | null;
compareSource: CompareSource | null;
/** Same as `priceToman`. */
toman: number | null;
amountUnitFa: string;
currency: string;
/** Set only while a promotion is live (started and not ended). */
promotion: {
percent: number;
badgeFa: string;
priceToman: number | null;
perMonthToman: number | null;
/** `null` when the promotion is indefinite; missing when a non-indefinite one has no end date. */
endsAt?: string | null;
indefinite: boolean;
timeLabelFa: string | null;
} | null;
features: string[];
perMonthLabelFa: string | null;
};

View File

@ -0,0 +1,3 @@
import { http } from '@lumina/libs/http';
export const channelHttp = http.extend({});

View File

@ -0,0 +1,8 @@
export type { PublicTierEntity } from './entities/public-tier';
export { channelKeys, channelRepository } from './repositories/channel';
export type {
ChannelArgs,
PublicCreatorPayload,
PublicTierPayload,
TierPromotionPayload,
} from './repositories/channel';

View File

@ -0,0 +1,40 @@
import { channelHttp } from '../../http';
import { CHANNEL_ENDPOINTS } from './constants';
import { toPublicCreatorPayload, toPublicTiersPayload } from './mappers';
import type {
ChannelArgs,
PublicCreatorPayload,
PublicCreatorResponseDto,
PublicTierPayload,
PublicTiersResponseDto,
} from './types';
/**
* A creator's public channel; both reads work without a session. The API resolves creators by
* account or profile id only, never by username.
*/
export const channelRepository = {
/** 404 for an unknown or not yet approved creator. */
async getCreator(
args: ChannelArgs,
{ signal }: { signal?: AbortSignal } = {},
): Promise<PublicCreatorPayload> {
const response = await channelHttp.get<PublicCreatorResponseDto>(
CHANNEL_ENDPOINTS.creator(args.creatorId),
{ signal },
);
return toPublicCreatorPayload(response);
},
/** Active tiers, cheapest first; empty when pricing is not set (or the id is unknown). */
async listTiers(
args: ChannelArgs,
{ signal }: { signal?: AbortSignal } = {},
): Promise<PublicTierPayload[]> {
const response = await channelHttp.get<PublicTiersResponseDto>(
CHANNEL_ENDPOINTS.tiers(args.creatorId),
{ signal },
);
return toPublicTiersPayload(response);
},
};

View File

@ -0,0 +1,15 @@
export const CHANNEL_ENDPOINTS = {
creator: (creatorId: string) => `/traders/${encodeURIComponent(creatorId)}`,
tiers: (creatorId: string) =>
`/subscriptions/creators/${encodeURIComponent(creatorId)}/tiers`,
} as const;
/** Keyed by the creator's account id, so invalidating `creator(id)` refreshes the whole channel. */
export const channelKeys = {
all: ['channel'] as const,
creator: (creatorId: string) => [...channelKeys.all, creatorId] as const,
profile: (creatorId: string) =>
[...channelKeys.creator(creatorId), 'profile'] as const,
tiers: (creatorId: string) =>
[...channelKeys.creator(creatorId), 'tiers'] as const,
};

View File

@ -0,0 +1,8 @@
export { channelRepository } from './channel';
export { channelKeys } from './constants';
export type {
ChannelArgs,
PublicCreatorPayload,
PublicTierPayload,
TierPromotionPayload,
} from './types';

View File

@ -0,0 +1,54 @@
import { toApiUrl } from '../../../../shared/utils';
import type { PublicTierEntity } from '../../entities/public-tier';
import type {
PublicCreatorPayload,
PublicCreatorResponseDto,
PublicTierPayload,
PublicTiersResponseDto,
} from './types';
export function toPublicCreatorPayload(
dto: PublicCreatorResponseDto,
): PublicCreatorPayload {
return {
profileId: dto.id,
creatorId: dto.userId,
username: dto.username,
displayName: dto.displayName || null,
bio: dto.bio || null,
avatarUrl: toApiUrl(dto.avatar),
socialLinks: (dto.socialLinks ?? []).map(({ label, url }) => ({
label,
url,
})),
tradingStyle: dto.tradingStyle ?? null,
markets: dto.markets ?? [],
};
}
function toPublicTierPayload(tier: PublicTierEntity): PublicTierPayload {
return {
id: tier.id,
creatorId: tier.traderId,
billingPeriod: tier.billingPeriod,
priceToman: tier.priceToman,
standingPriceToman: tier.standingPriceToman,
perMonthToman: tier.perMonthToman,
compareAtToman: tier.compareAtToman,
compareSource: tier.compareSource,
promotion: tier.promotion && {
percent: tier.promotion.percent,
priceToman: tier.promotion.priceToman,
perMonthToman: tier.promotion.perMonthToman,
endsAt: tier.promotion.endsAt ?? null,
indefinite: tier.promotion.indefinite,
},
features: tier.features,
};
}
export function toPublicTiersPayload(
dto: PublicTiersResponseDto,
): PublicTierPayload[] {
return dto.items.map(toPublicTierPayload);
}

View File

@ -0,0 +1,60 @@
import type {
BillingPeriod,
CompareSource,
} from '../../../../shared/constants';
import type { Market, SocialLinkPayload, TradingStyle } from '../../../profile';
import type { PublicCreatorEntity } from '../../entities/public-creator';
import type { PublicTierEntity } from '../../entities/public-tier';
/** The creator's account id; the profile endpoint also accepts the profile id. Not a username. */
export type ChannelArgs = { creatorId: string };
/**
* An approved creator's public page header. Unapproved creators answer 404, so every creator here
* is verified. Follower counts are never shown publicly, so none are fetched.
*/
export type PublicCreatorPayload = {
profileId: string;
/** The creator's account id; follow, tiers, posts and checkout all take this one. */
creatorId: string;
username: string;
displayName: string | null;
bio: string | null;
avatarUrl: string | null;
socialLinks: SocialLinkPayload[];
tradingStyle: TradingStyle | null;
markets: Market[];
};
export type PublicCreatorResponseDto = PublicCreatorEntity;
/** A live promotion on a tier; prices are its promotional totals in Toman. */
export type TierPromotionPayload = {
percent: number;
priceToman: number | null;
perMonthToman: number | null;
/** ISO date; `null` when `indefinite`. */
endsAt: string | null;
indefinite: boolean;
};
/**
* One active subscription tier as the channel and checkout show it. Money is Toman; `priceToman`
* is what the investor pays now (promotion applied), `standingPriceToman` the regular price.
*/
export type PublicTierPayload = {
id: string;
creatorId: string;
billingPeriod: BillingPeriod;
priceToman: number | null;
standingPriceToman: number | null;
/** `priceToman` spread over the period's months. */
perMonthToman: number | null;
/** The struck-through price, when there is one. */
compareAtToman: number | null;
compareSource: CompareSource | null;
promotion: TierPromotionPayload | null;
features: string[];
};
export type PublicTiersResponseDto = { items: PublicTierEntity[] };

View File

@ -0,0 +1,15 @@
import 'server-only';
import { cache } from 'react';
import { checkoutRepository } from '../repositories/checkout';
import type { CheckoutPayload } from '../repositories/checkout';
/**
* The signed-in investor's U9 checkout for a creator, once per render. Throws the API's error as
* is: 401 without a session, 403 for a non-investor or a creator who is not approved or suspended.
*/
export const getCheckoutScreen = cache(
(creatorId: string): Promise<CheckoutPayload> =>
checkoutRepository.getScreen(creatorId),
);

View File

@ -0,0 +1,3 @@
import 'server-only';
export { getCheckoutScreen } from './checkout-screen';

Some files were not shown because too many files have changed in this diff Show More