Hello Typescript!

This commit is contained in:
undefined committed 2020-07-07 19:58:21 +08:00
1 parent c9b6412527
commit ba03d7a7bf
98 files changed
+3186 -2616

No files matched your search

-19
View File
@@ -1,19 +0,0 @@
const superagent = require('superagent');
const fs = require('fs');
async function _download(url, path, retry) {
const w = fs.createWriteStream(path);
await superagent.get(url).retry(retry).pipe(w);
await new Promise((resolve, reject) => {
w.on('finish', resolve);
w.on('error', reject);
});
return path;
}
function download(url, path, retry = 3) {
if (path) return _download(url, path, retry);
return superagent.get(url).retry(retry);
}
global.Hydro.lib.download = module.exports = download;
+19
View File
@@ -0,0 +1,19 @@
import superagent from 'superagent';
import fs from 'fs';
async function _download(url: string, path: string, retry: number) {
const w = fs.createWriteStream(path);
superagent.get(url).retry(retry).pipe(w);
await new Promise((resolve, reject) => {
w.on('finish', resolve);
w.on('error', reject);
});
return path;
}
export default function download(url: string, path: string | undefined | null, retry = 3) {
if (path) return _download(url, path, retry);
return superagent.get(url).retry(retry);
}
global.Hydro.lib.download = download;
-7
View File
@@ -1,7 +0,0 @@
const crypto = require('crypto');
function hash(password, salt) {
return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha256').toString('hex').substr(0, 64);
}
global.Hydro.lib['hash.hydro'] = module.exports = hash;
+7
View File
@@ -0,0 +1,7 @@
import crypto from 'crypto';
export default function hash(password: string, salt: string) {
return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha256').toString('hex').substr(0, 64);
}
global.Hydro.lib['hash.hydro'] = hash;
+13 -12
View File
@@ -1,13 +1,13 @@
/* eslint-disable import/no-dynamic-require */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-eval */
const fs = require('fs');
const os = require('os');
const path = require('path');
const download = require('./download');
const { folderSize } = require('../utils');
import fs from 'fs';
import os from 'os';
import path from 'path';
import download from './download';
import { folderSize } from '../utils';
function root(name) {
function root(name: string) {
return path.resolve(process.cwd(), name);
}
@@ -17,7 +17,8 @@ const moduleRoots = [
root(path.resolve(os.homedir(), '.hydro', 'module')),
root('.'),
];
let moduleRoot;
let moduleRoot: string;
for (const i of moduleRoots) {
if (fs.existsSync(i) && fs.statSync(i).isDirectory()) {
moduleRoot = i;
@@ -25,7 +26,7 @@ for (const i of moduleRoots) {
}
}
async function getInstalled() {
export async function getInstalled() {
const modules = [];
const files = fs.readdirSync(`${os.tmpdir()}/hydro/tmp`);
for (const file of files) {
@@ -37,7 +38,7 @@ async function getInstalled() {
return modules;
}
async function getDetail() {
export async function getDetail() {
const modules = [];
const files = fs.readdirSync(`${os.tmpdir()}/hydro/tmp`);
for (const file of files) {
@@ -56,14 +57,14 @@ async function getDetail() {
return modules;
}
async function del(id) {
export async function del(id: string) {
fs.unlinkSync(root(`${moduleRoot}/${id}.hydro`));
}
function install(url) {
export function install(url: string) {
return download(url, root(`${moduleRoot}/${String.random(16)}.hydro`));
}
global.Hydro.lib.hpm = module.exports = {
global.Hydro.lib.hpm = {
getInstalled, getDetail, del, install,
};
+11 -3
View File
@@ -1,5 +1,13 @@
const locales = {};
declare global {
interface String {
format: (...args: Array<any>) => string;
rawformat: (object: any) => string;
translate: (language: string | undefined) => string;
}
}
String.prototype.format = function formatStr(...args) {
let result = this;
if (args.length > 0) {
@@ -24,7 +32,7 @@ String.prototype.format = function formatStr(...args) {
String.prototype.rawformat = function rawFormat(object) {
const res = this.split('{@}');
return [res[0], object, res[1]];
return [res[0], object, res[1]].join();
};
String.prototype.translate = function translate(language = 'zh_CN') {
@@ -34,7 +42,7 @@ String.prototype.translate = function translate(language = 'zh_CN') {
return this;
};
function load(data) {
export default function load(data) {
for (const i in data) {
if (!locales[i]) locales[i] = data[i];
else locales[i] = Object.assign(locales[i], data[i]);
@@ -42,4 +50,4 @@ function load(data) {
}
global.Hydro.locales = locales;
global.Hydro.lib.i18n = module.exports = load;
global.Hydro.lib.i18n = load;
+6 -5
View File
@@ -1,13 +1,13 @@
function decodeBase64WithUriEncoding(encodedText) {
function decodeBase64WithUriEncoding(encodedText: string) {
return Buffer.from(encodedText, 'base64').toString('utf8');
}
function unescapedString(escapedString) {
function unescapedString(escapedString: string) {
escapedString += new Array(5 - (escapedString.length % 4)).join('=');
return escapedString.replace(/-/g, '+').replace(/_/g, '/');
}
function decodeJWT(idToken) {
function decodeJWT(idToken: string) {
const token = idToken.split('.');
if (token.length !== 3) {
throw new Error('Invalid idToken');
@@ -27,9 +27,10 @@ function decodeJWT(idToken) {
}
}
function decode(idToken) {
// eslint-disable-next-line import/prefer-default-export
export function decode(idToken: string) {
const decodedJWT = decodeJWT(idToken);
return decodedJWT.payload;
}
global.Hydro.lib.jwt = module.exports = { decode };
global.Hydro.lib.jwt = { decode };
+23 -9
View File
@@ -1,7 +1,7 @@
const yaml = require('js-yaml');
import yaml from 'js-yaml';
function warp(func, type) {
return (...args) => {
function wrap(func: Function, type: string) {
return (...args: any) => {
const time = new Date();
func(...args);
if (global.Hydro.model.message) {
@@ -21,13 +21,27 @@ function warp(func, type) {
}
class Logger {
log: (...args: any[]) => void;
error: (...args: any[]) => void;
info: (...args: any[]) => void;
warn: (...args: any[]) => void;
debug: (...args: any[]) => void;
constructor() {
this.log = warp(console.log, 'log');
this.error = warp(console.error, 'error');
this.info = warp(console.info, 'info');
this.warn = warp(console.warn, 'warn');
this.debug = warp(console.debug, 'debug');
this.log = wrap(console.log, 'log');
this.error = wrap(console.error, 'error');
this.info = wrap(console.info, 'info');
this.warn = wrap(console.warn, 'warn');
this.debug = wrap(console.debug, 'debug');
}
}
global.Hydro.lib.logger = module.exports = new Logger();
const exp = new Logger();
global.Hydro.lib.logger = exp;
export default exp;
+6 -4
View File
@@ -1,4 +1,5 @@
const nodemailer = require('nodemailer');
import nodemailer from 'nodemailer';
const { SendMailError } = require('../error');
/**
@@ -7,8 +8,9 @@ const { SendMailError } = require('../error');
* @param {string} text
* @param {string} html
*/
async function sendMail(to, subject, text, html) {
let t;
// eslint-disable-next-line import/prefer-default-export
export async function sendMail(to: string, subject: string, text: string, html: string) {
let t: unknown;
try {
const { system } = global.Hydro.model;
const [host, port, secure, user, pass, from] = await Promise.all([
@@ -40,6 +42,6 @@ async function sendMail(to, subject, text, html) {
return t;
}
global.Hydro.lib.mail = module.exports = {
global.Hydro.lib.mail = {
sendMail,
};
+17 -16
View File
@@ -1,12 +1,10 @@
const MarkdownIt = require('markdown-it');
const md = MarkdownIt();
const Prism = require('prismjs');
import MarkdownIt from 'markdown-it';
import Prism from 'prismjs';
// For math: $a\times b\eq 10$
const katex = require('@hydrooj/markdown-it-katex');
import katex from '@hydrooj/markdown-it-katex';
// Specific image size: ![image](image.png =100x100)
const Imsize = require('markdown-it-imsize');
import Imsize from 'markdown-it-imsize';
/* Footnote support.
Here is a footnote reference,[^1] and another.[^longnote]
@@ -17,17 +15,18 @@ Here is a footnote reference,[^1] and another.[^longnote]
Subsequent paragraphs are indented to show that they
belong to the previous footnote.
*/
const Footnote = require('markdown-it-footnote');
import Footnote from 'markdown-it-footnote';
// ==Highlight==
const Mark = require('markdown-it-mark');
import Mark from 'markdown-it-mark';
// :::warn This page requires javascript. :::
// :::record-pass Accepted :::
const Container = require('markdown-it-container');
let Anchor = require('markdown-it-anchor');
// For webpack
if (Anchor.default) Anchor = Anchor.default;
import Container from 'markdown-it-container';
const TOC = require('markdown-it-table-of-contents');
import TOC from 'markdown-it-table-of-contents';
import Anchor from 'markdown-it-anchor';
const md = MarkdownIt();
require('prismjs/components/index');
@@ -78,7 +77,9 @@ class Markdown extends MarkdownIt {
}
}
global.Hydro.lib.markdown = module.exports = {
unsafe: new Markdown(false),
safe: new Markdown(true),
export const safe = new Markdown(true);
export const unsafe = new Markdown(false);
global.Hydro.lib.markdown = {
safe, unsafe,
};
+5 -1
View File
@@ -130,4 +130,8 @@ function rstr2hex(input) {
return output;
}
global.Hydro.lib.md5 = module.exports = (s) => rstr2hex(rstrMD5(unescape(encodeURIComponent(s))));
export default function md5(s: string) {
return rstr2hex(rstrMD5(unescape(encodeURIComponent(s))));
}
global.Hydro.lib.md5 = md5;
+11 -11
View File
@@ -1,17 +1,17 @@
const { default: AnsiUp } = require('ansi_up');
const md5 = require('./md5');
import AnsiUp from 'ansi_up';
import md5 from './md5';
const AU = new AnsiUp();
function ansiToHtml(str) {
export function ansiToHtml(str) {
return AU.ansi_to_html(str);
}
function gravatar(email, s = 32) {
export function gravatar(email, s = 32) {
return `//gravatar.loli.net/avatar/${md5((email || '').toString().trim().toLowerCase())}?d=mm&s=${s}`;
}
function datetimeSpan(dt, relative = true, format = '%Y-%m-%d %H:%M:%S') {
export function datetimeSpan(dt, relative = true, format = '%Y-%m-%d %H:%M:%S') {
if (!dt) return 'DATETIME_SPAN_ERROR';
if (dt.generationTime) dt = new Date(dt.generationTime * 1000);
else if (typeof dt === 'number' || typeof dt === 'string') dt = new Date(dt);
@@ -22,7 +22,7 @@ function datetimeSpan(dt, relative = true, format = '%Y-%m-%d %H:%M:%S') {
);
}
function* paginate(page, numPages) {
export function* paginate(page, numPages) {
const radius = 2; let first; let
last;
if (page > 1) {
@@ -45,7 +45,7 @@ function* paginate(page, numPages) {
yield ['last', numPages];
}
function size(s, base = 1) {
export function size(s, base = 1) {
s *= base;
const unit = 1024;
const unitNames = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
@@ -56,13 +56,13 @@ function size(s, base = 1) {
return '{0} {1}'.format(Math.round(s * unit), unitNames[unitNames.length - 1]);
}
function _digit2(number) {
export function _digit2(number: number) {
if (number < 10) return `0${number}`;
return number.toString();
}
function formatSeconds(seconds = 0) {
seconds = parseInt(seconds, 10);
export function formatSeconds(_seconds = '0') {
const seconds = parseInt(_seconds, 10);
return '{0}:{1}:{2}'.format(
_digit2(Math.floor(seconds / 3600)),
_digit2(Math.floor((seconds % 3600) / 60)),
@@ -70,6 +70,6 @@ function formatSeconds(seconds = 0) {
);
}
global.Hydro.lib.misc = module.exports = {
global.Hydro.lib.misc = {
gravatar, datetimeSpan, paginate, size, formatSeconds, ansiToHtml,
};
+22 -14
View File
@@ -1,27 +1,34 @@
const { isNull } = require('lodash');
const { PRIV, PERM } = require('../model/builtin');
import { isNull } from 'lodash';
import { PERM, PRIV } from '../model/builtin';
global.Hydro.ui.nav = [];
const trueChecker = () => true;
const Checker = (perm, priv, checker = trueChecker) => (handler) => (
const Checker = (perm: string, priv: number, checker: Function = trueChecker) => (handler) => (
checker(handler)
&& (perm ? handler.user.hasPerm(perm) : true)
&& (priv ? handler.user.hasPriv(priv) : true)
);
const Item = (name, args, prefix, ...permPrivChecker) => {
let _priv;
let _perm;
let checker = trueChecker;
const Item = (
name: string, args: any, prefix: string,
...permPrivChecker: Array<number | string | Function | Array<number | string>>
) => {
let _priv: number;
let _perm: string;
let checker: Function = trueChecker;
for (const item of permPrivChecker) {
if (typeof item === 'object' && !isNull(item)) {
if (typeof item.call !== 'undefined') {
if (item instanceof Object && !isNull(item)) {
if (item instanceof Array) {
if (typeof item[0] === 'number') {
// @ts-ignore
_priv = item;
} else if (typeof item[0] === 'string') {
// @ts-ignore
_perm = item;
}
} else if (typeof item.call !== 'undefined') {
checker = item;
} if (typeof item[0] === 'number') {
_priv = item;
} else if (typeof item[0] === 'string') {
_perm = item;
}
} else if (typeof item === 'number') {
_priv = item;
@@ -46,4 +53,5 @@ Item('ranking', null, 'ranking', PERM.PERM_VIEW_RANKING);
Item('domain_dashboard', null, 'domain', PERM.PERM_EDIT_DOMAIN);
Item('manage_dashboard', null, 'manage', PRIV.PRIV_EDIT_SYSTEM);
global.Hydro.lib.nav = module.exports = Item;
global.Hydro.lib.nav = Item;
export default Item;
@@ -1,12 +1,6 @@
const { ValidationError } = require('../error');
import { ValidationError } from '../error';
/**
* @param {import('mongodb').Cursor} cursor
* @param {number} page
* @param {number} pageSize
* @returns {Promise<Array[]>} pageDocs numPages count
*/
async function paginate(cursor, page, pageSize) {
async function paginate(cursor: import('mongodb').Cursor, page: number, pageSize: number): Promise<[any[], number, number]> {
if (page <= 0) throw new ValidationError('page');
const [count, pageDocs] = await Promise.all([
cursor.count(),
@@ -16,4 +10,5 @@ async function paginate(cursor, page, pageSize) {
return [pageDocs, numPages, count];
}
global.Hydro.lib.paginate = module.exports = paginate;
global.Hydro.lib.paginate = paginate;
export default paginate;
+2 -1
View File
@@ -10,4 +10,5 @@ function* ranked(diter, equ = (a, b) => a === b) {
}
}
global.Hydro.lib.rank = module.exports = ranked;
global.Hydro.lib.rank = ranked;
export default ranked;
+14 -3
View File
@@ -1,5 +1,13 @@
class User {
constructor(rank, old, uid = 0) {
rank: any;
old: any;
seed: number;
uid: number;
constructor(rank: number, old: number, uid = 0) {
this.rank = rank;
this.old = old;
this.seed = 1;
@@ -8,6 +16,8 @@ class User {
}
class RatingCalculator {
users: any;
constructor(users) {
this.users = [];
for (const user of users) {
@@ -80,9 +90,10 @@ class RatingCalculator {
}
}
function calculate(users) {
function calculate(users: any[]) {
const calculator = new RatingCalculator(users);
return calculator.calculate();
}
module.exports = calculate;
global.Hydro.lib.rating = calculate;
export default calculate;
@@ -1,6 +1,6 @@
const Zip = require('adm-zip');
import Zip from 'adm-zip';
async function readConfig(filePath) {
async function readConfig(filePath: string) {
const data = new Zip(filePath);
const entries = data.getEntries();
for (const entry of entries) {
@@ -16,4 +16,5 @@ async function readConfig(filePath) {
return '';
}
global.Hydro.lib.readConfig = module.exports = readConfig;
global.Hydro.lib.readConfig = readConfig;
export default readConfig;
-10
View File
@@ -1,10 +0,0 @@
const crypto = require('crypto');
/**
* @param {any} content
* @return {string}
*/
global.Hydro.lib.sha1 = module.exports = (content) => {
const hash = crypto.createHash('sha1');
hash.update(content);
return hash.digest('hex');
};
+10
View File
@@ -0,0 +1,10 @@
import crypto from 'crypto';
function sha1(content: string) {
const hash = crypto.createHash('sha1');
hash.update(content);
return hash.digest('hex');
}
global.Hydro.lib.sha1 = sha1;
export default sha1;
@@ -1,9 +1,11 @@
const systeminformation = require('systeminformation');
const { size } = require('./misc');
import systeminformation from 'systeminformation';
import { size } from './misc';
const cache = {};
const cache = {
mid: '', cpu: '', osinfo: '', flags: '',
};
async function get() {
export async function get() {
const [Cpu, Memory, OsInfo, CurrentLoad, CpuFlags, CpuTemp, Battery] = await Promise.all([
systeminformation.cpu(),
systeminformation.mem(),
@@ -31,7 +33,7 @@ async function get() {
};
}
async function update() {
export async function update(): Promise<[string, any, any]> {
const [Memory, CurrentLoad, CpuTemp, Battery] = await Promise.all([
systeminformation.mem(),
systeminformation.currentLoad(),
@@ -57,4 +59,4 @@ async function update() {
];
}
global.Hydro.lib.sysinfo = module.exports = { get, update };
global.Hydro.lib.sysinfo = { get, update };
@@ -1,7 +1,7 @@
const nunjucks = require('nunjucks');
const markdown = require('./markdown');
const { STATUS, PERM, PRIV } = require('../model/builtin');
const misc = require('./misc');
import nunjucks from 'nunjucks';
import * as markdown from './markdown';
import { STATUS, PERM, PRIV } from '../model/builtin';
import * as misc from './misc';
function Loader() { }
Loader.prototype.getSource = function getSource(name) {
@@ -28,7 +28,7 @@ class Nunjucks extends nunjucks.Environment {
}
const env = new Nunjucks();
function render(name, state) {
export function render(name: string, state: any): Promise<string> {
return new Promise((resolve, reject) => {
env.render(name, {
page_name: name.split('.')[0],
@@ -44,7 +44,7 @@ function render(name, state) {
gravatar: misc.gravatar,
model: global.Hydro.model,
Context: global.Hydro.ui,
isIE: (str) => str.includes('MSIE') || str.includes('rv:11.0'),
isIE: (str: string) => str.includes('MSIE') || str.includes('rv:11.0'),
}, (err, res) => {
if (err) reject(err);
else resolve(res);
@@ -52,4 +52,4 @@ function render(name, state) {
});
}
global.Hydro.lib.template = module.exports = { render };
global.Hydro.lib.template = { render };
@@ -1,15 +1,15 @@
const yaml = require('js-yaml');
import yaml from 'js-yaml';
function convert(ini) {
export default function convert(ini: string) {
const f = ini.split('\n');
const count = f[0];
const count = parseInt(f[0], 10);
const res = { cases: [] };
for (let i = 1; i <= count; i++) {
const [input, output, time, score, memory] = f[i].split('|');
const cur = { input, output, score: parseInt(score, 10) };
cur.time = `${time}s`;
const cur = {
input, output, score: parseInt(score, 10), time: `${time}s`, memory: '128m',
};
if (!Number.isNaN(parseInt(memory, 10))) cur.memory = `${Math.floor(parseInt(memory, 10) / 1024)}m`;
else cur.memory = '128m';
res.cases.push(cur);
}
if (res.cases.length > 0) {
@@ -29,4 +29,4 @@ function convert(ini) {
});
}
global.Hydro.lib['testdata.convert.ini'] = module.exports = convert;
global.Hydro.lib['testdata.convert.ini'] = convert;
-11
View File
@@ -1,11 +0,0 @@
const browser = require('detect-browser');
function parse(str) {
return browser.parseUserAgent(str);
}
function icon(str) {
return str.split(' ')[0].toLowerCase();
}
global.Hydro.lib.useragent = module.exports = { parse, icon };
+12
View File
@@ -0,0 +1,12 @@
import browser from 'detect-browser';
export function parse(str: string) {
return browser.parseUserAgent(str);
}
export function icon(str: string) {
return str.split(' ')[0].toLowerCase();
}
global.Hydro.lib.useragent = { parse, icon };
export default { parse, icon };
-91
View File
@@ -1,91 +0,0 @@
const { ValidationError } = require('../error');
const RE_UID = /^-?\d+$/i;
const RE_PID = /^([a-zA-Z]+[a-zA-Z0-9]*)|$/i;
const RE_UNAME = /[^\s\u3000](.{,254}[^\s\u3000])?$/i;
const RE_ROLE = /^[_0-9A-Za-z]{1,256}$/i;
const RE_MAIL = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/i;
const isTitle = (s) => s && s.length < 64;
const checkTitle = (s) => { if (!isTitle(s)) throw new ValidationError('title'); else return s; };
const isUid = (s) => RE_UID.test(s);
const checkUid = (s) => { if (!isUid(s)) throw new ValidationError('uid'); else return s; };
const isUname = (s) => RE_UNAME.test(s);
const checkUname = (s) => { if (!isUname(s)) throw new ValidationError('uname'); else return s; };
const isRole = (s) => RE_ROLE.test(s);
const checkRole = (s) => { if (!isRole(s)) throw new ValidationError('role'); else return s; };
const isPassword = (s) => s.length >= 5;
const checkPassword = (s) => { if (!isPassword(s)) throw new ValidationError('password'); else return s; };
const isEmail = (s) => RE_MAIL.test(s);
const checkEmail = (s) => { if (!isEmail(s)) throw new ValidationError('mail'); else return s; };
const isContent = (s) => s && s.length < 65536;
const checkContent = (s) => { if (!isContent(s)) throw new ValidationError('content'); else return s; };
const isName = (s) => s && s.length < 256;
const checkName = (s) => { if (!isName(s)) throw new ValidationError('name'); else return s; };
const isPid = (s) => RE_PID.test(s.toString());
const checkPid = (s) => { if (!RE_PID.test(s)) throw new ValidationError('pid'); else return s; };
const isIntro = () => true;
const checkIntro = (s) => { if (!isIntro(s)) throw new ValidationError('intro'); else return s; };
const isDescription = () => true;
const checkDescription = (s) => { if (!isDescription(s)) throw new ValidationError('description'); else return s; };
global.Hydro.lib.validator = module.exports = {
isTitle,
checkTitle,
isUid,
checkUid,
isUname,
checkUname,
isRole,
checkRole,
isPassword,
checkPassword,
isEmail,
checkEmail,
isContent,
checkContent,
isName,
checkName,
isPid,
checkPid,
isIntro,
checkIntro,
isDescription,
checkDescription,
};
/*
ID_RE = re.compile(r'[^\\/\s\u3000]([^\\/\n\r]*[^\\/\s\u3000])?')
def is_id(s):
return bool(ID_RE.fullmatch(s))
def check_category_name(s):
if not is_id(s):
raise error.ValidationError('category_name')
def check_node_name(s):
if not is_id(s):
raise error.ValidationError('node_name')
def is_intro(s):
return isinstance(s, str) and 0 < len(s.strip()) < 500
def check_intro(s):
if not is_intro(s):
raise error.ValidationError('intro')
def is_description(s):
return isinstance(s, str) and len(s) < 65536
def check_description(s):
if not is_description(s):
raise error.ValidationError('description')
def is_lang(i):
return i in constant.language.LANG_TEXTS
def check_lang(i):
if not is_lang(i):
raise error.ValidationError('lang')
*/
+91
View File
@@ -0,0 +1,91 @@
import { ValidationError } from '../error';
const RE_UID = /^-?\d+$/i;
const RE_PID = /^([a-zA-Z]+[a-zA-Z0-9]*)|$/i;
const RE_UNAME = /[^\s\u3000](.{,254}[^\s\u3000])?$/i;
const RE_ROLE = /^[_0-9A-Za-z]{1,256}$/i;
const RE_MAIL = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+$/i;
export const isTitle = (s) => s && s.length < 64;
export const checkTitle = (s) => { if (!isTitle(s)) throw new ValidationError('title'); else return s; };
export const isUid = (s) => RE_UID.test(s);
export const checkUid = (s) => { if (!isUid(s)) throw new ValidationError('uid'); else return s; };
export const isUname = (s) => RE_UNAME.test(s);
export const checkUname = (s) => { if (!isUname(s)) throw new ValidationError('uname'); else return s; };
export const isRole = (s) => RE_ROLE.test(s);
export const checkRole = (s) => { if (!isRole(s)) throw new ValidationError('role'); else return s; };
export const isPassword = (s) => s.length >= 5;
export const checkPassword = (s) => { if (!isPassword(s)) throw new ValidationError('password'); else return s; };
export const isEmail = (s) => RE_MAIL.test(s);
export const checkEmail = (s) => { if (!isEmail(s)) throw new ValidationError('mail'); else return s; };
export const isContent = (s) => s && s.length < 65536;
export const checkContent = (s) => { if (!isContent(s)) throw new ValidationError('content'); else return s; };
export const isName = (s) => s && s.length < 256;
export const checkName = (s) => { if (!isName(s)) throw new ValidationError('name'); else return s; };
export const isPid = (s) => RE_PID.test(s.toString());
export const checkPid = (s) => { if (!RE_PID.test(s)) throw new ValidationError('pid'); else return s; };
export const isIntro = () => true;
export const checkIntro = (s) => { if (!isIntro()) throw new ValidationError('intro'); else return s; };
export const isDescription = () => true;
export const checkDescription = (s) => { if (!isDescription()) throw new ValidationError('description'); else return s; };
global.Hydro.lib.validator = {
isTitle,
checkTitle,
isUid,
checkUid,
isUname,
checkUname,
isRole,
checkRole,
isPassword,
checkPassword,
isEmail,
checkEmail,
isContent,
checkContent,
isName,
checkName,
isPid,
checkPid,
isIntro,
checkIntro,
isDescription,
checkDescription,
};
/*
ID_RE = re.compile(r'[^\\/\s\u3000]([^\\/\n\r]*[^\\/\s\u3000])?')
def is_id(s):
return bool(ID_RE.fullmatch(s))
def check_category_name(s):
if not is_id(s):
raise error.ValidationError('category_name')
def check_node_name(s):
if not is_id(s):
raise error.ValidationError('node_name')
def is_intro(s):
return isinstance(s, str) and 0 < len(s.strip()) < 500
def check_intro(s):
if not is_intro(s):
raise error.ValidationError('intro')
def is_description(s):
return isinstance(s, str) and len(s) < 65536
def check_description(s):
if not is_description(s):
raise error.ValidationError('description')
def is_lang(i):
return i in export const ant.language.LANG_TEXTS
def check_lang(i):
if not is_lang(i):
raise error.ValidationError('lang')
*/