@econneq/gql-auth 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,4 +19,4 @@ This package standardizes how frontend projects interact with a Django GraphQL b
19
19
  ## 📦 Installation
20
20
 
21
21
  ```bash
22
- npm install @e-conneq/gql-auth
22
+ npm install @econneq/gql-auth
@@ -0,0 +1,31 @@
1
+ type SubmitOptions = {
2
+ newData: any;
3
+ editData?: any;
4
+ mutationName: string;
5
+ modelName: string;
6
+ successField?: string;
7
+ query: any;
8
+ params: any;
9
+ router: any;
10
+ token?: string;
11
+ config: {
12
+ protocol: string;
13
+ RootApi: string;
14
+ NoDomainRootApi: string;
15
+ Subdomains: any[];
16
+ };
17
+ onAlert: (options: {
18
+ title: string;
19
+ status: boolean;
20
+ duration: number;
21
+ }) => void;
22
+ redirect?: boolean;
23
+ redirectPath?: string;
24
+ returnResponseField?: boolean;
25
+ returnResponseObject?: boolean;
26
+ reload?: boolean;
27
+ getFileMap?: (item: any) => Record<string, File>;
28
+ };
29
+ export declare const ApiFactory: (options: SubmitOptions) => Promise<any>;
30
+ export {};
31
+ //# sourceMappingURL=api-factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-factory.d.ts","sourceRoot":"","sources":["../src/api-factory.ts"],"names":[],"mappings":"AAIA,KAAK,aAAa,GAAG;IACnB,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,CAAC,EAAE,GAAG,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,GAAG,CAAC;IACX,MAAM,EAAE,GAAG,CAAC;IACZ,MAAM,EAAE,GAAG,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE;QACN,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,eAAe,EAAE,MAAM,CAAC;QACxB,UAAU,EAAE,GAAG,EAAE,CAAC;KACnB,CAAC;IACF,OAAO,EAAE,CAAC,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;IACjF,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;CAClD,CAAC;AAEF,eAAO,MAAM,UAAU,GAAU,SAAS,aAAa,iBA4DtD,CAAC"}
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiFactory = void 0;
4
+ const upload_gql_1 = require("./upload-gql");
5
+ const utils_1 = require("./utils");
6
+ const ApiFactory = async (options) => {
7
+ const { newData, editData, mutationName, modelName, successField = "title", query, router, params, reload = true, redirect, redirectPath, returnResponseField = false, returnResponseObject = false, getFileMap, token, config, onAlert } = options;
8
+ const items = Array.isArray(newData || editData) ? (newData || editData) : [(newData || editData)];
9
+ const successMessages = [];
10
+ const errorMessages = [];
11
+ let responseFieldData = null;
12
+ for (let res of items) {
13
+ try {
14
+ console.log("launching e-conneq/auth-gql ......");
15
+ const response = await (0, upload_gql_1.uploadGraphQLMutation)({
16
+ query: query.loc?.source.body || "",
17
+ variables: (0, utils_1.removeEmptyFields)(res),
18
+ fileMap: getFileMap ? getFileMap(res) : {},
19
+ params, // Pass domain params for multi-tenancy
20
+ token,
21
+ config, // Pass global URLs and Subdomain list
22
+ });
23
+ console.log("response e-conneq/auth-gql ......");
24
+ const result = response?.data?.[mutationName]?.[modelName];
25
+ if (response?.data?.[mutationName]) {
26
+ successMessages.push(result?.[successField] || "operation successful ✅");
27
+ if (returnResponseObject)
28
+ responseFieldData = response.data[mutationName];
29
+ if (result?.id && returnResponseField)
30
+ responseFieldData = result[successField];
31
+ if (result?.id || result?.token || result === null) {
32
+ }
33
+ }
34
+ // Error Handling
35
+ if (response?.errors) {
36
+ handleGraphQLErrors(response.errors, errorMessages);
37
+ }
38
+ }
39
+ catch (err) {
40
+ errorMessages.push(`Error: ${err.message}`);
41
+ }
42
+ }
43
+ // Handle Response/UI Logic
44
+ if (successMessages.length > 0 && errorMessages.length === 0) {
45
+ if (returnResponseObject || returnResponseField)
46
+ return responseFieldData;
47
+ onAlert({ title: "successfully submitted ✅", status: true, duration: 3000 });
48
+ if (redirect && redirectPath)
49
+ router.push(redirectPath);
50
+ else if (reload)
51
+ window.location.reload();
52
+ }
53
+ else if (errorMessages.length > 0) {
54
+ onAlert({
55
+ title: `❌ Errors:\n${errorMessages.join("\n")}`,
56
+ status: false,
57
+ duration: 5000
58
+ });
59
+ }
60
+ };
61
+ exports.ApiFactory = ApiFactory;
62
+ // Internal Helper for Error Parsing
63
+ const handleGraphQLErrors = (errors, errorList) => {
64
+ errors.forEach(error => {
65
+ if (error.message.includes("duplicate"))
66
+ errorList.push("Record Already Exists ❌");
67
+ else if (error.message.includes("Authentication"))
68
+ errorList.push("Login Required ❌");
69
+ else
70
+ errorList.push(error.message);
71
+ });
72
+ };
@@ -0,0 +1,12 @@
1
+ import { ApolloClient } from '@apollo/client';
2
+ export default function getApolloClient(options?: {
3
+ csrfToken?: string;
4
+ cookie?: string;
5
+ }, domain?: string | null, config?: {
6
+ protocol: string;
7
+ RootApi: string;
8
+ NoDomainRootApi: string;
9
+ Subdomains: any[];
10
+ apiKey: string;
11
+ }): Promise<ApolloClient | null>;
12
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAA2B,MAAM,gBAAgB,CAAC;AAGvE,wBAA8B,eAAe,CAC3C,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,EACjD,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,EACtB,MAAM,CAAC,EAAE;IACP,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,GAAG,EAAE,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;CAChB,GACA,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CA+C9B"}
package/dist/client.js ADDED
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = getApolloClient;
7
+ // src/client.ts
8
+ const client_1 = require("@apollo/client");
9
+ const js_cookie_1 = __importDefault(require("js-cookie"));
10
+ async function getApolloClient(options, domain, config) {
11
+ if (!config)
12
+ throw new Error("Configuration is required for getApolloClient");
13
+ const isServer = typeof window === "undefined";
14
+ const { protocol, RootApi, NoDomainRootApi, Subdomains, apiKey } = config;
15
+ // 1. Find Tenant Data
16
+ const tenant = domain
17
+ ? Subdomains.find((s) => s.subdomain.toLowerCase() === domain.toLowerCase())
18
+ : null;
19
+ // 2. Multi-tenant URL Logic
20
+ // Fallback to NoDomainRootApi if no valid tenant is found
21
+ const baseUrl = tenant
22
+ ? `${protocol}api${tenant.subdomain}${RootApi}`
23
+ : `${protocol}${NoDomainRootApi}`;
24
+ const uri = `${baseUrl}/graphql/`;
25
+ // 3. Header Logic
26
+ const csrfToken = options?.csrfToken || (!isServer ? js_cookie_1.default.get("csrftoken") : "");
27
+ const headers = {
28
+ 'Content-Type': 'application/json',
29
+ 'X-API-KEY': apiKey,
30
+ ...(options?.cookie && { 'Cookie': options.cookie }),
31
+ ...(csrfToken && { 'X-CSRFToken': csrfToken }),
32
+ ...(tenant && {
33
+ 'X-Tenant-ID': tenant.id.toString(),
34
+ 'X-Process-ID': tenant.processId,
35
+ 'X-Widget-ID': tenant.widgetID || "",
36
+ }),
37
+ 'Referer': baseUrl,
38
+ };
39
+ return new client_1.ApolloClient({
40
+ link: new client_1.HttpLink({
41
+ uri,
42
+ fetch, // Next.js polyfills fetch on server automatically
43
+ headers,
44
+ }),
45
+ cache: new client_1.InMemoryCache(),
46
+ defaultOptions: {
47
+ mutate: { fetchPolicy: 'no-cache' },
48
+ query: { fetchPolicy: 'no-cache' },
49
+ },
50
+ });
51
+ }
@@ -0,0 +1,83 @@
1
+ import { ReactNode } from "react";
2
+ export { default as getApolloClient } from './client';
3
+ export { queryServerGraphQL } from './query-server';
4
+ export { ApiFactory } from './api-factory';
5
+ export { uploadGraphQLMutation } from './upload-gql';
6
+ export type ConfigType = {
7
+ protocol: string;
8
+ RootApi: string;
9
+ NoDomainRootApi: string;
10
+ Subdomains: SubdomainItem[];
11
+ apiKey: string;
12
+ fonts: string[];
13
+ };
14
+ export type SubdomainItem = {
15
+ id: number;
16
+ subdomain: string;
17
+ processId: string;
18
+ widgetID?: string;
19
+ };
20
+ export type ApolloOptions = {
21
+ csrfToken?: string;
22
+ cookie?: string;
23
+ };
24
+ export type SelectOptions = string | {
25
+ label: string;
26
+ value: string | number;
27
+ };
28
+ export interface InterLoginData {
29
+ username: string;
30
+ password: string;
31
+ }
32
+ export interface JwtPayload {
33
+ iss?: string;
34
+ sub?: string;
35
+ aud?: string[] | string;
36
+ exp: number;
37
+ nbf?: number;
38
+ iat?: number;
39
+ jti?: string;
40
+ user_id?: number;
41
+ username?: string;
42
+ matricle?: string;
43
+ photo?: string;
44
+ is_superuser?: boolean;
45
+ is_staff?: boolean;
46
+ is_active?: boolean;
47
+ is_hod?: boolean;
48
+ role?: string;
49
+ dept?: string[] | any;
50
+ page?: string[] | any;
51
+ school?: number[] | any;
52
+ domain?: number[] | any;
53
+ language?: string[];
54
+ last_login?: any;
55
+ }
56
+ export interface InterField {
57
+ name: string;
58
+ label: string;
59
+ inputType: 'text' | "textarea" | 'number' | 'float' | 'search-select' | 'select' | 'file' | 'date' | 'password';
60
+ type: 'text' | 'textarea' | 'number' | 'float' | 'email' | 'date' | 'file' | 'password';
61
+ required?: boolean;
62
+ min?: number;
63
+ max?: number;
64
+ message?: string;
65
+ options?: {
66
+ value: string | number;
67
+ label: string;
68
+ }[];
69
+ show?: boolean;
70
+ sort?: boolean;
71
+ placeholder?: string;
72
+ acceptedFileType?: string;
73
+ icon?: ReactNode;
74
+ labelIcon?: ReactNode;
75
+ }
76
+ export interface InterFieldList {
77
+ rowId: number | string;
78
+ desktopCols: 1 | 2 | 3 | 4;
79
+ mobileCols: 1 | 2;
80
+ fields: InterField[];
81
+ }
82
+ export { capitalizeEachWord, removeEmptyFields, errorLog, decodeUrlID, formatText, getUser, getToken, getTemplate, getLanguage, getStoredFont, getTimeAgo, Alert, validateFormFields, } from './utils';
83
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAIlC,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAIrD,MAAM,MAAM,UAAU,GAAG;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAA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G,CAAC,CAAC;IAC3B,UAAU,EAAE,CAAC,GAAG,CAAC,CAAC;IAClB,MAAM,EAAE,UAAU,EAAE,CAAC;CACxB;AAGD,OAAO,EACL,kBAAkB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EACxE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,KAAK,EAAE,kBAAkB,GAClG,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.validateFormFields = exports.Alert = exports.getTimeAgo = exports.getStoredFont = exports.getLanguage = exports.getTemplate = exports.getToken = exports.getUser = exports.formatText = exports.decodeUrlID = exports.errorLog = exports.removeEmptyFields = exports.capitalizeEachWord = exports.uploadGraphQLMutation = exports.ApiFactory = exports.queryServerGraphQL = exports.getApolloClient = void 0;
7
+ // 1. Export the Core Functions
8
+ var client_1 = require("./client");
9
+ Object.defineProperty(exports, "getApolloClient", { enumerable: true, get: function () { return __importDefault(client_1).default; } });
10
+ var query_server_1 = require("./query-server");
11
+ Object.defineProperty(exports, "queryServerGraphQL", { enumerable: true, get: function () { return query_server_1.queryServerGraphQL; } });
12
+ var api_factory_1 = require("./api-factory");
13
+ Object.defineProperty(exports, "ApiFactory", { enumerable: true, get: function () { return api_factory_1.ApiFactory; } });
14
+ var upload_gql_1 = require("./upload-gql");
15
+ Object.defineProperty(exports, "uploadGraphQLMutation", { enumerable: true, get: function () { return upload_gql_1.uploadGraphQLMutation; } });
16
+ // 3. Export Helper Utilities (Optional)
17
+ var utils_1 = require("./utils");
18
+ Object.defineProperty(exports, "capitalizeEachWord", { enumerable: true, get: function () { return utils_1.capitalizeEachWord; } });
19
+ Object.defineProperty(exports, "removeEmptyFields", { enumerable: true, get: function () { return utils_1.removeEmptyFields; } });
20
+ Object.defineProperty(exports, "errorLog", { enumerable: true, get: function () { return utils_1.errorLog; } });
21
+ Object.defineProperty(exports, "decodeUrlID", { enumerable: true, get: function () { return utils_1.decodeUrlID; } });
22
+ Object.defineProperty(exports, "formatText", { enumerable: true, get: function () { return utils_1.formatText; } });
23
+ Object.defineProperty(exports, "getUser", { enumerable: true, get: function () { return utils_1.getUser; } });
24
+ Object.defineProperty(exports, "getToken", { enumerable: true, get: function () { return utils_1.getToken; } });
25
+ Object.defineProperty(exports, "getTemplate", { enumerable: true, get: function () { return utils_1.getTemplate; } });
26
+ Object.defineProperty(exports, "getLanguage", { enumerable: true, get: function () { return utils_1.getLanguage; } });
27
+ Object.defineProperty(exports, "getStoredFont", { enumerable: true, get: function () { return utils_1.getStoredFont; } });
28
+ Object.defineProperty(exports, "getTimeAgo", { enumerable: true, get: function () { return utils_1.getTimeAgo; } });
29
+ Object.defineProperty(exports, "Alert", { enumerable: true, get: function () { return utils_1.Alert; } });
30
+ Object.defineProperty(exports, "validateFormFields", { enumerable: true, get: function () { return utils_1.validateFormFields; } });
@@ -0,0 +1,15 @@
1
+ type ServerQueryArgs = {
2
+ query: any;
3
+ variables?: Record<string, any>;
4
+ domain?: string | null;
5
+ config: {
6
+ protocol: string;
7
+ RootApi: string;
8
+ NoDomainRootApi: string;
9
+ Subdomains: any[];
10
+ apiKey: string;
11
+ };
12
+ };
13
+ export declare function queryServerGraphQL<T = any>({ query, variables, domain, config, }: ServerQueryArgs): Promise<T | null>;
14
+ export {};
15
+ //# sourceMappingURL=query-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-server.d.ts","sourceRoot":"","sources":["../src/query-server.ts"],"names":[],"mappings":"AAIA,KAAK,eAAe,GAAG;IACrB,KAAK,EAAE,GAAG,CAAC;IACX,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAChC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE;QACN,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,eAAe,EAAE,MAAM,CAAC;QACxB,UAAU,EAAE,GAAG,EAAE,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;CACH,CAAC;AAEF,wBAAsB,kBAAkB,CAAC,CAAC,GAAG,GAAG,EAAE,EAChD,KAAK,EACL,SAAc,EACd,MAAM,EACN,MAAM,GACP,EAAE,eAAe,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CA8BrC"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.queryServerGraphQL = queryServerGraphQL;
7
+ // src/server-query.ts
8
+ const headers_1 = require("next/headers");
9
+ const client_1 = __importDefault(require("./client"));
10
+ async function queryServerGraphQL({ query, variables = {}, domain, config, }) {
11
+ try {
12
+ // 1. Get server-side cookies
13
+ const cookieStore = await (0, headers_1.cookies)();
14
+ const cookieString = cookieStore.toString();
15
+ // 2. Call getApolloClient with the correct 3 arguments:
16
+ // Arg 1: options (cookies)
17
+ // Arg 2: domain (subdomain string)
18
+ // Arg 3: config (URLs and Subdomain array)
19
+ const client = await (0, client_1.default)({ cookie: cookieString }, domain, config);
20
+ if (!client)
21
+ return null;
22
+ const result = await client.query({
23
+ query,
24
+ variables,
25
+ fetchPolicy: 'no-cache',
26
+ });
27
+ console.log("getting @e-conneq/gql-auth ........");
28
+ return result?.data;
29
+ }
30
+ catch (err) {
31
+ // On the server, we console.error instead of using Swal
32
+ console.error("GraphQL Server Error:", err);
33
+ return null;
34
+ }
35
+ }
@@ -0,0 +1,17 @@
1
+ type UploadGraphQLArgs = {
2
+ query: string;
3
+ variables: Record<string, any>;
4
+ fileMap: Record<string, File>;
5
+ token?: string;
6
+ params: any;
7
+ config: {
8
+ protocol: string;
9
+ RootApi: string;
10
+ NoDomainRootApi: string;
11
+ Subdomains: any[];
12
+ apiKey?: string;
13
+ };
14
+ };
15
+ export declare function uploadGraphQLMutation({ query, variables, fileMap, token, params, config }: UploadGraphQLArgs): Promise<any>;
16
+ export {};
17
+ //# sourceMappingURL=upload-gql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload-gql.d.ts","sourceRoot":"","sources":["../src/upload-gql.ts"],"names":[],"mappings":"AAAA,KAAK,iBAAiB,GAAG;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,GAAG,CAAC;IACZ,MAAM,EAAE;QACN,QAAQ,EAAE,MAAM,CAAC;QACjB,OAAO,EAAE,MAAM,CAAC;QAChB,eAAe,EAAE,MAAM,CAAC;QACxB,UAAU,EAAE,GAAG,EAAE,CAAC;QAClB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC;CACH,CAAC;AAEF,wBAAsB,qBAAqB,CAAC,EAC1C,KAAK,EACL,SAAS,EACT,OAAO,EACP,KAAK,EACL,MAAM,EACN,MAAM,EACP,EAAE,iBAAiB,gBA4DnB"}
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.uploadGraphQLMutation = uploadGraphQLMutation;
4
+ async function uploadGraphQLMutation({ query, variables, fileMap, token, params, config }) {
5
+ const { protocol, RootApi, NoDomainRootApi, Subdomains, apiKey } = config;
6
+ const formData = new FormData();
7
+ const updatedVariables = { ...variables };
8
+ // 1. Prepare GraphQL Multipart Request (Spec compliant)
9
+ Object.keys(fileMap).forEach((key) => {
10
+ updatedVariables[key] = null;
11
+ });
12
+ const operations = { query, variables: updatedVariables };
13
+ const map = {};
14
+ const fileKeys = Object.keys(fileMap);
15
+ fileKeys.forEach((key, index) => {
16
+ map[`${index}`] = [`variables.${key}`];
17
+ });
18
+ formData.append("operations", JSON.stringify(operations));
19
+ formData.append("map", JSON.stringify(map));
20
+ fileKeys.forEach((key, index) => {
21
+ formData.append(`${index}`, fileMap[key]);
22
+ });
23
+ // 2. Multi-tenant URL and Data Logic
24
+ const requestedDomain = params?.domain || "";
25
+ const tenantData = Subdomains.find((d) => d.subdomain.toLowerCase() === requestedDomain.toLowerCase());
26
+ // Determine URL: Use subdomain api if tenant exists, otherwise use root API
27
+ const API_LINK = tenantData
28
+ ? `${protocol}api${tenantData.subdomain}${RootApi}/graphql/`
29
+ : `${protocol}${NoDomainRootApi}/graphql/`;
30
+ // 3. Construct Headers
31
+ const headers = {
32
+ ...(token ? { "Authorization": `Bearer ${token}` } : {}),
33
+ ...(apiKey ? { "X-API-KEY": apiKey } : {}),
34
+ };
35
+ // Inject specific tenant metadata into headers for Django to read
36
+ if (tenantData) {
37
+ headers["X-Tenant-ID"] = String(tenantData.id);
38
+ headers["X-Process-ID"] = tenantData.processId || "";
39
+ headers["X-Widget-ID"] = tenantData.widgetID || "";
40
+ }
41
+ // 4. Execute Fetch
42
+ const res = await fetch(API_LINK, {
43
+ method: "POST",
44
+ headers,
45
+ body: formData,
46
+ // credentials: "include" is important if you use cookies alongside headers
47
+ credentials: "include",
48
+ });
49
+ return await res.json();
50
+ }
@@ -0,0 +1,24 @@
1
+ import { InterFieldList, JwtPayload } from ".";
2
+ export declare const capitalizeEachWord: (str: string) => string;
3
+ export declare const errorLog: (err: any, show?: boolean) => string;
4
+ export declare const getToken: () => string | null;
5
+ export declare const getUser: () => JwtPayload | null;
6
+ export declare const getStoredFont: (FONTS: string[]) => string;
7
+ export declare const getTimeAgo: (dateStr: string, type: "past" | "future") => string;
8
+ export declare const getLanguage: () => "en" | "fr";
9
+ export declare const getTemplate: () => number;
10
+ export declare const decodeUrlID: (urlID: string) => string;
11
+ export declare function getAcademicYear(): string;
12
+ export declare const removeEmptyFields: (obj: any) => any;
13
+ export declare const Alert: ({ title, duration, status }: {
14
+ title: string;
15
+ duration: 1000 | 1500 | 2000 | 3000 | 4000 | 5000;
16
+ status?: boolean;
17
+ }) => void;
18
+ export declare const validateFormFields: (formData: any, currentStepFields: InterFieldList[]) => Record<string, string>;
19
+ export declare const lastYears: (number: number) => {
20
+ value: string;
21
+ label: string;
22
+ }[];
23
+ export declare const formatText: (text: string) => string;
24
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,GAAG,CAAC;AAI/C,eAAO,MAAM,kBAAkB,GAAI,KAAK,MAAM,WAM7C,CAAC;AAEF,eAAO,MAAM,QAAQ,GAAI,KAAK,GAAG,EAAE,OAAO,OAAO,WAyBhD,CAAC;AAKF,eAAO,MAAM,QAAQ,qBAKpB,CAAC;AAEF,eAAO,MAAM,OAAO,yBAKnB,CAAA;AAED,eAAO,MAAM,aAAa,GAAI,OAAO,MAAM,EAAE,WAO5C,CAAC;AAEF,eAAO,MAAM,UAAU,GACnB,SAAS,MAAM,EACf,MAAM,MAAM,GAAG,QAAQ,KACxB,MA0CF,CAAC;AAGF,eAAO,MAAM,WAAW,mBAOvB,CAAC;AAEF,eAAO,MAAM,WAAW,cAMvB,CAAC;AAEF,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,WAIxC,CAAA;AAED,wBAAgB,eAAe,IAAI,MAAM,CAUxC;AAED,eAAO,MAAM,iBAAiB,GAAI,KAAK,GAAG,QAUzC,CAAC;AAGF,eAAO,MAAM,KAAK,GACd,6BACI;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,SAU7F,CAAC;AAIF,eAAO,MAAM,kBAAkB,GAAI,UAAU,GAAG,EAAE,mBAAmB,cAAc,EAAE,2BAkDpF,CAAC;AAEF,eAAO,MAAM,SAAS,GAAI,QAAQ,MAAM;;;GAKvC,CAAC;AAEF,eAAO,MAAM,UAAU,GAAI,MAAM,MAAM,WAiDtC,CAAC"}
package/dist/utils.js ADDED
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.formatText = exports.lastYears = exports.validateFormFields = exports.Alert = exports.removeEmptyFields = exports.decodeUrlID = exports.getTemplate = exports.getLanguage = exports.getTimeAgo = exports.getStoredFont = exports.getUser = exports.getToken = exports.errorLog = exports.capitalizeEachWord = void 0;
7
+ exports.getAcademicYear = getAcademicYear;
8
+ const sweetalert2_1 = __importDefault(require("sweetalert2"));
9
+ const js_cookie_1 = __importDefault(require("js-cookie"));
10
+ const jwt_decode_1 = require("jwt-decode");
11
+ const capitalizeEachWord = (str) => {
12
+ if (!str)
13
+ return ''; // Handle empty or null strings
14
+ return str
15
+ .split(' ')
16
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
17
+ .join(' ');
18
+ };
19
+ exports.capitalizeEachWord = capitalizeEachWord;
20
+ const errorLog = (err, show) => {
21
+ let mes = "An unknown error occurred";
22
+ if (typeof err === "string")
23
+ mes = err;
24
+ else if (err?.graphQLErrors?.length > 0)
25
+ mes = err.graphQLErrors.map((e) => e.message).join('\n');
26
+ else if (err?.networkError) {
27
+ const netErr = err.networkError;
28
+ if ("result" in netErr && netErr.result?.errors?.length > 0)
29
+ mes = netErr.result.errors.map((e) => e.message).join('\n');
30
+ else if (netErr.message)
31
+ mes = netErr.message;
32
+ }
33
+ else if (err?.extraInfo)
34
+ mes = String(err.extraInfo);
35
+ else if (err?.message)
36
+ mes = err.message;
37
+ if (show) {
38
+ sweetalert2_1.default.fire({
39
+ title: mes,
40
+ icon: 'error',
41
+ timer: 3000,
42
+ timerProgressBar: true,
43
+ showConfirmButton: false,
44
+ });
45
+ }
46
+ return mes;
47
+ };
48
+ exports.errorLog = errorLog;
49
+ const currentYear = new Date().getFullYear();
50
+ const getToken = () => {
51
+ if (typeof window === "undefined") {
52
+ return null;
53
+ }
54
+ return js_cookie_1.default.get("token") || localStorage.getItem("token");
55
+ };
56
+ exports.getToken = getToken;
57
+ const getUser = () => {
58
+ // const token = typeof window !== 'undefined' ? localStorage.getItem("token") : null;
59
+ const token = (0, exports.getToken)();
60
+ const user = token ? (0, jwt_decode_1.jwtDecode)(token) : null;
61
+ return user;
62
+ };
63
+ exports.getUser = getUser;
64
+ const getStoredFont = (FONTS) => {
65
+ if (typeof window === "undefined")
66
+ return FONTS[0]; // Default for SSR
67
+ const up = localStorage.getItem("user-pref");
68
+ if (!up)
69
+ return FONTS[5]; // Default to Ubuntu (6th index)
70
+ const fontIndex = parseInt(up[1]) - 1;
71
+ return FONTS[fontIndex] || FONTS[5];
72
+ };
73
+ exports.getStoredFont = getStoredFont;
74
+ const getTimeAgo = (dateStr, type) => {
75
+ if (!dateStr)
76
+ return "";
77
+ const now = new Date();
78
+ const item = new Date(dateStr);
79
+ let diffMs = 0;
80
+ if (type === "past")
81
+ diffMs = now.getTime() - item.getTime();
82
+ if (type === "future")
83
+ diffMs = item.getTime() - now.getTime();
84
+ // Handle invalid date ranges
85
+ if (diffMs < 0) {
86
+ return type === "past" ? "just now" : "Closed";
87
+ }
88
+ const seconds = Math.floor(diffMs / 1000);
89
+ const minutes = Math.floor(seconds / 60);
90
+ const hours = Math.floor(minutes / 60);
91
+ const days = Math.floor(hours / 24);
92
+ const weeks = Math.floor(days / 7);
93
+ const months = Math.floor(days / 30.44); // Use average month length
94
+ const years = Math.floor(days / 365.25); // Account for leap years
95
+ const suffix = type === "past" ? "ago" : "left";
96
+ // 1. Logic for Past Dates (e.g., Posted 2 days ago)
97
+ if (type === "past") {
98
+ if (days === 0)
99
+ return "Today";
100
+ if (days === 1)
101
+ return "Yesterday";
102
+ if (days < 7)
103
+ return `${days} days ago`;
104
+ if (weeks < 5)
105
+ return `${weeks} week${weeks > 1 ? "s" : ""} ago`;
106
+ if (months < 12)
107
+ return `${months} month${months > 1 ? "s" : ""} ago`;
108
+ return `${years} year${years > 1 ? "s" : ""} ago`;
109
+ }
110
+ // 2. Logic for Future Dates (e.g., 5 days left)
111
+ if (days === 0)
112
+ return "Ends today";
113
+ if (days === 1)
114
+ return "1 day left";
115
+ if (days < 7)
116
+ return `${days} days left`;
117
+ if (weeks < 5)
118
+ return `${weeks} week${weeks > 1 ? "s" : ""} left`;
119
+ if (months < 12)
120
+ return `${months} month${months > 1 ? "s" : ""} left`;
121
+ return `${years} year${years > 1 ? "s" : ""} left`;
122
+ };
123
+ exports.getTimeAgo = getTimeAgo;
124
+ const getLanguage = () => {
125
+ if (typeof window === "undefined")
126
+ return "en";
127
+ const up = localStorage.getItem("user-pref");
128
+ if (!up)
129
+ return "en";
130
+ const langNumber = parseInt(up[0]);
131
+ return langNumber === 1 ? "en" : "fr";
132
+ };
133
+ exports.getLanguage = getLanguage;
134
+ const getTemplate = () => {
135
+ if (typeof window === "undefined")
136
+ return 1;
137
+ const up = localStorage.getItem("user-pref");
138
+ if (!up)
139
+ return 1;
140
+ return parseInt(up[2]);
141
+ };
142
+ exports.getTemplate = getTemplate;
143
+ const decodeUrlID = (urlID) => {
144
+ const base64DecodedString = decodeURIComponent(urlID); // Decodes %3D%3D to ==
145
+ const id = Buffer.from(base64DecodedString, 'base64').toString('utf-8'); // Decoding from base64
146
+ return id.split(":")[1];
147
+ };
148
+ exports.decodeUrlID = decodeUrlID;
149
+ function getAcademicYear() {
150
+ const today = new Date();
151
+ const year = today.getFullYear();
152
+ const month = today.getMonth(); // 0 = January, 7 = August
153
+ if (month < 7) {
154
+ return `${year - 1}/${year}`;
155
+ }
156
+ else {
157
+ return `${year}/${year + 1}`;
158
+ }
159
+ }
160
+ const removeEmptyFields = (obj) => {
161
+ const newObj = {};
162
+ for (const key in obj) {
163
+ // Keep File objects and non-empty values
164
+ if (obj[key] instanceof File ||
165
+ (obj[key] !== null && obj[key] !== undefined && obj[key] !== '')) {
166
+ newObj[key] = obj[key];
167
+ }
168
+ }
169
+ return newObj;
170
+ };
171
+ exports.removeEmptyFields = removeEmptyFields;
172
+ const Alert = ({ title, duration, status = true }) => {
173
+ sweetalert2_1.default.fire({
174
+ title: (0, exports.capitalizeEachWord)(title),
175
+ timer: duration,
176
+ timerProgressBar: true,
177
+ showConfirmButton: false,
178
+ icon: status ? 'success' : 'error',
179
+ });
180
+ };
181
+ exports.Alert = Alert;
182
+ const validateFormFields = (formData, currentStepFields) => {
183
+ const newErrors = {};
184
+ // 1. Flatten the fields from all rows in the step
185
+ const fieldsToValidate = currentStepFields.flatMap(row => row.fields);
186
+ fieldsToValidate.forEach((field) => {
187
+ // Skip validation if the field is hidden
188
+ if (field.show === false)
189
+ return;
190
+ // 2. Get the value from formData
191
+ const value = formData[field.name];
192
+ // 3. Check Required
193
+ if (field.required && (!value || value.toString().trim() === "")) {
194
+ newErrors[field.name] = `${(0, exports.capitalizeEachWord)(field.label)} is required`;
195
+ // return;
196
+ }
197
+ // 4. Check Type (Email)
198
+ if (field.type === 'email' && value) {
199
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
200
+ if (!emailRegex.test(value)) {
201
+ newErrors[field.name] = "Invalid email format";
202
+ }
203
+ }
204
+ // 5. Check Numbers (Min/Max)
205
+ if (field.type === 'number' && value) {
206
+ const numValue = Number(value);
207
+ if (field.min !== undefined && numValue < field.min) {
208
+ newErrors[field.name] = `Minimum value is ${field.min}`;
209
+ }
210
+ if (field.max !== undefined && numValue > field.max) {
211
+ newErrors[field.name] = `Maximum value is ${field.max}`;
212
+ }
213
+ }
214
+ // 6. Check Length (Strings)
215
+ if (field.type === 'text' && value) {
216
+ if (field.min !== undefined && value.length < field.min) {
217
+ newErrors[field.name] = `Too short (min ${field.min} chars)`;
218
+ }
219
+ if (field.max !== undefined && value.length > field.max) {
220
+ newErrors[field.name] = `Too long (min ${field.max} chars)`;
221
+ }
222
+ }
223
+ });
224
+ return newErrors;
225
+ };
226
+ exports.validateFormFields = validateFormFields;
227
+ const lastYears = (number) => {
228
+ return Array.from({ length: number }, (_, i) => ({
229
+ value: (currentYear - i).toString(),
230
+ label: (currentYear - i).toString()
231
+ })).sort((a, b) => Number(b.value) - Number(a.value));
232
+ };
233
+ exports.lastYears = lastYears;
234
+ const formatText = (text) => {
235
+ return text;
236
+ if (!text || typeof text !== "string")
237
+ return "";
238
+ return text
239
+ // Ensure space after "." if it's not part of abbreviation/number
240
+ .replace(/\.(?!\s|$|[a-zA-Z0-9])/g, ". ")
241
+ // Split sentences by ". " but preserve delimiter
242
+ .split(/(\. )/g)
243
+ .map((segment) => {
244
+ if (segment === ". ")
245
+ return segment; // keep delimiter
246
+ return segment
247
+ .split(" ")
248
+ .map((word, i) => {
249
+ if (word === "")
250
+ return word;
251
+ // Preserve existing ALL CAPS words
252
+ if (word.length > 1 && /^[A-Z]+$/.test(word)) {
253
+ return word;
254
+ }
255
+ // Abbreviations like g.a, n.l.n
256
+ if (/^([a-zA-Z]\.)+[a-zA-Z]?$/.test(word)) {
257
+ return word.toUpperCase(); // → G.A, N.L.N
258
+ }
259
+ // Version numbers like 3.0.1
260
+ if (/^\d+(\.\d+)+$/.test(word)) {
261
+ return word;
262
+ }
263
+ // Mixed abbrev/numbers (like p.m2.5 or covid-19 v2.0)
264
+ if (/[a-zA-Z]\.\d/.test(word) || /\d+\.\d+[a-zA-Z]?/.test(word)) {
265
+ return word; // leave as-is
266
+ }
267
+ // First word of sentence → capitalize first letter
268
+ if (i === 0) {
269
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
270
+ }
271
+ // Other words → lowercase
272
+ return word.toLowerCase();
273
+ })
274
+ .join(" ");
275
+ })
276
+ .join("");
277
+ };
278
+ exports.formatText = formatText;
package/package.json CHANGED
@@ -1,19 +1,30 @@
1
1
  {
2
2
  "name": "@econneq/gql-auth",
3
- "version": "1.0.0",
4
- "main": "dist/index.js",
5
- "module": "dist/index.mjs",
6
- "types": "dist/index.d.ts",
3
+ "version": "1.0.2",
4
+ "main": "./dist/index.js",
5
+ "module": "./dist/index.mjs",
6
+ "types": "./dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "prepublishOnly": "npm run build"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.mjs",
15
+ "require": "./dist/index.js"
16
+ }
17
+ },
7
18
  "files": [
8
19
  "dist"
9
20
  ],
10
21
  "peerDependencies": {
11
- "next": "^13.0.0 || ^14.0.0 || ^15.0.0",
12
- "react": "^18.0.0 || ^19.0.0",
13
- "react-dom": "^18.0.0 || ^19.0.0",
14
- "@apollo/client": "^3.0.0",
22
+ "@apollo/client": "^4.0.0",
15
23
  "graphql": "^16.0.0",
16
- "sweetalert2": "^11.26.17"
24
+ "next": "^16.0.0",
25
+ "react": "^19.0.0",
26
+ "react-dom": "^18.0.0 || ^19.0.0",
27
+ "sweetalert2": "^11.0.0"
17
28
  },
18
29
  "dependencies": {
19
30
  "js-cookie": "^3.0.0"