refactor: code review

This commit is contained in:
Amiram_se 2026-10-06 17:12:50 +04:00
parent dc221f50bf
commit cfa8cce1b0
28 changed files with 291 additions and 105 deletions

View File

@ -1,14 +1,24 @@
import { createClientEnv } from '@lumina/libs/env'; import { createClientEnv } from '@lumina/libs/env';
import * as v from 'valibot'; import * as v from 'valibot';
import { isOrigin } from './is-origin';
const required = v.pipe(v.string(), v.nonEmpty()); const required = v.pipe(v.string(), v.nonEmpty());
const url = v.pipe(v.string(), v.url()); const url = v.pipe(v.string(), v.url());
/** Scheme and host only: request paths and media URLs are joined to it, so `https://api.lumina.ir/` would give `//v1`. */
const origin = v.pipe(
url,
v.check(
isOrigin,
'Must be an origin such as https://api.lumina.ir, with no path or trailing slash.',
),
);
/** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */ /** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */
export const clientEnv = createClientEnv({ export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_', prefix: 'NEXT_PUBLIC_',
schema: { schema: {
NEXT_PUBLIC_API_ORIGIN: url, NEXT_PUBLIC_API_ORIGIN: origin,
NEXT_PUBLIC_SITE_URL: url, NEXT_PUBLIC_SITE_URL: url,
NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required,

View File

@ -3,10 +3,20 @@ import 'server-only';
import { createServerEnv } from '@lumina/libs/env/server'; import { createServerEnv } from '@lumina/libs/env/server';
import * as v from 'valibot'; import * as v from 'valibot';
import { isOrigin } from './is-origin';
/** Server variables; only server code imports them, through `env/server`. */ /** Server variables; only server code imports them, through `env/server`. */
export const serverEnv = createServerEnv({ export const serverEnv = createServerEnv({
schema: { schema: {
API_INTERNAL_ORIGIN: v.pipe(v.string(), v.url()), // Scheme and host only, as NEXT_PUBLIC_API_ORIGIN: request paths are joined to it.
API_INTERNAL_ORIGIN: v.pipe(
v.string(),
v.url(),
v.check(
isOrigin,
'Must be an origin such as http://gateway:3000, with no path or trailing slash.',
),
),
}, },
runtimeEnv: process.env, runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',

8
apps/bear/src/env/is-origin.ts vendored Normal file
View File

@ -0,0 +1,8 @@
/** `https://api.lumina.ir`, not `https://api.lumina.ir/` or `https://api.lumina.ir/v1`. */
export function isOrigin(value: string): boolean {
try {
return new URL(value).origin === value;
} catch {
return false;
}
}

View File

@ -1,14 +1,24 @@
import { createClientEnv } from '@lumina/libs/env'; import { createClientEnv } from '@lumina/libs/env';
import * as v from 'valibot'; import * as v from 'valibot';
import { isOrigin } from './is-origin';
const required = v.pipe(v.string(), v.nonEmpty()); const required = v.pipe(v.string(), v.nonEmpty());
const url = v.pipe(v.string(), v.url()); const url = v.pipe(v.string(), v.url());
/** Scheme and host only: request paths and media URLs are joined to it, so `https://api.lumina.ir/` would give `//v1`. */
const origin = v.pipe(
url,
v.check(
isOrigin,
'Must be an origin such as https://api.lumina.ir, with no path or trailing slash.',
),
);
/** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */ /** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */
export const clientEnv = createClientEnv({ export const clientEnv = createClientEnv({
prefix: 'NEXT_PUBLIC_', prefix: 'NEXT_PUBLIC_',
schema: { schema: {
NEXT_PUBLIC_API_ORIGIN: url, NEXT_PUBLIC_API_ORIGIN: origin,
NEXT_PUBLIC_SITE_URL: url, NEXT_PUBLIC_SITE_URL: url,
NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_BALE_HANDLE: required,
NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required,

View File

@ -3,10 +3,20 @@ import 'server-only';
import { createServerEnv } from '@lumina/libs/env/server'; import { createServerEnv } from '@lumina/libs/env/server';
import * as v from 'valibot'; import * as v from 'valibot';
import { isOrigin } from './is-origin';
/** Server variables; only server code imports them, through `env/server`. */ /** Server variables; only server code imports them, through `env/server`. */
export const serverEnv = createServerEnv({ export const serverEnv = createServerEnv({
schema: { schema: {
API_INTERNAL_ORIGIN: v.pipe(v.string(), v.url()), // Scheme and host only, as NEXT_PUBLIC_API_ORIGIN: request paths are joined to it.
API_INTERNAL_ORIGIN: v.pipe(
v.string(),
v.url(),
v.check(
isOrigin,
'Must be an origin such as http://gateway:3000, with no path or trailing slash.',
),
),
}, },
runtimeEnv: process.env, runtimeEnv: process.env,
skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', skipValidation: process.env.SKIP_ENV_VALIDATION === 'true',

8
apps/bull/src/env/is-origin.ts vendored Normal file
View File

@ -0,0 +1,8 @@
/** `https://api.lumina.ir`, not `https://api.lumina.ir/` or `https://api.lumina.ir/v1`. */
export function isOrigin(value: string): boolean {
try {
return new URL(value).origin === value;
} catch {
return false;
}
}

View File

@ -0,0 +1,27 @@
const noop = () => undefined;
/**
* One signal that aborts when any of `signals` does, with that signal's reason. Uses
* `AbortSignal.any` where it exists; Safari < 17.4, Chrome < 116 and Firefox < 124 lack it, so
* there a controller listens to each source. Call `release` once the request settles: it drops
* those listeners, which would otherwise pile up on long-lived signals such as the abort-all one.
*/
export function anySignal(
signals: AbortSignal[],
): [signal: AbortSignal, release: () => void] {
if (typeof AbortSignal.any === 'function')
return [AbortSignal.any(signals), noop];
const controller = new AbortController();
const listeners = new AbortController();
for (const source of signals) {
if (source.aborted) {
controller.abort(source.reason);
break;
}
source.addEventListener('abort', () => controller.abort(source.reason), {
once: true,
signal: listeners.signal,
});
}
return [controller.signal, () => listeners.abort()];
}

View File

@ -1,3 +1,4 @@
import { anySignal } from './any-signal';
import { import {
buildUrl, buildUrl,
isAbsoluteUrl, isAbsoluteUrl,
@ -312,7 +313,7 @@ export class HttpClient {
url, url,
requestId: createRequestId(), requestId: createRequestId(),
}; };
const signal = AbortSignal.any([ const [signal, releaseSignal] = anySignal([
...(options.signal ? [options.signal] : []), ...(options.signal ? [options.signal] : []),
...this.abortSignals(), ...this.abortSignals(),
]); ]);
@ -332,6 +333,8 @@ export class HttpClient {
toHttpError(thrown, context, signal), toHttpError(thrown, context, signal),
context, context,
); );
} finally {
releaseSignal();
} }
try { try {
for (const [onSuccess] of this.responseChain()) { for (const [onSuccess] of this.responseChain()) {
@ -421,9 +424,10 @@ export class HttpClient {
attempt.timeout === false attempt.timeout === false
? undefined ? undefined
: AbortSignal.timeout(attempt.timeout); : AbortSignal.timeout(attempt.timeout);
const signal = timeoutSignal // Both sources live no longer than this request, so their listeners need no release.
? AbortSignal.any([attempt.signal, timeoutSignal]) const [signal] = timeoutSignal
: attempt.signal; ? anySignal([attempt.signal, timeoutSignal])
: [attempt.signal];
// Which signal fired decides the code, never the message. // Which signal fired decides the code, never the message.
const failure = (cause: unknown) => const failure = (cause: unknown) =>
createHttpError( createHttpError(

View File

@ -147,7 +147,10 @@ function asString(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined; return typeof value === 'string' ? value : undefined;
} }
function toFieldErrors(value: unknown): Record<string, string> | undefined { // { field: ['first message', …] } → { field: 'first message' }; for app error-body mappers too.
export function toFieldErrors(
value: unknown,
): Record<string, string> | undefined {
if (!isRecord(value)) return undefined; if (!isRecord(value)) return undefined;
const entries = Object.entries(value).flatMap(([field, message]) => { const entries = Object.entries(value).flatMap(([field, message]) => {
const text: unknown = Array.isArray(message) ? message[0] : message; const text: unknown = Array.isArray(message) ? message[0] : message;

View File

@ -1,7 +1,7 @@
export { HTTP_ERROR_CODES } from './constants'; export { HTTP_ERROR_CODES } from './constants';
export { HttpClient } from './http-client'; export { HttpClient } from './http-client';
export { createHttpClient, http } from './http'; export { createHttpClient, http } from './http';
export { HttpError, isHttpError } from './http-error'; export { HttpError, isHttpError, toFieldErrors } from './http-error';
export type { export type {
DownloadOptions, DownloadOptions,
DownloadResult, DownloadResult,

View File

@ -13,6 +13,12 @@ export function shouldRetry(
if (attempt >= retry.attempts) return false; if (attempt >= retry.attempts) return false;
if (!optIn && !retry.methods.includes(method)) return false; if (!optIn && !retry.methods.includes(method)) return false;
if (error.code === 'ABORTED') return false; if (error.code === 'ABORTED') return false;
// The server asked for a longer wait than a retry may take: retrying sooner only hits it again.
if (
error.retryAfter !== undefined &&
error.retryAfter * 1000 > retry.maxDelay
)
return false;
if (error.code === 'TIMEOUT') if (error.code === 'TIMEOUT')
return retry.networkErrors && IDEMPOTENT_METHODS.includes(method); return retry.networkErrors && IDEMPOTENT_METHODS.includes(method);
if (error.code === 'NETWORK_ERROR') return retry.networkErrors; if (error.code === 'NETWORK_ERROR') return retry.networkErrors;
@ -26,14 +32,14 @@ export function shouldRetry(
return retry.statuses.includes(error.status); return retry.statuses.includes(error.status);
} }
// Retry-After wins when present; otherwise exponential backoff with full jitter. // Retry-After wins when present (shouldRetry already refused one past maxDelay); otherwise
// exponential backoff with full jitter.
export function getRetryDelay( export function getRetryDelay(
error: HttpError, error: HttpError,
retry: RetryConfig, retry: RetryConfig,
attempt: number, attempt: number,
): number { ): number {
if (error.retryAfter !== undefined) if (error.retryAfter !== undefined) return error.retryAfter * 1000;
return Math.min(retry.maxDelay, error.retryAfter * 1000);
return ( return (
Math.random() * Math.min(retry.maxDelay, retry.baseDelay * 2 ** attempt) Math.random() * Math.min(retry.maxDelay, retry.baseDelay * 2 ** attempt)
); );

View File

@ -44,6 +44,7 @@ export {
createHttpClient, createHttpClient,
http, http,
isHttpError, isHttpError,
toFieldErrors,
} from './http'; } from './http';
export type { export type {
DownloadOptions, DownloadOptions,

View File

@ -8,17 +8,29 @@ import { useAuthStore } from '../../../stores/auth';
/** /**
* The browser learns who the viewer is once per page load; auth-dependent parts wait in their * The browser learns who the viewer is once per page load; auth-dependent parts wait in their
* skeleton until then. When the session ends (sign-out, or a refresh that failed), the store goes * skeleton until then. A read that failed offline or on a gateway error leaves the viewer unknown,
* back to guest and every cached query is dropped: it belonged to the old account. * so it runs again when the connection comes back. When the session ends (sign-out, or a refresh
* that failed), the store goes back to guest and every cached query is dropped: it belonged to the
* old account.
*/ */
export function useSession(queryClient: QueryClient): void { export function useSession(queryClient: QueryClient): void {
useEffect(() => { useEffect(() => {
restoreSession().catch((error: unknown) => const restore = () =>
handleError(error, { where: 'app', name: 'restore-session' }), restoreSession().catch((error: unknown) =>
); handleError(error, { where: 'app', name: 'restore-session' }),
return eventEmitter.on(AUTH_EVENTS.logout, () => { );
const restoreIfUnknown = () => {
if (useAuthStore.getState().status === 'unknown') void restore();
};
void restore();
window.addEventListener('online', restoreIfUnknown);
const offLogout = eventEmitter.on(AUTH_EVENTS.logout, () => {
useAuthStore.getState().clearSession(); useAuthStore.getState().clearSession();
queryClient.clear(); queryClient.clear();
}); });
return () => {
window.removeEventListener('online', restoreIfUnknown);
offLogout();
};
}, [queryClient]); }, [queryClient]);
} }

View File

@ -1,3 +1,4 @@
import { toFieldErrors } from '@lumina/libs/http';
import type { HttpErrorShape } from '@lumina/libs/http'; import type { HttpErrorShape } from '@lumina/libs/http';
import type { ApiErrorEnvelope } from './types'; import type { ApiErrorEnvelope } from './types';
@ -6,28 +7,18 @@ function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value); 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: * Adapts the gateway's error contract to `HttpError`. Two shapes arrive:
* - the envelope `{ statusCode, error, message, details }`, where `message` is the server's text * - the envelope `{ statusCode, error, message, details }`, where `message` is the server's text
* (already translated), a list, or a field map; * (already translated), a list, or a field map. A body with `error` but no `statusCode` (from a
* proxy or another service) is read as an envelope too, so its `message` stays a message;
* - a bare field map `{ phone_number: ['…'] }` from DTO validation. * - 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. * 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. * `details` (a changed price, a frozen unfollow) passes through for the action that handles it.
*/ */
export function mapApiErrorBody(body: unknown): Partial<HttpErrorShape> { export function mapApiErrorBody(body: unknown): Partial<HttpErrorShape> {
if (!isRecord(body)) return {}; if (!isRecord(body)) return {};
if (typeof body.statusCode !== 'number') { if (typeof body.statusCode !== 'number' && typeof body.error !== 'string') {
return { fieldErrors: toFieldErrors(body) }; return { fieldErrors: toFieldErrors(body) };
} }
const { message, details } = body as ApiErrorEnvelope; const { message, details } = body as ApiErrorEnvelope;
@ -38,7 +29,7 @@ export function mapApiErrorBody(body: unknown): Partial<HttpErrorShape> {
: typeof message === 'string' : typeof message === 'string'
? message ? message
: undefined, : undefined,
fieldErrors: isRecord(message) ? toFieldErrors(message) : undefined, fieldErrors: toFieldErrors(message),
retryAfter: typeof retryAfter === 'number' ? retryAfter : undefined, retryAfter: typeof retryAfter === 'number' ? retryAfter : undefined,
details: isRecord(details) ? details : undefined, details: isRecord(details) ? details : undefined,
}; };

View File

@ -1,17 +1,21 @@
import { ROUTES } from './navigation'; import { ROUTES } from './navigation';
// Never fetched: only resolves a path to see which origin the browser would leave for.
const PROBE_ORIGIN = 'https://return-path.invalid';
/** /**
* A `?redirect=` value is only followed when it is a path on this site: `/dashboard`, never * A `?redirect=` value is only followed when it is a path on this site: `/dashboard`, never
* `https://evil.example` or `//evil.example`, so login can't be turned into an open redirect. * `https://evil.example` or `//evil.example`, so login can't be turned into an open redirect.
* The value is resolved the way the browser would resolve it: the URL parser drops tabs and line
* breaks and reads `\` as `/`, so `/\t/evil.example` and `/\evil.example` leave the site too.
*/ */
export function safeReturnPath(value: string | null | undefined): string { export function safeReturnPath(value: string | null | undefined): string {
if ( if (!value?.startsWith('/')) return ROUTES.home;
!value || try {
!value.startsWith('/') || const url = new URL(value, PROBE_ORIGIN);
value.startsWith('//') || if (url.origin !== PROBE_ORIGIN) return ROUTES.home;
value.startsWith('/\\') return `${url.pathname}${url.search}${url.hash}`;
) { } catch {
return ROUTES.home; return ROUTES.home;
} }
return value;
} }

View File

@ -1,3 +1,4 @@
import { handleError } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter'; import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth'; import { useAuthStore } from '../../../../stores/auth';
@ -10,8 +11,9 @@ import type { LoginOutcome } from './types';
/** /**
* Verifies the login code; the gateway sets the session cookies and the auth store learns the * Verifies the login code; the gateway sets the session cookies and the auth store learns the
* account, so every auth-dependent part renders its member variant. A suspended account gets no * account, so every auth-dependent part renders its member variant. A suspended account gets no
* session: the gateway still opens one, so it is closed again at once. Emits `auth.login` when * session: the gateway still opens one, so it is closed again at once. When that close fails the
* the person is signed in. * person still sees the suspended screen, and the next `restoreSession` closes the session. Emits
* `auth.login` when the person is signed in.
*/ */
export async function login( export async function login(
args: VerifyOtpArgs, args: VerifyOtpArgs,
@ -19,7 +21,11 @@ export async function login(
): Promise<LoginOutcome> { ): Promise<LoginOutcome> {
const { account } = await authRepository.verifyLoginOtp(args); const { account } = await authRepository.verifyLoginOtp(args);
if (account.status === 'suspended') { if (account.status === 'suspended') {
await authRepository.logout(); await authRepository
.logout()
.catch((error: unknown) =>
handleError(error, { where: 'action', name: 'logout-suspended' }),
);
useAuthFlowStore.getState().reset(); useAuthFlowStore.getState().reset();
return { status: 'suspended' }; return { status: 'suspended' };
} }

View File

@ -1,3 +1,4 @@
import { classifyError, handleError } from '@lumina/libs/error-handler';
import { eventEmitter } from '@lumina/libs/event-emitter'; import { eventEmitter } from '@lumina/libs/event-emitter';
import { useAuthStore } from '../../../../stores/auth'; import { useAuthStore } from '../../../../stores/auth';
@ -5,11 +6,19 @@ import type { ViewerStatus } from '../../../../stores/auth';
import { AUTH_EVENTS } from '../../constants'; import { AUTH_EVENTS } from '../../constants';
import { authRepository } from '../../repositories/auth'; import { authRepository } from '../../repositories/auth';
/** The connection or the gateway failed, so a later read may still succeed. */
function isTransient(error: unknown): boolean {
const { retry } = classifyError(error);
return retry === 'again' || retry === 'wait';
}
/** /**
* Learns who the viewer is, once per page load (the AppShell calls it). A guest is an empty * Learns who the viewer is, once per page load and again when the connection comes back (the
* session, not an error. An expired access cookie is refreshed by the HTTP client on the way. When * AppShell calls it). A guest is an empty session, not an error. An expired access cookie is
* the read still fails, the viewer is treated as a guest and the error is rethrown for reporting. * refreshed by the HTTP client on the way. A suspended account is no member: its session is closed
* Emits `auth.restore`. * and the viewer is a guest. When the read fails for a reason that may pass (offline, a timeout,
* a 5xx), who the viewer is stays unknown, so a member is never sent to login; any other failure
* makes the viewer a guest. Both rethrow for reporting. Emits `auth.restore`.
*/ */
export async function restoreSession({ export async function restoreSession({
emit = true, emit = true,
@ -18,11 +27,23 @@ export async function restoreSession({
let status: ViewerStatus; let status: ViewerStatus;
try { try {
const { account } = await authRepository.getSession(); const { account } = await authRepository.getSession();
if (account) setSession({ account }); if (account?.status === 'suspended') {
else clearSession(); clearSession();
status = account ? 'member' : 'guest'; void authRepository
.logout()
.catch((error: unknown) =>
handleError(error, { where: 'action', name: 'logout-suspended' }),
);
status = 'guest';
} else if (account) {
setSession({ account });
status = 'member';
} else {
clearSession();
status = 'guest';
}
} catch (error) { } catch (error) {
clearSession(); if (!isTransient(error)) clearSession();
throw error; throw error;
} }
if (emit) eventEmitter.emit(AUTH_EVENTS.restore, { status }); if (emit) eventEmitter.emit(AUTH_EVENTS.restore, { status });

View File

@ -7,28 +7,33 @@ import {
authErrorCode, authErrorCode,
authRepository, authRepository,
} from '../../repositories/auth'; } from '../../repositories/auth';
import type { SendCodeArgs } from './types'; import type { SendCodeArgs, SendCodeOptions } from './types';
/** /**
* Sends a sign-in or registration code to the number and starts the resend wait. Also the resend: * Sends a sign-in or registration code to the number and starts the resend wait. Also the resend:
* a new code replaces the previous one. Asked again for the same number inside the server's * a new code replaces the previous one. Asked again for the same number inside the server's
* cooldown, the code already sent still works, so that counts as sent. Emits `auth.code-sent`. * cooldown, the code already sent still works while it is unused, so that counts as sent; a code
* that already verified the number (registration) does not. The resend button passes
* `acceptPending: false`, so the person learns no new code went out. Emits `auth.code-sent` when a
* code is sent.
*/ */
export async function sendCode( export async function sendCode(
{ purpose, phone }: SendCodeArgs, { purpose, phone }: SendCodeArgs,
{ emit = true }: { emit?: boolean } = {}, { emit = true, acceptPending = true }: SendCodeOptions = {},
): Promise<'ok'> { ): Promise<'ok'> {
try { try {
if (purpose === 'login') await authRepository.requestLoginOtp({ phone }); if (purpose === 'login') await authRepository.requestLoginOtp({ phone });
else await authRepository.sendRegistrationOtp({ phone }); else await authRepository.sendRegistrationOtp({ phone });
} catch (error) { } catch (error) {
const flow = useAuthFlowStore.getState(); const flow = useAuthFlowStore.getState();
const isSameCode = const isPendingCode =
acceptPending &&
authErrorCode(error) === AUTH_ERROR_CODES.cooldown && authErrorCode(error) === AUTH_ERROR_CODES.cooldown &&
flow.purpose === purpose && flow.purpose === purpose &&
flow.phone === phone && flow.phone === phone &&
flow.codeSentAt !== null; flow.codeSentAt !== null &&
if (!isSameCode) throw error; flow.registration === null;
if (!isPendingCode) throw error;
return 'ok'; return 'ok';
} }
useAuthFlowStore.getState().codeSent(purpose, phone, Date.now()); useAuthFlowStore.getState().codeSent(purpose, phone, Date.now());

View File

@ -1,2 +1,2 @@
export { sendCode } from './actions'; export { sendCode } from './actions';
export type { SendCodeArgs } from './types'; export type { SendCodeArgs, SendCodeOptions } from './types';

View File

@ -5,3 +5,9 @@ export type SendCodeArgs = {
/** 09XXXXXXXXX; the repository sends E.164. */ /** 09XXXXXXXXX; the repository sends E.164. */
phone: string; phone: string;
}; };
export type SendCodeOptions = {
emit?: boolean;
/** Counts the server's cooldown for the same unused code as sent. Off for the resend button. */
acceptPending?: boolean;
};

View File

@ -115,7 +115,7 @@ export function useCodeStep({
const onResend = () => { const onResend = () => {
if (!phone || phase === 'sending') return; if (!phone || phase === 'sending') return;
setPhase('sending'); setPhase('sending');
sendCode({ purpose, phone }) sendCode({ purpose, phone }, { acceptPending: false })
.then(() => { .then(() => {
restart(); restart();
setPhase('sent'); setPhase('sent');

View File

@ -6,9 +6,10 @@ import { POST_PAGE_LIMIT, postRepository } from '../repositories/post';
import type { PostPagePayload } from '../repositories/post'; import type { PostPagePayload } from '../repositories/post';
/** /**
* A channel's first page for this request's viewer: drafts included for the creator, premium * A channel's first page as every visitor sees it: server reads carry no session, so drafts are
* posts locked for anyone without a subscription. Later pages load on the client with the same * left out and premium posts come locked. The creator's drafts and a subscriber's unlocked posts
* `POST_PAGE_LIMIT`. * load in the browser, in the auth-dependent part that replaces this page. Later pages load on the
* client with the same `POST_PAGE_LIMIT`.
*/ */
export const getCreatorPosts = cache( export const getCreatorPosts = cache(
async (creatorId: string): Promise<PostPagePayload> => async (creatorId: string): Promise<PostPagePayload> =>

View File

@ -6,8 +6,10 @@ import { postRepository } from '../repositories/post';
import type { PostPayload } from '../repositories/post'; import type { PostPayload } from '../repositories/post';
/** /**
* One post as this request's viewer may see it: in full, or locked for a premium post without a * One post as every visitor sees it: server reads carry no session, so a premium post comes locked
* subscription. A missing post or someone else's draft rejects with a 404 for `readOnServer`. * and the full post loads in the browser for a subscriber. A missing post or any draft, the
* creator's own included, rejects with a 404 for `readOnServer`; the creator opens a draft from a
* page that reads it in the browser.
*/ */
export const getPost = cache( export const getPost = cache(
async (id: string): Promise<PostPayload> => postRepository.get(id), async (id: string): Promise<PostPayload> => postRepository.get(id),

View File

@ -11,7 +11,7 @@ import type { AutosaveStatus, CreatorProfileForm } from './types';
/** /**
* Saves the creator's step 5 as a draft about a second after typing stops, at once on request * Saves the creator's step 5 as a draft about a second after typing stops, at once on request
* (a field lost focus), and when the page closes. Saves run one at a time, each from the newest * (a field lost focus), and when the page closes. Saves run one at a time, each from the newest
* values, and a save that would change nothing is skipped. A failure is reported and shown in the * values, except the one sent as the tab closes, and a save that would change nothing is skipped. A failure is reported and shown in the
* status line; it never toasts, because the next change tries again. * status line; it never toasts, because the next change tries again.
*/ */
export function useProfileAutosave( export function useProfileAutosave(
@ -25,36 +25,44 @@ export function useProfileAutosave(
const running = useRef<Promise<void> | null>(null); const running = useRef<Promise<void> | null>(null);
const isStopped = useRef(false); const isStopped = useRef(false);
// One request from the newest values, unless they are what the server already has.
const send = useCallback(
async ({ keepalive = false }: { keepalive?: boolean } = {}) => {
if (isStopped.current) return;
const args = toDraftArgs(form.getValues());
const key = JSON.stringify(args);
if (key === lastSaved.current) return;
const request = profileRepository
.saveDraft(args, { keepalive })
.then(
(profile) => {
lastSaved.current = key;
queryClient.setQueryData(profileKeys.mine(), profile);
setStatus({ phase: 'saved', at: Date.now() });
},
(error: unknown) => {
const errorClass = handleError(error, {
where: 'action',
name: 'profile-autosave',
});
if (errorClass.action !== 'silent') setStatus({ phase: 'failed' });
},
)
.finally(() => {
if (running.current === request) running.current = null;
});
running.current = request;
await request;
},
[form, queryClient],
);
const save = useCallback(async (): Promise<void> => { const save = useCallback(async (): Promise<void> => {
clearTimeout(timer.current); clearTimeout(timer.current);
while (running.current) await running.current; while (running.current) await running.current;
if (isStopped.current) return; await send();
const args = toDraftArgs(form.getValues()); }, [send]);
const key = JSON.stringify(args);
if (key === lastSaved.current) return;
const request = profileRepository
.saveDraft(args)
.then(
(profile) => {
lastSaved.current = key;
queryClient.setQueryData(profileKeys.mine(), profile);
setStatus({ phase: 'saved', at: Date.now() });
},
(error: unknown) => {
const errorClass = handleError(error, {
where: 'action',
name: 'profile-autosave',
});
if (errorClass.action !== 'silent') setStatus({ phase: 'failed' });
},
)
.finally(() => {
running.current = null;
});
running.current = request;
await request;
}, [form, queryClient]);
useEffect(() => { useEffect(() => {
const unsubscribe = form.subscribe({ const unsubscribe = form.subscribe({
@ -70,15 +78,20 @@ export function useProfileAutosave(
}; };
}, [form, save]); }, [form, save]);
// Closing the tab or leaving for another page keeps what is pending. // Closing the tab keeps what is pending: the save goes out at once with keepalive, which the
// browser finishes after the page is gone, instead of waiting for a save in flight that the
// unload would cancel. Leaving for another page of the app saves as usual.
useEffect(() => { useEffect(() => {
const flush = () => void save(); const flushOnUnload = () => {
window.addEventListener('pagehide', flush); clearTimeout(timer.current);
return () => { void send({ keepalive: true });
window.removeEventListener('pagehide', flush);
flush();
}; };
}, [save]); window.addEventListener('pagehide', flushOnUnload);
return () => {
window.removeEventListener('pagehide', flushOnUnload);
void save();
};
}, [send, save]);
return { return {
status, status,

View File

@ -43,12 +43,19 @@ export const profileRepository = {
/** Registration step 5's autosave: keeps what was typed without completing the profile. */ /** Registration step 5's autosave: keeps what was typed without completing the profile. */
async saveDraft( async saveDraft(
args: SaveProfileDraftArgs, args: SaveProfileDraftArgs,
{ signal }: { signal?: AbortSignal } = {}, {
signal,
keepalive = false,
}: {
signal?: AbortSignal;
/** The browser finishes the request after the page closes. */
keepalive?: boolean;
} = {},
): Promise<CreatorProfilePayload> { ): Promise<CreatorProfilePayload> {
const response = await profileHttp.patch<CreatorProfileResponseDto>( const response = await profileHttp.patch<CreatorProfileResponseDto>(
PROFILE_ENDPOINTS.mine, PROFILE_ENDPOINTS.mine,
toSaveProfileDraftDto(args), toSaveProfileDraftDto(args),
{ signal }, { signal, init: keepalive ? { keepalive } : undefined },
); );
return toCreatorProfilePayload(response); return toCreatorProfilePayload(response);
}, },

View File

@ -12,6 +12,14 @@
"interceptor-hint": "صفحه را دوباره بارگذاری کنید.", "interceptor-hint": "صفحه را دوباره بارگذاری کنید.",
"unknown": "مشکلی پیش آمد.", "unknown": "مشکلی پیش آمد.",
"unknown-hint": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید.", "unknown-hint": "دوباره تلاش کنید؛ اگر مشکل ادامه داشت، با پشتیبانی تماس بگیرید.",
"validation": "برخی از اطلاعات واردشده درست نیست.",
"bad-request": "درخواست قابل انجام نبود.",
"unauthorized": "برای ادامه وارد حساب خود شوید.",
"forbidden": "اجازه انجام این کار را ندارید.",
"not-found": "موردی که دنبالش بودید پیدا نشد.",
"conflict": "این اطلاعات در این فاصله تغییر کرده است.",
"rate-limited": "تعداد درخواست‌ها زیاد بود.",
"server": "سرور نتوانست درخواست را انجام دهد.",
"retry-after": "{{seconds}} ثانیه دیگر دوباره تلاش کنید." "retry-after": "{{seconds}} ثانیه دیگر دوباره تلاش کنید."
}, },
"fallback": { "fallback": {

View File

@ -1,4 +1,7 @@
import { SOCIAL_HANDLE_ADDRESSES } from '../validations/constants'; import {
SOCIAL_HANDLE_ADDRESSES,
SOCIAL_HANDLE_PATTERN,
} from '../validations/constants';
import type { SocialPlatform } from '../validations/types'; import type { SocialPlatform } from '../validations/types';
type HandlePlatform = keyof typeof SOCIAL_HANDLE_ADDRESSES; type HandlePlatform = keyof typeof SOCIAL_HANDLE_ADDRESSES;
@ -58,7 +61,9 @@ export function toSocialUrl(platform: SocialPlatform, handle: string): string {
/** /**
* A stored link back into a row. The label names the platform for links this form saved; older * A stored link back into a row. The label names the platform for links this form saved; older
* links fall back to their host, and anything else is a website. * links fall back to their host, and anything else is a website. A platform link whose path is no
* handle (`t.me/s/channel`, `youtube.com/channel/UC…`) stays a website row with its whole address:
* a row that can't be saved would be dropped from the draft, and the server would lose the link.
*/ */
export function fromSocialUrl( export function fromSocialUrl(
label: string, label: string,
@ -76,7 +81,8 @@ export function fromSocialUrl(
: undefined; : undefined;
const platform = byLabel ?? byHost; const platform = byLabel ?? byHost;
if (platform && address) { if (platform && address) {
return { platform, handle: handleFromPath(platform, address.path) }; const handle = handleFromPath(platform, address.path);
if (SOCIAL_HANDLE_PATTERN.test(handle)) return { platform, handle };
} }
return { platform: 'website', handle: url }; return { platform: 'website', handle: url };
} }

View File

@ -30,11 +30,18 @@ export const useAuthFlowStore = create<AuthFlowState>()(
}), }),
carryPhone: (phone) => carryPhone: (phone) =>
set((state) => { set((state) => {
// A different number starts clean: the sent code, the block and the misses belong to the
// old one.
if (state.phone !== phone) {
state.codeSentAt = null;
state.blockedUntil = null;
state.misses = 0;
}
state.phone = phone; state.phone = phone;
}), }),
codeSent: (purpose, phone, sentAt) => codeSent: (purpose, phone, sentAt) =>
set((state) => { set((state) => {
// A different number starts clean: the block and the misses belong to the old one. // A different number starts clean: the block belongs to the old one.
if (state.phone !== phone) state.blockedUntil = null; if (state.phone !== phone) state.blockedUntil = null;
state.purpose = purpose; state.purpose = purpose;
state.phone = phone; state.phone = phone;