hfs 0.56.0-alpha2 → 0.56.0-beta4

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/update.js CHANGED
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.update = exports.updateSupported = exports.localUpdateAvailable = exports.getUpdates = exports.autoCheckUpdateResult = void 0;
7
+ exports.update = exports.updateSupported = exports.previousAvailable = exports.localUpdateAvailable = exports.getUpdates = exports.getVersions = exports.autoCheckUpdateResult = void 0;
8
8
  const github_1 = require("./github");
9
9
  const const_1 = require("./const");
10
10
  const path_1 = require("path");
@@ -50,48 +50,53 @@ setInterval((0, misc_1.debounceAsync)(async () => {
50
50
  }), misc_1.HOUR);
51
51
  const ReleaseKeys = ['prerelease', 'tag_name', 'name', 'body', 'assets', 'isNewer', 'versionScalar'];
52
52
  const ReleaseAssetKeys = ['name', 'browser_download_url'];
53
+ const curV = config_1.currentVersion.scalar;
54
+ function prepareRelease(r) {
55
+ const v = (0, config_1.versionToScalar)(r.name);
56
+ return Object.assign(lodash_1.default.pick(r, ReleaseKeys), {
57
+ versionScalar: v,
58
+ isNewer: v > curV,
59
+ assets: r.assets.map((a) => lodash_1.default.pick(a, ReleaseAssetKeys))
60
+ });
61
+ }
62
+ async function getVersions(interrupt) {
63
+ if (!updateToBeta.get() && !const_1.RUNNING_BETA)
64
+ return [];
65
+ const ret = [];
66
+ for await (const x of (0, github_1.apiGithubPaginated)(`repos/${const_1.HFS_REPO}/releases`)) {
67
+ if (x.name.endsWith('-ignore'))
68
+ continue;
69
+ const rel = prepareRelease(x);
70
+ if (rel.versionScalar === curV)
71
+ continue;
72
+ if (interrupt === null || interrupt === void 0 ? void 0 : interrupt(rel))
73
+ break; // avoid fetching too much data
74
+ ret.push(rel);
75
+ }
76
+ return lodash_1.default.sortBy(ret, x => -x.versionScalar);
77
+ }
78
+ exports.getVersions = getVersions;
53
79
  async function getUpdates(strict = false) {
54
80
  (0, github_1.getProjectInfo)(); // check for alerts
55
- const stable = await (0, github_1.getRepoInfo)(const_1.HFS_REPO + '/releases/latest');
56
- stable.isNewer = config_1.currentVersion.olderThan(stable.tag_name);
57
- stable.versionScalar = (0, config_1.versionToScalar)(stable.name);
58
- const ret = await getBetas();
81
+ const stable = prepareRelease(await (0, github_1.getRepoInfo)(const_1.HFS_REPO + '/releases/latest'));
82
+ const res = await getVersions(r => r.versionScalar < stable.versionScalar); // we don't consider betas before stable
83
+ const ret = res.filter(x => x.prerelease && (strict ? x.isNewer : (x.versionScalar !== curV)));
59
84
  if (stable.isNewer || const_1.RUNNING_BETA)
60
85
  ret.push(stable);
61
- // prune a bit, as it will be serialized, but it has a lot of unused data
62
- return lodash_1.default.sortBy(ret, x => -x.versionScalar).filter(x => !strict || x.isNewer).map(x => Object.assign(lodash_1.default.pick(x, ReleaseKeys), { assets: x.assets.map(a => lodash_1.default.pick(a, ReleaseAssetKeys)) }));
63
- async function getBetas() {
64
- if (!updateToBeta.get() && !const_1.RUNNING_BETA)
65
- return [];
66
- let page = 1;
67
- const ret = [];
68
- while (1) {
69
- const per = 100;
70
- const res = await (0, github_1.getRepoInfo)(const_1.HFS_REPO + `/releases?per_page=${per}&page=${page++}`);
71
- if (!res.length)
72
- break;
73
- const curV = config_1.currentVersion.getScalar();
74
- for (const x of res) {
75
- if (!x.prerelease || x.name.endsWith('-ignore'))
76
- continue;
77
- const v = x.versionScalar = (0, config_1.versionToScalar)(x.name);
78
- if (v < stable.versionScalar) // we don't consider betas before stable
79
- return ret;
80
- if (v === curV)
81
- continue; // skip current
82
- x.isNewer = v > curV; // make easy to know what's newer
83
- ret.push(x);
84
- }
85
- }
86
- return ret;
87
- }
86
+ return ret;
88
87
  }
89
88
  exports.getUpdates = getUpdates;
90
89
  const LOCAL_UPDATE = 'hfs-update.zip'; // update from file takes precedence over net
90
+ const INSTALLED_FN = 'hfs-installed.zip';
91
+ const PREVIOUS_FN = 'hfs-previous.zip';
91
92
  function localUpdateAvailable() {
92
93
  return (0, misc_1.exists)(LOCAL_UPDATE);
93
94
  }
94
95
  exports.localUpdateAvailable = localUpdateAvailable;
96
+ function previousAvailable() {
97
+ return (0, misc_1.exists)(PREVIOUS_FN);
98
+ }
99
+ exports.previousAvailable = previousAvailable;
95
100
  async function updateSupported() {
96
101
  return process.env.DISABLE_UPDATE ? false : (argv_1.argv.forceupdate || const_1.IS_BINARY && !await util_os_1.RUNNING_AS_SERVICE);
97
102
  }
@@ -99,10 +104,10 @@ exports.updateSupported = updateSupported;
99
104
  async function update(tagOrUrl = '') {
100
105
  if (!await updateSupported())
101
106
  throw "only binary versions supports automatic update for now";
102
- let doingLocal = '';
103
- let updateSource = tagOrUrl.includes('://') ? await (0, misc_1.httpStream)(tagOrUrl)
104
- : await localUpdateAvailable() && (0, fs_1.createReadStream)(doingLocal = LOCAL_UPDATE);
105
- if (!updateSource) {
107
+ let url = tagOrUrl.includes('://') && tagOrUrl;
108
+ if (tagOrUrl === const_1.PREVIOUS_TAG)
109
+ await (0, promises_1.rename)(PREVIOUS_FN, LOCAL_UPDATE);
110
+ else if (tagOrUrl && !url) {
106
111
  if (/^\d/.test(tagOrUrl)) // work even if the tag is passed without the initial 'v' (useful for console commands)
107
112
  tagOrUrl = 'v' + tagOrUrl;
108
113
  const update = !tagOrUrl ? (await getUpdates(true))[0]
@@ -121,9 +126,14 @@ async function update(tagOrUrl = '') {
121
126
  || update.assets.find((x) => x.name.endsWith(legacyAssetSearch));
122
127
  if (!asset)
123
128
  throw "asset not found";
124
- const url = asset.browser_download_url;
129
+ url = asset.browser_download_url;
130
+ }
131
+ if (url) {
125
132
  console.log("downloading", url);
126
- updateSource = await (0, misc_1.httpStream)(url);
133
+ const { body } = await (0, misc_1.httpWithBody)(url);
134
+ if (!body)
135
+ throw "download failed for " + url;
136
+ await (0, promises_1.writeFile)(LOCAL_UPDATE, body);
127
137
  }
128
138
  const bin = process.execPath;
129
139
  const binPath = (0, path_1.dirname)(bin);
@@ -134,15 +144,16 @@ async function update(tagOrUrl = '') {
134
144
  } while ((0, fs_1.existsSync)((0, path_1.join)(binPath, newBinFile)));
135
145
  plugins_1.pluginsWatcher.pause();
136
146
  try {
137
- await (0, misc_1.unzip)(updateSource, path => (0, path_1.join)(binPath, path === binFile ? newBinFile : path));
147
+ await (0, misc_1.unzip)((0, fs_1.createReadStream)(LOCAL_UPDATE), path => (0, path_1.join)(binPath, path === binFile ? newBinFile : path));
138
148
  const newBin = (0, path_1.join)(binPath, newBinFile);
139
149
  if (!const_1.IS_WINDOWS) {
140
150
  const { mode } = await (0, promises_1.stat)(bin);
141
151
  await (0, promises_1.chmod)(newBin, mode).catch(console.error);
142
152
  }
153
+ await (0, promises_1.rename)(INSTALLED_FN, PREVIOUS_FN).catch(console.warn);
154
+ await (0, promises_1.rename)(LOCAL_UPDATE, INSTALLED_FN).catch(console.warn);
143
155
  (0, first_1.onProcessExit)(() => {
144
156
  const oldBinFile = 'old-' + binFile;
145
- console.log("old version is kept as", oldBinFile);
146
157
  const oldBin = (0, path_1.join)(binPath, oldBinFile);
147
158
  try {
148
159
  (0, fs_1.unlinkSync)(oldBin);
@@ -150,13 +161,6 @@ async function update(tagOrUrl = '') {
150
161
  catch (_a) { }
151
162
  (0, fs_1.renameSync)(bin, oldBin);
152
163
  console.log("launching new version in background", newBinFile);
153
- if (doingLocal)
154
- try {
155
- (0, fs_1.renameSync)(doingLocal, 'old-' + doingLocal);
156
- }
157
- catch (e) {
158
- console.warn(e);
159
- }
160
164
  launch(newBin, ['--updating', binFile, '--cwd .'], { sync: true }); // sync necessary to work on Mac by double-click
161
165
  });
162
166
  console.log("quitting");
package/src/util-files.js CHANGED
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  return (mod && mod.__esModule) ? mod : { "default": mod };
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.parseFile = exports.parseFileCache = exports.exists = exports.isValidFileName = exports.createFileWithPath = exports.prepareFolder = exports.unzip = exports.dirStream = exports.adjustStaticPathForGlob = exports.dirTraversal = exports.watchDir = exports.readFileBusy = exports.isDirectory = void 0;
7
+ exports.parseFile = exports.parseFileCache = exports.exists = exports.isValidFileName = exports.createFileWithPath = exports.prepareFolder = exports.unzip = exports.adjustStaticPathForGlob = exports.dirTraversal = exports.watchDir = exports.readFileBusy = exports.isDirectory = void 0;
8
8
  const promises_1 = require("fs/promises");
9
9
  const misc_1 = require("./misc");
10
10
  const fs_1 = require("fs");
@@ -12,7 +12,6 @@ const path_1 = require("path");
12
12
  const fast_glob_1 = __importDefault(require("fast-glob"));
13
13
  const const_1 = require("./const");
14
14
  const stream_1 = require("stream");
15
- const dirStream_1 = require("./dirStream");
16
15
  // @ts-ignore
17
16
  const unzip_stream_1 = __importDefault(require("unzip-stream"));
18
17
  async function isDirectory(path) {
@@ -79,17 +78,6 @@ function adjustStaticPathForGlob(path) {
79
78
  return fast_glob_1.default.escapePath(path.replace(/\\/g, '/'));
80
79
  }
81
80
  exports.adjustStaticPathForGlob = adjustStaticPathForGlob;
82
- async function* dirStream(path, { depth = 0, onlyFiles = false, onlyFolders = false, hidden = true } = {}) {
83
- if (!await isDirectory(path))
84
- throw Error('ENOTDIR');
85
- for await (const entry of (0, dirStream_1.createDirStream)(path, { depth, hidden })) {
86
- const dirent = entry;
87
- if (dirent.isDirectory() ? onlyFiles : (onlyFolders || !dirent.isFile()))
88
- continue;
89
- yield dirent;
90
- }
91
- }
92
- exports.dirStream = dirStream;
93
81
  async function unzip(stream, cb) {
94
82
  let pending = Promise.resolve();
95
83
  return new Promise((resolve, reject) => stream.pipe(unzip_stream_1.default.Parse())
package/src/util-os.js CHANGED
@@ -12,9 +12,11 @@ const csv_1 = __importDefault(require("@gregoranders/csv"));
12
12
  const node_process_1 = require("node:process");
13
13
  const util_1 = require("util");
14
14
  const const_1 = require("./const");
15
+ const promises_1 = require("fs/promises");
16
+ const promises_2 = require("node:fs/promises");
15
17
  const DF_TIMEOUT = 2000;
16
18
  function getDiskSpaceSync(path) {
17
- while (path && !(0, fs_1.existsSync)(path))
19
+ while (path && !(0, misc_1.isWindowsDrive)(path) && !(0, fs_1.existsSync)(path))
18
20
  path = (0, path_1.dirname)(path);
19
21
  const res = (0, fs_1.statfsSync)(path);
20
22
  return { free: res.bavail * res.bsize, total: res.blocks * res.bsize, name: path };
@@ -29,9 +31,9 @@ function cmdEscape(par) {
29
31
  }
30
32
  exports.cmdEscape = cmdEscape;
31
33
  async function getDiskSpace(path) {
32
- while (path && !(0, misc_1.isWindowsDrive)(path) && !(0, fs_1.existsSync)(path))
34
+ while (path && !(0, misc_1.isWindowsDrive)(path) && !(0, promises_1.access)(path))
33
35
  path = (0, path_1.dirname)(path);
34
- const res = (0, fs_1.statfsSync)(path);
36
+ const res = await (0, promises_2.statfs)(path);
35
37
  return { free: res.bavail * res.bsize, total: res.blocks * res.bsize, name: path };
36
38
  }
37
39
  exports.getDiskSpace = getDiskSpace;
package/src/vfs.js CHANGED
@@ -15,6 +15,9 @@ const events_1 = __importDefault(require("./events"));
15
15
  const perm_1 = require("./perm");
16
16
  const auth_1 = require("./auth");
17
17
  const fswin_1 = __importDefault(require("fswin"));
18
+ const comments_1 = require("./comments");
19
+ const walkDir_1 = require("./walkDir");
20
+ const node_stream_1 = require("node:stream");
18
21
  const showHiddenFiles = (0, config_1.defineConfig)('show_hidden_files', false);
19
22
  function permsFromParent(parent, child) {
20
23
  const ret = {};
@@ -90,7 +93,7 @@ async function urlToNode(url, ctx, parent = exports.vfs, getRest) {
90
93
  try {
91
94
  if (!showHiddenFiles.get() && await isHiddenFile(ret.source))
92
95
  throw 'hiddenFile';
93
- ret.isFolder = (await nodeStats(ret)).isDirectory(); // throws if doesn't exist on disk
96
+ ret.isFolder = (await nodeStats(ret)).isDirectory(); // throws if it doesn't exist on disk
94
97
  }
95
98
  catch (_a) {
96
99
  if (!getRest)
@@ -175,7 +178,7 @@ function getNodeName(node) {
175
178
  const base = (0, path_1.basename)(source);
176
179
  if (/^[./\\]*$/.test(base)) // if empty or special-chars-only
177
180
  return (0, path_1.basename)((0, path_1.resolve)(source)); // resolve to try to get more
178
- if (base.includes('\\')) // source was Windows but now we are running posix. This probably happens only debugging, so it's DX
181
+ if (base.includes('\\') && !source.includes('/')) // source was Windows but now we are running posix. This probably happens only debugging, so it's DX
179
182
  return source.slice(source.lastIndexOf('\\') + 1);
180
183
  return base;
181
184
  }
@@ -243,85 +246,115 @@ function statusCodeForMissingPerm(node, perm, ctx, assign = true) {
243
246
  exports.statusCodeForMissingPerm = statusCodeForMissingPerm;
244
247
  // it's responsibility of the caller to verify you have list permission on parent, as callers have different needs.
245
248
  async function* walkNode(parent, { ctx, depth = Infinity, prefixPath = '', requiredPerm, onlyFolders = false, onlyFiles = false, } = {}) {
246
- var _a, _b;
247
- const { children, source } = parent;
248
- const took = prefixPath ? undefined : new Set();
249
- const maskApplier = parentMaskApplier(parent);
250
- const parentsCache = new Map(); // we use this only if depth > 0
251
- if (children)
252
- for (const child of children) {
253
- if (await nodeIsDirectory(child) ? onlyFiles : onlyFolders)
254
- continue;
255
- const nodeName = getNodeName(child);
256
- const name = prefixPath + nodeName;
257
- took === null || took === void 0 ? void 0 : took.add(normalizeFilename(name));
258
- const item = { ...child, name };
259
- if (!await canSee(item))
260
- continue;
261
- if (item.source) // real items must be accessible
249
+ let started = false;
250
+ const stream = new node_stream_1.Readable({
251
+ objectMode: true,
252
+ async read() {
253
+ if (started)
254
+ return; // for simplicity, we care about starting, and never suspend
255
+ started = true;
256
+ const { children, source } = parent;
257
+ const taken = prefixPath ? undefined : new Set();
258
+ const maskApplier = parentMaskApplier(parent);
259
+ const parentsCache = new Map(); // we use this only if depth > 0
260
+ const visitLater = [];
261
+ if (children)
262
+ for (const child of children) {
263
+ const nodeName = getNodeName(child);
264
+ const name = prefixPath + nodeName;
265
+ taken === null || taken === void 0 ? void 0 : taken.add(normalizeFilename(name));
266
+ const item = { ...child, name };
267
+ if (await cantSee(item))
268
+ continue;
269
+ if (item.source) // real items must be accessible
270
+ try {
271
+ await promises_1.default.access(item.source);
272
+ }
273
+ catch (_a) {
274
+ continue;
275
+ }
276
+ const isFolder = await nodeIsDirectory(child);
277
+ if (onlyFiles ? !isFolder : (!onlyFolders || isFolder))
278
+ stream.push(item);
279
+ if (!depth || !isFolder || cantRecur(item))
280
+ continue;
281
+ parentsCache.set(name, item);
282
+ visitLater.push([item, name]); // prioritize siblings
283
+ }
284
+ try {
285
+ if (!source)
286
+ return;
287
+ if (requiredPerm && ctx // no permission, no reason to continue (at least for dynamic elements)
288
+ && !hasPermission(parent, requiredPerm, ctx)
289
+ && !masksCouldGivePermission(parent.masks, requiredPerm))
290
+ return;
262
291
  try {
263
- await promises_1.default.access(item.source);
292
+ let lastDir = prefixPath.slice(0, -1) || '.';
293
+ parentsCache.set(lastDir, parent);
294
+ await (0, walkDir_1.walkDir)(source, { depth, hidden: showHiddenFiles.get() }, async (entry) => {
295
+ var _a, _b;
296
+ if (ctx === null || ctx === void 0 ? void 0 : ctx.isAborted()) {
297
+ stream.push(null);
298
+ return null;
299
+ }
300
+ const { path } = entry;
301
+ const isFolder = entry.isDirectory();
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)
304
+ return;
305
+ if (taken === null || taken === void 0 ? void 0 : taken.has(normalizeFilename(name))) // taken by vfs node above
306
+ return false; // false just in case it's a folder
307
+ if (depth) {
308
+ const dir = (0, path_1.dirname)(name);
309
+ if (dir !== lastDir)
310
+ parent = parentsCache.get(lastDir = dir);
311
+ }
312
+ const item = {
313
+ name,
314
+ isFolder,
315
+ source: (0, path_1.join)(source, path),
316
+ rename: renameUnderPath(parent.rename, path),
317
+ };
318
+ if (await cantSee(item)) // can't see: don't produce and don't recur
319
+ return false;
320
+ if (onlyFiles ? !isFolder : (!onlyFolders || isFolder))
321
+ stream.push(item);
322
+ if (cantRecur(item))
323
+ return false;
324
+ if (isFolder)
325
+ parentsCache.set(name, item);
326
+ (_b = entry.closingBranch) === null || _b === void 0 ? void 0 : _b.then(p => parentsCache.delete(p || '.'));
327
+ });
264
328
  }
265
- catch (_c) {
266
- continue;
329
+ catch (e) {
330
+ console.debug('walkNode', source, e); // ENOTDIR, or lacking permissions
267
331
  }
268
- yield item;
269
- if (!depth || !await nodeIsDirectory(child).catch(() => false))
270
- continue;
271
- parentsCache.set(name, item);
272
- inheritMasks(item, parent, nodeName);
273
- if (!ctx || hasPermission(item, 'can_list', ctx)) // check perm before recursion
274
- yield* walkNode(item, { ctx, depth: depth - 1, prefixPath: name + '/', requiredPerm, onlyFolders });
275
- }
276
- if (!source)
277
- return;
278
- if (requiredPerm && ctx // no permission, no reason to continue (at least for dynamic elements)
279
- && !hasPermission(parent, requiredPerm, ctx)
280
- && !masksCouldGivePermission(parent.masks, requiredPerm))
281
- return;
282
- try {
283
- let lastDir = prefixPath.slice(0, -1) || '.';
284
- parentsCache.set(lastDir, parent);
285
- for await (const entry of (0, misc_1.dirStream)(source, { depth, onlyFolders, hidden: showHiddenFiles.get() })) {
286
- if (ctx === null || ctx === void 0 ? void 0 : ctx.isAborted())
287
- break;
288
- const { path } = entry;
289
- const isFolder = entry.isDirectory();
290
- const name = prefixPath + (((_a = parent.rename) === null || _a === void 0 ? void 0 : _a[path]) || path);
291
- if (took === null || took === void 0 ? void 0 : took.has(normalizeFilename(name)))
292
- continue;
293
- if (depth) {
294
- const dir = (0, path_1.dirname)(name);
295
- if (dir !== lastDir)
296
- parent = parentsCache.get(lastDir = dir);
332
+ parentsCache.clear(); // hoping for faster GC
333
+ }
334
+ finally {
335
+ for (const [item, name] of visitLater)
336
+ for await (const x of walkNode(item, { ctx, depth: depth - 1, prefixPath: name + '/', requiredPerm, onlyFolders }))
337
+ stream.push(x);
338
+ stream.push(null);
339
+ }
340
+ function cantRecur(item) {
341
+ if (ctx && !hasPermission(item, 'can_list', ctx))
342
+ return true;
343
+ inheritMasks(item, parent);
344
+ }
345
+ // item will be changed, so be sure to pass a temp node
346
+ async function cantSee(item) {
347
+ await maskApplier(item);
348
+ inheritFromParent(parent, item);
349
+ if (ctx && !hasPermission(item, 'can_see', ctx))
350
+ return true;
351
+ item.isTemp = true;
297
352
  }
298
- const item = {
299
- name,
300
- isFolder,
301
- source: (0, path_1.join)(source, path),
302
- rename: renameUnderPath(parent.rename, path),
303
- };
304
- if (isFolder) // store it even if we can't see it (masks), as its children can be produced by dirStream
305
- parentsCache.set(name, item);
306
- if (!(onlyFiles && isFolder) && await canSee(item))
307
- yield item;
308
- (_b = entry.closingBranch) === null || _b === void 0 ? void 0 : _b.then(p => parentsCache.delete(p || '.'));
309
353
  }
310
- }
311
- catch (e) {
312
- console.debug('walkNode', source, e); // ENOTDIR, or lacking permissions
313
- }
314
- parentsCache.clear(); // hoping for faster GC
315
- // item will be changed, so be sure to pass a temp node
316
- async function canSee(item) {
317
- // we basename for depth>0 where we already have the rest of the path in the parent's url, and would be duplicated
318
- await maskApplier(item, (0, path_1.basename)(getNodeName(item)));
319
- inheritFromParent(parent, item);
320
- if (ctx && !hasPermission(item, 'can_see', ctx))
321
- return;
322
- item.isTemp = true;
323
- return item;
324
- }
354
+ });
355
+ // must use a stream to be able to work with the callback-based mechanism of walkDir, but Readable is not typed so we wrap it with a generator
356
+ for await (const item of stream)
357
+ yield item;
325
358
  }
326
359
  exports.walkNode = walkNode;
327
360
  function masksCouldGivePermission(masks, perm) {
@@ -345,7 +378,7 @@ function parentMaskApplier(parent) {
345
378
  k = k.startsWith('**/') ? k.slice(3) : !k.includes('/') ? k : ''; // ** globstar matches also zero subfolders, so this mask must be applied here too
346
379
  return k && { mods, matcher: (0, misc_1.makeMatcher)(k), mustBeFolder };
347
380
  }));
348
- return async (item, virtualBasename = getNodeName(item)) => {
381
+ return async (item, virtualBasename = (0, path_1.basename)(getNodeName(item))) => {
349
382
  let isFolder = undefined;
350
383
  for (const { matcher, mods, mustBeFolder } of matchers) {
351
384
  if (mustBeFolder !== undefined) {
@@ -361,7 +394,7 @@ function parentMaskApplier(parent) {
361
394
  };
362
395
  }
363
396
  exports.parentMaskApplier = parentMaskApplier;
364
- function inheritMasks(item, parent, virtualBasename) {
397
+ function inheritMasks(item, parent, virtualBasename = getNodeName(item)) {
365
398
  const { masks } = parent;
366
399
  if (!masks)
367
400
  return;
@@ -3,49 +3,32 @@ 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.DirentFromStats = exports.createDirStream = void 0;
6
+ exports.DirentFromStats = exports.walkDir = void 0;
7
7
  const makeQ_1 = require("./makeQ");
8
8
  const promises_1 = require("fs/promises");
9
9
  const const_1 = require("./const");
10
10
  const path_1 = require("path");
11
- const stream_1 = require("stream");
12
11
  const cross_1 = require("./cross");
13
12
  const node_fs_1 = require("node:fs");
14
13
  const fswin_1 = __importDefault(require("fswin"));
14
+ const util_files_1 = require("./util-files");
15
15
  const dirQ = (0, makeQ_1.makeQ)(3);
16
- function createDirStream(startPath, { depth = 0, hidden = true }) {
16
+ // cb returns void = just go on, null = stop, false = go on but don't recur (in case of depth)
17
+ function walkDir(path, { depth = 0, hidden = true }, cb) {
17
18
  let stopped = false;
18
- let started = false;
19
19
  const closingQ = [];
20
- const stream = new stream_1.Readable({
21
- objectMode: true,
22
- read() {
23
- if (started)
24
- return;
25
- started = true;
26
- dirQ.add(() => readDir('', depth)
27
- .then(res => {
28
- Promise.resolve(res === null || res === void 0 ? void 0 : res.branchDone).then(() => {
29
- stream.push(null);
30
- });
31
- }, e => {
32
- stream.emit('error', e);
33
- return stream.push(null);
34
- }));
35
- }
36
- });
37
- stream.on('close', () => stopped = true);
38
- return Object.assign(stream, {
39
- stop() {
40
- stopped = true;
41
- if (!dirQ.isWorking())
42
- stream.push(null);
43
- },
20
+ return new Promise(async (resolve, reject) => {
21
+ if (!await (0, util_files_1.isDirectory)(path))
22
+ return reject(Error('ENOTDIR'));
23
+ dirQ.add(() => readDir('', depth)
24
+ .then(res => {
25
+ Promise.resolve(res === null || res === void 0 ? void 0 : res.branchDone).then(resolve);
26
+ }, reject));
44
27
  });
45
- async function readDir(path, depth) {
28
+ async function readDir(relativePath, depth) {
46
29
  if (stopped)
47
30
  return;
48
- const base = (0, path_1.join)(startPath, path);
31
+ const base = (0, path_1.join)(path, relativePath);
49
32
  const subDirsDone = [];
50
33
  let n = 0;
51
34
  let last;
@@ -63,7 +46,7 @@ function createDirStream(startPath, { depth = 0, hidden = true }) {
63
46
  break;
64
47
  if (!hidden && f.IS_HIDDEN)
65
48
  continue;
66
- work(Object.assign(Object.create(methods), {
49
+ await work(Object.assign(Object.create(methods), {
67
50
  isDir: f.IS_DIRECTORY,
68
51
  name: f.LONG_NAME,
69
52
  stats: { size: f.SIZE, birthtime: f.CREATION_TIME, mtime: f.LAST_WRITE_TIME }
@@ -84,38 +67,42 @@ function createDirStream(startPath, { depth = 0, hidden = true }) {
84
67
  const expanded = entry;
85
68
  if (stats)
86
69
  expanded.stats = stats;
87
- work(expanded);
70
+ await work(expanded);
88
71
  }
89
- function work(entry) {
90
- entry.path = (path && path + '/') + entry.name;
72
+ async function work(entry) {
73
+ entry.path = (relativePath && relativePath + '/') + entry.name;
91
74
  if (last && closingQ.length) // pending entries
92
75
  last.closingBranch = Promise.resolve(closingQ.shift());
93
76
  last = entry;
94
- if (depth > 0 && entry.isDirectory()) {
95
- const branchDone = (0, cross_1.pendingPromise)(); // per-job
96
- const job = () => readDir(entry.path, depth - 1) // recur
97
- .then(x => x, () => { }) // mute errors
98
- .then(res => {
99
- if (!(res === null || res === void 0 ? void 0 : res.n))
100
- closingQ.push(entry.path); // no children to tell i'm done
101
- Promise.resolve(res === null || res === void 0 ? void 0 : res.branchDone).then(() => branchDone.resolve());
102
- });
103
- dirQ.add(job); // this won't start until next tick
104
- subDirsDone.push(branchDone);
105
- }
106
- stream.push(entry);
77
+ const res = await cb(entry);
78
+ if (res === null)
79
+ return stopped = true;
80
+ if (res === false)
81
+ return;
107
82
  n++;
83
+ if (!depth || !entry.isDirectory())
84
+ return;
85
+ const branchDone = (0, cross_1.pendingPromise)(); // per-job
86
+ const job = () => readDir(entry.path, depth - 1) // recur
87
+ .then(x => x, () => { }) // mute errors
88
+ .then(res => {
89
+ if (!(res === null || res === void 0 ? void 0 : res.n))
90
+ closingQ.push(entry.path); // no children to tell i'm done
91
+ Promise.resolve(res === null || res === void 0 ? void 0 : res.branchDone).then(() => branchDone.resolve());
92
+ });
93
+ dirQ.add(job); // this won't start until next tick
94
+ subDirsDone.push(branchDone);
108
95
  }
109
96
  const branchDone = Promise.allSettled(subDirsDone).then(() => { });
110
97
  if (last) // using streams, we don't know when the entries are received, so we need to notify on last item
111
- last.closingBranch = branchDone.then(() => path);
98
+ last.closingBranch = branchDone.then(() => relativePath);
112
99
  else
113
- closingQ.push(path); // ok, we'll ask next one to carry this info
100
+ closingQ.push(relativePath); // ok, we'll ask next one to carry this info
114
101
  // don't return the promise directly, as this job ends here, but communicate to caller the promise for the whole branch
115
102
  return { branchDone, n };
116
103
  }
117
104
  }
118
- exports.createDirStream = createDirStream;
105
+ exports.walkDir = walkDir;
119
106
  const kStats = Symbol('stats');
120
107
  // Adapting an internal class in Node.js to mimic the behavior of `Dirent` when creating it manually from `Stats`.
121
108
  // https://github.com/nodejs/node/blob/a4cf6b204f0b160480153dc293ae748bf15225f9/lib/internal/fs/utils.js#L199C1-L213
package/src/zip.js CHANGED
@@ -14,10 +14,12 @@ const config_1 = require("./config");
14
14
  const path_1 = require("path");
15
15
  const serveFile_1 = require("./serveFile");
16
16
  const const_1 = require("./const");
17
+ const api_get_file_list_1 = require("./api.get_file_list");
18
+ const comments_1 = require("./comments");
17
19
  // expects 'node' to have had permissions checked by caller
18
20
  async function zipStreamFromFolder(node, ctx) {
19
21
  var _a;
20
- const list = (_a = (0, misc_1.wantArray)(ctx.query.list)[0]) === null || _a === void 0 ? void 0 : _a.split('*'); // we are using * as separator because it cannot be used in a file name and doesn't need url encoding
22
+ const list = (_a = (0, misc_1.wantArray)(ctx.query.list)[0]) === null || _a === void 0 ? void 0 : _a.split('//'); // slash is the only char not allowed in file names both for windows and unix, but still we need to encode whole paths, so the only safe choice to separate the entries is the double slash
21
23
  if (!list && (0, vfs_1.statusCodeForMissingPerm)(node, 'can_archive', ctx))
22
24
  return;
23
25
  ctx.status = const_1.HTTP_OK;
@@ -25,7 +27,7 @@ async function zipStreamFromFolder(node, ctx) {
25
27
  // ctx.query.list is undefined | string | string[]
26
28
  const name = (list === null || list === void 0 ? void 0 : list.length) === 1 ? (0, misc_1.safeDecodeURIComponent)((0, path_1.basename)(list[0])) : (0, vfs_1.getNodeName)(node);
27
29
  (0, serveFile_1.forceDownload)(ctx, ((0, misc_1.isWindowsDrive)(name) ? name[0] : (name || 'archive')) + '.zip');
28
- const filter = (0, misc_1.pattern2filter)(String(ctx.query.search || ''));
30
+ const { filterName, filterComment } = (0, api_get_file_list_1.paramsToFilter)(ctx.query);
29
31
  const walker = !list ? (0, vfs_1.walkNode)(node, { ctx, requiredPerm: 'can_archive' })
30
32
  : (async function* () {
31
33
  for await (const uri of list) {
@@ -52,8 +54,11 @@ async function zipStreamFromFolder(node, ctx) {
52
54
  if (!(0, vfs_1.hasPermission)(el, 'can_archive', ctx))
53
55
  return; // the fact you see it doesn't mean you can get it
54
56
  const { source } = el;
55
- const name = (0, vfs_1.getNodeName)(el);
56
- if (!filter(name))
57
+ let name = (0, vfs_1.getNodeName)(el);
58
+ if (!const_1.IS_WINDOWS) // posix supports \ in file names, but zip tools don't
59
+ name = name.replaceAll('\\', '_');
60
+ if (filterName && !filterName(name)
61
+ || filterComment && !filterComment(await (0, comments_1.getCommentFor)(source) || ''))
57
62
  return;
58
63
  try {
59
64
  if (el.isFolder)
@@ -1 +0,0 @@
1
- .ariaOnly{position:absolute;clip-path:rect(1px 1px 1px 1px);clip:rect(1px,1px,1px,1px)}.icon{font-size:1.2em;height:1.2em;width:1.4em;display:inline-block;text-align:center}@keyframes blink{0%{opacity:1}50%{opacity:.2}}:root{height:100dvh;--success: #5c5}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;height:100vh;background:#000}#root{min-height:100%;display:flex}main{word-break:break-word}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}img.flag{width:1.5em;height:1em;vertical-align:text-top;margin-top:1px}.icon-w-text{margin-right:.5em}form{max-width:100%}.MuiSvgIcon-root{vertical-align:bottom}div.MuiTreeItem-content{padding:0}.MuiDataGrid-columnHeaders{background-color:#8882}.MuiDataGrid-cell{line-height:1.1em}.MuiDataGrid-filterForm{flex-wrap:wrap;justify-content:space-evenly;row-gap:1em}.wrap[role=cell]{white-space:normal!important}ol,ul{margin-top:.2em;margin-bottom:.2em;padding-left:1.5em}h2.MuiDialogTitle-root{padding-top:2px;padding-bottom:2px}.dialog-alert .MuiDialogContent-root{max-width:45em;padding:.5em 1em}.animated-dashed-line{width:100%;height:2px;background-image:linear-gradient(to right,currentColor 50%,transparent 50%);background-size:10px 100%;animation:animate-dash 1s alternate linear infinite}@keyframes animate-dash{to{background-position:20px 0}}@keyframes success{50%{transform:scale(1.3);color:var(--success)}to{transform:inherit;color:inherit}}::-webkit-scrollbar{width:4px}::-webkit-scrollbar-thumb{background:#8888}::-webkit-scrollbar-track{background:#8882}.token.operator{background:unset!important}.dialog-backdrop{position:fixed;inset:0;background:#8886;backdrop-filter:blur(2px);display:flex;justify-content:center;align-items:center;z-index:1000}.dialog{background:#fff;background:var(--bg);padding:.5em;padding:max(.5em,1vw,2vh);padding-top:0;border-radius:1em;position:relative;margin:0 3vw;overflow:hidden;max-height:calc(100vh - 2em);display:flex;flex-direction:column;justify-content:center}.dialog-icon{color:#fff;background-color:var(--color);position:absolute;top:0;width:2em;height:1.8em;text-align:center;border-radius:.8em 0}.dialog-icon-text{display:flex;align-items:center;justify-content:center}.dialog-title{font-size:120%;font-weight:400;margin:.3em 0;padding:0 .5em;min-height:1.2em}.dialog-closer~.dialog-title{margin-right:2em}.dialog-type~.dialog-title{margin-left:2em}.dialog-icon~.dialog-title{text-align:center}.dialog-closer{border-radius:0 .8em;right:0;padding:0;background-color:#c88}.dialog-icon~.dialog-content{margin-top:1em}.dialog-type{left:0;top:0;overflow:hidden;opacity:.7}.dialog-content{overflow:auto;max-height:calc(100vh - 4.5em)}.dialog-content p{white-space:pre-wrap;margin:.5em 0}.dialog-confirm .dialog-content button{margin-top:1em}.dialog-alert-info{--color: #282 }.dialog-alert-warning{--color: #c91 }.dialog-alert-error{--color: #822}@media (max-width: 42em){.dialog-icon{font-size:120%}.dialog-icon~.dialog-content{margin-top:1.5em}}.dialog-prompt label{display:block;margin:.5em .1em}.toasts{position:fixed;right:0;display:flex;flex-direction:column;margin-top:.5em;gap:.5em;z-index:1001}.toast{background:var(--faint-contrast);color:var(--text-high-contrast);transition:all .5s ease-in;position:relative;left:-.5em;overflow:hidden;display:flex;align-items:center;padding:.3em .6em;border-radius:.5em;box-shadow:0 0 .3em .3em #8883;box-sizing:border-box}.toast .toast-icon{margin-right:.3em;animation:zoomRotating 1.5s}.toast.toast-success{background-color:var(--success)}.toast.toast-warning{background-color:var(--warning)}.toast.toast-error{background-color:var(--error)}.toast.before{left:100%;transform:scale(.1);padding-top:0;padding-bottom:0}.toast.after{height:0!important;padding-top:0;padding-bottom:0;transition-duration:.2s;transform:scale(0)}@keyframes zoomRotating{0%{transform:scale(0)}to{transform:scale(1) rotate(360deg)}}code[class*=language-],pre[class*=language-]{color:#657b83;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection{background:#073642}pre[class*=language-]::selection,pre[class*=language-] ::selection,code[class*=language-]::selection,code[class*=language-] ::selection{background:#073642}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto;border-radius:.3em}:not(pre)>code[class*=language-],pre[class*=language-]{background-color:#fdf6e3}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em}.token.comment,.token.prolog,.token.doctype,.token.cdata{color:#93a1a1}.token.punctuation{color:#586e75}.token.namespace{opacity:.7}.token.property,.token.tag,.token.boolean,.token.number,.token.constant,.token.symbol,.token.deleted{color:#268bd2}.token.selector,.token.attr-name,.token.string,.token.char,.token.builtin,.token.url,.token.inserted{color:#2aa198}.token.entity{color:#657b83;background:#eee8d5}.token.atrule,.token.attr-value,.token.keyword{color:#859900}.token.function,.token.class-name{color:#b58900}.token.regex,.token.important,.token.variable{color:#cb4b16}.token.important,.token.bold{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}