Compare commits

...

14 Commits

84 changed files with 9765 additions and 3158 deletions

1
.env.example Normal file
View File

@ -0,0 +1 @@
NEXT_PUBLIC_API_URL=http://your.api/api

2
.gitignore vendored
View File

@ -123,8 +123,6 @@ dist
# yarn v2
.yarn
.DS_Store
.idea
.yarnrc.yml

BIN
.yarn/install-state.gz Normal file

Binary file not shown.

942
.yarn/releases/yarn-4.9.2.cjs vendored Normal file

File diff suppressed because one or more lines are too long

3
.yarnrc.yml Normal file
View File

@ -0,0 +1,3 @@
nodeLinker: node-modules
yarnPath: .yarn/releases/yarn-4.9.2.cjs

View File

@ -1,16 +0,0 @@
import PageContainer from "@/components/PageContainer/PageContainer";
import PageItem from "@/components/PageBlock/PageItem";
import Logo from "@/components/Logo/Logo";
import ConfirmAccessForm from "@/components/ConfirmAccessForm/ConfirmAccessForm";
export default function ConfirmAccessPage() {
return (
<PageContainer center>
<PageItem fullScreenMobile>
<Logo title={"Вход с помощью LogiDex ID"} />
<ConfirmAccessForm />
</PageItem>
</PageContainer>
)
}

View File

@ -1,15 +0,0 @@
import LoginForm from "@/components/LoginForm/LoginForm";
import Logo from "@/components/Logo/Logo";
import PageItem from "@/components/PageBlock/PageItem";
import PageContainer from "@/components/PageContainer/PageContainer";
export default function MainPage() {
return (
<PageContainer center>
<PageItem fullScreenMobile>
<Logo title={"Вход"} />
<LoginForm />
</PageItem>
</PageContainer>
);
}

6
build_docker.sh Normal file → Executable file
View File

@ -1,4 +1,2 @@
sudo docker build -t git.logidex.ru/aserbin/logidex-id-frontend:latest .
sudo docker images git.logidex.ru/aserbin/logidex-id-frontend:latest
sudo docker login git.logidex.ru
sudo docker push git.logidex.ru/aserbin/logidex-id-frontend:latest
docker build -t git.logidex.ru/fakz9/logidex-id-frontend:latest .
docker push git.logidex.ru/fakz9/logidex-id-frontend:latest

View File

@ -1,44 +0,0 @@
"use client";
import { FC, useEffect, useState } from "react";
import { redirect } from "next/navigation";
import { useSelector } from "react-redux";
import { Button, Text } from "@mantine/core";
import SERVICES from "@/constants/services";
import { ServiceCode } from "@/enums/ServiceCode";
import { RootState } from "@/lib/store";
import ServiceData from "@/types/ServiceData";
const ConfirmAccessButton: FC = () => {
const serviceCode = useSelector(
(state: RootState) => state.targetService.serviceCode
);
const [serviceData, setServiceData] = useState<ServiceData>();
useEffect(() => {
if (serviceCode === ServiceCode.UNDEFINED) {
redirect("services");
}
setServiceData(SERVICES[serviceCode]);
}, [serviceCode]);
const confirmAccess = () => {};
return (
<>
<Button
onClick={() => confirmAccess()}
variant={"filled"}>
Войти
</Button>
<Text
fz={"h4"}
ta="center">
Сервис {serviceData?.name} получит{" "}
{serviceData?.requiredAccesses}
</Text>
</>
);
};
export default ConfirmAccessButton;

View File

@ -1,12 +0,0 @@
'use client';
import { motion, MotionProps } from 'framer-motion';
import { ReactNode } from 'react';
interface MotionWrapperProps extends MotionProps {
children: ReactNode;
}
export function MotionWrapper({ children, ...props }: MotionWrapperProps) {
return <motion.div {...props}>{children}</motion.div>;
}

View File

@ -1,20 +0,0 @@
import { ServiceCode } from "@/enums/ServiceCode";
import ServiceData from "@/types/ServiceData";
const SERVICES = {
[ServiceCode.UNDEFINED]: {
code: ServiceCode.UNDEFINED,
name: "undefined",
link: "",
requiredAccesses: "",
},
[ServiceCode.CRM]: {
code: ServiceCode.CRM,
name: "LogiDex CRM",
link: "https://skirbo.ru",
requiredAccesses:
"доступ к учетной записи и сделкам по фулфиллменту",
} as ServiceData,
};
export default SERVICES;

View File

@ -1,4 +0,0 @@
export enum ServiceCode {
CRM = "crm",
UNDEFINED = "",
}

View File

@ -1,10 +0,0 @@
import { combineReducers } from "@reduxjs/toolkit";
import targetServiceReducer from "@/lib/features/targetService/targetServiceSlice";
import verificationReducer from "@/lib/features/verification/verificationSlice";
const rootReducer = combineReducers({
targetService: targetServiceReducer,
verification: verificationReducer,
});
export default rootReducer;

21
openapi-ts.config.ts Normal file
View File

@ -0,0 +1,21 @@
import { defaultPlugins, defineConfig } from "@hey-api/openapi-ts";
export default defineConfig({
input: "../back/combined.yaml",
output: "src/client",
plugins: [
...defaultPlugins,
{
asClass: true,
name: "@hey-api/sdk",
validator: "zod",
},
{
name: "@hey-api/client-next",
runtimeConfigPath:"./src/hey-api-config.ts",
},
{
name: "@hey-api/typescript",
},
],
});

View File

@ -17,15 +17,18 @@
"prettier:write": "prettier --write \"**/*.{ts,tsx}\"",
"test": "npm run prettier:check && npm run lint && npm run typecheck && npm run jest",
"storybook": "storybook dev -p 6006",
"storybook:build": "storybook build"
"storybook:build": "storybook build",
"openapi-ts": "openapi-ts"
},
"dependencies": {
"@mantine/core": "8.1.2",
"@mantine/form": "^8.1.3",
"@mantine/hooks": "8.1.2",
"@mantine/notifications": "^8.2.1",
"@next/bundle-analyzer": "^15.3.3",
"@reduxjs/toolkit": "^2.8.2",
"@tabler/icons-react": "^3.34.0",
"axios": "^1.11.0",
"classnames": "^2.5.1",
"framer-motion": "^12.23.7",
"i18n-iso-countries": "^7.14.0",
@ -36,11 +39,13 @@
"react-imask": "^7.6.1",
"react-redux": "^9.2.0",
"redux-persist": "^6.0.0",
"sharp": "^0.34.3"
"sharp": "^0.34.3",
"zod": "^4.0.10"
},
"devDependencies": {
"@babel/core": "^7.27.4",
"@eslint/js": "^9.29.0",
"@hey-api/openapi-ts": "0.80.1",
"@ianvs/prettier-plugin-sort-imports": "^4.4.2",
"@storybook/nextjs": "^8.6.8",
"@storybook/react": "^8.6.8",

View File

@ -0,0 +1,89 @@
"use client";
import { FC, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useSelector } from "react-redux";
import { Button, Text } from "@mantine/core";
import { Auth } from "@/client";
import SCOPES from "@/constants/scopes";
import { Scopes } from "@/enums/Scopes";
import { notifications } from "@/lib/notifications";
import { RootState } from "@/lib/store/store";
const ConsentButton: FC = () => {
const searchParams = useSearchParams();
const auth = useSelector((state: RootState) => state.auth);
const [clientName, setClientName] = useState<string>(Scopes.UNDEFINED);
const [serviceRequiredAccess, setServiceRequiredAccess] =
useState<string>("");
const setAccessesForScope = () => {
const accesses: string[] = [];
(auth.scope ?? []).forEach((scopeItem: Scopes) => {
const access = SCOPES[scopeItem];
if (access) accesses.push(access);
});
setServiceRequiredAccess(accesses.join("\n"));
};
const requestConsent = () => {
};
useEffect(() => {
setAccessesForScope();
requestConsent();
}, []);
const confirmAccess = () => {
const phoneNumber = auth.phoneNumber;
if (!phoneNumber) {
console.error("Phone number is not set");
return;
}
const consentChallenge = searchParams.get("consent_challenge");
if (!consentChallenge) {
console.error("Consent challenge is missing in the URL");
return;
}
Auth.postAuthConsentAccept({
body: {
consent_challenge: consentChallenge,
phone_number: phoneNumber,
},
})
.then(response => response.data)
.then(response => {
if (!response) {
console.error("Response is empty");
return;
}
const { redirect_url, ok, message } = response;
notifications.guess(ok, { message });
if (redirect_url) {
window.location.href = redirect_url;
} else {
console.error("Redirect URL is missing in the response");
}
});
};
return (
<>
<Button
onClick={() => confirmAccess()}
variant={"filled"}>
Войти
</Button>
<Text
fz={"h4"}
ta="center">
Сервис {clientName} получит {serviceRequiredAccess}
</Text>
</>
);
};
export default ConsentButton;

View File

@ -1,9 +1,9 @@
import { FC } from "react";
import { Stack, Text } from "@mantine/core";
import ConfirmAccessButton from "@/components/ConfirmAccessForm/ConfirmAccessButton";
import styles from "./ConfirmAccessForm.module.css";
import ConfirmAccessButton from "@/app/consent/components/ConsentButton/ConsentButton";
import styles from "./ConsentForm.module.css";
const ConfirmAccessForm: FC = () => {
const ConsentForm: FC = () => {
return (
<Stack
align={"center"}
@ -19,4 +19,4 @@ const ConfirmAccessForm: FC = () => {
);
};
export default ConfirmAccessForm;
export default ConsentForm;

16
src/app/consent/page.tsx Normal file
View File

@ -0,0 +1,16 @@
import PageContainer from "@/components/layout/PageContainer/PageContainer";
import PageItem from "@/components/layout/PageBlock/PageItem";
import Logo from "@/components/ui/Logo/Logo";
import ConsentForm from "@/app/consent/components/ConsentForm/ConsentForm";
export default function ConfirmAccessPage() {
return (
<PageContainer center>
<PageItem fullScreenMobile>
<Logo title={"Вход с помощью LogiDex ID"} />
<ConsentForm />
</PageItem>
</PageContainer>
)
}

View File

@ -1,7 +1,7 @@
import LoginForm from "@/components/LoginForm/LoginForm";
import Logo from "@/components/Logo/Logo";
import PageItem from "@/components/PageBlock/PageItem";
import PageContainer from "@/components/PageContainer/PageContainer";
import LoginForm from "@/components/features/LoginForm/LoginForm";
import Logo from "@/components/ui/Logo/Logo";
import PageItem from "@/components/layout/PageBlock/PageItem";
import PageContainer from "@/components/layout/PageContainer/PageContainer";
export default function CreateIdPage() {
return (

View File

@ -1,19 +1,21 @@
import "@mantine/core/styles.css";
import "@mantine/notifications/styles.css";
import React, { ReactNode } from "react";
import {
ColorSchemeScript,
mantineHtmlProps,
MantineProvider,
} from "@mantine/core";
import Header from "@/components/Header/Header";
import Header from "@/components/layout/Header/Header";
import { theme } from "@/theme";
import "@/app/global.css";
import Footer from "@/components/Footer/Footer";
import { Notifications } from "@mantine/notifications";
import Footer from "@/components/layout/Footer/Footer";
import ReduxProvider from "@/providers/ReduxProvider";
export const metadata = {
title: "LogiDex ID",
description: "LogiDex ID",
title: "ID LogiDex",
description: "ID LogiDex",
};
type Props = {
@ -50,6 +52,7 @@ export default function RootLayout({ children }: Props) {
{children}
<Footer />
</ReduxProvider>
<Notifications />
</MantineProvider>
</body>
</html>

21
src/app/login/page.tsx Normal file
View File

@ -0,0 +1,21 @@
import LoginForm from "@/components/features/LoginForm/LoginForm";
import PageItem from "@/components/layout/PageBlock/PageItem";
import PageContainer from "@/components/layout/PageContainer/PageContainer";
import Logo from "@/components/ui/Logo/Logo";
interface LoginPageProps {
searchParams: Promise<{ login_challenge?: string }>;
}
export default async function LoginPage({ searchParams }: LoginPageProps) {
const params = await searchParams;
return (
<PageContainer center>
<PageItem fullScreenMobile>
<Logo title={"Вход"} />
<LoginForm loginChallenge={params.login_challenge} />
</PageItem>
</PageContainer>
);
}

5
src/app/page.tsx Normal file
View File

@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function MainPage() {
redirect("/login");
}

View File

@ -3,27 +3,31 @@
import { useMemo } from "react";
import { redirect } from "next/navigation";
import { Button, Stack, Title } from "@mantine/core";
import styles from "@/components/ServicesList/ServicesList.module.css";
import TitleWithLines from "@/components/TitleWithLines/TitleWithLines";
import SERVICES from "@/constants/services";
import { ServiceCode } from "@/enums/ServiceCode";
import { setTargetService } from "@/lib/features/targetService/targetServiceSlice";
import { useAppDispatch } from "@/lib/store";
import ServiceData from "@/types/ServiceData";
import styles from "@/app/services/components/ServicesList/ServicesList.module.css";
import TitleWithLines from "@/components/ui/TitleWithLines/TitleWithLines";
import SCOPES from "@/constants/scopes";
import { Scopes } from "@/enums/Scopes";
import { setTargetService } from "@/lib/store/features/targetService/targetServiceSlice";
import { useAppDispatch } from "@/lib/store/store";
type ServiceData = {
id: number;
code: Scopes;
name: string;
};
const ServicesList = () => {
const dispatch = useAppDispatch();
const services = useMemo(
() =>
Object.entries(SERVICES)
.filter(([key]) => key !== ServiceCode.UNDEFINED)
Object.entries(SCOPES)
.filter(([key]) => key !== Scopes.UNDEFINED)
.map(([, value]) => value),
[SERVICES]
[SCOPES]
);
const onServiceClick = (service: ServiceData) => {
dispatch(setTargetService(service.code));
redirect("confirm-access");
redirect("consent");
};
const getServiceButton = (service: ServiceData, key: number) => {
@ -56,7 +60,9 @@ const ServicesList = () => {
<Stack
className={styles.container}
gap={"lg"}>
{services.map((service, i) => getServiceButton(service, i))}
{services.map((service, i) =>
getServiceButton(service as unknown as ServiceData, i)
)}
<TitleWithLines title="Скоро будет" />
{getServiceInDevelopment("Analytics")}
</Stack>

View File

@ -1,7 +1,7 @@
import Logo from "@/components/Logo/Logo";
import PageItem from "@/components/PageBlock/PageItem";
import PageContainer from "@/components/PageContainer/PageContainer";
import ServicesList from "@/components/ServicesList/ServicesList";
import Logo from "@/components/ui/Logo/Logo";
import PageItem from "@/components/layout/PageBlock/PageItem";
import PageContainer from "@/components/layout/PageContainer/PageContainer";
import ServicesList from "@/app/services/components/ServicesList/ServicesList";
export default function ServicesPage() {
return (

View File

@ -3,9 +3,9 @@
import { FC, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Button } from "@mantine/core";
import { setLastSendTime } from "@/lib/features/verification/verificationSlice";
import { RootState } from "@/lib/store";
import { MAX_COUNTDOWN } from "@/constants/verification";
import { setLastSendTime } from "@/lib/store/features/verification/verificationSlice";
import { RootState } from "@/lib/store/store";
const ResendVerificationCode: FC = () => {
const [countdown, setCountdown] = useState(0);

View File

@ -2,10 +2,14 @@
import { FC } from "react";
import { redirect } from "next/navigation";
import { useSelector } from "react-redux";
import { Button, PinInput, Stack } from "@mantine/core";
import { useForm } from "@mantine/form";
import ResendVerificationCode from "@/components/ResendVerificationCode/ResendVerificationCode";
import style from "@/components/VerifyPhoneForm/VerifyPhone.module.css";
import ResendVerificationCode from "@/app/verify-phone/components/ResendVerificationCode/ResendVerificationCode";
import style from "@/app/verify-phone/components/VerifyPhoneForm/VerifyPhone.module.css";
import { Auth } from "@/client";
import { notifications } from "@/lib/notifications";
import { RootState } from "@/lib/store/store";
type VerifyNumberForm = {
code: string;
@ -20,11 +24,32 @@ const VerifyPhoneForm: FC = () => {
code: code => code.length !== 6 && "Введите весь код",
},
});
const authState = useSelector((state: RootState) => state.auth);
const handleSubmit = (values: VerifyNumberForm) => {
console.log(values);
if (!authState.phoneNumber || !authState.loginChallenge) return;
console.log(authState.phoneNumber.replace(/ /g, ""));
redirect("/services");
Auth.postAuthOtpVerify({
body: {
phone_number: authState.phoneNumber,
login_challenge: authState.loginChallenge,
otp: values.code,
},
})
.then(response => response.data)
.then(response => {
if (!response) return;
const { redirect_url, ok } = response;
if (!ok) {
notifications.error({
message: "Ошибка при подтверждении номера",
});
return;
}
window.location.href = redirect_url;
});
};
const navigateToLogin = () => redirect("/");

View File

@ -1,7 +1,7 @@
import Logo from "@/components/Logo/Logo";
import PageItem from "@/components/PageBlock/PageItem";
import PageContainer from "@/components/PageContainer/PageContainer";
import VerifyPhoneForm from "@/components/VerifyPhoneForm/VerifyPhoneForm";
import VerifyPhoneForm from "@/app/verify-phone/components/VerifyPhoneForm/VerifyPhoneForm";
import PageItem from "@/components/layout/PageBlock/PageItem";
import PageContainer from "@/components/layout/PageContainer/PageContainer";
import Logo from "@/components/ui/Logo/Logo";
export default function CreateIdPage() {
return (

17
src/client/client.gen.ts Normal file
View File

@ -0,0 +1,17 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { ClientOptions } from './types.gen';
import { type Config, type ClientOptions as DefaultClientOptions, createClient, createConfig } from './client';
import { createClientConfig } from '../hey-api-config';
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends DefaultClientOptions = ClientOptions> = (override?: Config<DefaultClientOptions & T>) => Config<Required<DefaultClientOptions> & T>;
export const client = createClient(createClientConfig(createConfig<ClientOptions>()));

177
src/client/client/client.ts Normal file
View File

@ -0,0 +1,177 @@
import type { Client, Config, RequestOptions } from './types';
import {
buildUrl,
createConfig,
createInterceptors,
getParseAs,
mergeConfigs,
mergeHeaders,
setAuthParams,
} from './utils';
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
body?: any;
headers: ReturnType<typeof mergeHeaders>;
};
export const createClient = (config: Config = {}): Client => {
let _config = mergeConfigs(createConfig(), config);
const getConfig = (): Config => ({ ..._config });
const setConfig = (config: Config): Config => {
_config = mergeConfigs(_config, config);
return getConfig();
};
const interceptors = createInterceptors<Response, unknown, RequestOptions>();
// @ts-expect-error
const request: Client['request'] = async (options) => {
const opts = {
..._config,
...options,
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
headers: mergeHeaders(_config.headers, options.headers),
};
if (opts.security) {
await setAuthParams({
...opts,
security: opts.security,
});
}
if (opts.requestValidator) {
await opts.requestValidator(opts);
}
if (opts.body && opts.bodySerializer) {
opts.body = opts.bodySerializer(opts.body);
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.body === undefined || opts.body === '') {
opts.headers.delete('Content-Type');
}
for (const fn of interceptors.request._fns) {
if (fn) {
await fn(opts);
}
}
const url = buildUrl(opts);
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = opts.fetch!;
let response = await _fetch(url, {
...opts,
body: opts.body as ReqInit['body'],
});
for (const fn of interceptors.response._fns) {
if (fn) {
response = await fn(response, opts);
}
}
const result = {
response,
};
if (response.ok) {
if (
response.status === 204 ||
response.headers.get('Content-Length') === '0'
) {
return {
data: {},
...result,
};
}
const parseAs =
(opts.parseAs === 'auto'
? getParseAs(response.headers.get('Content-Type'))
: opts.parseAs) ?? 'json';
let data: any;
switch (parseAs) {
case 'arrayBuffer':
case 'blob':
case 'formData':
case 'json':
case 'text':
data = await response[parseAs]();
break;
case 'stream':
return {
data: response.body,
...result,
};
}
if (parseAs === 'json') {
if (opts.responseValidator) {
await opts.responseValidator(data);
}
if (opts.responseTransformer) {
data = await opts.responseTransformer(data);
}
}
return {
data,
...result,
};
}
const textError = await response.text();
let jsonError: unknown;
try {
jsonError = JSON.parse(textError);
} catch {
// noop
}
const error = jsonError ?? textError;
let finalError = error;
for (const fn of interceptors.error._fns) {
if (fn) {
finalError = (await fn(error, response, opts)) as string;
}
}
finalError = finalError || ({} as string);
if (opts.throwOnError) {
throw finalError;
}
return {
error: finalError,
...result,
};
};
return {
buildUrl,
connect: (options) => request({ ...options, method: 'CONNECT' }),
delete: (options) => request({ ...options, method: 'DELETE' }),
get: (options) => request({ ...options, method: 'GET' }),
getConfig,
head: (options) => request({ ...options, method: 'HEAD' }),
interceptors,
options: (options) => request({ ...options, method: 'OPTIONS' }),
patch: (options) => request({ ...options, method: 'PATCH' }),
post: (options) => request({ ...options, method: 'POST' }),
put: (options) => request({ ...options, method: 'PUT' }),
request,
setConfig,
trace: (options) => request({ ...options, method: 'TRACE' }),
};
};

View File

@ -0,0 +1,21 @@
export type { Auth } from '../core/auth';
export type { QuerySerializerOptions } from '../core/bodySerializer';
export {
formDataBodySerializer,
jsonBodySerializer,
urlSearchParamsBodySerializer,
} from '../core/bodySerializer';
export { buildClientParams } from '../core/params';
export { createClient } from './client';
export type {
Client,
ClientOptions,
Config,
CreateClientConfig,
Options,
OptionsLegacyParser,
RequestOptions,
RequestResult,
TDataShape,
} from './types';
export { createConfig } from './utils';

173
src/client/client/types.ts Normal file
View File

@ -0,0 +1,173 @@
import type { Auth } from '../core/auth';
import type {
Client as CoreClient,
Config as CoreConfig,
} from '../core/types';
import type { Middleware } from './utils';
export interface Config<T extends ClientOptions = ClientOptions>
extends Omit<RequestInit, 'body' | 'headers' | 'method'>,
CoreConfig {
/**
* Base URL for all requests made by this client.
*/
baseUrl?: T['baseUrl'];
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* Return the response data parsed in a specified format. By default, `auto`
* will infer the appropriate method from the `Content-Type` response header.
* You can override this behavior with any of the {@link Body} methods.
* Select `stream` if you don't want to parse response data at all.
*
* @default 'auto'
*/
parseAs?:
| 'arrayBuffer'
| 'auto'
| 'blob'
| 'formData'
| 'json'
| 'stream'
| 'text';
/**
* Throw an error instead of returning it in the response?
*
* @default false
*/
throwOnError?: T['throwOnError'];
}
export interface RequestOptions<
ThrowOnError extends boolean = boolean,
Url extends string = string,
> extends Config<{
throwOnError: ThrowOnError;
}> {
/**
* Any body that you want to add to your request.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
*/
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
/**
* Security mechanism(s) to use for the request.
*/
security?: ReadonlyArray<Auth>;
url: Url;
}
export type RequestResult<
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = boolean,
> = ThrowOnError extends true
? Promise<{
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
response: Response;
}>
: Promise<
(
| {
data: TData extends Record<string, unknown>
? TData[keyof TData]
: TData;
error: undefined;
}
| {
data: undefined;
error: TError extends Record<string, unknown>
? TError[keyof TError]
: TError;
}
) & {
response: Response;
}
>;
export interface ClientOptions {
baseUrl?: string;
throwOnError?: boolean;
}
type MethodFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
>(
options: Omit<RequestOptions<ThrowOnError>, 'method'>,
) => RequestResult<TData, TError, ThrowOnError>;
type RequestFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
>(
options: Omit<RequestOptions<ThrowOnError>, 'method'> &
Pick<Required<RequestOptions<ThrowOnError>>, 'method'>,
) => RequestResult<TData, TError, ThrowOnError>;
type BuildUrlFn = <
TData extends {
body?: unknown;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
url: string;
},
>(
options: Pick<TData, 'url'> & Options<TData>,
) => string;
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
interceptors: Middleware<Response, unknown, RequestOptions>;
};
/**
* The `createClientConfig()` function will be called on client initialization
* and the returned object will become the client's initial configuration.
*
* You may want to initialize your client this way instead of calling
* `setConfig()`. This is useful for example if you're using Next.js
* to ensure your client always has the correct values.
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
override?: Config<ClientOptions & T>,
) => Config<Required<ClientOptions> & T>;
export interface TDataShape {
body?: unknown;
headers?: unknown;
path?: unknown;
query?: unknown;
url: string;
}
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
export type Options<
TData extends TDataShape = TDataShape,
ThrowOnError extends boolean = boolean,
> = OmitKeys<RequestOptions<ThrowOnError>, 'body' | 'path' | 'query' | 'url'> &
Omit<TData, 'url'>;
export type OptionsLegacyParser<
TData = unknown,
ThrowOnError extends boolean = boolean,
> = TData extends { body?: any }
? TData extends { headers?: any }
? OmitKeys<RequestOptions<ThrowOnError>, 'body' | 'headers' | 'url'> & TData
: OmitKeys<RequestOptions<ThrowOnError>, 'body' | 'url'> &
TData &
Pick<RequestOptions<ThrowOnError>, 'headers'>
: TData extends { headers?: any }
? OmitKeys<RequestOptions<ThrowOnError>, 'headers' | 'url'> &
TData &
Pick<RequestOptions<ThrowOnError>, 'body'>
: OmitKeys<RequestOptions<ThrowOnError>, 'url'> & TData;

407
src/client/client/utils.ts Normal file
View File

@ -0,0 +1,407 @@
import { getAuthToken } from '../core/auth';
import type {
QuerySerializer,
QuerySerializerOptions,
} from '../core/bodySerializer';
import { jsonBodySerializer } from '../core/bodySerializer';
import {
serializeArrayParam,
serializeObjectParam,
serializePrimitiveParam,
} from '../core/pathSerializer';
import type { Client, ClientOptions, Config, RequestOptions } from './types';
interface PathSerializer {
path: Record<string, unknown>;
url: string;
}
const PATH_PARAM_RE = /\{[^{}]+\}/g;
type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
type MatrixStyle = 'label' | 'matrix' | 'simple';
type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
let url = _url;
const matches = _url.match(PATH_PARAM_RE);
if (matches) {
for (const match of matches) {
let explode = false;
let name = match.substring(1, match.length - 1);
let style: ArraySeparatorStyle = 'simple';
if (name.endsWith('*')) {
explode = true;
name = name.substring(0, name.length - 1);
}
if (name.startsWith('.')) {
name = name.substring(1);
style = 'label';
} else if (name.startsWith(';')) {
name = name.substring(1);
style = 'matrix';
}
const value = path[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
url = url.replace(
match,
serializeArrayParam({ explode, name, style, value }),
);
continue;
}
if (typeof value === 'object') {
url = url.replace(
match,
serializeObjectParam({
explode,
name,
style,
value: value as Record<string, unknown>,
valueOnly: true,
}),
);
continue;
}
if (style === 'matrix') {
url = url.replace(
match,
`;${serializePrimitiveParam({
name,
value: value as string,
})}`,
);
continue;
}
const replaceValue = encodeURIComponent(
style === 'label' ? `.${value as string}` : (value as string),
);
url = url.replace(match, replaceValue);
}
}
return url;
};
export const createQuerySerializer = <T = unknown>({
allowReserved,
array,
object,
}: QuerySerializerOptions = {}) => {
const querySerializer = (queryParams: T) => {
const search: string[] = [];
if (queryParams && typeof queryParams === 'object') {
for (const name in queryParams) {
const value = queryParams[name];
if (value === undefined || value === null) {
continue;
}
if (Array.isArray(value)) {
const serializedArray = serializeArrayParam({
allowReserved,
explode: true,
name,
style: 'form',
value,
...array,
});
if (serializedArray) search.push(serializedArray);
} else if (typeof value === 'object') {
const serializedObject = serializeObjectParam({
allowReserved,
explode: true,
name,
style: 'deepObject',
value: value as Record<string, unknown>,
...object,
});
if (serializedObject) search.push(serializedObject);
} else {
const serializedPrimitive = serializePrimitiveParam({
allowReserved,
name,
value: value as string,
});
if (serializedPrimitive) search.push(serializedPrimitive);
}
}
}
return search.join('&');
};
return querySerializer;
};
/**
* Infers parseAs value from provided Content-Type header.
*/
export const getParseAs = (
contentType: string | null,
): Exclude<Config['parseAs'], 'auto'> => {
if (!contentType) {
// If no Content-Type header is provided, the best we can do is return the raw response body,
// which is effectively the same as the 'stream' option.
return 'stream';
}
const cleanContent = contentType.split(';')[0]?.trim();
if (!cleanContent) {
return;
}
if (
cleanContent.startsWith('application/json') ||
cleanContent.endsWith('+json')
) {
return 'json';
}
if (cleanContent === 'multipart/form-data') {
return 'formData';
}
if (
['application/', 'audio/', 'image/', 'video/'].some((type) =>
cleanContent.startsWith(type),
)
) {
return 'blob';
}
if (cleanContent.startsWith('text/')) {
return 'text';
}
return;
};
export const setAuthParams = async ({
security,
...options
}: Pick<Required<RequestOptions>, 'security'> &
Pick<RequestOptions, 'auth' | 'query'> & {
headers: Headers;
}) => {
for (const auth of security) {
const token = await getAuthToken(auth, options.auth);
if (!token) {
continue;
}
const name = auth.name ?? 'Authorization';
switch (auth.in) {
case 'query':
if (!options.query) {
options.query = {};
}
options.query[name] = token;
break;
case 'cookie':
options.headers.append('Cookie', `${name}=${token}`);
break;
case 'header':
default:
options.headers.set(name, token);
break;
}
return;
}
};
export const buildUrl: Client['buildUrl'] = (options) => {
const url = getUrl({
baseUrl: options.baseUrl as string,
path: options.path,
query: options.query,
querySerializer:
typeof options.querySerializer === 'function'
? options.querySerializer
: createQuerySerializer(options.querySerializer),
url: options.url,
});
return url;
};
export const getUrl = ({
baseUrl,
path,
query,
querySerializer,
url: _url,
}: {
baseUrl?: string;
path?: Record<string, unknown>;
query?: Record<string, unknown>;
querySerializer: QuerySerializer;
url: string;
}) => {
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
let url = (baseUrl ?? '') + pathUrl;
if (path) {
url = defaultPathSerializer({ path, url });
}
let search = query ? querySerializer(query) : '';
if (search.startsWith('?')) {
search = search.substring(1);
}
if (search) {
url += `?${search}`;
}
return url;
};
export const mergeConfigs = (a: Config, b: Config): Config => {
const config = { ...a, ...b };
if (config.baseUrl?.endsWith('/')) {
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
}
config.headers = mergeHeaders(a.headers, b.headers);
return config;
};
export const mergeHeaders = (
...headers: Array<Required<Config>['headers'] | undefined>
): Headers => {
const mergedHeaders = new Headers();
for (const header of headers) {
if (!header || typeof header !== 'object') {
continue;
}
const iterator =
header instanceof Headers ? header.entries() : Object.entries(header);
// @ts-ignore
for (const [key, value] of iterator) {
if (value === null) {
mergedHeaders.delete(key);
} else if (Array.isArray(value)) {
for (const v of value) {
mergedHeaders.append(key, v as string);
}
} else if (value !== undefined) {
// assume object headers are meant to be JSON stringified, i.e. their
// content value in OpenAPI specification is 'application/json'
mergedHeaders.set(
key,
typeof value === 'object' ? JSON.stringify(value) : (value as string),
);
}
}
}
return mergedHeaders;
};
type ErrInterceptor<Err, Res, Options> = (
error: Err,
response: Res,
options: Options,
) => Err | Promise<Err>;
type ReqInterceptor<Options> = (options: Options) => void | Promise<void>;
type ResInterceptor<Res, Options> = (
response: Res,
options: Options,
) => Res | Promise<Res>;
class Interceptors<Interceptor> {
_fns: (Interceptor | null)[];
constructor() {
this._fns = [];
}
clear() {
this._fns = [];
}
getInterceptorIndex(id: number | Interceptor): number {
if (typeof id === 'number') {
return this._fns[id] ? id : -1;
} else {
return this._fns.indexOf(id);
}
}
exists(id: number | Interceptor) {
const index = this.getInterceptorIndex(id);
return !!this._fns[index];
}
eject(id: number | Interceptor) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = null;
}
}
update(id: number | Interceptor, fn: Interceptor) {
const index = this.getInterceptorIndex(id);
if (this._fns[index]) {
this._fns[index] = fn;
return id;
} else {
return false;
}
}
use(fn: Interceptor) {
this._fns = [...this._fns, fn];
return this._fns.length - 1;
}
}
// `createInterceptors()` response, meant for external use as it does not
// expose internals
export interface Middleware<Res, Err, Options> {
error: Pick<Interceptors<ErrInterceptor<Err, Res, Options>>, 'eject' | 'use'>;
request: Pick<Interceptors<ReqInterceptor<Options>>, 'eject' | 'use'>;
response: Pick<Interceptors<ResInterceptor<Res, Options>>, 'eject' | 'use'>;
}
// do not add `Middleware` as return type so we can use _fns internally
export const createInterceptors = <Res, Err, Options>() => ({
error: new Interceptors<ErrInterceptor<Err, Res, Options>>(),
request: new Interceptors<ReqInterceptor<Options>>(),
response: new Interceptors<ResInterceptor<Res, Options>>(),
});
const defaultQuerySerializer = createQuerySerializer({
allowReserved: false,
array: {
explode: true,
style: 'form',
},
object: {
explode: true,
style: 'deepObject',
},
});
const defaultHeaders = {
'Content-Type': 'application/json',
};
export const createConfig = <T extends ClientOptions = ClientOptions>(
override: Config<Omit<ClientOptions, keyof T> & T> = {},
): Config<Omit<ClientOptions, keyof T> & T> => ({
...jsonBodySerializer,
headers: defaultHeaders,
parseAs: 'auto',
querySerializer: defaultQuerySerializer,
...override,
});

40
src/client/core/auth.ts Normal file
View File

@ -0,0 +1,40 @@
export type AuthToken = string | undefined;
export interface Auth {
/**
* Which part of the request do we use to send the auth?
*
* @default 'header'
*/
in?: 'header' | 'query' | 'cookie';
/**
* Header or query parameter name.
*
* @default 'Authorization'
*/
name?: string;
scheme?: 'basic' | 'bearer';
type: 'apiKey' | 'http';
}
export const getAuthToken = async (
auth: Auth,
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
): Promise<string | undefined> => {
const token =
typeof callback === 'function' ? await callback(auth) : callback;
if (!token) {
return;
}
if (auth.scheme === 'bearer') {
return `Bearer ${token}`;
}
if (auth.scheme === 'basic') {
return `Basic ${btoa(token)}`;
}
return token;
};

View File

@ -0,0 +1,88 @@
import type {
ArrayStyle,
ObjectStyle,
SerializerOptions,
} from './pathSerializer';
export type QuerySerializer = (query: Record<string, unknown>) => string;
export type BodySerializer = (body: any) => any;
export interface QuerySerializerOptions {
allowReserved?: boolean;
array?: SerializerOptions<ArrayStyle>;
object?: SerializerOptions<ObjectStyle>;
}
const serializeFormDataPair = (
data: FormData,
key: string,
value: unknown,
): void => {
if (typeof value === 'string' || value instanceof Blob) {
data.append(key, value);
} else {
data.append(key, JSON.stringify(value));
}
};
const serializeUrlSearchParamsPair = (
data: URLSearchParams,
key: string,
value: unknown,
): void => {
if (typeof value === 'string') {
data.append(key, value);
} else {
data.append(key, JSON.stringify(value));
}
};
export const formDataBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): FormData => {
const data = new FormData();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeFormDataPair(data, key, v));
} else {
serializeFormDataPair(data, key, value);
}
});
return data;
},
};
export const jsonBodySerializer = {
bodySerializer: <T>(body: T): string =>
JSON.stringify(body, (_key, value) =>
typeof value === 'bigint' ? value.toString() : value,
),
};
export const urlSearchParamsBodySerializer = {
bodySerializer: <T extends Record<string, any> | Array<Record<string, any>>>(
body: T,
): string => {
const data = new URLSearchParams();
Object.entries(body).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
if (Array.isArray(value)) {
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
} else {
serializeUrlSearchParamsPair(data, key, value);
}
});
return data.toString();
},
};

151
src/client/core/params.ts Normal file
View File

@ -0,0 +1,151 @@
type Slot = 'body' | 'headers' | 'path' | 'query';
export type Field =
| {
in: Exclude<Slot, 'body'>;
/**
* Field name. This is the name we want the user to see and use.
*/
key: string;
/**
* Field mapped name. This is the name we want to use in the request.
* If omitted, we use the same value as `key`.
*/
map?: string;
}
| {
in: Extract<Slot, 'body'>;
/**
* Key isn't required for bodies.
*/
key?: string;
map?: string;
};
export interface Fields {
allowExtra?: Partial<Record<Slot, boolean>>;
args?: ReadonlyArray<Field>;
}
export type FieldsConfig = ReadonlyArray<Field | Fields>;
const extraPrefixesMap: Record<string, Slot> = {
$body_: 'body',
$headers_: 'headers',
$path_: 'path',
$query_: 'query',
};
const extraPrefixes = Object.entries(extraPrefixesMap);
type KeyMap = Map<
string,
{
in: Slot;
map?: string;
}
>;
const buildKeyMap = (fields: FieldsConfig, map?: KeyMap): KeyMap => {
if (!map) {
map = new Map();
}
for (const config of fields) {
if ('in' in config) {
if (config.key) {
map.set(config.key, {
in: config.in,
map: config.map,
});
}
} else if (config.args) {
buildKeyMap(config.args, map);
}
}
return map;
};
interface Params {
body: unknown;
headers: Record<string, unknown>;
path: Record<string, unknown>;
query: Record<string, unknown>;
}
const stripEmptySlots = (params: Params) => {
for (const [slot, value] of Object.entries(params)) {
if (value && typeof value === 'object' && !Object.keys(value).length) {
delete params[slot as Slot];
}
}
};
export const buildClientParams = (
args: ReadonlyArray<unknown>,
fields: FieldsConfig,
) => {
const params: Params = {
body: {},
headers: {},
path: {},
query: {},
};
const map = buildKeyMap(fields);
let config: FieldsConfig[number] | undefined;
for (const [index, arg] of args.entries()) {
if (fields[index]) {
config = fields[index];
}
if (!config) {
continue;
}
if ('in' in config) {
if (config.key) {
const field = map.get(config.key)!;
const name = field.map || config.key;
(params[field.in] as Record<string, unknown>)[name] = arg;
} else {
params.body = arg;
}
} else {
for (const [key, value] of Object.entries(arg ?? {})) {
const field = map.get(key);
if (field) {
const name = field.map || key;
(params[field.in] as Record<string, unknown>)[name] = value;
} else {
const extra = extraPrefixes.find(([prefix]) =>
key.startsWith(prefix),
);
if (extra) {
const [prefix, slot] = extra;
(params[slot] as Record<string, unknown>)[
key.slice(prefix.length)
] = value;
} else {
for (const [slot, allowed] of Object.entries(
config.allowExtra ?? {},
)) {
if (allowed) {
(params[slot as Slot] as Record<string, unknown>)[key] = value;
break;
}
}
}
}
}
}
}
stripEmptySlots(params);
return params;
};

View File

@ -0,0 +1,179 @@
interface SerializeOptions<T>
extends SerializePrimitiveOptions,
SerializerOptions<T> {}
interface SerializePrimitiveOptions {
allowReserved?: boolean;
name: string;
}
export interface SerializerOptions<T> {
/**
* @default true
*/
explode: boolean;
style: T;
}
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
type MatrixStyle = 'label' | 'matrix' | 'simple';
export type ObjectStyle = 'form' | 'deepObject';
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
value: string;
}
export const separatorArrayExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const separatorArrayNoExplode = (style: ArraySeparatorStyle) => {
switch (style) {
case 'form':
return ',';
case 'pipeDelimited':
return '|';
case 'spaceDelimited':
return '%20';
default:
return ',';
}
};
export const separatorObjectExplode = (style: ObjectSeparatorStyle) => {
switch (style) {
case 'label':
return '.';
case 'matrix':
return ';';
case 'simple':
return ',';
default:
return '&';
}
};
export const serializeArrayParam = ({
allowReserved,
explode,
name,
style,
value,
}: SerializeOptions<ArraySeparatorStyle> & {
value: unknown[];
}) => {
if (!explode) {
const joinedValues = (
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
).join(separatorArrayNoExplode(style));
switch (style) {
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
case 'simple':
return joinedValues;
default:
return `${name}=${joinedValues}`;
}
}
const separator = separatorArrayExplode(style);
const joinedValues = value
.map((v) => {
if (style === 'label' || style === 'simple') {
return allowReserved ? v : encodeURIComponent(v as string);
}
return serializePrimitiveParam({
allowReserved,
name,
value: v as string,
});
})
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};
export const serializePrimitiveParam = ({
allowReserved,
name,
value,
}: SerializePrimitiveParam) => {
if (value === undefined || value === null) {
return '';
}
if (typeof value === 'object') {
throw new Error(
'Deeply-nested arrays/objects arent supported. Provide your own `querySerializer()` to handle these.',
);
}
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
};
export const serializeObjectParam = ({
allowReserved,
explode,
name,
style,
value,
valueOnly,
}: SerializeOptions<ObjectSeparatorStyle> & {
value: Record<string, unknown> | Date;
valueOnly?: boolean;
}) => {
if (value instanceof Date) {
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
}
if (style !== 'deepObject' && !explode) {
let values: string[] = [];
Object.entries(value).forEach(([key, v]) => {
values = [
...values,
key,
allowReserved ? (v as string) : encodeURIComponent(v as string),
];
});
const joinedValues = values.join(',');
switch (style) {
case 'form':
return `${name}=${joinedValues}`;
case 'label':
return `.${joinedValues}`;
case 'matrix':
return `;${name}=${joinedValues}`;
default:
return joinedValues;
}
}
const separator = separatorObjectExplode(style);
const joinedValues = Object.entries(value)
.map(([key, v]) =>
serializePrimitiveParam({
allowReserved,
name: style === 'deepObject' ? `${name}[${key}]` : key,
value: v as string,
}),
)
.join(separator);
return style === 'label' || style === 'matrix'
? separator + joinedValues
: joinedValues;
};

118
src/client/core/types.ts Normal file
View File

@ -0,0 +1,118 @@
import type { Auth, AuthToken } from './auth';
import type {
BodySerializer,
QuerySerializer,
QuerySerializerOptions,
} from './bodySerializer';
export interface Client<
RequestFn = never,
Config = unknown,
MethodFn = never,
BuildUrlFn = never,
> {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn;
connect: MethodFn;
delete: MethodFn;
get: MethodFn;
getConfig: () => Config;
head: MethodFn;
options: MethodFn;
patch: MethodFn;
post: MethodFn;
put: MethodFn;
request: RequestFn;
setConfig: (config: Config) => Config;
trace: MethodFn;
}
export interface Config {
/**
* Auth token or a function returning auth token. The resolved value will be
* added to the request payload as defined by its `security` array.
*/
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
/**
* A function for serializing request body parameter. By default,
* {@link JSON.stringify()} will be used.
*/
bodySerializer?: BodySerializer | null;
/**
* An object containing any HTTP headers that you want to pre-populate your
* `Headers` object with.
*
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
*/
headers?:
| RequestInit['headers']
| Record<
string,
| string
| number
| boolean
| (string | number | boolean)[]
| null
| undefined
| unknown
>;
/**
* The request method.
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?:
| 'CONNECT'
| 'DELETE'
| 'GET'
| 'HEAD'
| 'OPTIONS'
| 'PATCH'
| 'POST'
| 'PUT'
| 'TRACE';
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
* style, and reserved characters are percent-encoded.
*
* This method will have no effect if the native `paramsSerializer()` Axios
* API function is used.
*
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
*/
querySerializer?: QuerySerializer | QuerySerializerOptions;
/**
* A function validating request data. This is useful if you want to ensure
* the request conforms to the desired shape, so it can be safely sent to
* the server.
*/
requestValidator?: (data: unknown) => Promise<unknown>;
/**
* A function transforming response data before it's returned. This is useful
* for post-processing data, e.g. converting ISO strings into Date objects.
*/
responseTransformer?: (data: unknown) => Promise<unknown>;
/**
* A function validating response data. This is useful if you want to ensure
* the response conforms to the desired shape, so it can be safely passed to
* the transformers and returned to the user.
*/
responseValidator?: (data: unknown) => Promise<unknown>;
}
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
? true
: [T] extends [never | undefined]
? [undefined] extends [T]
? false
: true
: false;
export type OmitNever<T extends Record<string, unknown>> = {
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true
? never
: K]: T[K];
};

3
src/client/index.ts Normal file
View File

@ -0,0 +1,3 @@
// This file is auto-generated by @hey-api/openapi-ts
export * from './types.gen';
export * from './sdk.gen';

82
src/client/sdk.gen.ts Normal file
View File

@ -0,0 +1,82 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Options as ClientOptions, TDataShape, Client } from './client';
import type { PostAuthOtpRequestData, PostAuthOtpRequestResponses, PostAuthOtpRequestErrors, PostAuthOtpVerifyData, PostAuthOtpVerifyResponses, PostAuthOtpVerifyErrors, PostAuthConsentAcceptData, PostAuthConsentAcceptResponses, PostAuthConsentAcceptErrors } from './types.gen';
import { zPostAuthOtpRequestData, zPostAuthOtpRequestResponse, zPostAuthOtpVerifyData, zPostAuthOtpVerifyResponse, zPostAuthConsentAcceptData, zPostAuthConsentAcceptResponse } from './zod.gen';
import { client as _heyApiClient } from './client.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = ClientOptions<TData, ThrowOnError> & {
/**
* You can provide a client instance returned by `createClient()` instead of
* individual options. This might be also useful if you want to implement a
* custom client.
*/
client?: Client;
/**
* You can pass arbitrary values through the `meta` object. This can be
* used to access values that aren't defined as part of the SDK function.
*/
meta?: Record<string, unknown>;
};
export class Auth {
/**
* Request OTP
*/
public static postAuthOtpRequest<ThrowOnError extends boolean = false>(options: Options<PostAuthOtpRequestData, ThrowOnError>) {
return (options.client ?? _heyApiClient).post<PostAuthOtpRequestResponses, PostAuthOtpRequestErrors, ThrowOnError>({
requestValidator: async (data) => {
return await zPostAuthOtpRequestData.parseAsync(data);
},
responseValidator: async (data) => {
return await zPostAuthOtpRequestResponse.parseAsync(data);
},
url: '/auth/otp/request',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* Verify OTP
*/
public static postAuthOtpVerify<ThrowOnError extends boolean = false>(options: Options<PostAuthOtpVerifyData, ThrowOnError>) {
return (options.client ?? _heyApiClient).post<PostAuthOtpVerifyResponses, PostAuthOtpVerifyErrors, ThrowOnError>({
requestValidator: async (data) => {
return await zPostAuthOtpVerifyData.parseAsync(data);
},
responseValidator: async (data) => {
return await zPostAuthOtpVerifyResponse.parseAsync(data);
},
url: '/auth/otp/verify',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
}
/**
* Accept consent
*/
public static postAuthConsentAccept<ThrowOnError extends boolean = false>(options: Options<PostAuthConsentAcceptData, ThrowOnError>) {
return (options.client ?? _heyApiClient).post<PostAuthConsentAcceptResponses, PostAuthConsentAcceptErrors, ThrowOnError>({
requestValidator: async (data) => {
return await zPostAuthConsentAcceptData.parseAsync(data);
},
responseValidator: async (data) => {
return await zPostAuthConsentAcceptResponse.parseAsync(data);
},
url: '/auth/consent/accept',
...options,
headers: {
'Content-Type': 'application/json',
...options.headers
}
});
}
}

151
src/client/types.gen.ts Normal file
View File

@ -0,0 +1,151 @@
// This file is auto-generated by @hey-api/openapi-ts
export type RequestOtpRequest = {
/**
* Phone number to send OTP to
*/
phone_number: string;
};
export type RequestOtpResponse = {
/**
* Confirmation message
*/
message: string;
/**
* Status of the request
*/
ok: boolean;
};
export type VerifyOtpRequest = {
/**
* Phone number to verify OTP for
*/
phone_number: string;
/**
* One-time password to verify
*/
otp: string;
/**
* Login challenge for verification
*/
login_challenge: string;
};
export type VerifyOtpResponse = {
/**
* URL to redirect to after successful verification
*/
redirect_url: string;
/**
* Status of the verification
*/
ok: boolean;
/**
* Confirmation message
*/
message: string;
};
export type AcceptConsentRequest = {
/**
* The consent challenge to accept
*/
consent_challenge: string;
/**
* Phone number associated with the consent
*/
phone_number: string;
};
export type AcceptConsentResponse = {
/**
* URL to redirect to after accepting consent
*/
redirect_url: string;
/**
* Status of the consent acceptance
*/
ok: boolean;
message: string;
};
export type PostAuthOtpRequestData = {
body: RequestOtpRequest;
path?: never;
query?: never;
url: '/auth/otp/request';
};
export type PostAuthOtpRequestErrors = {
/**
* Bad request
*/
400: RequestOtpResponse;
};
export type PostAuthOtpRequestError = PostAuthOtpRequestErrors[keyof PostAuthOtpRequestErrors];
export type PostAuthOtpRequestResponses = {
/**
* OTP requested successfully
*/
200: RequestOtpResponse;
};
export type PostAuthOtpRequestResponse = PostAuthOtpRequestResponses[keyof PostAuthOtpRequestResponses];
export type PostAuthOtpVerifyData = {
body: VerifyOtpRequest;
path?: never;
query?: never;
url: '/auth/otp/verify';
};
export type PostAuthOtpVerifyErrors = {
/**
* Bad request
*/
400: VerifyOtpResponse;
};
export type PostAuthOtpVerifyError = PostAuthOtpVerifyErrors[keyof PostAuthOtpVerifyErrors];
export type PostAuthOtpVerifyResponses = {
/**
* OTP verified successfully
*/
200: VerifyOtpResponse;
};
export type PostAuthOtpVerifyResponse = PostAuthOtpVerifyResponses[keyof PostAuthOtpVerifyResponses];
export type PostAuthConsentAcceptData = {
body: AcceptConsentRequest;
path?: never;
query?: never;
url: '/auth/consent/accept';
};
export type PostAuthConsentAcceptErrors = {
/**
* Bad request
*/
400: AcceptConsentResponse;
};
export type PostAuthConsentAcceptError = PostAuthConsentAcceptErrors[keyof PostAuthConsentAcceptErrors];
export type PostAuthConsentAcceptResponses = {
/**
* Consent accepted successfully
*/
200: AcceptConsentResponse;
};
export type PostAuthConsentAcceptResponse = PostAuthConsentAcceptResponses[keyof PostAuthConsentAcceptResponses];
export type ClientOptions = {
baseUrl: `${string}://${string}` | (string & {});
};

68
src/client/zod.gen.ts Normal file
View File

@ -0,0 +1,68 @@
// This file is auto-generated by @hey-api/openapi-ts
import { z } from 'zod';
export const zRequestOtpRequest = z.object({
phone_number: z.string().max(15)
});
export const zRequestOtpResponse = z.object({
message: z.string(),
ok: z.boolean()
});
export const zVerifyOtpRequest = z.object({
phone_number: z.string().max(15),
otp: z.string().max(6),
login_challenge: z.string()
});
export const zVerifyOtpResponse = z.object({
redirect_url: z.string(),
ok: z.boolean(),
message: z.string()
});
export const zAcceptConsentRequest = z.object({
consent_challenge: z.string(),
phone_number: z.string().max(15)
});
export const zAcceptConsentResponse = z.object({
redirect_url: z.string(),
ok: z.boolean(),
message: z.string()
});
export const zPostAuthOtpRequestData = z.object({
body: zRequestOtpRequest,
path: z.optional(z.never()),
query: z.optional(z.never())
});
/**
* OTP requested successfully
*/
export const zPostAuthOtpRequestResponse = zRequestOtpResponse;
export const zPostAuthOtpVerifyData = z.object({
body: zVerifyOtpRequest,
path: z.optional(z.never()),
query: z.optional(z.never())
});
/**
* OTP verified successfully
*/
export const zPostAuthOtpVerifyResponse = zVerifyOtpResponse;
export const zPostAuthConsentAcceptData = z.object({
body: zAcceptConsentRequest,
path: z.optional(z.never()),
query: z.optional(z.never())
});
/**
* Consent accepted successfully
*/
export const zPostAuthConsentAcceptResponse = zAcceptConsentResponse;

View File

@ -1,21 +1,30 @@
"use client";
import { FC, useState } from "react";
import { redirect } from "next/navigation";
import { FC, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button, Stack } from "@mantine/core";
import { useForm } from "@mantine/form";
import PhoneInput from "@/components/PhoneInput/PhoneInput";
import { Auth } from "@/client";
import PhoneInput from "@/components/ui/PhoneInput/PhoneInput";
import {
setLoginChallenge,
setPhoneNumber,
} from "@/lib/store/features/auth/authSlice";
import { notifications } from "@/lib/notifications";
import { useAppDispatch } from "@/lib/store/store";
type LoginForm = {
phoneNumber: string;
};
type Props = {
loginChallenge?: string;
isCreatingId?: boolean;
};
const LoginForm: FC<Props> = ({ isCreatingId = false }) => {
const LoginForm: FC<Props> = ({ loginChallenge, isCreatingId = false }) => {
const [phoneMask, setPhoneMask] = useState<string>("");
const router = useRouter();
const form = useForm<LoginForm>({
initialValues: {
phoneNumber: "",
@ -26,17 +35,38 @@ const LoginForm: FC<Props> = ({ isCreatingId = false }) => {
"Введите корректный номер",
},
});
const dispatch = useAppDispatch();
useEffect(() => {
dispatch(setLoginChallenge(loginChallenge ?? null));
}, [loginChallenge]);
const handleSubmit = (values: LoginForm) => {
console.log(values);
console.log(phoneMask);
redirect("/verify-phone");
const phoneNumber = values.phoneNumber.replace(/ /g, "");
dispatch(setPhoneNumber(phoneNumber));
Auth.postAuthOtpRequest({
body: { phone_number: phoneNumber },
})
.then(response => response.data)
.then(response => {
console.log(response);
if (!response) {
notifications.error({
message: "Ошибка при отправке запроса",
});
return;
}
const { ok, message } = response;
notifications.guess(ok, { message });
if (ok) {
router.push("/verify-phone");
}
});
};
const navigateToCreateId = () => redirect("/create-id");
const navigateToCreateId = () => router.push("/create-id");
const navigateToLogin = () => redirect("/");
const navigateToLogin = () => router.push("/");
return (
<form onSubmit={form.onSubmit(handleSubmit)}>

View File

@ -1,5 +1,5 @@
import { Group } from "@mantine/core";
import { ColorSchemeToggle } from "@/components/ColorSchemeToggle/ColorSchemeToggle";
import { ColorSchemeToggle } from "@/components/ui/ColorSchemeToggle/ColorSchemeToggle";
const Header = () => {
return (

View File

@ -0,0 +1,12 @@
"use client";
import { ReactNode } from "react";
import { motion, MotionProps } from "framer-motion";
interface MotionWrapperProps extends MotionProps {
children: ReactNode;
}
export function MotionWrapper({ children, ...props }: MotionWrapperProps) {
return <motion.div {...props}>{children}</motion.div>;
}

View File

@ -1,6 +1,6 @@
import { CSSProperties, FC, ReactNode } from "react";
import classNames from "classnames";
import { MotionWrapper } from "@/components/MotionWrapper/MotionWrapper";
import { MotionWrapper } from "@/components/layout/MotionWrapper/MotionWrapper";
import styles from "./PageItem.module.css";
type Props = {

View File

@ -8,7 +8,6 @@
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.16),
0 4px 24px rgba(0, 0, 0, 0.16);
}
padding: rem(25);
}
.icon {

View File

@ -7,7 +7,7 @@ import {
useComputedColorScheme,
useMantineColorScheme,
} from "@mantine/core";
import style from "./ActionToggle.module.css";
import style from "./ColorSchemeToggle.module.css";
export function ColorSchemeToggle() {
const { setColorScheme } = useMantineColorScheme();

View File

@ -7,10 +7,8 @@ import {
type InputBaseProps,
type PolymorphicComponentProps,
} from "@mantine/core";
import CountrySelect from "@/components/PhoneInput/components/CountrySelect";
import { Country } from "@/components/PhoneInput/types";
import getInitialDataFromValue from "@/components/PhoneInput/utils/getInitialDataFromValue";
import getPhoneMask from "@/components/PhoneInput/utils/getPhoneMask";
import { Country } from "@/components/ui/PhoneInput/types";
import getInitialDataFromValue from "@/components/ui/PhoneInput/utils/getInitialDataFromValue";
type AdditionalProps = {
onChange: (value: string | null) => void;
@ -20,14 +18,13 @@ type AdditionalProps = {
type InputProps = Omit<
PolymorphicComponentProps<typeof IMaskInput, InputBaseProps>,
"onChange" | "defaultValue"
"onChange" | "defaultValue" | "value"
>;
export type Props = AdditionalProps & InputProps;
const PhoneInput = ({
initialCountryCode = "RU",
value: _value,
onChange: _onChange,
setPhoneMask: _setPhoneMask,
...props
@ -41,8 +38,6 @@ const PhoneInput = ({
const inputRef = useRef<HTMLInputElement>(null);
const [dropdownWidth, setDropdownWidth] = useState<number>(300);
const lastNotifiedValue = useRef<string | null>(value ?? "");
const onChange = (numberWithoutCode: string) => {
setValue(numberWithoutCode);
_onChange(`+${country.callingCode} ${numberWithoutCode}`);
@ -57,14 +52,6 @@ const PhoneInput = ({
setPhoneMask(initialData.current.format, country);
}, [initialData.current.format]);
useEffect(() => {
const localValue = value.trim();
if (localValue !== lastNotifiedValue.current) {
lastNotifiedValue.current = localValue;
onChange(localValue);
}
}, [country.code, value]);
const { readOnly, disabled } = props;
const leftSectionWidth = 90;
@ -79,20 +66,21 @@ const PhoneInput = ({
component={IMaskInput}
inputRef={inputRef}
leftSection={
<CountrySelect
disabled={disabled || readOnly}
country={country}
setCountry={country => {
setCountry(country);
setPhoneMask(getPhoneMask(country.code), country);
setValue("");
if (inputRef.current) {
inputRef.current.focus();
}
}}
leftSectionWidth={leftSectionWidth}
inputWidth={dropdownWidth}
/>
<></>
// <CountrySelect
// disabled={disabled || readOnly}
// country={country}
// setCountry={country => {
// setCountry(country);
// setPhoneMask(getPhoneMask(country.code), country);
// setValue("");
// if (inputRef.current) {
// inputRef.current.focus();
// }
// }}
// leftSectionWidth={leftSectionWidth}
// inputWidth={dropdownWidth}
// />
}
leftSectionWidth={leftSectionWidth}
styles={{
@ -108,7 +96,7 @@ const PhoneInput = ({
inputMode={"numeric"}
mask={mask}
value={value}
onAccept={value => setValue(value)}
onAccept={onChange}
/>
);
};

View File

@ -10,9 +10,10 @@ import {
Text,
useCombobox,
} from "@mantine/core";
import style from "@/components/PhoneInput/PhoneInput.module.css";
import { Country } from "@/components/PhoneInput/types";
import countryOptionsDataMap from "@/components/PhoneInput/utils/countryOptionsDataMap";
import style from "@/components/ui/PhoneInput/PhoneInput.module.css";
import { Country } from "@/components/ui/PhoneInput/types";
import countryOptionsDataMap from "@/components/ui/PhoneInput/utils/countryOptionsDataMap";
const countryOptionsData = Object.values(countryOptionsDataMap);

View File

@ -1,9 +1,9 @@
import countries from "i18n-iso-countries";
import ru from "i18n-iso-countries/langs/ru.json";
import { type CountryCode, getCountries } from "libphonenumber-js";
import getFlagEmoji from "@/components/PhoneInput/utils/getFlagEmoji";
import getFlagEmoji from "@/components/ui/PhoneInput/utils/getFlagEmoji";
import { getCountryCallingCode } from "libphonenumber-js/max";
import { Country } from "@/components/PhoneInput/types";
import { Country } from "@/components/ui/PhoneInput/types";
countries.registerLocale(ru);

View File

@ -1,7 +1,7 @@
import { CountryCode } from "libphonenumber-js";
import { Country } from "@/components/PhoneInput/types";
import countryOptionsDataMap from "@/components/PhoneInput/utils/countryOptionsDataMap";
import getPhoneMask from "@/components/PhoneInput/utils/getPhoneMask";
import { Country } from "@/components/ui/PhoneInput/types";
import countryOptionsDataMap from "@/components/ui/PhoneInput/utils/countryOptionsDataMap";
import getPhoneMask from "@/components/ui/PhoneInput/utils/getPhoneMask";
type InitialDataFromValue = {
country: Country;

8
src/constants/scopes.ts Normal file
View File

@ -0,0 +1,8 @@
import { Scopes } from "@/enums/Scopes";
const SCOPES = {
[Scopes.UNDEFINED]: "",
[Scopes.OPENID]: "доступ к учетной записи и номеру телефона",
};
export default SCOPES;

4
src/enums/Scopes.ts Normal file
View File

@ -0,0 +1,4 @@
export enum Scopes {
OPENID = "openid",
UNDEFINED = "",
}

6
src/hey-api-config.ts Normal file
View File

@ -0,0 +1,6 @@
import type { CreateClientConfig } from './client/client.gen';
export const createClientConfig: CreateClientConfig = (config) => ({
...config,
baseUrl: process.env.NEXT_PUBLIC_API_URL,
});

View File

@ -0,0 +1 @@
export * from "./notifications";

View File

@ -0,0 +1,46 @@
import { notifications } from "@mantine/notifications";
type CustomNotifications = {
notify: (...params: Parameters<typeof notifications.show>) => void;
success: (...params: Parameters<typeof notifications.show>) => void;
warn: (...params: Parameters<typeof notifications.show>) => void;
error: (...params: Parameters<typeof notifications.show>) => void;
guess: (
ok: boolean,
...params: Parameters<typeof notifications.show>
) => void;
} & typeof notifications;
const customNotifications: CustomNotifications = {
...notifications,
notify: params => {
return notifications.show({
...params,
color: "blue",
});
},
success: params => {
return notifications.show({
...params,
color: "green",
});
},
warn: params => {
return notifications.show({
...params,
color: "yellow",
});
},
error: params => {
return notifications.show({
...params,
color: "red",
});
},
guess: (ok: boolean, params) => {
if (ok) return customNotifications.success(params);
return customNotifications.error(params);
},
};
export { customNotifications as notifications };

View File

@ -0,0 +1,34 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Scopes } from "@/enums/Scopes";
interface AuthState {
loginChallenge: string | null;
phoneNumber: string | null;
scope: Scopes[];
}
const initialState: AuthState = {
loginChallenge: null,
phoneNumber: null,
scope: [],
};
export const authSlice = createSlice({
name: "authentication",
initialState,
reducers: {
setLoginChallenge: (state, action: PayloadAction<string | null>) => {
state.loginChallenge = action.payload;
},
setPhoneNumber: (state, action: PayloadAction<string | null>) => {
state.phoneNumber = action.payload;
},
setScope: (state, action: PayloadAction<Scopes[]>) => {
state.scope = action.payload;
}
},
});
export const { setLoginChallenge, setPhoneNumber, setScope } = authSlice.actions;
export default authSlice.reducer;

View File

@ -0,0 +1,12 @@
import { combineReducers } from "@reduxjs/toolkit";
import authReducer from "@/lib/store/features/auth/authSlice";
import targetServiceReducer from "@/lib/store/features/targetService/targetServiceSlice";
import verificationReducer from "@/lib/store/features/verification/verificationSlice";
const rootReducer = combineReducers({
targetService: targetServiceReducer,
verification: verificationReducer,
auth: authReducer,
});
export default rootReducer;

View File

@ -1,19 +1,19 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ServiceCode } from "@/enums/ServiceCode";
import { Scopes } from "@/enums/Scopes";
interface TargetServiceState {
serviceCode: ServiceCode;
serviceCode: Scopes;
}
const initialState: TargetServiceState = {
serviceCode: ServiceCode.UNDEFINED,
serviceCode: Scopes.UNDEFINED,
};
export const targetServiceSlice = createSlice({
name: "targetService",
initialState,
reducers: {
setTargetService: (state, action: PayloadAction<ServiceCode>) => {
setTargetService: (state, action: PayloadAction<Scopes>) => {
state.serviceCode = action.payload;
},
},

View File

@ -2,12 +2,12 @@ import { configureStore } from "@reduxjs/toolkit";
import { useDispatch } from "react-redux";
import { persistReducer, persistStore } from "redux-persist";
import storage from "redux-persist/lib/storage";
import rootReducer from "@/lib/features/rootReducer";
import rootReducer from "@/lib/store/features/rootReducer";
const persistConfig = {
key: "root",
storage,
whitelist: ["targetService", "verification"],
whitelist: ["targetService", "verification", "auth"],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);

View File

@ -3,7 +3,7 @@
import { ReactNode } from "react";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { persistor, store } from "@/lib/store";
import { persistor, store } from "@/lib/store/store";
type Props = {
children: ReactNode;

View File

@ -1,7 +1,7 @@
{
"compilerOptions": {
"types": ["node", "jest", "@testing-library/jest-dom"],
"target": "es5",
"target": "es2015",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
@ -16,10 +16,10 @@
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": ["./*"]
"@/*": ["./src/*"]
},
"plugins": [{ "name": "next" }]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
"exclude": ["node_modules", "src/client/*"]
}

View File

@ -1,10 +0,0 @@
import { ServiceCode } from "@/enums/ServiceCode";
type ServiceData = {
code: ServiceCode;
name: string;
link: string;
requiredAccesses: string;
}
export default ServiceData;

9625
yarn.lock

File diff suppressed because it is too large Load Diff