UNPKG

nabii-sdk

Version:

Private SDK of Nabii by Ulysse Dupont

1,593 lines (1,572 loc) 46.4 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; // src/v1/error.ts import * as stackTraceParser from "stacktrace-parser"; // src/v1/lang/en/error.json var error_default = { missing_credentials: "Internal SDK error: Missing authentication access token", missing_login: "Internal SDK error: You should be logged to access this method", missing_permission: "Internal SDK error: You currently not have permission to access this method of the platform {platform}", invalid_language: "Internal SDK error: SDK Language modification failed, new value is incorrect. -> \xAB {language} \xBB", invalid_url: "Internal SDK error: Modification of the SDK URL has failed, the format is incorrect. -> \xAB {url} \xBB", invalid_mode: "SDK internal error: SDK mode modification failed, new value is invalid. -> \xAB {mode} \xBB", invalid_credentials: "Internal SDK error: The format of the authentication tokens is incorrect. -> \xAB {err} \xBB", firebase_granted: "Internal SDK error: Push notifications permission not granted", firebase_platform: "Internal SDK error: the \xAB PushNotifications \xBB plugin is not implemented on the web. Use the method: \xAB nabii.v1.Notification.disable() \xBB pour disable the plugin." }; // src/v1/lang/fr/error.json var error_default2 = { missing_credentials: "Erreur interne du SDK : Jeton d'acc\xE8s d'authentification manquant", missing_login: "Erreur interne du SDK : Vous devez \xEAtre connect\xE9 pour acc\xE9der \xE0 cette m\xE9thode", missing_permission: "Erreur interne du SDK : Vous n'avez pas la permission d'acc\xE9der \xE0 cette m\xE9thode de la plateforme {platform}", invalid_language: "Erreur interne du SDK : La modification de la langue du SDK a \xE9chou\xE9, la nouvelle valeur est incorrecte. -> \xAB {language} \xBB", invalid_url: "Erreur interne du SDK : La modification de l'URL du SDK a \xE9chou\xE9, le format est incorrecte. -> \xAB {url} \xBB", invalid_mode: "Erreur interne du SDK : La modification du mode du SDK a \xE9chou\xE9, la nouvelle valeur est incorrecte. -> \xAB {mode} \xBB", invalid_credentials: "Erreur interne du SDK : Le format des jetons d'authentification est incorrect. -> \xAB {err} \xBB", firebase_granted: "Erreur interne du SDK : La permission des notifications push n'est pas accord\xE9e", firebase_platform: "Erreur interne du SDK : le plugin \xAB PushNotifications \xBB n'est pas impl\xE9ment\xE9 sur le web. Utilisez la m\xE9thode: \xAB nabii.v1.Notification.disable() \xBB pour d\xE9sactiver le plugin." }; // src/v1/error.ts import { AxiosError } from "axios"; var errors = { fr: error_default2, en: error_default }; var NabiiError = class _NabiiError extends AxiosError { constructor(error) { super( error.message, error.code, error.config, error.request, error.response ); Object.setPrototypeOf(this, _NabiiError.prototype); this.name = "NabiiError"; } }; function errorParser(key, lang, payload = {}) { const error = new Error(); let data = errors[lang][key]; Object.entries(payload).forEach(([key2, value]) => { data = data.replaceAll(`{${key2}}`, `${value}`); }); const stacks = stackTraceParser.parse(error.stack); for (let i = 0; i < stacks.length; i++) { const stack = stacks[i]; if (!stack?.file?.includes("sdk\\dist\\.")) { const file = stack ? ` (file:"${stack.file}:${stack.lineNumber}:${stack?.column}")` : ""; return new Error(`${data}${file}`); } } return new Error(key); } // src/v1/config.ts var ConfigV1 = class { constructor() { /** * ⚠️ Use `setLang()` to modify the language ⚠️ */ this.lang = "fr"; /** * ⚠️ Use `setUrl()` to modify the url ⚠️ */ this.url = "http://localhost:1338"; /** * ⚠️ Use `setMode()` to modify the mode ⚠️ */ this.mode = "production"; this.isLogged = false; this.platform = "application" /* APPLICATION */; this.allowSocket = true; this.allowFirebaseToken = false; this.credentials = {}; this.errorHandler = () => void 0; this.eventListener = { login: [], logout: [], refresh: [] }; } get roles() { return { BANNED: 0, USER: 100, SUPERVISOR: 150, ADMIN: 200 }; } get strategies() { return { LOCAL: "local", GOOGLE: "google", FACEBOOK: "facebook", APPLE: "apple" }; } }; var configV1 = new ConfigV1(); var languages = { /** * French language. * @default */ FR: "fr", /** * English language. */ EN: "en" }; var modes = { /** * {@link modes}: * - `test` mode for unit testing */ TEST: "test", /** * {@link modes}: * - `production` mode * @default */ PRODUCTION: "production" }; // src/instances.ts import axios from "axios"; import { io } from "socket.io-client"; var Axios = class { static { /** * Axios WEB Client for Nabii v1 API */ this.v1 = axios.create(); } }; var SocketIo = class { static { /** * Axios WEB socket Client for Nabii v1 API */ this.v1 = (...config) => io(...config); } }; // src/v1/schemas.ts import { z } from "zod"; var languageSchema = z.nativeEnum(languages); function transformUrl(url) { const newUrl = url.replace(/\\/g, "/"); if (newUrl.endsWith("/") || newUrl.endsWith("\\")) { return transformUrl(newUrl.slice(0, -1)); } return newUrl; } var urlSchema = z.string().url().transform(transformUrl); var modeSchema = z.nativeEnum(modes); var credentialSchema = z.object({ accessToken: z.string().trim(), refreshToken: z.string().trim(), user: z.object({ id: z.number(), firstName: z.string(), lastName: z.string(), avatar: z.string().url(), strategy: z.nativeEnum(configV1.strategies), email: z.string().trim().email(), role: z.nativeEnum({ ...configV1.roles }), firebaseToken: z.string().trim().nullable(), lastConnection: z.string().datetime().nullable(), isActivated: z.boolean() }) }); // src/v1/base.ts import { PushNotifications } from "@capacitor/push-notifications"; import { FirebaseMessaging } from "@capacitor-firebase/messaging"; import { AxiosError as AxiosError2 } from "axios"; var BaseV1 = class { constructor() { this._axios = Axios.v1; this._config = configV1; } _initAxiosHooks() { this._axios.interceptors.request.use((config) => { config.url = `${this._config.url}${config.url}`; config.responseType = "json"; if ("accessToken" in this._config.credentials) { config.headers["Authorization"] = `Bearer ${this._config.credentials.accessToken}`; } config.headers.lang = this._config.lang; config.headers.mode = this._config.mode; return config; }); this._axios.interceptors.response.use( (response) => response.data, //*ON SUCCESS* async (err) => { if (err instanceof AxiosError2 && err.response?.status !== 401 && err.config?.url !== `${this._config.url}/`) { return this._throwError(err); } throw err instanceof AxiosError2 ? new NabiiError(err) : err; } //!ON ERROR! ); } async _throwError(err) { await this._config.errorHandler(err); throw err instanceof AxiosError2 ? new NabiiError(err) : err; } _initSocket() { this._config.socket = SocketIo.v1(this._config.url, { withCredentials: true, secure: true, auth: { token: null, platform: this._config.platform }, autoConnect: false }); } _updateSocketConnection() { if ("accessToken" in this._config.credentials) { this._config.socket.auth = { token: `Bearer ${this._config.credentials.accessToken}`, platform: this._config.platform }; if (!this._config.allowSocket) return Promise.resolve(void 0); return this._connectSocket(); } else { throw errorParser("missing_credentials", this._config.lang); } } _connectSocket() { return new Promise((resolve, reject) => { this._config.socket.connect(); this._config.socket.on("connect_error", reject); if (this._config.socket.connected) { resolve(); } else { this._config.socket.on("connect_success", resolve); } }); } _disconnectSocket() { return new Promise((resolve) => { this._config.socket.disconnect(); if (this._config.socket.connected) { this._config.socket.on("disconnect", () => resolve()); } else { resolve(); } }); } async _resetSocket() { if (this._config.socket.connected) { await this._disconnectSocket(); } this._initSocket(); if (this._config.isLogged) { await this._updateSocketConnection(); } } async _triggerEventListener(eventName, ...payload) { const params = payload.map((p) => p); for (const trigger of this._config.eventListener[eventName]) { await trigger(...params); } } _refresh() { return new Promise((resolve, reject) => { const { refreshToken, accessToken } = this._config.credentials; if (!refreshToken || !accessToken) { throw errorParser("missing_credentials", this._config.lang); } this._axios.post("/auth/refresh", { refreshToken }).then((credentials) => { this._config.credentials = { ...this._config.credentials, ...credentials }; this._config.isLogged = true; Promise.all([ this._updateSocketConnection(), this._triggerEventListener("refresh", this._config.credentials) ]).then(() => resolve(credentials)); }).catch(reject); }); } async _logout() { if (this._config.isLogged && this._config.platform === "application" /* APPLICATION */) { if (this._config.allowFirebaseToken) { await this._disableFirebaseToken(); } this._config.credentials = {}; this._config.isLogged = false; this._config.socket.off(); await this._disconnectSocket(); } await this._triggerEventListener("logout"); } async _setCredentials(credentials) { try { this._config.credentials = { ...this._config.credentials, ...credentialSchema.partial().parse(credentials) }; } catch (err) { throw errorParser("invalid_credentials", this._config.lang, { err }); } const result = await this._refresh(); await this._checkEnableFirebaseToken(); return result; } async _checkEnableFirebaseToken() { if (this._config.allowFirebaseToken) { await this._enableFirebaseToken(); } } async _enableFirebaseToken() { try { const { receive } = await PushNotifications.requestPermissions(); if (receive === "granted") { await PushNotifications.register(); const { token: firebaseToken } = await FirebaseMessaging.getToken(); await this._axios.patch("/user/add-token", { firebaseToken }); this._config.firebaseToken = firebaseToken; } else { throw errorParser("firebase_granted", this._config.lang); } } catch (err) { if (err instanceof NabiiError) { throw err; } else { throw errorParser("firebase_platform", this._config.lang); } } } async _disableFirebaseToken() { await this._axios.patch("/user/remove-token"); this._config.firebaseToken = void 0; } }; // src/v1/decorators.ts function Logged(_, __, descriptor) { if (!descriptor.value) { throw new TypeError("Invalid property descriptor"); } const original = descriptor.value; descriptor.value = function(...args) { if (!this._config.isLogged || !("accessToken" in this._config.credentials)) { throw errorParser("missing_login", this._config.lang); } return original.apply(this, args); }; return descriptor; } function Permission(platform) { return function(_, __, descriptor) { if (!descriptor.value) { throw new TypeError("Invalid property descriptor"); } const original = descriptor.value; descriptor.value = function(...args) { if (platform !== this._config.platform) { throw errorParser("missing_permission", this._config.lang, { platform }); } return original.apply(this, args); }; return descriptor; }; } function Refresh(_, __, descriptor) { if (!descriptor.value) { throw new TypeError("Invalid property descriptor"); } const original = descriptor.value; descriptor.value = async function(...args) { try { return await original.apply(this, args); } catch (err) { if (err instanceof NabiiError) { if (err.response?.status === 401) { await this._refresh(); return original.apply(this, args); } throw err; } } }; return descriptor; } // src/v1/modules/socket/socket.sdk.ts var SocketV1 = class extends BaseV1 { emit(evName, ...payload) { this._config.socket.emit(evName.toString(), ...payload); } /** * @public * `📱 SOCLE 📱` * #### ⬇️ Receive a socket from the server ⬇️ * @param evName the name of the target socket event refer to {@link IOnEvents} * @param listener the listener to apply to this event refer to {@link IOnEvents} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * nabii.v1.Socket.on("pong", msg => { * console.log("Message:", msg); * }); * ``` * @returns a void function * @since v1.0.0 */ on(evName, listener) { this._config.socket.on(evName.toString(), listener); } /** * @public * `📱 SOCLE 📱` * #### 🗑️ Kill a socket event from the server 🗑️ * @param evName the name of the target socket event refer to {@link IOnEvents} * @param listener the listener to apply to this event refer to {@link IOnEvents} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * nabii.v1.Socket.off("pong", msg => { * console.log("Message:", msg); * }); * nabii.v1.Socket.off("pong"); * ``` * @returns a void function * @since v1.0.0 */ off(evName, listener) { this._config.socket.off(evName.toString(), listener); } /** * @public * `📱 SOCLE 📱` * #### 🔗 Check if socket is connected to {@link NabiiV1} (you must call the `login` or `setCredential` method before) 🔗 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * if (nabii.v1.Socket.isLogged()) { * console.log("Socket is up!"); * } * ``` * @returns the login as socket state * @since v1.0.0 */ isLogged() { return this._config.socket.connected && this._config.isLogged && this._config.platform === "application" /* APPLICATION */; } /** * @public * `📱 SOCLE 📱` * #### ✅ Enable socket connection to {@link NabiiV1} ✅ * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * await nabii.v1.Socket.enable(); * console.log("Socket is up!"); * ``` * @returns a void function * @since v1.0.0 */ enable() { this._config.allowSocket = true; return this._connectSocket(); } /** * @public * `📱 SOCLE 📱` * #### ❌ Disable socket connection to {@link NabiiV1} ❌ * @example * ```tsx * import { nabii } from "nabii-sdk"; * * import { nabii } from "nabii-sdk"; * * await nabii.v1.Socket.disable(); * console.log("Socket is down!"); * ``` * @returns a void function * @since v1.0.0 */ disable() { this._config.allowSocket = false; return this._disconnectSocket(); } }; __decorateClass([ Permission("application" /* APPLICATION */) ], SocketV1.prototype, "emit", 1); // src/form.ts import FormData from "form-data"; import { fileTypeFromBuffer } from "file-type"; async function useFormData(data, propertyGuard) { try { if (typeof data !== "object") { throw new Error("Form Data should be an object."); } const form = new FormData(); const appendToFormData = async (key, value) => { if (Buffer.isBuffer(value)) { const fileType = await fileTypeFromBuffer(value); if (!fileType) throw new Error("Unknown extension type."); form.append(key, value, `${key}.${fileType.ext}`); } else if (value instanceof Blob) { const arrayBuffer = await value.arrayBuffer(); const fileType = await fileTypeFromBuffer(Buffer.from(arrayBuffer)); if (!fileType) throw new Error("Unknown extension type."); form.append(key, value, `${key}.${fileType.ext}`); } else { form.append(key, `${value}`); } }; for (const [key, value] of Object.entries(data)) { if (!value || propertyGuard && !propertyGuard.some((p) => p === key)) { continue; } if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { await appendToFormData(`${key}[${i}]`, value[i]); } } else { await appendToFormData(key, value); } } form.append("__timestamp__", (/* @__PURE__ */ new Date()).getTime().toString()); return form; } catch (error) { if (error instanceof Error) { throw new NabiiError({ message: error.message, isAxiosError: false, toJSON: () => ({}), name: error.name }); } else { throw new NabiiError({ message: `${error}`, isAxiosError: false, toJSON: () => ({}), name: "Internal Error" }); } } } // src/v1/modules/auth/auth.sdk.ts var AuthV1 = class extends BaseV1 { /** * @public * `📱 SOCLE 📱` * #### 🔑 Get the login `href` URL to {@link NabiiV1} Oauth SSO strategy 🔑 * @description this URL will redirect you to the SSO provider login page, on success, the callback will be called and open the application * page `/login/cb` with query params `{accessToken, refreshToken, strategy}`, then you will have to call the SDK method {@link AuthV1.setCredentials} method with the query params and finally redirect to the home page to be connected. * @example * ```tsx * <a href={nabii.v1.Auth.strategy("google")}>Sign in with Google</a> * <a href={nabii.v1.Auth.strategy("apple")}>Sign in with Apple</a> * <a href={nabii.v1.Auth.strategy("facebook")}>Sign in with Facebook</a> * ``` * @param name The strategy names used to authenticate users with SSO. * - `google` *(implemented)* : the strategy used to authenticate with [Google SSO](https://console.developers.google.com/). * - `facebook` *(not implemented)* : the strategy used to authenticate with [Facebook SSO](https://developers.facebook.com/). * - `apple` *(not implemented)* : the strategy used to authenticate with [Apple SSO](https://developer.apple.com/account/). * @returns the server URL to handle SSO login request * @since v1.0.10 */ strategy(name) { return `${this._config.url}/auth/${name}`; } /** * The list of strategies used to authenticate users. * - `google` *(implemented)* : the strategy used to authenticate with [Google SSO](https://console.developers.google.com/). * - `facebook` *(not implemented)* : the strategy used to authenticate with [Facebook SSO](https://developers.facebook.com/). * - `apple` *(not implemented)* : the strategy used to authenticate with [Apple SSO](https://developer.apple.com/account/). * @returns the server URL to handle SSO login request * @since v1.0.19 */ get strategies() { return configV1.strategies; } /** * @public * `📱 SOCLE 📱` * #### 🆕 Create a new {@link NabiiV1} {@link IUser} 🆕 * @param data user data to create * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const user = await nabii.v1.User.Admin.create({ * firstName : "MyName", * lastName: "MyLastName", * email: "email@domain.com", * password: "my_password", * }); // {...} * ``` * @returns the created {@link IUser} object * @since v1.0.0 */ async register(data) { const formData = await useFormData(data, [ "email", "password", "firstName", "lastName", "avatar" ]); return this._axios.post("/user", formData); } /** * @public * `📱 SOCLE 📱` * ### ♻️ Callback email creation to get another email sent ♻️ * @param email your email address to receive an email * @example * ```ts * await nabii.v1.Auth.callbackActivateAccount("email@domain.com"); // {...} * ``` * @returns the object result of email receive * @since v1.0.12 */ callbackActivateAccount(email) { return this._axios.post("/auth/activate-account/callback", { email }); } /** * @public * `📱 SOCLE 📱` * #### 🔐 Login to {@link NabiiV1} 🔐 * *ℹ If you are already logged in from storage, use the {@link AuthV1.setCredentials} method instead. ℹ* * @param email Your {@link NabiiV1} email address * @param password Your {@link NabiiV1} account password * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { accessToken } = await nabii.v1.Auth.login( * "email@domain.com", * "my_password" * ); * console.log("I am logged!"); * ``` * @returns the {@link ICredentials} object * @since v1.0.0 */ login(email, password) { return new Promise((resolve, reject) => { this._axios.post("/auth/login", { email, password }).then((credentials) => { try { this._config.credentials = credentialSchema.parse(credentials); } catch (err) { throw errorParser("invalid_credentials", this._config.lang, { err }); } this._config.isLogged = true; this._config.platform = "application" /* APPLICATION */; Promise.all([ this._updateSocketConnection(), this._triggerEventListener("login", this._config.credentials), this._checkEnableFirebaseToken() ]).then(() => resolve(credentials)).catch( (err) => this._logout().then( () => reject(err instanceof Error ? err : new Error(`${err}`)) ) ); }).catch(reject); }); } /** * @public * `📱 SOCLE 📱` * #### 📡 Set credentials to {@link NabiiV1} when you're already logged in from `storage` 📡 * @param credentials app credentials (accessToken, refreshToken and user object: {@link ICredentials}) * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const { accessToken, refreshToken, user } = storage; * await nabii.v1.Auth.setCredentials({ * accessToken, * refreshToken, * user, * }); * ``` * @returns the {@link ICredentials} `accessToken` up-to-date * @since v1.0.0 */ setCredentials(credentials) { return this._setCredentials(credentials); } /** * @public * `📱 SOCLE 📱` * #### 📡 Get credentials when you're already logged 📡 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * if (!nabii.v1.Auth.isLogged()) { * throw new Error("Not logged!"); * } * const { * accessToken, * refreshToken, * user * } = await nabii.v1.Auth.getCredentials(); * ``` * @returns the {@link ICredentials} object * @since v1.0.0 */ getCredentials() { return this._config.credentials; } /** * @public * `📱 SOCLE 📱` * #### 🔗 Check if your are connected to {@link NabiiV1} API 🔗 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * if (nabii.v1.Auth.isLogged()) { * console.log("I am logged!"); * const { user } = nabii.v1.Auth.getCredentials(); * console.log(`Hello ${user.firstName}!`); * } * ``` * @returns a `boolean` at true if you are logged * @since v1.0.0 */ isLogged() { return this._config.isLogged && this._config.platform === "application" /* APPLICATION */; } /** * @public * `📱 SOCLE 📱` * #### 🔗 Check if your are connected to {@link NabiiV1} API as `administrator` 🔗 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * if (nabii.v1.Auth.isAdmin()) { * console.log("I am logged as administrator!"); * const { user } = nabii.v1.Auth.getCredentials(); * console.log(`Hello ${user.firstName}!`); * } * ``` * @returns a `boolean` at true if you are logged as administrator * @since v1.0.0 */ isAdmin() { return this.isLogged() && !!this._config.credentials.user && this._config.credentials.user.role === this._config.roles.ADMIN; } me() { return this._axios.get("/auth/me"); } /** * @public * `📱 SOCLE 📱` * #### 🛌 Logout from {@link NabiiV1} 🛌 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * await nabii.v1.Auth.logout(); * ``` * @returns a void function * @since v1.0.0 */ logout() { return this._logout(); } /** * @public * `📱 SOCLE 📱` `🖥️ ADMIN 🖥️` * #### ♻️ Receive an email to reset your password ♻️ * @param email your email address to receive an email * @example * ```tsx * import { nabii } from "nabii-sdk"; * * await nabii.v1.Auth.forgotPassword(myEmail); // {...} * ``` * @returns the {@link IEmailSentResult} object result of email receive * @since v1.0.0 */ forgotPassword(email) { return this._axios.post("/auth/forgot-password", { email }); } /** * `📱 SOCLE 📱` * #### ♻️ Callback email creation to get another email sent ♻️ * @param token your email link `JWT` request token * @param subject the subject of the email: {@link IEmailSubject} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/reset-password?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * const {tokenIsValid} = await nabii.v1.Auth.checkTokenValidity(token, "forgotPassword"); // true | false * ``` * @returns the {@link ICheckTokenResponseType} object representing the token validity and user information. * @since v1.0.0 */ checkTokenValidity(token, subject) { return this._axios.get( `/auth/check-token?token=${token}&subject=${subject}` ); } /** * `📱 SOCLE 📱` * #### ✅ Activate your {@link NabiiV1} account when you have changed your email ✅ * @param token your email link `JWT` request token with subject `"activateAccount"` * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/activate-account?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * if (await nabii.v1.Auth.checkTokenValidity(token, "activateAccount")) { * await nabii.v1.Auth.activateAccount(token); // {...} * } * ``` * @returns the {@link IUserUpdatedResult} object result of updated user * @since v1.0.0 */ activateAccount(token) { return this._axios.patch("/auth/activate-account", { token }); } /** * `📱 SOCLE 📱` * #### 💾 Set your new {@link NabiiV1} account password 💾 * @param token your email link `JWT` request token with subject `"activateAccountInvite"` * @param password the new password of your {@link NabiiV1} account * - must contain at least `8 characters` * - must contain a maximum of `64 characters` * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/set-password?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * if (await nabii.v1.Auth.checkTokenValidity(token, "activateAccountInvite")) { * const password = "@TestNabii1"; * await nabii.v1.Auth.setPassword(token, password); // {...} * } * ``` * @returns the {@link IUserUpdatedResult} object result of updated user * @since v1.0.0 */ setPassword(token, password) { return this._axios.patch("/auth/set-password", { token, password }); } /** * `📱 SOCLE 📱` * #### ♻️ Reset your {@link NabiiV1} account password ♻️ * @param token your email link `JWT` request token with subject `"forgotPassword"` * @param newPassword the new password of your {@link NabiiV1} account * - must contain at least `8 characters` * - must contain a maximum of `64 characters` * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // "/auth/reset-password?token={TOKEN}"; * const { query } = useRouter(); * const { token } = query; * if (await nabii.v1.Auth.checkTokenValidity(token, "forgotPassword")) { * const password = "@TestNabii1"; * await nabii.v1.Auth.resetPassword(token, password); // {...} * } * ``` * @returns the {@link IUserUpdatedResult} object result of updated user * @since v1.0.0 */ resetPassword(token, newPassword) { return this._axios.patch("/auth/reset-password", { token, password: newPassword }); } }; __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AuthV1.prototype, "me", 1); // src/v1/mixins.ts function applyMixins(derivedCtor, childCtors) { const generateBaseV1 = () => { return class GeneratedBaseV1 extends BaseV1 { }; }; childCtors.forEach(([className, childCtor]) => { const generatedBaseV1 = generateBaseV1(); Object.getOwnPropertyNames(childCtor.prototype).forEach((propertyKey) => { if (propertyKey !== "constructor") { const attributes = Object.getOwnPropertyDescriptor( childCtor.prototype, propertyKey ); if (attributes) { Object.defineProperty( generatedBaseV1.prototype, propertyKey, attributes ); } } }); Object.defineProperty(derivedCtor.prototype, className, { value: new generatedBaseV1(), writable: false, enumerable: false, configurable: false }); }); } var AdminMixin = class extends BaseV1 { }; function WithModules(modules) { return function(constructor) { applyMixins(constructor, Object.entries(modules)); }; } function Admin(module) { return function(constructor) { applyMixins(constructor, [ [ "admin" /* ADMIN */.charAt(0).toLocaleUpperCase() + "admin" /* ADMIN */.slice(1), module ] ]); }; } // src/v1/modules/user/admin.user.sdk.ts var AdminUserV1 = class extends BaseV1 { getAllPending(params) { return this._axios.get("/admin/user/pending", { params }); } getAll(params) { return this._axios.get("/admin/user", { params }); } getByPk(pk) { return this._axios.get(`/admin/user/${pk}`); } async create(data) { const formData = await useFormData(data, [ "avatar", "email", "firstName", "lastName" ]); return this._axios.post("/admin/user", formData); } async update(pk, data) { const formData = await useFormData(data, [ "avatar", "email", "firstName", "lastName" ]); return this._axios.patch(`/admin/user/${pk}`, formData); } async delete(pk) { await this._axios.delete(`/admin/user/${pk}`); } updateRole(pk, newRole) { return this._axios.patch(`/admin/user/${pk}/role`, { role: newRole }); } getAllAdmins(params) { return this._axios.get("/admin/user/admin", { params }); } export() { return this._axios.get("/admin/user/export"); } import(users) { return this._axios.post("/admin/user/import", { users }); } }; __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "getAllPending", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "getAll", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "getByPk", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "create", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "update", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "delete", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "updateRole", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "getAllAdmins", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "export", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminUserV1.prototype, "import", 1); // src/v1/modules/user/users.sdk.ts var UserV1 = class extends AdminMixin { /** * `📱 SOCLE 📱` * * List of user roles. * * This interface defines the various roles a user can have in {@link NabiiV1}. * Each role is associated with a specific integer value. * * @interface {@link IRoles} */ get roles() { return this._config.roles; } emailIsAvailable(email) { return this._axios.get(`/user/check-email/${email}`); } async updateMe(data) { const formData = await useFormData(data, [ "avatar", "firstName", "lastName", "password" ]); return this._axios.patch("/user", formData); } async deleteMe() { await this._axios.delete("/user"); if (this._config.isLogged && this._config.platform === "application" /* APPLICATION */) { this._config.credentials = {}; this._config.isLogged = false; await this._disconnectSocket(); await this._triggerEventListener("logout"); } } checkPassword(password) { if (!password) return Promise.resolve(false); return this._axios.get(`/user/check-password/${password}`); } changeEmail(email) { return this._axios.patch("/user/email", { email }); } }; __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], UserV1.prototype, "updateMe", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], UserV1.prototype, "deleteMe", 1); __decorateClass([ Logged, Refresh ], UserV1.prototype, "checkPassword", 1); __decorateClass([ Logged, Refresh ], UserV1.prototype, "changeEmail", 1); UserV1 = __decorateClass([ Admin(AdminUserV1) ], UserV1); // src/v1/modules/notification/notification.sdk.ts import { PushNotifications as PushNotifications2 } from "@capacitor/push-notifications"; var NotificationV1 = class extends BaseV1 { /** * `📱 SOCLE 📱` * `🖥️ ADMIN 🖥️` * #### 💬 Current firebase messaging push token 💬 * @since v1.0.0 * @default undefined */ get token() { return this._config.firebaseToken; } get addEventListener() { if (!this._config.allowFirebaseToken) { throw errorParser("firebase_platform", this._config.lang); } return PushNotifications2.addListener; } get removeAllListeners() { if (!this._config.allowFirebaseToken) { throw errorParser("firebase_platform", this._config.lang); } return PushNotifications2.removeAllListeners; } /** * `📱 SOCLE 📱` * `🖥️ ADMIN 🖥️` * #### 💬 Enable firebase messaging instance to get a push token 💬 * ##### *if you are working with a phone platform* * @example * ```tsx * import { nabii } from "nabii-sdk"; * import { Capacitor } from "@capacitor/core"; * * const platform = Capacitor.getPlatform(); * if (platform === "ios" || platform === "android") { * await nabii.v1.Notification.enable(); * } * ``` * @returns a void function * @since v1.0.0 * @default enable=false */ async enable() { this._config.allowFirebaseToken = true; if (this._config.isLogged) { return this._enableFirebaseToken(); } } /** * `📱 SOCLE 📱` * `🖥️ ADMIN 🖥️` * #### 💬 Disabled firebase messaging 💬 * ##### *if you are working with a web platform* * @example * ```tsx * import { nabii } from "nabii-sdk"; * * // disabled notification for WEB platform! * await nabii.v1.Notification.disable(); * ``` * @returns a void function * @since v1.0.0 * @default enable=false */ async disable() { this._config.allowFirebaseToken = false; if (this._config.isLogged) { await this._disableFirebaseToken(); } } }; // src/v1/modules/version/admin.version.sdk.ts var AdminVersionV1 = class extends BaseV1 { getAll(params) { return this._axios.get("/admin/version", { params }); } getByPk(pk) { return this._axios.get(`/admin/version/${pk}`); } create(data) { return this._axios.post("/admin/version", data); } }; __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminVersionV1.prototype, "getAll", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminVersionV1.prototype, "getByPk", 1); __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], AdminVersionV1.prototype, "create", 1); // src/v1/modules/version/version.sdk.ts var VersionV1 = class extends AdminMixin { /** * `📱 SOCLE 📱` * * List of version types. * * This interface defines the various types a version can have in {@link NabiiV1}. * Each type is associated with a specific string value. * * @interface {@link IVersionTypes} */ get types() { return { MAJOR: "major", MINOR: "minor", PATCH: "patch" }; } check(name) { return this._axios.get(`/version/check/${name}`); } }; __decorateClass([ Logged, Permission("application" /* APPLICATION */), Refresh ], VersionV1.prototype, "check", 1); VersionV1 = __decorateClass([ Admin(AdminVersionV1) ], VersionV1); // src/v1/modules/index.ts var modulesV1 = { /** * 📦 {@link SocketV1} module 📦 * @since v1.0.0 */ Socket: SocketV1, /** * 📦 {@link AuthV1} module 📦 * @since v1.0.0 */ Auth: AuthV1, /** * 📦 {@link UserV1} module 📦 * @since v1.0.0 */ User: UserV1, /** * 📦 {@link NotificationV1} module 📦 * @since v1.0.0 */ Notification: NotificationV1, /** * 📦 {@link VersionV1} module 📦 * @since v1.0.0 */ Version: VersionV1 }; // src/v1/index.ts var NabiiV1 = class extends BaseV1 { /** * @constructor Initialize axios hooks */ constructor() { super(); this._initAxiosHooks(); this._initSocket(); } /** * @public * `🌐 GLOBAL 🌐` * #### 🏓 Attempt to reach {@link NabiiV1} API with current `url` 🏓 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * if (!(await nabii.v1.resolve())) { * console.log("Can't reach the server!"); * } * ``` * @returns the {@link NabiiV1} resolve status * @since v1.0.0 */ async resolve() { try { await this._axios.get("/ping"); return true; } catch (error) { return error instanceof NabiiError && !!error.response; } } /** * @public * `🌐 GLOBAL 🌐` * #### ⛔️ Set {@link NabiiV1} error callback function ⛔️ * @param callback your callback function that never return (throw an error) * @example * ```tsx * import { nabii } from "nabii-sdk"; * * nabii.v1.onError((_) => { * if (err.response) { * console.log(err.response.data); * } else { * console.log("No internet connection!"); * } * }); * ``` * @default (_) => void 0; * @returns the {@link NabiiV1} instance updated * @since v1.0.0 */ onError(callback) { this._config.errorHandler = callback; return this; } /** * @public * `🌐 GLOBAL 🌐` * #### 🔠 Get {@link NabiiV1} response `language` 🔠 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const language = nabii.v1.getLang(); * console.log(language); // "fr" * ``` * @default "fr" * @returns the current {@link NabiiV1} error {@link ILanguage} * @since v1.0.0 */ getLang() { return this._config.lang; } /** * @public * `🌐 GLOBAL 🌐` * #### 🔠 Set {@link NabiiV1} response `language` 🔠 * @param language {@link NabiiV1} {@link ILanguage} to use * @example * ```tsx * import { nabii } from "nabii-sdk"; * * nabii.v1.setLang("fr"); * console.log(nabii.getLang()); // "fr" * ``` * @default "fr" * @returns the {@link NabiiV1} instance updated * @since v1.0.0 */ setLang(language) { try { this._config.lang = languageSchema.parse(language); return this; } catch (_) { throw errorParser("invalid_language", this._config.lang, { language }); } } /** * @public * `🌐 GLOBAL 🌐` * #### 🖥 Get {@link NabiiV1} server `URL` 🖥 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const url = nabii.v1.getUrl(); * console.log(url); // "https://server.com" * ``` * @default "http://localhost:1338" * @returns the current {@link NabiiV1} instance `URL` * @since v1.0.0 */ getUrl() { return this._config.url; } /** * @public * `🌐 GLOBAL 🌐` * #### 🖥 Set {@link NabiiV1} server `URL` 🖥 * @param url {@link NabiiV1} new server URL * @example * ```tsx * import { nabii } from "nabii-sdk"; * * nabii.v1.setUrl("https://server2.com"); * console.log(nabii.getUrl()); // "https://server2.com" * ``` * @default "http://localhost:1338" * @returns the {@link NabiiV1} instance updated * @since v1.0.0 */ setUrl(url) { try { this._config.url = urlSchema.parse(url); this._resetSocket(); return this; } catch (_) { throw errorParser("invalid_url", this._config.lang, { url }); } } /** * @public * `🌐 GLOBAL 🌐` * #### 🔧 Get {@link NabiiV1} header `mode` 🔧 * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const mode = nabii.v1.getMode(); * console.log(mode); // "production" * ``` * @default "production" * @returns the current {@link NabiiV1} instance {@link IMode} * @since v1.0.0 */ getMode() { return this._config.mode; } /** * @public * `🌐 GLOBAL 🌐` * #### 🔧 Set {@link NabiiV1} headers `mode` for unit test 🔧 * @param mode {@link NabiiV1} API {@link IMode} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * nabii.v1.setMode("test"); * console.log(nabii.getMode()); // "test" * ``` * @default "production" * @returns the {@link NabiiV1} instance updated * @since v1.0.0 */ setMode(mode) { try { this._config.mode = modeSchema.parse(mode); return this; } catch (_) { throw errorParser("invalid_mode", this._config.lang, { mode }); } } /** * @public * `🌐 GLOBAL 🌐` * #### 📳 Add a custom {@link NabiiV1} `event` listener 📳 * @param eventName the target {@link TEventName} * @default "login" | "refresh" | "logout" * @param callback the callback `function` linked to the {@link TEventName} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * nabii.v1.addEventListener("login", ({ user }) => { * console.log(`Hello ${user.email}!`); * }); * ``` * @returns the {@link NabiiV1} instance updated * @since v1.0.0 */ addEventListener(eventName, callback) { this._config.eventListener[eventName].push(callback); return this; } /** * @public * `🌐 GLOBAL 🌐` * #### 📴 Remove a custom {@link NabiiV1} `event` listener 📴 * @param eventName the target {@link TEventName} * @default "login" | "refresh" | "logout" * @param callback the callback function linked to the {@link TEventName} * @example * ```tsx * import { nabii } from "nabii-sdk"; * * nabii.v1.removeEventListener("login", ({ user }) => { * console.log(`Hello ${user.email}!`); * }); * ``` * @returns the {@link NabiiV1} instance updated * @since v1.0.0 */ removeEventListener(eventName, callback) { this._config.eventListener[eventName].splice( this._config.eventListener[eventName].indexOf(callback), 1 ); return this; } /** * @public * `🌐 GLOBAL 🌐` * #### 📚 Get all custom {@link NabiiV1} `event` listener} 📚 * @param eventName the target {@link TEventName} * @default "login" | "refresh" | "logout" * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const events = nabii.v1.listEventListener("login"); // [...] * ``` * @returns the array of all event `functions` from {@link TEventName} * @since v1.0.0 */ listEventListeners(eventName) { return this._config.eventListener[eventName]; } }; NabiiV1 = __decorateClass([ WithModules(modulesV1) ], NabiiV1); // src/index.ts var nabii = { /** * @version 1.0.x * #### Welcome to {@link NabiiV1} SDK ! * - Project: <https://github.com/NABII-app/sdk> * - API: <https://github.com/NABII-app/NABII_api> * @example * ```tsx * import { nabii } from "nabii-sdk"; * * const NABIIV1 = nabii.v1; * ``` * @author Ulysse Dupont <https://github.com/Dulysse> * #### --------------------------- * #### [Click for more information](https://github.com/NABII-app/sdk/blob/master/README.md) * #### --------------------------- */ v1: new NabiiV1() }; var index_default = nabii; export { NabiiError, index_default as default }; //# sourceMappingURL=index.js.map