Updates
This commit is contained in:
+13
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
clientId: string;
|
||||
redirectUrl: string;
|
||||
setLoading?: (arg0: boolean) => void;
|
||||
scopes?: string[];
|
||||
};
|
||||
/**
|
||||
* Login with Github Function
|
||||
* ===============================================================================
|
||||
* @description This function uses github api to login a user with datasquirel
|
||||
*/
|
||||
export default function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }: Param): void;
|
||||
export {};
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getAccessToken;
|
||||
/**
|
||||
* Login with Github Function
|
||||
* ===============================================================================
|
||||
* @description This function uses github api to login a user with datasquirel
|
||||
*/
|
||||
function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
|
||||
if (setLoading)
|
||||
setLoading(true);
|
||||
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
||||
const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`;
|
||||
window.location.assign(fetchUrl);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
interface GoogleGetAccessTokenFunctionParams {
|
||||
clientId: string;
|
||||
triggerPrompt?: boolean;
|
||||
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
|
||||
}
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*/
|
||||
export default function getAccessToken(params: GoogleGetAccessTokenFunctionParams): Promise<string>;
|
||||
/**
|
||||
* # Google Login Function
|
||||
*/
|
||||
export declare function googleLogin({ google, clientId, setLoading, triggerPrompt, }: GoogleGetAccessTokenFunctionParams & {
|
||||
google: any;
|
||||
}): Promise<unknown>;
|
||||
export {};
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getAccessToken;
|
||||
exports.googleLogin = googleLogin;
|
||||
let interval;
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*/
|
||||
function getAccessToken(params) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a, _b;
|
||||
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
|
||||
const response = (yield new Promise((resolve, reject) => {
|
||||
interval = setInterval(() => {
|
||||
// @ts-ignore
|
||||
let google = window.google;
|
||||
if (google) {
|
||||
window.clearInterval(interval);
|
||||
resolve(googleLogin(Object.assign(Object.assign({}, params), { google })));
|
||||
}
|
||||
}, 500);
|
||||
}));
|
||||
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
/**
|
||||
* # Google Login Function
|
||||
*/
|
||||
function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
|
||||
setTimeout(() => {
|
||||
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
|
||||
}, 3000);
|
||||
return new Promise((resolve, reject) => {
|
||||
/**
|
||||
* # Callback Function
|
||||
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
|
||||
*/
|
||||
function handleCredentialResponse(response) {
|
||||
resolve(response.access_token);
|
||||
}
|
||||
const googleAuth = google.accounts.oauth2.initTokenClient({
|
||||
client_id: clientId,
|
||||
scope: "email profile",
|
||||
callback: handleCredentialResponse,
|
||||
});
|
||||
googleAuth.requestAccessToken();
|
||||
if (triggerPrompt) {
|
||||
google.accounts.id.prompt(triggerGooglePromptCallback);
|
||||
}
|
||||
/**
|
||||
* Google prompt notification callback
|
||||
* ========================================================
|
||||
* @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification
|
||||
*/
|
||||
function triggerGooglePromptCallback(notification) {
|
||||
console.log(notification);
|
||||
}
|
||||
});
|
||||
}
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*/
|
||||
export default function logout(params: {
|
||||
[s: string]: any;
|
||||
} | null): Promise<boolean>;
|
||||
Vendored
+102
@@ -0,0 +1,102 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = logout;
|
||||
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*/
|
||||
function logout(params) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
const localUser = localStorage.getItem("user");
|
||||
let targetUser;
|
||||
try {
|
||||
targetUser = JSON.parse(localUser || "");
|
||||
}
|
||||
catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
if (!targetUser) {
|
||||
return false;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const cookies = (0, parseClientCookies_1.default)();
|
||||
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
|
||||
typeof cookies.datasquirel_social_id == "string" &&
|
||||
!cookies.datasquirel_social_id.match(/^null$/i)
|
||||
? cookies.datasquirel_social_id
|
||||
: null;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
localStorage.setItem("user", "{}");
|
||||
localStorage.removeItem("csrf");
|
||||
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const response = yield new Promise((resolve, reject) => {
|
||||
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
|
||||
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
|
||||
if (googleClientId) {
|
||||
const googleScript = document.createElement("script");
|
||||
googleScript.src = "https://accounts.google.com/gsi/client";
|
||||
googleScript.className = "social-script-tag";
|
||||
document.body.appendChild(googleScript);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
googleScript.onload = function (e) {
|
||||
// @ts-ignore
|
||||
const google = window.google;
|
||||
if (google) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
google.accounts.id.initialize({
|
||||
client_id: googleClientId,
|
||||
});
|
||||
google.accounts.id.revoke(socialId, (done) => {
|
||||
console.log(done.error);
|
||||
resolve(true);
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
};
|
||||
}
|
||||
else {
|
||||
resolve(true);
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
else {
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
return response;
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
type FetchApiOptions = {
|
||||
method: "POST" | "GET" | "DELETE" | "PUT" | "PATCH" | "post" | "get" | "delete" | "put" | "patch";
|
||||
body?: object | string;
|
||||
headers?: FetchHeader;
|
||||
};
|
||||
type FetchHeader = HeadersInit & {
|
||||
[key: string]: string | null;
|
||||
};
|
||||
export type FetchApiReturn = {
|
||||
success: boolean;
|
||||
payload: any;
|
||||
msg?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
/**
|
||||
* # Fetch API
|
||||
*/
|
||||
export default function fetchApi(url: string, options?: FetchApiOptions, csrf?: boolean,
|
||||
/** Key to use to grab local Storage csrf value. */
|
||||
localStorageCSRFKey?: string): Promise<any>;
|
||||
export {};
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = fetchApi;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
/**
|
||||
* # Fetch API
|
||||
*/
|
||||
function fetchApi(url, options, csrf,
|
||||
/** Key to use to grab local Storage csrf value. */
|
||||
localStorageCSRFKey) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let data;
|
||||
const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf");
|
||||
let finalHeaders = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (csrf && csrfValue) {
|
||||
finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true";
|
||||
}
|
||||
if (typeof options === "string") {
|
||||
try {
|
||||
let fetchData;
|
||||
switch (options) {
|
||||
case "post":
|
||||
fetchData = yield fetch(url, {
|
||||
method: options,
|
||||
headers: finalHeaders,
|
||||
});
|
||||
data = fetchData.json();
|
||||
break;
|
||||
default:
|
||||
fetchData = yield fetch(url);
|
||||
data = fetchData.json();
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #1:", error.message);
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
else if (typeof options === "object") {
|
||||
try {
|
||||
let fetchData;
|
||||
if (options.body && typeof options.body === "object") {
|
||||
let oldOptionsBody = lodash_1.default.cloneDeep(options.body);
|
||||
options.body = JSON.stringify(oldOptionsBody);
|
||||
}
|
||||
if (options.headers) {
|
||||
options.headers = lodash_1.default.merge(options.headers, finalHeaders);
|
||||
const finalOptions = Object.assign({}, options);
|
||||
fetchData = yield fetch(url, finalOptions);
|
||||
}
|
||||
else {
|
||||
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
|
||||
fetchData = yield fetch(url, finalOptions);
|
||||
}
|
||||
data = fetchData.json();
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #2:", error.message);
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
else {
|
||||
try {
|
||||
let fetchData = yield fetch(url);
|
||||
data = yield fetchData.json();
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #3:", error.message);
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
});
|
||||
}
|
||||
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
import imageInputFileToBase64 from "./media/imageInputFileToBase64";
|
||||
import imageInputToBase64 from "./media/imageInputToBase64";
|
||||
import inputFileToBase64 from "./media/inputFileToBase64";
|
||||
import getAccessToken from "./auth/google/getAccessToken";
|
||||
import getGithubAccessToken from "./auth/github/getAccessToken";
|
||||
import logout from "./auth/logout";
|
||||
import fetchApi from "./fetch";
|
||||
import serializeQuery from "../package-shared/utils/serialize-query";
|
||||
import serializeCookies from "../package-shared/utils/serialize-cookies";
|
||||
import numberfy from "../package-shared/utils/numberfy";
|
||||
import slugify from "../package-shared/utils/slugify";
|
||||
/**
|
||||
* Main Export
|
||||
*/
|
||||
declare const datasquirelClient: {
|
||||
media: {
|
||||
imageInputToBase64: typeof imageInputToBase64;
|
||||
imageInputFileToBase64: typeof imageInputFileToBase64;
|
||||
inputFileToBase64: typeof inputFileToBase64;
|
||||
};
|
||||
auth: {
|
||||
google: {
|
||||
getAccessToken: typeof getAccessToken;
|
||||
};
|
||||
github: {
|
||||
getAccessToken: typeof getGithubAccessToken;
|
||||
};
|
||||
logout: typeof logout;
|
||||
};
|
||||
fetch: {
|
||||
fetchApi: typeof fetchApi;
|
||||
clientFetch: typeof fetchApi;
|
||||
};
|
||||
utils: {
|
||||
serializeQuery: typeof serializeQuery;
|
||||
serializeCookies: typeof serializeCookies;
|
||||
EJSON: {
|
||||
parse: (string: string | null | number, reviver?: (this: any, key: string, value: any) => any) => {
|
||||
[s: string]: any;
|
||||
} | {
|
||||
[s: string]: any;
|
||||
}[] | undefined;
|
||||
stringify: (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number) => string | undefined;
|
||||
};
|
||||
numberfy: typeof numberfy;
|
||||
slugify: typeof slugify;
|
||||
};
|
||||
};
|
||||
export default datasquirelClient;
|
||||
Vendored
+60
@@ -0,0 +1,60 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64"));
|
||||
const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64"));
|
||||
const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64"));
|
||||
const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken"));
|
||||
const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken"));
|
||||
const logout_1 = __importDefault(require("./auth/logout"));
|
||||
const fetch_1 = __importDefault(require("./fetch"));
|
||||
const fetch_2 = __importDefault(require("./fetch"));
|
||||
const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query"));
|
||||
const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies"));
|
||||
const ejson_1 = __importDefault(require("../package-shared/utils/ejson"));
|
||||
const numberfy_1 = __importDefault(require("../package-shared/utils/numberfy"));
|
||||
const slugify_1 = __importDefault(require("../package-shared/utils/slugify"));
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* Media Functions Object
|
||||
*/
|
||||
const media = {
|
||||
imageInputToBase64: imageInputToBase64_1.default,
|
||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||
inputFileToBase64: inputFileToBase64_1.default,
|
||||
};
|
||||
/**
|
||||
* User Auth Object
|
||||
*/
|
||||
const auth = {
|
||||
google: {
|
||||
getAccessToken: getAccessToken_1.default,
|
||||
},
|
||||
github: {
|
||||
getAccessToken: getAccessToken_2.default,
|
||||
},
|
||||
logout: logout_1.default,
|
||||
};
|
||||
const utils = {
|
||||
serializeQuery: serialize_query_1.default,
|
||||
serializeCookies: serialize_cookies_1.default,
|
||||
EJSON: ejson_1.default,
|
||||
numberfy: numberfy_1.default,
|
||||
slugify: slugify_1.default,
|
||||
};
|
||||
/**
|
||||
* Fetch
|
||||
*/
|
||||
const fetch = {
|
||||
fetchApi: fetch_1.default,
|
||||
clientFetch: fetch_2.default,
|
||||
};
|
||||
/**
|
||||
* Main Export
|
||||
*/
|
||||
const datasquirelClient = { media, auth, fetch, utils };
|
||||
exports.default = datasquirelClient;
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
import imageInputFileToBase64 from "./imageInputFileToBase64";
|
||||
import imageInputToBase64 from "./imageInputToBase64";
|
||||
/**
|
||||
* ==========================
|
||||
* Main Export
|
||||
* ==========================
|
||||
*/
|
||||
declare const datasquirelClient: {
|
||||
media: {
|
||||
imageInputToBase64: typeof imageInputToBase64;
|
||||
imageInputFileToBase64: typeof imageInputFileToBase64;
|
||||
};
|
||||
};
|
||||
export default datasquirelClient;
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const imageInputFileToBase64_1 = __importDefault(require("./imageInputFileToBase64"));
|
||||
const imageInputToBase64_1 = __importDefault(require("./imageInputToBase64"));
|
||||
/**
|
||||
* ==========================
|
||||
* Media Functions Object
|
||||
* ==========================
|
||||
*/
|
||||
const media = {
|
||||
imageInputToBase64: imageInputToBase64_1.default,
|
||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||
};
|
||||
/**
|
||||
* ==========================
|
||||
* Media Functions Object
|
||||
* ==========================
|
||||
*/
|
||||
const auth = {
|
||||
imageInputToBase64: imageInputToBase64_1.default,
|
||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||
};
|
||||
/**
|
||||
* ==========================
|
||||
* Main Export
|
||||
* ==========================
|
||||
*/
|
||||
const datasquirelClient = {
|
||||
media: media,
|
||||
};
|
||||
exports.default = datasquirelClient;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import { ImageInputFileToBase64FunctionReturn } from "../../package-shared/types";
|
||||
type Param = {
|
||||
imageInputFile: File;
|
||||
maxWidth?: number;
|
||||
imagePreviewNode?: HTMLImageElement;
|
||||
};
|
||||
/**
|
||||
* # Image input File top Base64
|
||||
*/
|
||||
export default function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, }: Param): Promise<ImageInputFileToBase64FunctionReturn>;
|
||||
export {};
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = imageInputFileToBase64;
|
||||
/**
|
||||
* # Image input File top Base64
|
||||
*/
|
||||
function imageInputFileToBase64(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ imageInputFile, maxWidth, imagePreviewNode, }) {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imageName = imageInputFile.name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
let imageSize;
|
||||
let canvas = document.createElement("canvas");
|
||||
const MIME_TYPE = imageInputFile.type;
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
const file = imageInputFile;
|
||||
const blobURL = URL.createObjectURL(file);
|
||||
const img = new Image();
|
||||
/** ********************* Add source to new image */
|
||||
img.src = blobURL;
|
||||
imageDataBase64 = yield new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
console.log("Cannot load image");
|
||||
};
|
||||
/** ********************* Handle new image when loaded */
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
}
|
||||
else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
if (imagePreviewNode) {
|
||||
imagePreviewNode.src = srcEncoded;
|
||||
}
|
||||
res(srcEncoded);
|
||||
};
|
||||
});
|
||||
imageSize = yield new Promise((res, rej) => {
|
||||
canvas.toBlob((blob) => {
|
||||
res(blob === null || blob === void 0 ? void 0 : blob.size);
|
||||
}, MIME_TYPE, QUALITY);
|
||||
});
|
||||
return {
|
||||
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
imageSize: imageSize,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
return {
|
||||
imageBase64: undefined,
|
||||
imageBase64Full: undefined,
|
||||
imageName: undefined,
|
||||
imageSize: undefined,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
type FunctionReturn = {
|
||||
imageBase64?: string;
|
||||
imageBase64Full?: string;
|
||||
imageName?: string;
|
||||
};
|
||||
type Param = {
|
||||
imageInput: HTMLInputElement;
|
||||
maxWidth?: number;
|
||||
mimeType?: string;
|
||||
};
|
||||
/**
|
||||
* # Image Input Element to Base 64
|
||||
*/
|
||||
export default function imageInputToBase64({ imageInput, maxWidth, mimeType, }: Param): Promise<FunctionReturn>;
|
||||
export {};
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = imageInputToBase64;
|
||||
/**
|
||||
* # Image Input Element to Base 64
|
||||
*/
|
||||
function imageInputToBase64(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ imageInput, maxWidth, mimeType, }) {
|
||||
var _b, _c;
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
|
||||
let imageName = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0].name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
const file = (_c = imageInput.files) === null || _c === void 0 ? void 0 : _c[0];
|
||||
const blobURL = file ? URL.createObjectURL(file) : undefined;
|
||||
const img = new Image();
|
||||
if (blobURL) {
|
||||
img.src = blobURL;
|
||||
imageDataBase64 = yield new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
window.alert("Cannot load image!");
|
||||
};
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
const canvas = document.createElement("canvas");
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
}
|
||||
else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
if (imagePreviewNode) {
|
||||
document
|
||||
.querySelectorAll(`[data-imagepreview='image']`)
|
||||
.forEach((_img) => {
|
||||
const _imgEl = _img;
|
||||
_imgEl.src = srcEncoded;
|
||||
});
|
||||
}
|
||||
res(srcEncoded);
|
||||
};
|
||||
});
|
||||
return {
|
||||
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
return {};
|
||||
}
|
||||
});
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
type FunctionReturn = {
|
||||
fileBase64?: string;
|
||||
fileBase64Full?: string;
|
||||
fileName?: string;
|
||||
fileSize?: number;
|
||||
fileType?: string;
|
||||
};
|
||||
type Param = {
|
||||
inputFile: File;
|
||||
allowedRegex?: RegExp;
|
||||
};
|
||||
/**
|
||||
* Input File to base64
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description This function takes in a *SINGLE* input file from a HTML file input element.
|
||||
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
||||
* file from the array.
|
||||
*/
|
||||
export default function inputFileToBase64({ inputFile, allowedRegex, }: Param): Promise<FunctionReturn>;
|
||||
export {};
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = inputFileToBase64;
|
||||
/**
|
||||
* Input File to base64
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description This function takes in a *SINGLE* input file from a HTML file input element.
|
||||
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
||||
* file from the array.
|
||||
*/
|
||||
function inputFileToBase64(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ inputFile, allowedRegex, }) {
|
||||
var _b;
|
||||
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
||||
if (!((_b = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _b === void 0 ? void 0 : _b.match(allowedTypesRegex))) {
|
||||
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
|
||||
return {
|
||||
fileName: inputFile.name,
|
||||
};
|
||||
}
|
||||
try {
|
||||
let fileName = inputFile.name.replace(/\..*/, "");
|
||||
const fileData = yield new Promise((resolve, reject) => {
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(inputFile);
|
||||
reader.onload = function () {
|
||||
var _a;
|
||||
resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString());
|
||||
};
|
||||
reader.onerror = function (/** @type {*} */ error) {
|
||||
console.log("Error: ", error.message);
|
||||
};
|
||||
});
|
||||
return {
|
||||
fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""),
|
||||
fileBase64Full: fileData,
|
||||
fileName: fileName,
|
||||
fileSize: inputFile.size,
|
||||
fileType: inputFile.type,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.log("File Processing Error! =>", error.message);
|
||||
return {
|
||||
fileName: inputFile.name,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Parse request cookies
|
||||
* ============================================================================== *
|
||||
* @description This function takes in a request object and returns the cookies as a JS object
|
||||
*/
|
||||
export default function (): {
|
||||
[s: string]: any;
|
||||
} | null;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
/**
|
||||
* Parse request cookies
|
||||
* ============================================================================== *
|
||||
* @description This function takes in a request object and returns the cookies as a JS object
|
||||
*/
|
||||
function default_1() {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
const cookieString = document.cookie;
|
||||
if (!cookieString || typeof cookieString !== "string") {
|
||||
return null;
|
||||
}
|
||||
const cookieSplitArray = cookieString.split(";");
|
||||
let cookieObject = {};
|
||||
cookieSplitArray.forEach((keyValueString) => {
|
||||
const [key, value] = keyValueString.split("=");
|
||||
if (key && typeof key == "string") {
|
||||
cookieObject[key.replace(/^ +| +$/, "")] =
|
||||
value && typeof value == "string"
|
||||
? value.replace(/^ +| +$/, "")
|
||||
: null;
|
||||
}
|
||||
});
|
||||
return cookieObject;
|
||||
}
|
||||
Reference in New Issue
Block a user