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
```
*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
@ -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.
## Deploying to the web
### With [now](https://zeit.co/now)

131
build.ts
View File

@ -1,17 +1,13 @@
import * as rollup from "rollup";
import * as svelte from 'rollup-plugin-svelte';
import * as resolve from 'rollup-plugin-node-resolve';
import * as commonjs from 'rollup-plugin-commonjs';
import * as svelte from "rollup-plugin-svelte";
import * as resolve from "rollup-plugin-node-resolve";
import * as commonjs from "rollup-plugin-commonjs";
import * as typescript from "rollup-plugin-typescript2";
import * as fs from "fs";
import * as copy from "rollup-plugin-copy-assets";
import {
sass
} from 'svelte-preprocess-sass';
import {
terser
} from 'rollup-plugin-terser';
import { sass } from "svelte-preprocess-sass";
import { terser } from "rollup-plugin-terser";
const production = process.argv.indexOf("-d") < 0;
console.log(`Runnung in ${production ? "production" : "development"} mode!`);
@ -19,20 +15,18 @@ console.log(`Runnung in ${production ? "production" : "development"} mode!`);
let plg = [];
if (production) {
plg.push(terser())
plg.push(terser());
}
if (!fs.existsSync("build"))
fs.mkdirSync("build");
if (!fs.existsSync("build")) fs.mkdirSync("build");
const pages = ["Login", "Home", "User"];
let configs = pages.map(page => {
let configs = pages.map((page) => {
if (!fs.existsSync("build/" + page.toLowerCase()))
fs.mkdirSync("build/" + page.toLowerCase());
const pageHtml = generateHtml(page)
const pageHtml = generateHtml(page);
fs.writeFileSync(`build/${page.toLowerCase()}/index.html`, pageHtml);
@ -40,37 +34,37 @@ let configs = pages.map(page => {
input: `./src/${page}/main.js`,
output: {
sourcemap: !production,
format: 'iife',
format: "iife",
name: "app",
file: `build/${page.toLowerCase()}/bundle.js`
file: `build/${page.toLowerCase()}/bundle.js`,
},
watch: {
clearScreen: false
clearScreen: false,
},
treeshake: production,
plugins: [
(typescript as any)({
tsconfig: "./src/tsconfig.json"
tsconfig: "./src/tsconfig.json",
}),
svelte({
// enable run-time checks when not in production
dev: !production,
css: css => {
css: (css) => {
css.write(`build/${page.toLowerCase()}/bundle.css`);
},
preprocess: {
style: sass({
includePaths: ['src', 'node_modules']
})
}
includePaths: ["src", "node_modules"],
}),
},
}),
(resolve as any)(),
(commonjs as any)(),
...plg
]
...plg,
],
};
})
});
import * as path from "path";
@ -99,12 +93,12 @@ function generateHtml(pagename: string) {
<script src='bundle.js'></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto" lazyload>
</body>
</html>`
</html>`;
}
let start: [number, number];
if (process.argv.indexOf("-w") >= 0) {
rollup.watch(configs).on("event", event => {
rollup.watch(configs).on("event", (event) => {
if (event.code === "BUNDLE_START") {
start = process.hrtime();
} else if (event.code === "BUNDLE_END") {
@ -118,20 +112,29 @@ if (process.argv.indexOf("-w") >= 0) {
} else {
console.log(event);
}
})
});
} else {
start = process.hrtime();
Promise.all(configs.map(config => {
return rollup.rollup(config).then((value) => {
return value.write(Array.isArray(config.output) ? config.output[0] : config.output);
}).catch(err => {
handleError(err, true);
// console.error(err);
Promise.all(
configs.map((config) => {
return rollup
.rollup(config)
.then((value) => {
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);
console.log(`--- Took ${diff[0] * 1000 + diff[1] / 1000000}ms`);
})
});
}
var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
@ -148,8 +151,7 @@ function isAbsolute(path) {
// }
function relativeId(id) {
if (typeof process === 'undefined' || !isAbsolute(id))
return id;
if (typeof process === "undefined" || !isAbsolute(id)) return id;
return path.relative(process.cwd(), id);
}
@ -157,7 +159,7 @@ const tc: any = {
enabled:
process.env.FORCE_COLOR ||
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 defineProp = Object.defineProperty;
@ -167,7 +169,7 @@ const init = (style, open, close, re) => {
len = 1,
seq = [(Styles[style] = { open, close, re })];
const fn = s => {
const fn = (s) => {
if (tc.enabled) {
for (i = 0, s += ""; i < len; i++) {
style = seq[i];
@ -180,19 +182,19 @@ const init = (style, open, close, re) => {
}
len = 1;
}
return s
return s;
};
defineProp(tc, style, {
get: () => {
for (let k in Styles)
defineProp(fn, k, {
get: () => ((seq[len++] = Styles[k]), fn)
get: () => ((seq[len++] = Styles[k]), fn),
});
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;
function handleError(err, recover) {
if (recover === void 0) { recover = false; }
if (recover === void 0) {
recover = false;
}
var description = err.message || err;
if (err.name)
description = err.name + ": " + description;
var message = (err.plugin
? "(" + err.plugin + " plugin) " + description
: description) || err;
console.error(turbocolor.bold.red("[!] " + turbocolor.bold(message.toString())));
if (err.name) description = err.name + ": " + description;
var message =
(err.plugin
? "(" + err.plugin + " plugin) " + description
: description) || err;
console.error(
turbocolor.bold.red("[!] " + turbocolor.bold(message.toString()))
);
if (err.url) {
console.error(turbocolor.cyan(err.url));
}
if (err.loc) {
console.error(relativeId(err.loc.file || err.id) + " (" + err.loc.line + ":" + err.loc.column + ")");
}
else if (err.id) {
console.error(
relativeId(err.loc.file || err.id) +
" (" +
err.loc.line +
":" +
err.loc.column +
")"
);
} else if (err.id) {
console.error(relativeId(err.id));
}
if (err.frame) {
console.error(turbocolor.dim(err.frame));
}
if (err.stack) {
//console.error(turbocolor.dim(err.stack));
}
console.error('');
if (!recover)
process.exit(1);
}
console.error("");
if (!recover) 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({
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 sha from "../sha512";
import {
setCookie,
getCookie
} from "../cookie"
import { setCookie, getCookie } from "../cookie";
export interface TwoFactor {
id: string;
@ -15,7 +12,7 @@ export enum TFATypes {
OTC,
BACKUP_CODE,
U2F,
APP_ALLOW
APP_ALLOW,
}
// const Api = {
@ -41,8 +38,9 @@ export interface IToken {
}
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var result = "";
var characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
@ -62,98 +60,123 @@ export default class Api {
return this.username || getCookie("username");
}
static async setUsername(username: string): Promise<{ error: string | undefined }> {
return request("/api/user/login", {
type: "username",
username
}, "POST").then(res => {
this.salt = res.salt;
this.username = username;
return {
error: undefined
}
}).catch(err => {
let error = err.message;
return { error }
})
static async setUsername(
username: string
): Promise<{ error: string | undefined }> {
return request(
"/api/user/login",
{
type: "username",
username,
},
"POST"
)
.then((res) => {
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();
let pw = sha(sha(this.salt + password) + date.toString());
return request("/api/user/login", {
type: "password"
}, "POST", {
username: this.username,
password: pw,
date
}
).then(({
login,
special,
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
return request(
"/api/user/login",
{
type: "password",
},
"POST",
{
username: this.username,
password: pw,
date,
}
}).catch(err => {
let error = err.message;
return { error }
})
)
.then(({ login, special, 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;
return { error };
});
}
static gettok() {
return {
login: this.login.token,
special: this.special.token
}
special: this.special.token,
};
}
static async sendBackup(id: string, code: string) {
return request("/api/user/twofactor/backup", this.gettok(), "PUT", { code, id }).then(({ login_exp, special_exp }) => {
this.login.expires = login_exp;
this.special.expires = special_exp;
return {};
}).catch(err => ({ error: err.message }));
return request("/api/user/twofactor/backup", this.gettok(), "PUT", {
code,
id,
})
.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) {
return request("/api/user/twofactor/otc", this.gettok(), "PUT", { code, id }).then(({ login_exp, special_exp }) => {
this.login.expires = login_exp;
this.special.expires = special_exp;
return {};
}).catch(error => ({ error: error.message }))
return request("/api/user/twofactor/otc", this.gettok(), "PUT", {
code,
id,
})
.then(({ login_exp, special_exp }) => {
this.login.expires = login_exp;
this.special.expires = special_exp;
return {};
})
.catch((error) => ({ error: error.message }));
}
static finish() {
let d = new Date()
d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000)); //Keep the username 30 days
let d = new Date();
d.setTime(d.getTime() + 30 * 24 * 60 * 60 * 1000); //Keep the username 30 days
setCookie("username", this.username, d.toUTCString());
setCookie("login", this.login.token, new Date(this.login.expires).toUTCString());
setCookie("special", this.special.token, new Date(this.special.expires).toUTCString());
setCookie(
"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 state = url.searchParams.get("state")
let red = "/"
let state = url.searchParams.get("state");
let red = "/";
if (state) {
let base64 = url.searchParams.get("base64")
if (base64)
red = atob(state)
else
red = state
let base64 = url.searchParams.get("base64");
if (base64) red = atob(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({
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({
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) {
const expires = exdate ? `;expires=${exdate}` : "";
document.cookie = `${cname}=${cvalue}${expires};path=/;`
document.cookie = `${cname}=${cvalue}${expires};path=/;`;
}
export function getCookie(cname: string) {
const name = cname + "=";
const dc = decodeURIComponent(document.cookie);
const ca = dc.split(';');
const ca = dc.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
while (c.charAt(0) == " ") {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
@ -17,4 +17,4 @@ export function getCookie(cname: string) {
}
}
return "";
}
}

View File

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

View File

@ -4,7 +4,14 @@ import { getCookie } from "./cookie";
// const baseURL = "http://localhost:3000";
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 = [];
if (authInParam) {
@ -26,19 +33,23 @@ export default async function request(endpoint: string, parameters: { [key: stri
body: JSON.stringify(body),
credentials: "same-origin",
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

View File

@ -3,4 +3,4 @@
"module": "esnext",
"sourceMap": true
}
}
}