Running prettier

This commit is contained in:
Fabian Stamm 2020-08-07 16:16:23 +02:00
parent e4d08dcbf9
commit 4191522b24
13 changed files with 4904 additions and 3979 deletions

View File

@ -1,4 +1,4 @@
*Psst  looking for a shareable component template? Go here --> [sveltejs/component-template](https://github.com/sveltejs/component-template)* _Psst <14>looking for a shareable component template? Go here --> [sveltejs/component-template](https://github.com/sveltejs/component-template)_
--- ---
@ -15,8 +15,7 @@ degit sveltejs/template svelte-app
cd svelte-app cd svelte-app
``` ```
*Note that you will need to have [Node.js](https://nodejs.org) installed.* _Note that you will need to have [Node.js](https://nodejs.org) installed._
## Get started ## Get started
@ -35,7 +34,6 @@ npm run dev
Navigate to [localhost:5000](http://localhost:5000). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes. Navigate to [localhost:5000](http://localhost:5000). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.
## Deploying to the web ## Deploying to the web
### With [now](https://zeit.co/now) ### With [now](https://zeit.co/now)

129
build.ts
View File

@ -1,17 +1,13 @@
import * as rollup from "rollup"; import * as rollup from "rollup";
import * as svelte from 'rollup-plugin-svelte'; import * as svelte from "rollup-plugin-svelte";
import * as resolve from 'rollup-plugin-node-resolve'; import * as resolve from "rollup-plugin-node-resolve";
import * as commonjs from 'rollup-plugin-commonjs'; import * as commonjs from "rollup-plugin-commonjs";
import * as typescript from "rollup-plugin-typescript2"; import * as typescript from "rollup-plugin-typescript2";
import * as fs from "fs"; import * as fs from "fs";
import * as copy from "rollup-plugin-copy-assets"; import * as copy from "rollup-plugin-copy-assets";
import { import { sass } from "svelte-preprocess-sass";
sass import { terser } from "rollup-plugin-terser";
} from 'svelte-preprocess-sass';
import {
terser
} from 'rollup-plugin-terser';
const production = process.argv.indexOf("-d") < 0; const production = process.argv.indexOf("-d") < 0;
console.log(`Runnung in ${production ? "production" : "development"} mode!`); console.log(`Runnung in ${production ? "production" : "development"} mode!`);
@ -19,20 +15,18 @@ console.log(`Runnung in ${production ? "production" : "development"} mode!`);
let plg = []; let plg = [];
if (production) { if (production) {
plg.push(terser()) plg.push(terser());
} }
if (!fs.existsSync("build")) if (!fs.existsSync("build")) fs.mkdirSync("build");
fs.mkdirSync("build");
const pages = ["Login", "Home", "User"]; const pages = ["Login", "Home", "User"];
let configs = pages.map(page => { let configs = pages.map((page) => {
if (!fs.existsSync("build/" + page.toLowerCase())) if (!fs.existsSync("build/" + page.toLowerCase()))
fs.mkdirSync("build/" + page.toLowerCase()); fs.mkdirSync("build/" + page.toLowerCase());
const pageHtml = generateHtml(page) const pageHtml = generateHtml(page);
fs.writeFileSync(`build/${page.toLowerCase()}/index.html`, pageHtml); fs.writeFileSync(`build/${page.toLowerCase()}/index.html`, pageHtml);
@ -40,37 +34,37 @@ let configs = pages.map(page => {
input: `./src/${page}/main.js`, input: `./src/${page}/main.js`,
output: { output: {
sourcemap: !production, sourcemap: !production,
format: 'iife', format: "iife",
name: "app", name: "app",
file: `build/${page.toLowerCase()}/bundle.js` file: `build/${page.toLowerCase()}/bundle.js`,
}, },
watch: { watch: {
clearScreen: false clearScreen: false,
}, },
treeshake: production, treeshake: production,
plugins: [ plugins: [
(typescript as any)({ (typescript as any)({
tsconfig: "./src/tsconfig.json" tsconfig: "./src/tsconfig.json",
}), }),
svelte({ svelte({
// enable run-time checks when not in production // enable run-time checks when not in production
dev: !production, dev: !production,
css: css => { css: (css) => {
css.write(`build/${page.toLowerCase()}/bundle.css`); css.write(`build/${page.toLowerCase()}/bundle.css`);
}, },
preprocess: { preprocess: {
style: sass({ style: sass({
includePaths: ['src', 'node_modules'] includePaths: ["src", "node_modules"],
}) }),
} },
}), }),
(resolve as any)(), (resolve as any)(),
(commonjs as any)(), (commonjs as any)(),
...plg ...plg,
] ],
}; };
}) });
import * as path from "path"; import * as path from "path";
@ -99,12 +93,12 @@ function generateHtml(pagename: string) {
<script src='bundle.js'></script> <script src='bundle.js'></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" lazyload> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" lazyload>
</body> </body>
</html>` </html>`;
} }
let start: [number, number]; let start: [number, number];
if (process.argv.indexOf("-w") >= 0) { if (process.argv.indexOf("-w") >= 0) {
rollup.watch(configs).on("event", event => { rollup.watch(configs).on("event", (event) => {
if (event.code === "BUNDLE_START") { if (event.code === "BUNDLE_START") {
start = process.hrtime(); start = process.hrtime();
} else if (event.code === "BUNDLE_END") { } else if (event.code === "BUNDLE_END") {
@ -118,20 +112,29 @@ if (process.argv.indexOf("-w") >= 0) {
} else { } else {
console.log(event); console.log(event);
} }
}) });
} else { } else {
start = process.hrtime(); start = process.hrtime();
Promise.all(configs.map(config => { Promise.all(
return rollup.rollup(config).then((value) => { configs.map((config) => {
return value.write(Array.isArray(config.output) ? config.output[0] : config.output); return rollup
}).catch(err => { .rollup(config)
handleError(err, true); .then((value) => {
// console.error(err); return value.write(
Array.isArray(config.output)
? config.output[0]
: config.output
);
})
.catch((err) => {
handleError(err, true);
// console.error(err);
});
}) })
})).then(vals => { ).then((vals) => {
let diff = process.hrtime(start); let diff = process.hrtime(start);
console.log(`--- Took ${diff[0] * 1000 + diff[1] / 1000000}ms`); console.log(`--- Took ${diff[0] * 1000 + diff[1] / 1000000}ms`);
}) });
} }
var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/; var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
@ -148,8 +151,7 @@ function isAbsolute(path) {
// } // }
function relativeId(id) { function relativeId(id) {
if (typeof process === 'undefined' || !isAbsolute(id)) if (typeof process === "undefined" || !isAbsolute(id)) return id;
return id;
return path.relative(process.cwd(), id); return path.relative(process.cwd(), id);
} }
@ -157,7 +159,7 @@ const tc: any = {
enabled: enabled:
process.env.FORCE_COLOR || process.env.FORCE_COLOR ||
process.platform === "win32" || process.platform === "win32" ||
(process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb") (process.stdout.isTTY && process.env.TERM && process.env.TERM !== "dumb"),
}; };
const Styles = (tc.Styles = {}); const Styles = (tc.Styles = {});
const defineProp = Object.defineProperty; const defineProp = Object.defineProperty;
@ -167,7 +169,7 @@ const init = (style, open, close, re) => {
len = 1, len = 1,
seq = [(Styles[style] = { open, close, re })]; seq = [(Styles[style] = { open, close, re })];
const fn = s => { const fn = (s) => {
if (tc.enabled) { if (tc.enabled) {
for (i = 0, s += ""; i < len; i++) { for (i = 0, s += ""; i < len; i++) {
style = seq[i]; style = seq[i];
@ -180,19 +182,19 @@ const init = (style, open, close, re) => {
} }
len = 1; len = 1;
} }
return s return s;
}; };
defineProp(tc, style, { defineProp(tc, style, {
get: () => { get: () => {
for (let k in Styles) for (let k in Styles)
defineProp(fn, k, { defineProp(fn, k, {
get: () => ((seq[len++] = Styles[k]), fn) get: () => ((seq[len++] = Styles[k]), fn),
}); });
delete tc[style]; delete tc[style];
return (tc[style] = fn) return (tc[style] = fn);
}, },
configurable: true configurable: true,
}); });
}; };
@ -224,33 +226,40 @@ init("bgWhite", "\x1b[47m", "\x1b[49m", /\x1b\[49m/g);
const turbocolor: any = tc; const turbocolor: any = tc;
function handleError(err, recover) { function handleError(err, recover) {
if (recover === void 0) { recover = false; } if (recover === void 0) {
recover = false;
}
var description = err.message || err; var description = err.message || err;
if (err.name) if (err.name) description = err.name + ": " + description;
description = err.name + ": " + description; var message =
var message = (err.plugin (err.plugin
? "(" + err.plugin + " plugin) " + description ? "(" + err.plugin + " plugin) " + description
: description) || err; : description) || err;
console.error(turbocolor.bold.red("[!] " + turbocolor.bold(message.toString()))); console.error(
turbocolor.bold.red("[!] " + turbocolor.bold(message.toString()))
);
if (err.url) { if (err.url) {
console.error(turbocolor.cyan(err.url)); console.error(turbocolor.cyan(err.url));
} }
if (err.loc) { if (err.loc) {
console.error(relativeId(err.loc.file || err.id) + " (" + err.loc.line + ":" + err.loc.column + ")"); console.error(
} relativeId(err.loc.file || err.id) +
else if (err.id) { " (" +
err.loc.line +
":" +
err.loc.column +
")"
);
} else if (err.id) {
console.error(relativeId(err.id)); console.error(relativeId(err.id));
} }
if (err.frame) { if (err.frame) {
console.error(turbocolor.dim(err.frame)); console.error(turbocolor.dim(err.frame));
} }
if (err.stack) { if (err.stack) {
//console.error(turbocolor.dim(err.stack)); //console.error(turbocolor.dim(err.stack));
} }
console.error(''); console.error("");
if (!recover) if (!recover) process.exit(1);
process.exit(1);
} }

4800
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
import App from './App.svelte'; import App from "./App.svelte";
var app = new App({ var app = new App({
target: document.getElementById("content") target: document.getElementById("content"),
}); });
export default app; export default app;

View File

@ -1,9 +1,6 @@
import request from "../request"; import request from "../request";
import sha from "../sha512"; import sha from "../sha512";
import { import { setCookie, getCookie } from "../cookie";
setCookie,
getCookie
} from "../cookie"
export interface TwoFactor { export interface TwoFactor {
id: string; id: string;
@ -15,7 +12,7 @@ export enum TFATypes {
OTC, OTC,
BACKUP_CODE, BACKUP_CODE,
U2F, U2F,
APP_ALLOW APP_ALLOW,
} }
// const Api = { // const Api = {
@ -41,8 +38,9 @@ export interface IToken {
} }
function makeid(length) { function makeid(length) {
var result = ''; var result = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var charactersLength = characters.length; var charactersLength = characters.length;
for (var i = 0; i < length; i++) { for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength)); result += characters.charAt(Math.floor(Math.random() * charactersLength));
@ -62,98 +60,123 @@ export default class Api {
return this.username || getCookie("username"); return this.username || getCookie("username");
} }
static async setUsername(username: string): Promise<{ error: string | undefined }> { static async setUsername(
return request("/api/user/login", { username: string
type: "username", ): Promise<{ error: string | undefined }> {
username return request(
}, "POST").then(res => { "/api/user/login",
this.salt = res.salt; {
this.username = username; type: "username",
return { username,
error: undefined },
} "POST"
}).catch(err => { )
let error = err.message; .then((res) => {
return { error } this.salt = res.salt;
}) this.username = username;
return {
error: undefined,
};
})
.catch((err) => {
let error = err.message;
return { error };
});
} }
static async setPassword(password: string): Promise<{ error: string | undefined, twofactor?: any }> { static async setPassword(
password: string
): Promise<{ error: string | undefined; twofactor?: any }> {
const date = new Date().valueOf(); const date = new Date().valueOf();
let pw = sha(sha(this.salt + password) + date.toString()); let pw = sha(sha(this.salt + password) + date.toString());
return request("/api/user/login", { return request(
type: "password" "/api/user/login",
}, "POST", { {
username: this.username, type: "password",
password: pw, },
date "POST",
} {
).then(({ username: this.username,
login, password: pw,
special, date,
tfa
}) => {
this.login = login;
this.special = special;
if (tfa && Array.isArray(tfa) && tfa.length > 0)
this.twofactor = tfa;
else
this.twofactor = undefined;
return {
error: undefined
} }
}).catch(err => { )
let error = err.message; .then(({ login, special, tfa }) => {
return { error } this.login = login;
}) this.special = special;
if (tfa && Array.isArray(tfa) && tfa.length > 0)
this.twofactor = tfa;
else this.twofactor = undefined;
return {
error: undefined,
};
})
.catch((err) => {
let error = err.message;
return { error };
});
} }
static gettok() { static gettok() {
return { return {
login: this.login.token, login: this.login.token,
special: this.special.token special: this.special.token,
} };
} }
static async sendBackup(id: string, code: string) { static async sendBackup(id: string, code: string) {
return request("/api/user/twofactor/backup", this.gettok(), "PUT", { code, id }).then(({ login_exp, special_exp }) => { return request("/api/user/twofactor/backup", this.gettok(), "PUT", {
this.login.expires = login_exp; code,
this.special.expires = special_exp; id,
return {}; })
}).catch(err => ({ error: err.message })); .then(({ login_exp, special_exp }) => {
this.login.expires = login_exp;
this.special.expires = special_exp;
return {};
})
.catch((err) => ({ error: err.message }));
} }
static async sendOTC(id: string, code: string) { static async sendOTC(id: string, code: string) {
return request("/api/user/twofactor/otc", this.gettok(), "PUT", { code, id }).then(({ login_exp, special_exp }) => { return request("/api/user/twofactor/otc", this.gettok(), "PUT", {
this.login.expires = login_exp; code,
this.special.expires = special_exp; id,
return {}; })
}).catch(error => ({ error: error.message })) .then(({ login_exp, special_exp }) => {
this.login.expires = login_exp;
this.special.expires = special_exp;
return {};
})
.catch((error) => ({ error: error.message }));
} }
static finish() { static finish() {
let d = new Date() let d = new Date();
d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); //Keep the username 30 days d.setTime(d.getTime() + 30 * 24 * 60 * 60 * 1000); //Keep the username 30 days
setCookie("username", this.username, d.toUTCString()); setCookie("username", this.username, d.toUTCString());
setCookie("login", this.login.token, new Date(this.login.expires).toUTCString()); setCookie(
setCookie("special", this.special.token, new Date(this.special.expires).toUTCString()); "login",
this.login.token,
new Date(this.login.expires).toUTCString()
);
setCookie(
"special",
this.special.token,
new Date(this.special.expires).toUTCString()
);
let url = new URL(window.location.href); let url = new URL(window.location.href);
let state = url.searchParams.get("state") let state = url.searchParams.get("state");
let red = "/" let red = "/";
if (state) { if (state) {
let base64 = url.searchParams.get("base64") let base64 = url.searchParams.get("base64");
if (base64) if (base64) red = atob(state);
red = atob(state) else red = state;
else
red = state
} }
setTimeout(() => window.location.href = red, 200); setTimeout(() => (window.location.href = red), 200);
} }
} }

View File

@ -1,8 +1,7 @@
import App from './App.svelte'; import App from "./App.svelte";
var app = new App({ var app = new App({
target: document.getElementById("content") target: document.getElementById("content"),
}); });
export default app; export default app;

View File

@ -1,7 +1,7 @@
import App from './App.svelte'; import App from "./App.svelte";
var app = new App({ var app = new App({
target: document.getElementById("content") target: document.getElementById("content"),
}); });
export default app; export default app;

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,15 @@
export function setCookie(cname: string, cvalue: string, exdate: string) { export function setCookie(cname: string, cvalue: string, exdate: string) {
const expires = exdate ? `;expires=${exdate}` : ""; const expires = exdate ? `;expires=${exdate}` : "";
document.cookie = `${cname}=${cvalue}${expires};path=/;` document.cookie = `${cname}=${cvalue}${expires};path=/;`;
} }
export function getCookie(cname: string) { export function getCookie(cname: string) {
const name = cname + "="; const name = cname + "=";
const dc = decodeURIComponent(document.cookie); const dc = decodeURIComponent(document.cookie);
const ca = dc.split(';'); const ca = dc.split(";");
for (let i = 0; i < ca.length; i++) { for (let i = 0; i < ca.length; i++) {
let c = ca[i]; let c = ca[i];
while (c.charAt(0) == ' ') { while (c.charAt(0) == " ") {
c = c.substring(1); c = c.substring(1);
} }
if (c.indexOf(name) == 0) { if (c.indexOf(name) == 0) {

View File

@ -2,7 +2,7 @@
const elements = new WeakSet(); const elements = new WeakSet();
function check() { function check() {
document.querySelectorAll(".floating>input").forEach(e => { document.querySelectorAll(".floating>input").forEach((e) => {
if (elements.has(e)) return; if (elements.has(e)) return;
elements.add(e); elements.add(e);
@ -10,26 +10,25 @@
console.log("Check State"); console.log("Check State");
if (e.value !== "") { if (e.value !== "") {
if (e.classList.contains("used")) return; if (e.classList.contains("used")) return;
e.classList.add("used") e.classList.add("used");
} else { } else {
if (e.classList.contains("used")) e.classList.remove("used") if (e.classList.contains("used")) e.classList.remove("used");
} }
} }
e.addEventListener("change", () => checkState()) e.addEventListener("change", () => checkState());
checkState() checkState();
}) });
}; }
const observer = new MutationObserver((mutations) => { const observer = new MutationObserver((mutations) => {
check(); check();
}); });
// Start observing the target node for configured mutations // Start observing the target node for configured mutations
observer.observe(window.document, { observer.observe(window.document, {
childList: true, childList: true,
subtree: true subtree: true,
}); });
check(); check();
})() })();

View File

@ -4,7 +4,14 @@ import { getCookie } from "./cookie";
// const baseURL = "http://localhost:3000"; // const baseURL = "http://localhost:3000";
const baseURL = ""; const baseURL = "";
export default async function request(endpoint: string, parameters: { [key: string]: string } = {}, method: "GET" | "POST" | "DELETE" | "PUT" = "GET", body?: any, authInParam = false, redirect = false) { export default async function request(
endpoint: string,
parameters: { [key: string]: string } = {},
method: "GET" | "POST" | "DELETE" | "PUT" = "GET",
body?: any,
authInParam = false,
redirect = false
) {
let pairs = []; let pairs = [];
if (authInParam) { if (authInParam) {
@ -26,19 +33,23 @@ export default async function request(endpoint: string, parameters: { [key: stri
body: JSON.stringify(body), body: JSON.stringify(body),
credentials: "same-origin", credentials: "same-origin",
headers: { headers: {
'content-type': 'application/json' "content-type": "application/json",
}, },
}).then(e => {
if (e.status !== 200) throw new Error(e.statusText)
return e.json()
}).then(data => {
if (data.error) {
if (redirect && data.additional && data.additional.auth) {
let state = btoa(window.location.pathname + window.location.hash);
window.location.href = `/login?state=${state}&base64=true`;
}
return Promise.reject(new Error(data.error))
}
return data;
}) })
.then((e) => {
if (e.status !== 200) throw new Error(e.statusText);
return e.json();
})
.then((data) => {
if (data.error) {
if (redirect && data.additional && data.additional.auth) {
let state = btoa(
window.location.pathname + window.location.hash
);
window.location.href = `/login?state=${state}&base64=true`;
}
return Promise.reject(new Error(data.error));
}
return data;
});
} }

File diff suppressed because one or more lines are too long