hfs 0.56.0 → 0.57.0-alpha1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cross.js CHANGED
@@ -18,7 +18,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.waitFor = exports.newObj = exports.findDefined = exports.isOrderedEqual = exports.swap = exports.tryJson = exports.dirname = exports.basename = exports.pendingPromise = exports._dbg = exports._log = exports.wantArray = exports.formatPerc = exports.with_ = exports.try_ = exports.setHidden = exports.onlyTruthy = exports.truthy = exports.stringAfter = exports.splitAt = exports.strinsert = exports.removeStarting = exports.enforceStarting = exports.enforceFinal = exports.objFromKeys = exports.objSameKeys = exports.haveTimeout = exports.wait = exports.join = exports.prefix = exports.formatSpeed = exports.formatBytes = exports.isWhoObject = exports.PERM_KEYS = exports.defaultPerms = exports.WHO_ANY_ACCOUNT = exports.WHO_NO_ONE = exports.WHO_ANYONE = exports.LIST = exports.CFG = exports.THEME_OPTIONS = exports.SORT_BY_OPTIONS = exports.FRONTEND_OPTIONS = exports.MAX_TILE_SIZE = exports.DAY = exports.HOUR = exports.MINUTE = exports.WIKI_URL = exports.REPO_URL = exports.WEBSITE = void 0;
21
- exports.shortenAgent = exports.popKey = exports.safeDecodeURIComponent = exports.callable = exports.mapFilter = exports.inCommon = exports.replace = exports.matches = exports.makeMatcher = exports.runAt = exports.pathEncode = exports.promiseBestEffort = exports.escapeHTML = exports.ipForUrl = exports.isIpLan = exports.isIpLocalHost = exports.normalizeHost = exports.xlate = exports.isEqualLax = exports.isTimestampString = exports.isWindowsDrive = exports.isIP = exports.isPrimitive = exports.isNumeric = exports.formatDate = exports.formatTime = exports.formatTimestamp = exports.repeat = exports.asyncGeneratorToArray = exports.filterMapGenerator = exports.throw_ = exports.hasProp = exports.typedEntries = exports.typedKeys = exports.objRenameKey = exports.randomId = exports.getOrSet = void 0;
21
+ exports.shortenAgent = exports.patchKey = exports.popKey = exports.safeDecodeURIComponent = exports.callable = exports.mapFilter = exports.inCommon = exports.replace = exports.matches = exports.makeMatcher = exports.runAt = exports.pathEncode = exports.promiseBestEffort = exports.escapeHTML = exports.ipForUrl = exports.isIpLan = exports.isIpLocalHost = exports.normalizeHost = exports.xlate = exports.isEqualLax = exports.isTimestampString = exports.isWindowsDrive = exports.isIP = exports.isPrimitive = exports.isNumeric = exports.formatDate = exports.formatTime = exports.formatTimestamp = exports.repeat = exports.asyncGeneratorToArray = exports.filterMapGenerator = exports.throw_ = exports.hasProp = exports.typedEntries = exports.typedKeys = exports.objRenameKey = exports.randomId = exports.getOrSet = void 0;
22
22
  // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt
23
23
  // all content here is shared between client and server
24
24
  const lodash_1 = __importDefault(require("lodash"));
@@ -46,10 +46,12 @@ exports.FRONTEND_OPTIONS = {
46
46
  };
47
47
  exports.SORT_BY_OPTIONS = ['name', 'extension', 'size', 'time', 'creation'];
48
48
  exports.THEME_OPTIONS = { auto: '', light: 'light', dark: 'dark' };
49
+ // had found an interesting way to infer a type from all the calls to defineConfig (by the literals passed), but would not be usable also by admin-panel
49
50
  exports.CFG = constMap(['geo_enable', 'geo_allow', 'geo_list', 'geo_allow_unknown', 'dynamic_dns_url',
50
51
  'log', 'error_log', 'log_rotation', 'dont_log_net', 'log_gui', 'log_api', 'log_ua', 'log_spam', 'track_ips',
51
52
  'max_downloads', 'max_downloads_per_ip', 'max_downloads_per_account', 'roots', 'force_address', 'split_uploads',
52
- 'allow_session_ip_change', 'force_lang', 'suspend_plugins', 'base_url', 'size_1024']);
53
+ 'allow_session_ip_change', 'force_lang', 'suspend_plugins', 'base_url', 'size_1024', 'disable_custom_html',
54
+ 'comments_storage']);
53
55
  exports.LIST = { add: '+', remove: '-', update: '=', props: 'props', ready: 'ready', error: 'e' };
54
56
  exports.WHO_ANYONE = true;
55
57
  exports.WHO_NO_ONE = false;
@@ -450,8 +452,11 @@ function makeMatcher(mask, emptyMaskReturns = false) {
450
452
  : () => emptyMaskReturns;
451
453
  }
452
454
  exports.makeMatcher = makeMatcher;
455
+ // this is caching all matchers, so don't use it with frequently changing masks. Benchmarks revealed that _.memoize make it slower than not using it, while this simple cache can speed up to 30x
453
456
  function matches(s, mask, emptyMaskReturns = false) {
454
- return makeMatcher(mask, emptyMaskReturns)(s);
457
+ var _a, _b;
458
+ const cache = (_a = matches).cache || (_a.cache = {});
459
+ return (cache[_b = mask + (emptyMaskReturns ? '1' : '0')] || (cache[_b] = makeMatcher(mask, emptyMaskReturns)))(s);
455
460
  }
456
461
  exports.matches = matches;
457
462
  // if delimiter is specified, it is prefixed to symbols. If it contains a space, the part after the space is considered as suffix.
@@ -500,6 +505,11 @@ function popKey(o, k) {
500
505
  return x;
501
506
  }
502
507
  exports.popKey = popKey;
508
+ function patchKey(o, k, replacer) {
509
+ o[k] = replacer(o[k]);
510
+ return o;
511
+ }
512
+ exports.patchKey = patchKey;
503
513
  function shortenAgent(agent) {
504
514
  var _a;
505
515
  return lodash_1.default.findKey(BROWSERS, re => re.test(agent))
package/src/customHtml.js CHANGED
@@ -3,9 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.saveCustomHtml = exports.getAllSections = exports.getSection = exports.watchLoadCustomHtml = exports.customHtml = exports.customHtmlSections = void 0;
6
+ exports.saveCustomHtml = exports.getAllSections = exports.getSection = exports.watchLoadCustomHtml = exports.disableCustomHtml = exports.customHtml = exports.customHtmlSections = void 0;
7
7
  const misc_1 = require("./misc");
8
8
  const watchLoad_1 = require("./watchLoad");
9
+ const config_1 = require("./config");
9
10
  const promises_1 = require("fs/promises");
10
11
  const plugins_1 = require("./plugins");
11
12
  const lodash_1 = __importDefault(require("lodash"));
@@ -13,6 +14,7 @@ const FILE = 'custom.html';
13
14
  exports.customHtmlSections = ['style', 'script', 'beforeHeader', 'afterHeader', 'afterMenuBar', 'afterList',
14
15
  'footer', 'top', 'bottom', 'afterEntryName', 'beforeLogin', 'unauthorized', 'htmlHead', 'userPanelAfterInfo'];
15
16
  exports.customHtml = watchLoadCustomHtml();
17
+ exports.disableCustomHtml = (0, config_1.defineConfig)(misc_1.CFG.disable_custom_html, false);
16
18
  function watchLoadCustomHtml(folder = '') {
17
19
  const sections = new Map();
18
20
  const res = (0, watchLoad_1.watchLoad)((0, misc_1.prefix)('', folder, '/') + FILE, data => {
@@ -35,7 +37,7 @@ function watchLoadCustomHtml(folder = '') {
35
37
  }
36
38
  exports.watchLoadCustomHtml = watchLoadCustomHtml;
37
39
  function getSection(name) {
38
- return (exports.customHtml.sections.get(name) || '')
40
+ return (!exports.disableCustomHtml.get() && exports.customHtml.sections.get(name) || '')
39
41
  + (0, plugins_1.mapPlugins)(pl => pl.getData().getCustomHtml()[name]).join('\n');
40
42
  }
41
43
  exports.getSection = getSection;
package/src/events.js CHANGED
@@ -19,7 +19,7 @@ class BetterEventEmitter {
19
19
  cbs.add(listener);
20
20
  if (cbs.size > warnAfter)
21
21
  console.warn("Warning: many event listeners for ", e);
22
- this.emit(e + LISTENERS_SUFFIX, cbs);
22
+ this.emit(e + LISTENERS_SUFFIX, cbs, listener);
23
23
  }
24
24
  if (callNow)
25
25
  try {
@@ -41,13 +41,15 @@ class BetterEventEmitter {
41
41
  return this.on(event + LISTENERS_SUFFIX, listener);
42
42
  }
43
43
  once(event, listener) {
44
- return new Promise(resolve => {
45
- const off = this.on(event, function (...args) {
44
+ let off;
45
+ const pro = new Promise(resolve => {
46
+ off = this.on(event, function (...args) {
46
47
  off();
47
- resolve(args);
48
- return listener === null || listener === void 0 ? void 0 : listener(...arguments);
48
+ resolve(args.slice(0, -1)); // remove the extra argument at the end of our emit()
49
+ return listener === null || listener === void 0 ? void 0 : listener(...args);
49
50
  });
50
51
  });
52
+ return Object.assign(off, { then: pro.then.bind(pro) });
51
53
  }
52
54
  multi(map) {
53
55
  const cbs = Object.entries(map).map(([name, cb]) => this.on(name.split(' '), cb));
package/src/fileAttr.js CHANGED
@@ -19,10 +19,11 @@ const FN = 'file-attr.kv';
19
19
  if ((0, fs_1.existsSync)(FN))
20
20
  fileAttrDb.open(FN);
21
21
  const FILE_ATTR_PREFIX = 'user.hfs.'; // user. prefix to be linux compatible
22
+ /* @param v must be JSON-able or undefined */
22
23
  async function storeFileAttr(path, k, v) {
23
24
  var _a, _b;
24
- const s = await (0, promises_2.stat)(path);
25
- if (await (fsx === null || fsx === void 0 ? void 0 : fsx.set(path, FILE_ATTR_PREFIX + k, JSON.stringify(v)).then(() => 1, () => 0))) {
25
+ const s = await (0, promises_2.stat)(path); // since we don't have fsx.remove, we simulate it with an empty string
26
+ if (await (fsx === null || fsx === void 0 ? void 0 : fsx.set(path, FILE_ATTR_PREFIX + k, v === undefined ? '' : JSON.stringify(v)).then(() => 1, () => 0))) {
26
27
  if (const_1.IS_WINDOWS)
27
28
  (0, promises_2.utimes)(path, s.atime, s.mtime); // restore timestamps, necessary only on Windows
28
29
  return true;
@@ -39,7 +40,7 @@ async function storeFileAttr(path, k, v) {
39
40
  exports.storeFileAttr = storeFileAttr;
40
41
  async function loadFileAttr(path, k) {
41
42
  var _a;
42
- return (_a = await (fsx === null || fsx === void 0 ? void 0 : fsx.get(path, FILE_ATTR_PREFIX + k).then((x) => x && (0, cross_1.tryJson)(String(x)), () => { }).then((x) => x !== null && x !== void 0 ? x : (fileAttrDb.isOpen() ? fileAttrDb.get(`${path}|${k}`) : null)))) !== null && _a !== void 0 ? _a : undefined; // normalize, as we get null instead of undefined on windows
43
+ return (_a = await (fsx === null || fsx === void 0 ? void 0 : fsx.get(path, FILE_ATTR_PREFIX + k).then((x) => x === '' ? undefined : (0, cross_1.tryJson)(String(x)), () => fileAttrDb.isOpen() ? fileAttrDb.get(`${path}|${k}`) : null))) !== null && _a !== void 0 ? _a : undefined; // normalize, as we get null instead of undefined on windows
43
44
  }
44
45
  exports.loadFileAttr = loadFileAttr;
45
46
  async function purgeFileAttr() {
package/src/geo.js CHANGED
@@ -17,6 +17,7 @@ const list = (0, config_1.defineConfig)(misc_1.CFG.geo_list, []);
17
17
  const allowUnknown = (0, config_1.defineConfig)(misc_1.CFG.geo_allow_unknown, false);
18
18
  enabled.sub(checkFiles);
19
19
  setInterval(checkFiles, misc_1.DAY); // keep updated at run-time
20
+ // benchmark: memoize can make this 44x faster
20
21
  exports.ip2country = lodash_1.default.memoize((ip) => ip2location.getCountryShortAsync(ip).then(v => v === '-' ? '' : v, () => ''));
21
22
  const geoFilter = async (ctx, next) => {
22
23
  var _a;
package/src/listen.js CHANGED
@@ -49,7 +49,7 @@ const persistence_1 = require("./persistence");
49
49
  const argv_1 = require("./argv");
50
50
  let httpSrv;
51
51
  let httpsSrv;
52
- const openBrowserAtStart = (0, config_1.defineConfig)('open_browser_at_start', !const_1.DEV);
52
+ const openBrowserAtStart = (0, config_1.defineConfig)('open_browser_at_start', true);
53
53
  exports.baseUrl = (0, config_1.defineConfig)(misc_1.CFG.base_url, '', x => { var _a; return (_a = /(?<=\/\/)[^\/]+/.exec(x)) === null || _a === void 0 ? void 0 : _a[0]; }); // compiled is host only
54
54
  async function getBaseUrlOrDefault() {
55
55
  return exports.baseUrl.get() || await nat_1.defaultBaseUrl.get();
@@ -121,7 +121,8 @@ const considerHttps = (0, misc_1.debounceAsync)(async () => {
121
121
  nat_1.defaultBaseUrl.port = (_a = getCurrentPort(httpSrv)) !== null && _a !== void 0 ? _a : 0;
122
122
  let port = exports.httpsPortCfg.get();
123
123
  try {
124
- httpsSrv = Object.assign(https.createServer(port === const_1.PORT_DISABLED ? {} : { ...commonServerOptions, key: httpsOptions.private_key, cert: httpsOptions.cert }, index_1.app.callback()), { name: 'https' }, commonServerAssign);
124
+ const moreOptions = Object.assign({}, ...await events_1.default.emitAsync('httpsServerOptions') || []);
125
+ httpsSrv = Object.assign(https.createServer(port === const_1.PORT_DISABLED ? {} : { ...commonServerOptions, key: httpsOptions.private_key, cert: httpsOptions.cert, ...moreOptions }, index_1.app.callback()), { name: 'https' }, commonServerAssign);
125
126
  if (port >= 0) {
126
127
  const cert = getCertObject();
127
128
  if (cert) {
package/src/log.js CHANGED
@@ -88,7 +88,7 @@ const logUA = (0, config_1.defineConfig)(misc_1.CFG.log_ua, false);
88
88
  const logSpam = (0, config_1.defineConfig)(misc_1.CFG.log_spam, false);
89
89
  const debounce = lodash_1.default.debounce(cb => cb(), 1000); // with this technique, i'll be able to debounce some code respecting the references in its closure
90
90
  const logMw = async (ctx, next) => {
91
- const now = new Date();
91
+ const now = new Date(); // request start
92
92
  // do it now so it's available for returning plugins
93
93
  ctx.state.completed = Promise.race([(0, stream_1.once)(ctx.res, 'finish'), (0, stream_1.once)(ctx.res, 'close')]);
94
94
  await next();
@@ -140,8 +140,15 @@ const logMw = async (ctx, next) => {
140
140
  const user = (0, auth_1.getCurrentUsername)(ctx);
141
141
  const length = (_c = ctx.state.length) !== null && _c !== void 0 ? _c : ctx.length;
142
142
  const uri = ctx.originalUrl;
143
- ctx.logExtra(ctx.state.includesLastByte && ctx.vfsNode && ctx.res.finished && { dl: 1 }
144
- || ctx.state.uploadPath && { size: ctx.state.opTotal, ul: ctx.state.uploads });
143
+ const duration = (Date.now() - Number(now)) / 1000;
144
+ ctx.logExtra(ctx.vfsNode && {
145
+ speed: Math.round(length / duration),
146
+ ...ctx.state.includesLastByte && ctx.res.finished && { dl: 1 }
147
+ } || ctx.state.uploadPath && {
148
+ ul: ctx.state.uploads,
149
+ size: ctx.state.opTotal,
150
+ speed: Math.round((ctx.state.opTotal - (ctx.state.opOffset || 0)) / duration)
151
+ });
145
152
  if (conn === null || conn === void 0 ? void 0 : conn.country)
146
153
  ctx.logExtra({ country: conn.country });
147
154
  if (logUA.get())
@@ -111,42 +111,26 @@ const prepareState = async (ctx, next) => {
111
111
  ctx.state.revProxyPath = ctx.get('x-forwarded-prefix');
112
112
  (0, connections_1.updateConnectionForCtx)(ctx);
113
113
  await next();
114
- async function urlLogin() {
114
+ function urlLogin() {
115
115
  const { login } = ctx.query;
116
116
  if (!login)
117
117
  return;
118
118
  const [u, p] = (0, misc_1.splitAt)(':', String(login));
119
- const a = await doLogin(u, p, 'url');
120
- if (!a)
121
- return;
122
119
  ctx.redirect(ctx.originalUrl.slice(0, -ctx.querystring.length - 1)); // redirect to hide credentials
123
- return a;
120
+ return u && (0, auth_1.clearTextLogin)(ctx, u, p, 'url');
124
121
  }
125
122
  function getHttpAccount() {
126
- var _a;
123
+ var _a, _b;
127
124
  const b64 = allowAuthorizationHeader.get() && ((_a = ctx.get('authorization')) === null || _a === void 0 ? void 0 : _a.split(' ')[1]);
128
125
  if (!b64)
129
126
  return;
130
127
  try {
131
128
  const [u, p] = atob(b64).split(':');
132
- return doLogin(u, p || '', 'header');
133
- }
134
- catch (_b) { }
135
- }
136
- async function doLogin(u, p, via) {
137
- var _a, _b;
138
- if (!u || u === ((_a = ctx.session) === null || _a === void 0 ? void 0 : _a.username))
139
- return; // providing credentials, but not needed
140
- if ((_b = (await events_1.default.emitAsync('attemptingLogin', { ctx, username: u, via }))) === null || _b === void 0 ? void 0 : _b.isDefaultPrevented())
141
- return;
142
- const a = await (0, auth_1.srpCheck)(u, p);
143
- if (a) {
144
- await (0, auth_1.setLoggedIn)(ctx, a.username);
145
- ctx.headers['x-username'] = a.username; // give an easier way to determine if the login was successful
129
+ if (!u || u === ((_b = ctx.session) === null || _b === void 0 ? void 0 : _b.username))
130
+ return; // providing credentials, but not needed
131
+ return (0, auth_1.clearTextLogin)(ctx, u, p || '', 'header');
146
132
  }
147
- else if (u)
148
- events_1.default.emit('failedLogin', ctx, { username: u, via });
149
- return a;
133
+ catch (_c) { }
150
134
  }
151
135
  };
152
136
  exports.prepareState = prepareState;
package/src/misc.js CHANGED
@@ -20,7 +20,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.deleteNode = exports.createStreamLimiter = exports.apiAssertTypes = exports.AsapStream = exports.asyncGeneratorToReadable = exports.same = exports.makeNetMatcher = exports.netMatches = exports.isLocalHost = exports.pattern2filter = void 0;
22
22
  const path_1 = require("path");
23
- const assert_1 = __importDefault(require("assert"));
24
23
  __exportStar(require("./util-http"), exports);
25
24
  __exportStar(require("./util-files"), exports);
26
25
  __exportStar(require("./fileAttr"), exports);
@@ -48,9 +47,11 @@ function isLocalHost(c) {
48
47
  return ip && (0, cross_1.isIpLocalHost)(ip);
49
48
  }
50
49
  exports.isLocalHost = isLocalHost;
51
- // this will memory-leak over mask, so be careful with what you use this
50
+ // this will memory-leak over mask, so be careful with what you use this. Object is 3x faster than _.memoize
52
51
  function netMatches(ip, mask, emptyMaskReturns = false) {
53
- return lodash_1.default.memoize(makeNetMatcher, (a, b) => `${a}\t${b ? 1 : 0}`)(mask, emptyMaskReturns)(ip); // cache the matcher
52
+ var _a, _b;
53
+ const cache = (_a = netMatches).cache || (_a.cache = {});
54
+ return (cache[_b = mask + (emptyMaskReturns ? '1' : '0')] || (cache[_b] = makeNetMatcher(mask, emptyMaskReturns)))(ip); // cache the matcher
54
55
  }
55
56
  exports.netMatches = netMatches;
56
57
  function makeNetMatcher(mask, emptyMaskReturns = false) {
@@ -108,13 +109,7 @@ function parseAddress(s) {
108
109
  return new node_net_1.SocketAddress({ address: s, family: (0, net_1.isIPv6)(s) ? 'ipv6' : 'ipv4' });
109
110
  }
110
111
  function same(a, b) {
111
- try {
112
- assert_1.default.deepStrictEqual(a, b);
113
- return true;
114
- }
115
- catch (_a) {
116
- return false;
117
- }
112
+ return lodash_1.default.isEqual(a, b);
118
113
  }
119
114
  exports.same = same;
120
115
  function asyncGeneratorToReadable(generator) {
package/src/perm.js CHANGED
@@ -30,7 +30,8 @@ function expandUsername(who) {
30
30
  exports.expandUsername = expandUsername;
31
31
  // check if current username or any ancestor match the provided usernames
32
32
  function ctxBelongsTo(ctx, usernames) {
33
- return (0, misc_1.getOrSet)(ctx.state, 'usernames', () => expandUsername((0, auth_1.getCurrentUsername)(ctx))) // cache ancestors' usernames inside context state
33
+ var _a;
34
+ return ((_a = ctx.state).usernames || (_a.usernames = expandUsername((0, auth_1.getCurrentUsername)(ctx)))) // cache ancestors' usernames inside context state
34
35
  .some((u) => usernames.includes(u));
35
36
  }
36
37
  exports.ctxBelongsTo = ctxBelongsTo;
@@ -181,7 +182,8 @@ function accountHasPassword(account) {
181
182
  }
182
183
  exports.accountHasPassword = accountHasPassword;
183
184
  function accountCanLogin(account) {
184
- return accountHasPassword(account) && !allDisabled(account);
185
+ var _a;
186
+ return (accountHasPassword(account) || ((_a = account.plugin) === null || _a === void 0 ? void 0 : _a.auth)) && !allDisabled(account);
185
187
  }
186
188
  exports.accountCanLogin = accountCanLogin;
187
189
  function allDisabled(account) {
@@ -193,7 +195,7 @@ function allDisabled(account) {
193
195
  && account.belongs.map(u => getAccount(u, false)).every(a => a && allDisabled(a)));
194
196
  }
195
197
  function accountCanLoginAdmin(account) {
196
- return accountCanLogin(account) && Boolean(getFromAccount(account, a => a.admin));
198
+ return accountCanLogin(account) && getFromAccount(account, a => a.admin) || false;
197
199
  }
198
200
  exports.accountCanLoginAdmin = accountCanLoginAdmin;
199
201
  async function changeSrpHelper(account, salt, verifier) {
package/src/plugins.js CHANGED
@@ -133,14 +133,33 @@ function getPluginConfigFields(id) {
133
133
  exports.getPluginConfigFields = getPluginConfigFields;
134
134
  async function initPlugin(pl, morePassedToInit) {
135
135
  var _a;
136
+ const undoEvents = [];
137
+ const timeouts = [];
136
138
  const res = await ((_a = pl.init) === null || _a === void 0 ? void 0 : _a.call(pl, {
137
139
  Const,
138
140
  require,
139
141
  getConnections: connections_1.getConnections,
140
- events: events_1.default,
142
+ // intercept all subscriptions, so to be able to undo them on unload
143
+ events: Object.create(events_1.default, (0, misc_1.objFromKeys)(['on', 'once', 'multi'], k => ({
144
+ value() {
145
+ const ret = events_1.default[k](...arguments);
146
+ undoEvents.push(ret);
147
+ return ret;
148
+ }
149
+ }))),
141
150
  log: console.log,
142
151
  setError(msg) { setError((morePassedToInit === null || morePassedToInit === void 0 ? void 0 : morePassedToInit.id) || 'server_code', msg); },
143
152
  getHfsConfig: config_1.getConfig,
153
+ setInterval() {
154
+ const ret = setInterval(...arguments);
155
+ timeouts.push(ret); // intervals can be canceled by clearTimeout (source: MDN)
156
+ return ret;
157
+ },
158
+ setTimeout() {
159
+ const ret = setTimeout(...arguments);
160
+ timeouts.push(ret);
161
+ return ret;
162
+ },
144
163
  customApiCall,
145
164
  notifyClient: frontEndApis_1.notifyClient,
146
165
  addBlock: block_1.addBlock,
@@ -152,6 +171,14 @@ async function initPlugin(pl, morePassedToInit) {
152
171
  ...morePassedToInit
153
172
  }));
154
173
  Object.assign(pl, typeof res === 'function' ? { unload: res } : res);
174
+ (0, misc_1.patchKey)(pl, 'unload', was => () => {
175
+ for (const x of timeouts)
176
+ clearTimeout(x);
177
+ for (const cb of undoEvents)
178
+ cb();
179
+ if (typeof was === 'function')
180
+ return was(...arguments);
181
+ });
155
182
  events_1.default.emit('pluginInitialized', pl);
156
183
  return pl;
157
184
  }
@@ -233,6 +260,7 @@ class Plugin {
233
260
  this.started = new Date();
234
261
  if (!data)
235
262
  throw 'invalid data';
263
+ this.log = [];
236
264
  this.data = data = { ...data }; // clone to make object modifiable. Objects coming from import are not.
237
265
  // some validation
238
266
  for (const k of ['frontend_css', 'frontend_js']) {
@@ -479,6 +507,7 @@ function watchPlugin(id, path) {
479
507
  await (0, promises_1.mkdir)(storageDir, { recursive: true });
480
508
  const openDbs = [];
481
509
  const subbedConfigs = [];
510
+ const pluginReady = (0, misc_1.pendingPromise)();
482
511
  await initPlugin(pluginData, {
483
512
  id,
484
513
  srcDir: __dirname,
@@ -493,6 +522,14 @@ function watchPlugin(id, path) {
493
522
  },
494
523
  log(...args) {
495
524
  console.log('plugin', id + ':', ...args);
525
+ pluginReady.then(() => {
526
+ if (!plugin)
527
+ return;
528
+ plugin.log.unshift({ ts: new Date, msg: args.map(x => x && typeof x === 'object' ? JSON.stringify(x) : String(x)).join(' ') });
529
+ plugin.log.length = Math.min(100, plugin.log.length); // truncate
530
+ events_1.default.emit('pluginLog:' + id, plugin.log[0]);
531
+ events_1.default.emit('pluginLog', id, plugin.log[0]);
532
+ });
496
533
  },
497
534
  getConfig(cfgKey) {
498
535
  var _a, _b, _c, _d;
@@ -536,6 +573,7 @@ function watchPlugin(id, path) {
536
573
  await Promise.allSettled(openDbs.map(x => x.close()));
537
574
  openDbs.length = 0;
538
575
  });
576
+ pluginReady.resolve();
539
577
  if (alreadyRunning)
540
578
  events_1.default.emit('pluginUpdated', Object.assign(lodash_1.default.pick(plugin, 'started'), getPluginInfo(id)));
541
579
  else {
@@ -582,13 +620,14 @@ function setError(id, error) {
582
620
  }
583
621
  function deleteModule(id) {
584
622
  var _a;
623
+ var _b;
585
624
  const { cache } = require;
586
625
  // build reversed map of dependencies
587
626
  const requiredBy = { '.': ['.'] }; // don't touch main entry
588
627
  for (const k in cache)
589
628
  if (k !== id)
590
629
  for (const child of (0, misc_1.wantArray)((_a = cache[k]) === null || _a === void 0 ? void 0 : _a.children))
591
- (0, misc_1.getOrSet)(requiredBy, child.id, () => []).push(k);
630
+ (requiredBy[_b = child.id] || (requiredBy[_b] = [])).push(k);
592
631
  const deleted = [];
593
632
  (function deleteCache(id) {
594
633
  const mod = cache[id];
@@ -603,7 +642,7 @@ function deleteModule(id) {
603
642
  }
604
643
  (0, first_1.onProcessExit)(() => Promise.allSettled(mapPlugins(pl => pl.unload())));
605
644
  function parsePluginSource(id, source) {
606
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
645
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
607
646
  const pl = { id };
608
647
  pl.description = (0, misc_1.tryJson)((_a = /exports.description *= *(".*")/.exec(source)) === null || _a === void 0 ? void 0 : _a[1]);
609
648
  pl.repo = (0, misc_1.tryJson)((_b = /exports.repo *= *(.*);? *$/m.exec(source)) === null || _b === void 0 ? void 0 : _b[1]);
@@ -611,8 +650,9 @@ function parsePluginSource(id, source) {
611
650
  pl.apiRequired = (_f = (0, misc_1.tryJson)((_e = /exports.apiRequired *= *([ \d.,[\]]+)/.exec(source)) === null || _e === void 0 ? void 0 : _e[1])) !== null && _f !== void 0 ? _f : undefined;
612
651
  pl.isTheme = (_h = (0, misc_1.tryJson)((_g = /exports.isTheme *= *(true|false|"light"|"dark")/.exec(source)) === null || _g === void 0 ? void 0 : _g[1])) !== null && _h !== void 0 ? _h : (id.endsWith('-theme') || undefined);
613
652
  pl.preview = (_k = (0, misc_1.tryJson)((_j = /exports.preview *= *(.+)/.exec(source)) === null || _j === void 0 ? void 0 : _j[1])) !== null && _k !== void 0 ? _k : undefined;
614
- pl.depend = (_m = (0, misc_1.tryJson)((_l = /exports.depend *= *(\[.*])/m.exec(source)) === null || _l === void 0 ? void 0 : _l[1])) === null || _m === void 0 ? void 0 : _m.filter((x) => typeof x.repo === 'string' && x.version === undefined || typeof x.version === 'number'
653
+ pl.depend = (_m = (0, misc_1.tryJson)((_l = /exports.depend *= *(\[[\s\S]*?])/m.exec(source)) === null || _l === void 0 ? void 0 : _l[1])) === null || _m === void 0 ? void 0 : _m.filter((x) => typeof x.repo === 'string' && x.version === undefined || typeof x.version === 'number'
615
654
  || console.warn("plugin dependency discarded", x));
655
+ pl.changelog = (0, misc_1.tryJson)((_o = /exports.changelog *= *(\[[\s\S]*?])/m.exec(source)) === null || _o === void 0 ? void 0 : _o[1]);
616
656
  if (Array.isArray(pl.apiRequired) && (pl.apiRequired.length !== 2 || !pl.apiRequired.every(lodash_1.default.isFinite))) // validate [from,to] form
617
657
  pl.apiRequired = undefined;
618
658
  calculateBadApi(pl);
package/src/roots.js CHANGED
@@ -42,9 +42,7 @@ const rootsMiddleware = (ctx, next) => (() => {
42
42
  return true; // true will avoid calling next
43
43
  }
44
44
  if (!root || root === '/')
45
- return; // not transformation is required
46
- if (root === '' || root === '/')
47
- return;
45
+ return; // no transformation is required
48
46
  changeUriParams(v => (0, misc_1.join)(root, v));
49
47
  if (!params)
50
48
  ctx.path = (0, misc_1.join)(root, ctx.path);
@@ -164,7 +164,7 @@ async function sendFolderList(node, ctx) {
164
164
  const { URL } = ctx;
165
165
  const base = prepend === undefined && listen_1.baseUrl.get()
166
166
  || URL.protocol + '//' + URL.host + ctx.state.revProxyPath;
167
- prepend = base + ctx.originalUrl.split('?')[0];
167
+ prepend = base + (0, misc_1.pathEncode)(decodeURI(ctx.path)); // redo the encoding our way, keeping unicode chars unchanged
168
168
  }
169
169
  const walker = (0, vfs_1.walkNode)(node, { ctx, depth: depth === '*' ? Infinity : Number(depth) });
170
170
  ctx.body = (0, misc_1.asyncGeneratorToReadable)((0, misc_1.filterMapGenerator)(walker, async (el) => {
@@ -24,10 +24,8 @@ const size1024 = (0, config_1.defineConfig)(misc_1.CFG.size_1024, false, x => mi
24
24
  const splitUploads = (0, config_1.defineConfig)(misc_1.CFG.split_uploads, 0);
25
25
  exports.logGui = (0, config_1.defineConfig)(misc_1.CFG.log_gui, false);
26
26
  lodash_1.default.each(misc_1.FRONTEND_OPTIONS, (v, k) => (0, config_1.defineConfig)(k, v)); // define default values
27
- // in case of dev env we have our static files within the 'dist' folder'
28
- const DEV_STATIC = process.env.DEV ? 'dist/' : '';
29
27
  function serveStatic(uri) {
30
- const folder = uri.slice(2, -1); // we know folder is very similar to uri
28
+ const folder = (const_1.DEV ? 'dist/' : '') + uri.slice(2, -1); // we know folder is very similar to uri
31
29
  let cache = {};
32
30
  customHtml_1.customHtml.emitter.on('change', () => cache = {}); // reset cache at every change
33
31
  return async (ctx) => {
@@ -41,7 +39,7 @@ function serveStatic(uri) {
41
39
  if (ctx.method !== 'GET')
42
40
  return ctx.status = const_1.HTTP_METHOD_NOT_ALLOWED;
43
41
  const serveApp = shouldServeApp(ctx);
44
- const fullPath = (0, path_1.join)(__dirname, '..', DEV_STATIC, folder, serveApp ? '/index.html' : ctx.path);
42
+ const fullPath = (0, path_1.join)(__dirname, '..', folder, serveApp ? '/index.html' : ctx.path);
45
43
  const content = await (0, misc_1.parseFileContent)(fullPath, raw => serveApp || !raw.length ? raw : adjustBundlerLinks(ctx, uri, raw))
46
44
  .catch(() => null);
47
45
  if (content === null)
package/src/throttler.js CHANGED
@@ -26,6 +26,7 @@ maxKbpsPerIp.sub(v => {
26
26
  });
27
27
  const throttler = async (ctx, next) => {
28
28
  var _a;
29
+ var _b;
29
30
  await next();
30
31
  let { body } = ctx;
31
32
  const downloadTotal = ctx.response.length;
@@ -35,10 +36,10 @@ const throttler = async (ctx, next) => {
35
36
  return;
36
37
  // we wrap the stream also for unlimited connections to get speed and other features
37
38
  const noLimit = ((_a = ctx.state.account) === null || _a === void 0 ? void 0 : _a.ignore_limits) || (0, misc_1.isLocalHost)(ctx);
38
- const ipGroup = (0, misc_1.getOrSet)(ip2group, noLimit ? '' : ctx.ip, () => ({
39
+ const ipGroup = ip2group[_b = noLimit ? '' : ctx.ip] || (ip2group[_b] = {
39
40
  count: 0,
40
41
  group: new ThrottledStream_1.ThrottleGroup(noLimit ? Infinity : maxKbpsPerIp.get(), noLimit ? undefined : mainThrottleGroup),
41
- }));
42
+ });
42
43
  const conn = (0, connections_1.getConnection)(ctx);
43
44
  if (!conn)
44
45
  throw 'assert throttler connection';
package/src/update.js CHANGED
@@ -125,7 +125,7 @@ async function update(tagOrUrl = '') {
125
125
  const asset = update.assets.find((x) => x.name.includes(assetSearch) && x.name.endsWith('.zip'))
126
126
  || update.assets.find((x) => x.name.endsWith(legacyAssetSearch));
127
127
  if (!asset)
128
- throw "asset not found";
128
+ throw `asset not found: ${assetSearch}`;
129
129
  url = asset.browser_download_url;
130
130
  }
131
131
  if (url) {
package/src/vfs.js CHANGED
@@ -300,7 +300,7 @@ async function* walkNode(parent, { ctx, depth = Infinity, prefixPath = '', requi
300
300
  const { path } = entry;
301
301
  const isFolder = entry.isDirectory();
302
302
  const name = prefixPath + (((_a = parent.rename) === null || _a === void 0 ? void 0 : _a[path]) || path);
303
- if (comments_1.descriptIon.get() && (0, path_1.basename)(name) === comments_1.DESCRIPT_ION)
303
+ if ((0, comments_1.usingDescriptIon)() && (0, path_1.basename)(name) === comments_1.DESCRIPT_ION)
304
304
  return;
305
305
  if (taken === null || taken === void 0 ? void 0 : taken.has(normalizeFilename(name))) // taken by vfs node above
306
306
  return false; // false just in case it's a folder