This commit is contained in:
Benjamin Toby
2025-07-05 14:59:30 +01:00
parent 6e334c2525
commit 7e8bb37c09
526 changed files with 17560 additions and 11386 deletions
+1 -4
View File
@@ -1,12 +1,9 @@
"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, }) {
export default function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
if (setLoading)
setLoading(true);
const scopeString = scopes ? scopes.join("%20") : "read:user";
+16 -31
View File
@@ -1,44 +1,29 @@
"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;
});
export default async function getAccessToken(params) {
var _a, _b;
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
const response = (await 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, }) {
export function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
setTimeout(() => {
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
}, 3000);
+72 -89
View File
@@ -1,103 +1,86 @@
"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 get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
import parseClientCookies from "../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* () {
export default async function logout(params) {
try {
const localUser = localStorage.getItem("user");
let targetUser;
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((0, get_csrf_header_name_1.default)());
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);
}
targetUser = JSON.parse(localUser || "");
}
catch (error) {
console.log(error);
}
if (!targetUser) {
return false;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const cookies = parseClientCookies();
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(getCsrfHeaderName());
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const response = await 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);
}
});
return response;
}
catch (error) {
return false;
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
else {
resolve(true);
}
});
return response;
}
catch (error) {
return false;
}
}
+3 -9
View File
@@ -1,10 +1,4 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = postLogin;
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
/**
* Client Setup After Login
* ===============================================================================
@@ -12,13 +6,13 @@ const get_csrf_header_name_1 = __importDefault(require("../../package-shared/act
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
* function
*/
function postLogin(res) {
export default function postLogin(res) {
try {
if (!res.payload)
return false;
if (!res.payload.csrf_k)
return false;
localStorage.setItem((0, get_csrf_header_name_1.default)(), res.payload.csrf_k);
localStorage.setItem(getCsrfHeaderName(), res.payload.csrf_k);
localStorage.setItem("user", JSON.stringify(res.payload));
return true;
}
+20 -5
View File
@@ -1,6 +1,10 @@
type FetchApiOptions = {
type FetchApiOptions<T extends {
[k: string]: any;
} = {
[k: string]: any;
}> = {
method: "POST" | "GET" | "DELETE" | "PUT" | "PATCH" | "post" | "get" | "delete" | "put" | "patch";
body?: object | string;
body?: T | string;
headers?: FetchHeader;
};
type FetchHeader = HeadersInit & {
@@ -15,7 +19,18 @@ export type FetchApiReturn = {
/**
* # 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 default function fetchApi<T extends {
[k: string]: any;
} = {
[k: string]: any;
}, R extends any = any>(url: string, options?: FetchApiOptions<T>, csrf?: boolean,
/**
* Key to use to grab local Storage csrf value.
*/
localStorageCSRFKey?: string,
/**
* Key with which to set the request header csrf
* value
*/
csrfHeaderKey?: string): Promise<R>;
export {};
+70 -80
View File
@@ -1,90 +1,80 @@
"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"));
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
import _ from "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 || (0, get_csrf_header_name_1.default)());
let finalHeaders = {
"Content-Type": "application/json",
};
if (csrf && csrfValue) {
finalHeaders[(0, get_csrf_header_name_1.default)()] = csrfValue;
}
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;
export default async function fetchApi(url, options, csrf,
/**
* Key to use to grab local Storage csrf value.
*/
localStorageCSRFKey,
/**
* Key with which to set the request header csrf
* value
*/
csrfHeaderKey) {
let data;
const csrfKey = "x-dsql-csrf-key";
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
let finalHeaders = {
"Content-Type": "application/json",
};
if (csrf && csrfValue) {
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
}
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = await fetch(url, {
method: options,
headers: finalHeaders,
});
data = fetchData.json();
break;
default:
fetchData = await fetch(url);
data = fetchData.json();
break;
}
}
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;
}
catch (error) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
else {
try {
let fetchData = yield fetch(url);
data = yield fetchData.json();
}
else if (typeof options === "object") {
try {
let fetchData;
if (options.body && typeof options.body === "object") {
let oldOptionsBody = _.cloneDeep(options.body);
options.body = JSON.stringify(oldOptionsBody);
}
catch (error) {
console.log("FetchAPI error #3:", error.message);
data = null;
if (options.headers) {
options.headers = _.merge(options.headers, finalHeaders);
const finalOptions = Object.assign({}, options);
fetchData = await fetch(url, finalOptions);
}
else {
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
fetchData = await fetch(url, finalOptions);
}
data = fetchData.json();
}
return data;
});
catch (error) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
}
else {
try {
let fetchData = await fetch(url);
data = await fetchData.json();
}
catch (error) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
}
+33 -38
View File
@@ -1,60 +1,55 @@
"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"));
const post_login_1 = __importDefault(require("./auth/post-login"));
const deserialize_query_1 = __importDefault(require("../package-shared/utils/deserialize-query"));
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
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 clientFetch from "./fetch";
import serializeQuery from "../package-shared/utils/serialize-query";
import serializeCookies from "../package-shared/utils/serialize-cookies";
import EJSON from "../package-shared/utils/ejson";
import numberfy from "../package-shared/utils/numberfy";
import slugify from "../package-shared/utils/slugify";
import postLogin from "./auth/post-login";
import deserializeQuery from "../package-shared/utils/deserialize-query";
import debugLog from "../package-shared/utils/logging/debug-log";
const media = {
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
inputFileToBase64: inputFileToBase64_1.default,
imageInputToBase64: imageInputToBase64,
imageInputFileToBase64: imageInputFileToBase64,
inputFileToBase64: inputFileToBase64,
};
/**
* User Auth Object
*/
const auth = {
google: {
getAccessToken: getAccessToken_1.default,
getAccessToken: getAccessToken,
},
github: {
getAccessToken: getAccessToken_2.default,
getAccessToken: getGithubAccessToken,
},
logout: logout_1.default,
postLogin: post_login_1.default,
logout,
postLogin,
};
const utils = {
deserializeQuery: deserialize_query_1.default,
serializeQuery: serialize_query_1.default,
serializeCookies: serialize_cookies_1.default,
EJSON: ejson_1.default,
numberfy: numberfy_1.default,
slugify: slugify_1.default,
debugLog: debug_log_1.default,
deserializeQuery,
serializeQuery,
serializeCookies,
EJSON,
numberfy,
slugify,
debugLog,
};
/**
* Fetch
*/
const fetch = {
fetchApi: fetch_1.default,
clientFetch: fetch_2.default,
fetchApi,
clientFetch,
};
/**
* Main Export
*/
const datasquirelClient = { media, auth, fetch, utils };
exports.default = datasquirelClient;
export default datasquirelClient;
+7 -12
View File
@@ -1,18 +1,13 @@
"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"));
import imageInputFileToBase64 from "./imageInputFileToBase64";
import imageInputToBase64 from "./imageInputToBase64";
/**
* ==========================
* Media Functions Object
* ==========================
*/
const media = {
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
imageInputToBase64: imageInputToBase64,
imageInputFileToBase64: imageInputFileToBase64,
};
/**
* ==========================
@@ -20,8 +15,8 @@ const media = {
* ==========================
*/
const auth = {
imageInputToBase64: imageInputToBase64_1.default,
imageInputFileToBase64: imageInputFileToBase64_1.default,
imageInputToBase64: imageInputToBase64,
imageInputFileToBase64: imageInputFileToBase64,
};
/**
* ==========================
@@ -31,4 +26,4 @@ const auth = {
const datasquirelClient = {
media: media,
};
exports.default = datasquirelClient;
export default datasquirelClient;
+72 -86
View File
@@ -1,92 +1,78 @@
"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,
export default async function imageInputFileToBase64({ 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 = await new Promise((res, rej) => {
/** ********************* Handle Errors in loading image */
img.onerror = function () {
URL.revokeObjectURL(this.src);
console.log("Cannot load image");
};
}
catch (error) {
console.log("Image Processing Error! =>", error.message);
return {
imageBase64: undefined,
imageBase64Full: undefined,
imageName: undefined,
imageSize: undefined,
/** ********************* 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 = await 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,
};
}
}
+68 -82
View File
@@ -1,90 +1,76 @@
"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,
export default async function imageInputToBase64({ imageInput, maxWidth, mimeType, }) {
var _a, _b;
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
try {
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
let imageName = (_a = imageInput.files) === null || _a === void 0 ? void 0 : _a[0].name.replace(/\..*/, "");
let imageDataBase64;
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
const QUALITY = 0.95;
const MAX_WIDTH = maxWidth ? maxWidth : null;
const file = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0];
const blobURL = file ? URL.createObjectURL(file) : undefined;
const img = new Image();
if (blobURL) {
img.src = blobURL;
imageDataBase64 = await new Promise((res, rej) => {
/** ********************* Handle Errors in loading image */
img.onerror = function () {
URL.revokeObjectURL(this.src);
window.alert("Cannot load image!");
};
}
else {
return {};
}
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,
};
}
catch ( /** @type {*} */error) {
console.log("Image Processing Error! =>", error.message);
else {
return {};
}
});
}
catch ( /** @type {*} */error) {
console.log("Image Processing Error! =>", error.message);
return {};
}
}
+34 -48
View File
@@ -1,15 +1,3 @@
"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
* ==============================================================================
@@ -18,42 +6,40 @@ exports.default = inputFileToBase64;
* 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,
export default async function inputFileToBase64({ inputFile, allowedRegex, }) {
var _a;
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
if (!((_a = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _a === void 0 ? void 0 : _a.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 = await 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());
};
}
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,
reader.onerror = function (/** @type {*} */ error) {
console.log("Error: ", error.message);
};
}
catch (error) {
console.log("File Processing Error! =>", error.message);
return {
fileName: inputFile.name,
};
}
});
});
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,
};
}
}
+1 -4
View File
@@ -1,12 +1,9 @@
"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() {
export default function () {
/**
* Check inputs
*