Upload via GUI (7543 Dateien)

This commit is contained in:
2026-10-22 06:58:16 +00:00
parent 68133f4d0f
commit 860c714301
50 changed files with 3039 additions and 0 deletions
+94
View File
@@ -0,0 +1,94 @@
# @electron-internal/extract-zip
> [!WARNING]
> **Internal to the Electron project.** This package exists to serve Electron's
> own tooling. Use from non-Electron packages is not supported: the API may
> change to suit Electron's needs, and bug reports or feature requests from
> outside use cases may be closed without action. If you need a general-purpose
> extractor, use [`extract-zip`](https://github.com/max-mapper/extract-zip).
Fast, safe, native zip extraction for Node.js. Drop-in replacement for [`extract-zip`](https://github.com/max-mapper/extract-zip).
- **Native**: Rust core via N-API, decompression runs off the event loop.
- **Fast**: ~2x faster on entry-heavy archives, never slower. See [benchmarks](#benchmarks).
- **Safe**: hardened against Zip Slip, symlink escapes, absolute paths, NUL injection, Windows reserved names, and zip bombs.
- **Zero runtime deps**: no `debug`/`yauzl`/`get-stream` in your tree.
- **Cross-platform**: prebuilt binaries for macOS, Linux (glibc/musl), and Windows (x64/arm64).
## Install
```sh
yarn add @electron-internal/extract-zip
```
## Usage
ESM only:
```js
import extract from '@electron-internal/extract-zip';
await extract('archive.zip', { dir: '/absolute/output/path' });
```
`dir` (required, absolute) is the only option. Everything else is fixed: existing
files are overwritten, archive mode bits (masked to `0o777`) and mtimes are
preserved, symlinks are created (skipped on Windows without symlink privilege),
and writes are parallelised across `min(cpus, 8)` workers. The original's
`onEntry`, `defaultDirMode`, and `defaultFileMode` are not supported, since no
consumer in the `electron` org uses them.
## Security
This package is hardened for extracting trusted Electron distribution archives,
enforcing path containment against Zip Slip, symlink escapes, absolute paths, NUL
injection, Windows reserved names, and zip bombs. Its threat model and the full
list of containment guarantees are documented in [`SECURITY.md`](./SECURITY.md).
Extracting untrusted or unverified archives is out of scope — see
[`SECURITY.md`](./SECURITY.md) for details.
## Benchmarks
`yarn bench` (Apple M-series, Node 24, median of 5):
| Corpus | Zip size | `extract-zip` (JS) | this | Speedup |
|---|--:|--:|--:|--:|
| electron-v42.2.0-darwin-arm64 | 112 MB | 817 ms | 441 ms | 1.9x |
| 8 x 4 MB compressible | 0.1 MB | 24 ms | 3 ms | 9.4x |
| 2000 small text files | 0.4 MB | 372 ms | 199 ms | 1.9x |
| 200 incompressible files | 6.2 MB | 40 ms | 22 ms | 1.8x |
| `node_modules` | 2.9 MB | 68 ms | 37 ms | 1.9x |
Extraction runs in phases: validate paths and create directories, inflate and
write files in parallel with zlib-ng, then apply symlinks and directory
metadata. The Electron number is gated by its single 182 MB framework binary,
which can't be split further.
## Distribution
One package ships all prebuilt binaries (~2 MB gzipped): macOS
`darwin-universal`, Windows `x64`/`arm64`, and Linux `x64`/`arm64` for both glibc
and musl. `binding.js` picks the right one at load time. No
`optionalDependencies`, no postinstall, no network at install.
## Building from source
Requires a Rust toolchain (and `cmake` for zlib-ng).
```sh
yarn install
yarn build # builds index.<your-platform>.node
yarn test
```
## Releasing
Releases are driven by [semantic-release](https://semantic-release.gitbook.io/)
on every push to `main`: conventional commit messages decide the version bump,
CI builds all targets, and the fat package is published to npm via trusted
publishing. No manual version bumps or tags.
## License
BSD-2-Clause
Binary file not shown.
Binary file not shown.
+69
View File
@@ -0,0 +1,69 @@
{
"name": "@electron-internal/extract-zip",
"version": "1.0.5",
"description": "Fast, safe, native zip extraction for Node.js. Drop-in replacement for extract-zip.",
"type": "module",
"exports": {
".": {
"types": "./index.d.ts",
"default": "./index.js"
}
},
"files": [
"index.js",
"index.d.ts",
"binding.js",
"binding.d.ts",
"index.*.node"
],
"napi": {
"binaryName": "index",
"packageName": "@electron-internal/extract-zip",
"targets": [
"x86_64-apple-darwin",
"aarch64-apple-darwin",
"universal-apple-darwin",
"x86_64-pc-windows-msvc",
"aarch64-pc-windows-msvc",
"x86_64-unknown-linux-gnu",
"aarch64-unknown-linux-gnu",
"x86_64-unknown-linux-musl",
"aarch64-unknown-linux-musl",
"i686-unknown-linux-gnu",
"armv7-unknown-linux-gnueabihf"
]
},
"scripts": {
"build": "napi build --platform --release --esm --output-dir . --js binding.js --dts binding.d.ts && node scripts/strip-binding-fallbacks.js",
"build:debug": "napi build --platform --esm --output-dir . --js binding.js --dts binding.d.ts && node scripts/strip-binding-fallbacks.js",
"universal": "napi universalize --output-dir .",
"test": "node --test test/*.test.js",
"bench": "node bench/bench.js",
"bench:electron": "node bench/electron.js",
"prepublishOnly": "node scripts/check-prebuilds.js"
},
"keywords": [
"zip",
"unzip",
"extract",
"native",
"fast"
],
"license": "BSD-2-Clause",
"packageManager": "yarn@4.10.3+sha512.c38cafb5c7bb273f3926d04e55e1d8c9dfa7d9c3ea1f36a4868fa028b9e5f72298f0b7f401ad5eb921749eb012eb1c3bb74bf7503df3ee43fd600d14a018266f",
"engines": {
"node": ">=22.12.0"
},
"publishConfig": {
"provenance": true,
"access": "public"
},
"repository": {
"url": "https://github.com/electron/extract-zip"
},
"devDependencies": {
"@napi-rs/cli": "patch:@napi-rs/cli@npm%3A3.6.2#~/.yarn/patches/@napi-rs-cli-npm-3.6.2-b710c59d43.patch",
"extract-zip": "2.0.1",
"yazl": "3.3.1"
}
}
+15
View File
@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+71
View File
@@ -0,0 +1,71 @@
# fs-minipass
Filesystem streams based on [minipass](http://npm.im/minipass).
4 classes are exported:
- ReadStream
- ReadStreamSync
- WriteStream
- WriteStreamSync
When using `ReadStreamSync`, all of the data is made available
immediately upon consuming the stream. Nothing is buffered in memory
when the stream is constructed. If the stream is piped to a writer,
then it will synchronously `read()` and emit data into the writer as
fast as the writer can consume it. (That is, it will respect
backpressure.) If you call `stream.read()` then it will read the
entire file and return the contents.
When using `WriteStreamSync`, every write is flushed to the file
synchronously. If your writes all come in a single tick, then it'll
write it all out in a single tick. It's as synchronous as you are.
The async versions work much like their node builtin counterparts,
with the exception of introducing significantly less Stream machinery
overhead.
## USAGE
It's just streams, you pipe them or read() them or write() to them.
```js
import { ReadStream, WriteStream } from 'fs-minipass'
// or: const { ReadStream, WriteStream } = require('fs-minipass')
const readStream = new ReadStream('file.txt')
const writeStream = new WriteStream('output.txt')
writeStream.write('some file header or whatever\n')
readStream.pipe(writeStream)
```
## ReadStream(path, options)
Path string is required, but somewhat irrelevant if an open file
descriptor is passed in as an option.
Options:
- `fd` Pass in a numeric file descriptor, if the file is already open.
- `readSize` The size of reads to do, defaults to 16MB
- `size` The size of the file, if known. Prevents zero-byte read()
call at the end.
- `autoClose` Set to `false` to prevent the file descriptor from being
closed when the file is done being read.
## WriteStream(path, options)
Path string is required, but somewhat irrelevant if an open file
descriptor is passed in as an option.
Options:
- `fd` Pass in a numeric file descriptor, if the file is already open.
- `mode` The mode to create the file with. Defaults to `0o666`.
- `start` The position in the file to start reading. If not
specified, then the file will start writing at position zero, and be
truncated by default.
- `autoClose` Set to `false` to prevent the file descriptor from being
closed when the stream is ended.
- `flags` Flags to use when opening the file. Irrelevant if `fd` is
passed in, since file won't be opened in that case. Defaults to
`'a'` if a `pos` is specified, or `'w'` otherwise.
+118
View File
@@ -0,0 +1,118 @@
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import EE from 'events';
import { Minipass } from 'minipass';
declare const _autoClose: unique symbol;
declare const _close: unique symbol;
declare const _ended: unique symbol;
declare const _fd: unique symbol;
declare const _finished: unique symbol;
declare const _flags: unique symbol;
declare const _flush: unique symbol;
declare const _handleChunk: unique symbol;
declare const _makeBuf: unique symbol;
declare const _mode: unique symbol;
declare const _needDrain: unique symbol;
declare const _onerror: unique symbol;
declare const _onopen: unique symbol;
declare const _onread: unique symbol;
declare const _onwrite: unique symbol;
declare const _open: unique symbol;
declare const _path: unique symbol;
declare const _pos: unique symbol;
declare const _queue: unique symbol;
declare const _read: unique symbol;
declare const _readSize: unique symbol;
declare const _reading: unique symbol;
declare const _remain: unique symbol;
declare const _size: unique symbol;
declare const _write: unique symbol;
declare const _writing: unique symbol;
declare const _defaultFlag: unique symbol;
declare const _errored: unique symbol;
export type ReadStreamOptions = Minipass.Options<Minipass.ContiguousData> & {
fd?: number;
readSize?: number;
size?: number;
autoClose?: boolean;
};
export type ReadStreamEvents = Minipass.Events<Minipass.ContiguousData> & {
open: [fd: number];
};
export declare class ReadStream extends Minipass<Minipass.ContiguousData, Buffer, ReadStreamEvents> {
[_errored]: boolean;
[_fd]?: number;
[_path]: string;
[_readSize]: number;
[_reading]: boolean;
[_size]: number;
[_remain]: number;
[_autoClose]: boolean;
constructor(path: string, opt: ReadStreamOptions);
get fd(): number | undefined;
get path(): string;
write(): void;
end(): void;
[_open](): void;
[_onopen](er?: NodeJS.ErrnoException | null, fd?: number): void;
[_makeBuf](): Buffer;
[_read](): void;
[_onread](er?: NodeJS.ErrnoException | null, br?: number, buf?: Buffer): void;
[_close](): void;
[_onerror](er: NodeJS.ErrnoException): void;
[_handleChunk](br: number, buf: Buffer): boolean;
emit<Event extends keyof ReadStreamEvents>(ev: Event, ...args: ReadStreamEvents[Event]): boolean;
}
export declare class ReadStreamSync extends ReadStream {
[_open](): void;
[_read](): void;
[_close](): void;
}
export type WriteStreamOptions = {
fd?: number;
autoClose?: boolean;
mode?: number;
captureRejections?: boolean;
start?: number;
flags?: string;
};
export declare class WriteStream extends EE {
readable: false;
writable: boolean;
[_errored]: boolean;
[_writing]: boolean;
[_ended]: boolean;
[_queue]: Buffer[];
[_needDrain]: boolean;
[_path]: string;
[_mode]: number;
[_autoClose]: boolean;
[_fd]?: number;
[_defaultFlag]: boolean;
[_flags]: string;
[_finished]: boolean;
[_pos]?: number;
constructor(path: string, opt: WriteStreamOptions);
emit(ev: string, ...args: any[]): boolean;
get fd(): number | undefined;
get path(): string;
[_onerror](er: NodeJS.ErrnoException): void;
[_open](): void;
[_onopen](er?: null | NodeJS.ErrnoException, fd?: number): void;
end(buf: string, enc?: BufferEncoding): this;
end(buf?: Buffer, enc?: undefined): this;
write(buf: string, enc?: BufferEncoding): boolean;
write(buf: Buffer, enc?: undefined): boolean;
[_write](buf: Buffer): void;
[_onwrite](er?: null | NodeJS.ErrnoException, bw?: number): void;
[_flush](): void;
[_close](): void;
}
export declare class WriteStreamSync extends WriteStream {
[_open](): void;
[_close](): void;
[_write](buf: Buffer): void;
}
export {};
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,OAAO,EAAE,MAAM,QAAQ,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAInC,QAAA,MAAM,UAAU,eAAuB,CAAA;AACvC,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,GAAG,eAAgB,CAAA;AACzB,QAAA,MAAM,SAAS,eAAsB,CAAA;AACrC,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,YAAY,eAAyB,CAAA;AAC3C,QAAA,MAAM,QAAQ,eAAqB,CAAA;AACnC,QAAA,MAAM,KAAK,eAAkB,CAAA;AAC7B,QAAA,MAAM,UAAU,eAAuB,CAAA;AACvC,QAAA,MAAM,QAAQ,eAAqB,CAAA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AG,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,SAAS,GAAG,IAAI;IAoBxC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,cAAc,GAAG,OAAO;IACjD,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,SAAS,GAAG,OAAO;IAsB5C,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,MAAM;IAWpB,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,cAAc,EAAE,EAAE,CAAC,EAAE,MAAM;IAwBzD,CAAC,MAAM,CAAC;IAgBR,CAAC,MAAM,CAAC;CAST;AAED,qBAAa,eAAgB,SAAQ,WAAW;IAC9C,CAAC,KAAK,CAAC,IAAI,IAAI;IAsBf,CAAC,MAAM,CAAC;IASR,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,MAAM;CAmBrB"}
+430
View File
@@ -0,0 +1,430 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WriteStreamSync = exports.WriteStream = exports.ReadStreamSync = exports.ReadStream = void 0;
const events_1 = __importDefault(require("events"));
const fs_1 = __importDefault(require("fs"));
const minipass_1 = require("minipass");
const writev = fs_1.default.writev;
const _autoClose = Symbol('_autoClose');
const _close = Symbol('_close');
const _ended = Symbol('_ended');
const _fd = Symbol('_fd');
const _finished = Symbol('_finished');
const _flags = Symbol('_flags');
const _flush = Symbol('_flush');
const _handleChunk = Symbol('_handleChunk');
const _makeBuf = Symbol('_makeBuf');
const _mode = Symbol('_mode');
const _needDrain = Symbol('_needDrain');
const _onerror = Symbol('_onerror');
const _onopen = Symbol('_onopen');
const _onread = Symbol('_onread');
const _onwrite = Symbol('_onwrite');
const _open = Symbol('_open');
const _path = Symbol('_path');
const _pos = Symbol('_pos');
const _queue = Symbol('_queue');
const _read = Symbol('_read');
const _readSize = Symbol('_readSize');
const _reading = Symbol('_reading');
const _remain = Symbol('_remain');
const _size = Symbol('_size');
const _write = Symbol('_write');
const _writing = Symbol('_writing');
const _defaultFlag = Symbol('_defaultFlag');
const _errored = Symbol('_errored');
class ReadStream extends minipass_1.Minipass {
[_errored] = false;
[_fd];
[_path];
[_readSize];
[_reading] = false;
[_size];
[_remain];
[_autoClose];
constructor(path, opt) {
opt = opt || {};
super(opt);
this.readable = true;
this.writable = false;
if (typeof path !== 'string') {
throw new TypeError('path must be a string');
}
this[_errored] = false;
this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined;
this[_path] = path;
this[_readSize] = opt.readSize || 16 * 1024 * 1024;
this[_reading] = false;
this[_size] = typeof opt.size === 'number' ? opt.size : Infinity;
this[_remain] = this[_size];
this[_autoClose] =
typeof opt.autoClose === 'boolean' ? opt.autoClose : true;
if (typeof this[_fd] === 'number') {
this[_read]();
}
else {
this[_open]();
}
}
get fd() {
return this[_fd];
}
get path() {
return this[_path];
}
//@ts-ignore
write() {
throw new TypeError('this is a readable stream');
}
//@ts-ignore
end() {
throw new TypeError('this is a readable stream');
}
[_open]() {
fs_1.default.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd));
}
[_onopen](er, fd) {
if (er) {
this[_onerror](er);
}
else {
this[_fd] = fd;
this.emit('open', fd);
this[_read]();
}
}
[_makeBuf]() {
return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]));
}
[_read]() {
if (!this[_reading]) {
this[_reading] = true;
const buf = this[_makeBuf]();
/* c8 ignore start */
if (buf.length === 0) {
return process.nextTick(() => this[_onread](null, 0, buf));
}
/* c8 ignore stop */
fs_1.default.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => this[_onread](er, br, b));
}
}
[_onread](er, br, buf) {
this[_reading] = false;
if (er) {
this[_onerror](er);
}
else if (this[_handleChunk](br, buf)) {
this[_read]();
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs_1.default.close(fd, er => er ? this.emit('error', er) : this.emit('close'));
}
}
[_onerror](er) {
this[_reading] = true;
this[_close]();
this.emit('error', er);
}
[_handleChunk](br, buf) {
let ret = false;
// no effect if infinite
this[_remain] -= br;
if (br > 0) {
ret = super.write(br < buf.length ? buf.subarray(0, br) : buf);
}
if (br === 0 || this[_remain] <= 0) {
ret = false;
this[_close]();
super.end();
}
return ret;
}
emit(ev, ...args) {
switch (ev) {
case 'prefinish':
case 'finish':
return false;
case 'drain':
if (typeof this[_fd] === 'number') {
this[_read]();
}
return false;
case 'error':
if (this[_errored]) {
return false;
}
this[_errored] = true;
return super.emit(ev, ...args);
default:
return super.emit(ev, ...args);
}
}
}
exports.ReadStream = ReadStream;
class ReadStreamSync extends ReadStream {
[_open]() {
let threw = true;
try {
this[_onopen](null, fs_1.default.openSync(this[_path], 'r'));
threw = false;
}
finally {
if (threw) {
this[_close]();
}
}
}
[_read]() {
let threw = true;
try {
if (!this[_reading]) {
this[_reading] = true;
do {
const buf = this[_makeBuf]();
/* c8 ignore start */
const br = buf.length === 0
? 0
: fs_1.default.readSync(this[_fd], buf, 0, buf.length, null);
/* c8 ignore stop */
if (!this[_handleChunk](br, buf)) {
break;
}
} while (true);
this[_reading] = false;
}
threw = false;
}
finally {
if (threw) {
this[_close]();
}
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs_1.default.closeSync(fd);
this.emit('close');
}
}
}
exports.ReadStreamSync = ReadStreamSync;
class WriteStream extends events_1.default {
readable = false;
writable = true;
[_errored] = false;
[_writing] = false;
[_ended] = false;
[_queue] = [];
[_needDrain] = false;
[_path];
[_mode];
[_autoClose];
[_fd];
[_defaultFlag];
[_flags];
[_finished] = false;
[_pos];
constructor(path, opt) {
opt = opt || {};
super(opt);
this[_path] = path;
this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined;
this[_mode] = opt.mode === undefined ? 0o666 : opt.mode;
this[_pos] = typeof opt.start === 'number' ? opt.start : undefined;
this[_autoClose] =
typeof opt.autoClose === 'boolean' ? opt.autoClose : true;
// truncating makes no sense when writing into the middle
const defaultFlag = this[_pos] !== undefined ? 'r+' : 'w';
this[_defaultFlag] = opt.flags === undefined;
this[_flags] = opt.flags === undefined ? defaultFlag : opt.flags;
if (this[_fd] === undefined) {
this[_open]();
}
}
emit(ev, ...args) {
if (ev === 'error') {
if (this[_errored]) {
return false;
}
this[_errored] = true;
}
return super.emit(ev, ...args);
}
get fd() {
return this[_fd];
}
get path() {
return this[_path];
}
[_onerror](er) {
this[_close]();
this[_writing] = true;
this.emit('error', er);
}
[_open]() {
fs_1.default.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd));
}
[_onopen](er, fd) {
if (this[_defaultFlag] &&
this[_flags] === 'r+' &&
er &&
er.code === 'ENOENT') {
this[_flags] = 'w';
this[_open]();
}
else if (er) {
this[_onerror](er);
}
else {
this[_fd] = fd;
this.emit('open', fd);
if (!this[_writing]) {
this[_flush]();
}
}
}
end(buf, enc) {
if (buf) {
//@ts-ignore
this.write(buf, enc);
}
this[_ended] = true;
// synthetic after-write logic, where drain/finish live
if (!this[_writing] &&
!this[_queue].length &&
typeof this[_fd] === 'number') {
this[_onwrite](null, 0);
}
return this;
}
write(buf, enc) {
if (typeof buf === 'string') {
buf = Buffer.from(buf, enc);
}
if (this[_ended]) {
this.emit('error', new Error('write() after end()'));
return false;
}
if (this[_fd] === undefined || this[_writing] || this[_queue].length) {
this[_queue].push(buf);
this[_needDrain] = true;
return false;
}
this[_writing] = true;
this[_write](buf);
return true;
}
[_write](buf) {
fs_1.default.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw));
}
[_onwrite](er, bw) {
if (er) {
this[_onerror](er);
}
else {
if (this[_pos] !== undefined && typeof bw === 'number') {
this[_pos] += bw;
}
if (this[_queue].length) {
this[_flush]();
}
else {
this[_writing] = false;
if (this[_ended] && !this[_finished]) {
this[_finished] = true;
this[_close]();
this.emit('finish');
}
else if (this[_needDrain]) {
this[_needDrain] = false;
this.emit('drain');
}
}
}
}
[_flush]() {
if (this[_queue].length === 0) {
if (this[_ended]) {
this[_onwrite](null, 0);
}
}
else if (this[_queue].length === 1) {
this[_write](this[_queue].pop());
}
else {
const iovec = this[_queue];
this[_queue] = [];
writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw));
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs_1.default.close(fd, er => er ? this.emit('error', er) : this.emit('close'));
}
}
}
exports.WriteStream = WriteStream;
class WriteStreamSync extends WriteStream {
[_open]() {
let fd;
// only wrap in a try{} block if we know we'll retry, to avoid
// the rethrow obscuring the error's source frame in most cases.
if (this[_defaultFlag] && this[_flags] === 'r+') {
try {
fd = fs_1.default.openSync(this[_path], this[_flags], this[_mode]);
}
catch (er) {
if (er?.code === 'ENOENT') {
this[_flags] = 'w';
return this[_open]();
}
else {
throw er;
}
}
}
else {
fd = fs_1.default.openSync(this[_path], this[_flags], this[_mode]);
}
this[_onopen](null, fd);
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs_1.default.closeSync(fd);
this.emit('close');
}
}
[_write](buf) {
// throw the original, but try to close if it fails
let threw = true;
try {
this[_onwrite](null, fs_1.default.writeSync(this[_fd], buf, 0, buf.length, this[_pos]));
threw = false;
}
finally {
if (threw) {
try {
this[_close]();
}
catch {
// ok error
}
}
}
}
}
exports.WriteStreamSync = WriteStreamSync;
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
+118
View File
@@ -0,0 +1,118 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import EE from 'events';
import { Minipass } from 'minipass';
declare const _autoClose: unique symbol;
declare const _close: unique symbol;
declare const _ended: unique symbol;
declare const _fd: unique symbol;
declare const _finished: unique symbol;
declare const _flags: unique symbol;
declare const _flush: unique symbol;
declare const _handleChunk: unique symbol;
declare const _makeBuf: unique symbol;
declare const _mode: unique symbol;
declare const _needDrain: unique symbol;
declare const _onerror: unique symbol;
declare const _onopen: unique symbol;
declare const _onread: unique symbol;
declare const _onwrite: unique symbol;
declare const _open: unique symbol;
declare const _path: unique symbol;
declare const _pos: unique symbol;
declare const _queue: unique symbol;
declare const _read: unique symbol;
declare const _readSize: unique symbol;
declare const _reading: unique symbol;
declare const _remain: unique symbol;
declare const _size: unique symbol;
declare const _write: unique symbol;
declare const _writing: unique symbol;
declare const _defaultFlag: unique symbol;
declare const _errored: unique symbol;
export type ReadStreamOptions = Minipass.Options<Minipass.ContiguousData> & {
fd?: number;
readSize?: number;
size?: number;
autoClose?: boolean;
};
export type ReadStreamEvents = Minipass.Events<Minipass.ContiguousData> & {
open: [fd: number];
};
export declare class ReadStream extends Minipass<Minipass.ContiguousData, Buffer, ReadStreamEvents> {
[_errored]: boolean;
[_fd]?: number;
[_path]: string;
[_readSize]: number;
[_reading]: boolean;
[_size]: number;
[_remain]: number;
[_autoClose]: boolean;
constructor(path: string, opt: ReadStreamOptions);
get fd(): number | undefined;
get path(): string;
write(): void;
end(): void;
[_open](): void;
[_onopen](er?: NodeJS.ErrnoException | null, fd?: number): void;
[_makeBuf](): Buffer;
[_read](): void;
[_onread](er?: NodeJS.ErrnoException | null, br?: number, buf?: Buffer): void;
[_close](): void;
[_onerror](er: NodeJS.ErrnoException): void;
[_handleChunk](br: number, buf: Buffer): boolean;
emit<Event extends keyof ReadStreamEvents>(ev: Event, ...args: ReadStreamEvents[Event]): boolean;
}
export declare class ReadStreamSync extends ReadStream {
[_open](): void;
[_read](): void;
[_close](): void;
}
export type WriteStreamOptions = {
fd?: number;
autoClose?: boolean;
mode?: number;
captureRejections?: boolean;
start?: number;
flags?: string;
};
export declare class WriteStream extends EE {
readable: false;
writable: boolean;
[_errored]: boolean;
[_writing]: boolean;
[_ended]: boolean;
[_queue]: Buffer[];
[_needDrain]: boolean;
[_path]: string;
[_mode]: number;
[_autoClose]: boolean;
[_fd]?: number;
[_defaultFlag]: boolean;
[_flags]: string;
[_finished]: boolean;
[_pos]?: number;
constructor(path: string, opt: WriteStreamOptions);
emit(ev: string, ...args: any[]): boolean;
get fd(): number | undefined;
get path(): string;
[_onerror](er: NodeJS.ErrnoException): void;
[_open](): void;
[_onopen](er?: null | NodeJS.ErrnoException, fd?: number): void;
end(buf: string, enc?: BufferEncoding): this;
end(buf?: Buffer, enc?: undefined): this;
write(buf: string, enc?: BufferEncoding): boolean;
write(buf: Buffer, enc?: undefined): boolean;
[_write](buf: Buffer): void;
[_onwrite](er?: null | NodeJS.ErrnoException, bw?: number): void;
[_flush](): void;
[_close](): void;
}
export declare class WriteStreamSync extends WriteStream {
[_open](): void;
[_close](): void;
[_write](buf: Buffer): void;
}
export {};
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,OAAO,EAAE,MAAM,QAAQ,CAAA;AAEvB,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAA;AAInC,QAAA,MAAM,UAAU,eAAuB,CAAA;AACvC,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,GAAG,eAAgB,CAAA;AACzB,QAAA,MAAM,SAAS,eAAsB,CAAA;AACrC,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,MAAM,eAAmB,CAAA;AAC/B,QAAA,MAAM,YAAY,eAAyB,CAAA;AAC3C,QAAA,MAAM,QAAQ,eAAqB,CAAA;AACnC,QAAA,MAAM,KAAK,eAAkB,CAAA;AAC7B,QAAA,MA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E,MAAM,EAAE,GAAG,CAAC,EAAE,cAAc,GAAG,IAAI;IAC5C,GAAG,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,SAAS,GAAG,IAAI;IAoBxC,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,cAAc,GAAG,OAAO;IACjD,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,SAAS,GAAG,OAAO;IAsB5C,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,MAAM;IAWpB,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC,cAAc,EAAE,EAAE,CAAC,EAAE,MAAM;IAwBzD,CAAC,MAAM,CAAC;IAgBR,CAAC,MAAM,CAAC;CAST;AAED,qBAAa,eAAgB,SAAQ,WAAW;IAC9C,CAAC,KAAK,CAAC,IAAI,IAAI;IAsBf,CAAC,MAAM,CAAC;IASR,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,MAAM;CAmBrB"}
+420
View File
@@ -0,0 +1,420 @@
import EE from 'events';
import fs from 'fs';
import { Minipass } from 'minipass';
const writev = fs.writev;
const _autoClose = Symbol('_autoClose');
const _close = Symbol('_close');
const _ended = Symbol('_ended');
const _fd = Symbol('_fd');
const _finished = Symbol('_finished');
const _flags = Symbol('_flags');
const _flush = Symbol('_flush');
const _handleChunk = Symbol('_handleChunk');
const _makeBuf = Symbol('_makeBuf');
const _mode = Symbol('_mode');
const _needDrain = Symbol('_needDrain');
const _onerror = Symbol('_onerror');
const _onopen = Symbol('_onopen');
const _onread = Symbol('_onread');
const _onwrite = Symbol('_onwrite');
const _open = Symbol('_open');
const _path = Symbol('_path');
const _pos = Symbol('_pos');
const _queue = Symbol('_queue');
const _read = Symbol('_read');
const _readSize = Symbol('_readSize');
const _reading = Symbol('_reading');
const _remain = Symbol('_remain');
const _size = Symbol('_size');
const _write = Symbol('_write');
const _writing = Symbol('_writing');
const _defaultFlag = Symbol('_defaultFlag');
const _errored = Symbol('_errored');
export class ReadStream extends Minipass {
[_errored] = false;
[_fd];
[_path];
[_readSize];
[_reading] = false;
[_size];
[_remain];
[_autoClose];
constructor(path, opt) {
opt = opt || {};
super(opt);
this.readable = true;
this.writable = false;
if (typeof path !== 'string') {
throw new TypeError('path must be a string');
}
this[_errored] = false;
this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined;
this[_path] = path;
this[_readSize] = opt.readSize || 16 * 1024 * 1024;
this[_reading] = false;
this[_size] = typeof opt.size === 'number' ? opt.size : Infinity;
this[_remain] = this[_size];
this[_autoClose] =
typeof opt.autoClose === 'boolean' ? opt.autoClose : true;
if (typeof this[_fd] === 'number') {
this[_read]();
}
else {
this[_open]();
}
}
get fd() {
return this[_fd];
}
get path() {
return this[_path];
}
//@ts-ignore
write() {
throw new TypeError('this is a readable stream');
}
//@ts-ignore
end() {
throw new TypeError('this is a readable stream');
}
[_open]() {
fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd));
}
[_onopen](er, fd) {
if (er) {
this[_onerror](er);
}
else {
this[_fd] = fd;
this.emit('open', fd);
this[_read]();
}
}
[_makeBuf]() {
return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]));
}
[_read]() {
if (!this[_reading]) {
this[_reading] = true;
const buf = this[_makeBuf]();
/* c8 ignore start */
if (buf.length === 0) {
return process.nextTick(() => this[_onread](null, 0, buf));
}
/* c8 ignore stop */
fs.read(this[_fd], buf, 0, buf.length, null, (er, br, b) => this[_onread](er, br, b));
}
}
[_onread](er, br, buf) {
this[_reading] = false;
if (er) {
this[_onerror](er);
}
else if (this[_handleChunk](br, buf)) {
this[_read]();
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'));
}
}
[_onerror](er) {
this[_reading] = true;
this[_close]();
this.emit('error', er);
}
[_handleChunk](br, buf) {
let ret = false;
// no effect if infinite
this[_remain] -= br;
if (br > 0) {
ret = super.write(br < buf.length ? buf.subarray(0, br) : buf);
}
if (br === 0 || this[_remain] <= 0) {
ret = false;
this[_close]();
super.end();
}
return ret;
}
emit(ev, ...args) {
switch (ev) {
case 'prefinish':
case 'finish':
return false;
case 'drain':
if (typeof this[_fd] === 'number') {
this[_read]();
}
return false;
case 'error':
if (this[_errored]) {
return false;
}
this[_errored] = true;
return super.emit(ev, ...args);
default:
return super.emit(ev, ...args);
}
}
}
export class ReadStreamSync extends ReadStream {
[_open]() {
let threw = true;
try {
this[_onopen](null, fs.openSync(this[_path], 'r'));
threw = false;
}
finally {
if (threw) {
this[_close]();
}
}
}
[_read]() {
let threw = true;
try {
if (!this[_reading]) {
this[_reading] = true;
do {
const buf = this[_makeBuf]();
/* c8 ignore start */
const br = buf.length === 0
? 0
: fs.readSync(this[_fd], buf, 0, buf.length, null);
/* c8 ignore stop */
if (!this[_handleChunk](br, buf)) {
break;
}
} while (true);
this[_reading] = false;
}
threw = false;
}
finally {
if (threw) {
this[_close]();
}
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs.closeSync(fd);
this.emit('close');
}
}
}
export class WriteStream extends EE {
readable = false;
writable = true;
[_errored] = false;
[_writing] = false;
[_ended] = false;
[_queue] = [];
[_needDrain] = false;
[_path];
[_mode];
[_autoClose];
[_fd];
[_defaultFlag];
[_flags];
[_finished] = false;
[_pos];
constructor(path, opt) {
opt = opt || {};
super(opt);
this[_path] = path;
this[_fd] = typeof opt.fd === 'number' ? opt.fd : undefined;
this[_mode] = opt.mode === undefined ? 0o666 : opt.mode;
this[_pos] = typeof opt.start === 'number' ? opt.start : undefined;
this[_autoClose] =
typeof opt.autoClose === 'boolean' ? opt.autoClose : true;
// truncating makes no sense when writing into the middle
const defaultFlag = this[_pos] !== undefined ? 'r+' : 'w';
this[_defaultFlag] = opt.flags === undefined;
this[_flags] = opt.flags === undefined ? defaultFlag : opt.flags;
if (this[_fd] === undefined) {
this[_open]();
}
}
emit(ev, ...args) {
if (ev === 'error') {
if (this[_errored]) {
return false;
}
this[_errored] = true;
}
return super.emit(ev, ...args);
}
get fd() {
return this[_fd];
}
get path() {
return this[_path];
}
[_onerror](er) {
this[_close]();
this[_writing] = true;
this.emit('error', er);
}
[_open]() {
fs.open(this[_path], this[_flags], this[_mode], (er, fd) => this[_onopen](er, fd));
}
[_onopen](er, fd) {
if (this[_defaultFlag] &&
this[_flags] === 'r+' &&
er &&
er.code === 'ENOENT') {
this[_flags] = 'w';
this[_open]();
}
else if (er) {
this[_onerror](er);
}
else {
this[_fd] = fd;
this.emit('open', fd);
if (!this[_writing]) {
this[_flush]();
}
}
}
end(buf, enc) {
if (buf) {
//@ts-ignore
this.write(buf, enc);
}
this[_ended] = true;
// synthetic after-write logic, where drain/finish live
if (!this[_writing] &&
!this[_queue].length &&
typeof this[_fd] === 'number') {
this[_onwrite](null, 0);
}
return this;
}
write(buf, enc) {
if (typeof buf === 'string') {
buf = Buffer.from(buf, enc);
}
if (this[_ended]) {
this.emit('error', new Error('write() after end()'));
return false;
}
if (this[_fd] === undefined || this[_writing] || this[_queue].length) {
this[_queue].push(buf);
this[_needDrain] = true;
return false;
}
this[_writing] = true;
this[_write](buf);
return true;
}
[_write](buf) {
fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) => this[_onwrite](er, bw));
}
[_onwrite](er, bw) {
if (er) {
this[_onerror](er);
}
else {
if (this[_pos] !== undefined && typeof bw === 'number') {
this[_pos] += bw;
}
if (this[_queue].length) {
this[_flush]();
}
else {
this[_writing] = false;
if (this[_ended] && !this[_finished]) {
this[_finished] = true;
this[_close]();
this.emit('finish');
}
else if (this[_needDrain]) {
this[_needDrain] = false;
this.emit('drain');
}
}
}
}
[_flush]() {
if (this[_queue].length === 0) {
if (this[_ended]) {
this[_onwrite](null, 0);
}
}
else if (this[_queue].length === 1) {
this[_write](this[_queue].pop());
}
else {
const iovec = this[_queue];
this[_queue] = [];
writev(this[_fd], iovec, this[_pos], (er, bw) => this[_onwrite](er, bw));
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'));
}
}
}
export class WriteStreamSync extends WriteStream {
[_open]() {
let fd;
// only wrap in a try{} block if we know we'll retry, to avoid
// the rethrow obscuring the error's source frame in most cases.
if (this[_defaultFlag] && this[_flags] === 'r+') {
try {
fd = fs.openSync(this[_path], this[_flags], this[_mode]);
}
catch (er) {
if (er?.code === 'ENOENT') {
this[_flags] = 'w';
return this[_open]();
}
else {
throw er;
}
}
}
else {
fd = fs.openSync(this[_path], this[_flags], this[_mode]);
}
this[_onopen](null, fd);
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] === 'number') {
const fd = this[_fd];
this[_fd] = undefined;
fs.closeSync(fd);
this.emit('close');
}
}
[_write](buf) {
// throw the original, but try to close if it fails
let threw = true;
try {
this[_onwrite](null, fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos]));
threw = false;
}
finally {
if (threw) {
try {
this[_close]();
}
catch {
// ok error
}
}
}
}
}
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
+72
View File
@@ -0,0 +1,72 @@
{
"name": "@isaacs/fs-minipass",
"version": "4.0.1",
"main": "./dist/commonjs/index.js",
"scripts": {
"prepare": "tshy",
"pretest": "npm run prepare",
"test": "tap",
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"format": "prettier --write . --loglevel warn",
"typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts"
},
"keywords": [],
"author": "Isaac Z. Schlueter",
"license": "ISC",
"repository": {
"type": "git",
"url": "https://github.com/npm/fs-minipass.git"
},
"description": "fs read and write streams based on minipass",
"dependencies": {
"minipass": "^7.0.4"
},
"devDependencies": {
"@types/node": "^20.11.30",
"mutate-fs": "^2.1.1",
"prettier": "^3.2.5",
"tap": "^18.7.1",
"tshy": "^1.12.0",
"typedoc": "^0.25.12"
},
"files": [
"dist"
],
"engines": {
"node": ">=18.0.0"
},
"tshy": {
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts"
}
},
"exports": {
"./package.json": "./package.json",
".": {
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
}
},
"types": "./dist/commonjs/index.d.ts",
"type": "module",
"prettier": {
"semi": false,
"printWidth": 75,
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"jsxSingleQuote": false,
"bracketSameLine": true,
"arrowParens": "avoid",
"endOfLine": "lf"
}
}
+12
View File
@@ -0,0 +1,12 @@
# Release History
## 1.1.1
- Add dependency on `debug` to log results of the file system checks
- Add `jest` tests
# 1.0.0
- First public release, a simple typescript library for checking whether a path exists
on the file system and optionally whether it points to a file or folder.
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2015 Steve King
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+1
View File
@@ -0,0 +1 @@
export * from './src';
+7
View File
@@ -0,0 +1,7 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./src"));
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;AACA,2BAAsB"}
+19
View File
@@ -0,0 +1,19 @@
/**
* Synchronous validation of a path existing either as a file or as a directory.
*
* @param {string} path The path to check
* @param {number} type One or both of the exported numeric constants
*/
export declare function exists(path: string, type?: number): boolean;
/**
* Constant representing a file
*/
export declare const FILE = 1;
/**
* Constant representing a folder
*/
export declare const FOLDER = 2;
/**
* Constant representing either a file or a folder
*/
export declare const READABLE: number;
+55
View File
@@ -0,0 +1,55 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs");
const debug_1 = __importDefault(require("debug"));
const log = debug_1.default('@kwsites/file-exists');
function check(path, isFile, isDirectory) {
log(`checking %s`, path);
try {
const stat = fs_1.statSync(path);
if (stat.isFile() && isFile) {
log(`[OK] path represents a file`);
return true;
}
if (stat.isDirectory() && isDirectory) {
log(`[OK] path represents a directory`);
return true;
}
log(`[FAIL] path represents something other than a file or directory`);
return false;
}
catch (e) {
if (e.code === 'ENOENT') {
log(`[FAIL] path is not accessible: %o`, e);
return false;
}
log(`[FATAL] %o`, e);
throw e;
}
}
/**
* Synchronous validation of a path existing either as a file or as a directory.
*
* @param {string} path The path to check
* @param {number} type One or both of the exported numeric constants
*/
function exists(path, type = exports.READABLE) {
return check(path, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0);
}
exports.exists = exists;
/**
* Constant representing a file
*/
exports.FILE = 1;
/**
* Constant representing a folder
*/
exports.FOLDER = 2;
/**
* Constant representing either a file or a folder
*/
exports.READABLE = exports.FILE + exports.FOLDER;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;AAAA,2BAA8B;AAC9B,kDAA0B;AAE1B,MAAM,GAAG,GAAG,eAAK,CAAC,sBAAsB,CAAC,CAAC;AAE1C,SAAS,KAAK,CAAC,IAAY,EAAE,MAAe,EAAE,WAAoB;IAC/D,GAAG,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;IAEzB,IAAI;QACD,MAAM,IAAI,GAAG,aAAQ,CAAC,IAAI,CAAC,CAAC;QAE5B,IAAI,IAAI,CAAC,MAAM,EAAE,IAAI,MAAM,EAAE;YAC1B,GAAG,CAAC,6BAA6B,CAAC,CAAC;YACnC,OAAO,IAAI,CAAC;SACd;QAED,IAAI,IAAI,CAAC,WAAW,EAAE,IAAI,WAAW,EAAE;YACpC,GAAG,CAAC,kCAAkC,CAAC,CAAC;YACxC,OAAO,IAAI,CAAC;SACd;QAED,GAAG,CAAC,iEAAiE,CAAC,CAAC;QACvE,OAAO,KAAK,CAAC;KACf;IAAC,OAAO,CAAC,EAAE;QACT,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE;YACtB,GAAG,CAAC,mCAAmC,EAAE,CAAC,CAAC,CAAC;YAC5C,OAAO,KAAK,CAAC;SACf;QAED,GAAG,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC;QACrB,MAAM,CAAC,CAAC;KACV;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAgB,MAAM,CAAC,IAAY,EAAE,OAAe,gBAAQ;IACzD,OAAO,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,GAAG,YAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,GAAG,cAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AAC9D,CAAC;AAFD,wBAEC;AAED;;GAEG;AACU,QAAA,IAAI,GAAG,CAAC,CAAC;AAEtB;;GAEG;AACU,QAAA,MAAM,GAAG,CAAC,CAAC;AAExB;;GAEG;AACU,QAAA,QAAQ,GAAG,YAAI,GAAG,cAAM,CAAC"}
+7
View File
@@ -0,0 +1,7 @@
export declare function statSync(...args: any[]): any;
export declare function addStatSyncMock(fn: any): void;
export declare function assertMocksUsed(): void;
declare const mockFs: {
statSync: typeof statSync;
};
export default mockFs;
+26
View File
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let statSyncMocks = [];
function statSync(...args) {
const mock = statSyncMocks.shift();
if (typeof mock !== 'function') {
throw new Error(`fs.statSync called without configuring a mock`);
}
return mock(...args);
}
exports.statSync = statSync;
function addStatSyncMock(fn) {
statSyncMocks.push(fn);
}
exports.addStatSyncMock = addStatSyncMock;
function assertMocksUsed() {
if (statSyncMocks.length) {
throw new Error(`fs.afterEach: statSync has ${statSyncMocks.length} unused mocks`);
}
}
exports.assertMocksUsed = assertMocksUsed;
const mockFs = {
statSync,
};
exports.default = mockFs;
//# sourceMappingURL=fs.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"fs.js","sourceRoot":"","sources":["../../../test/__mocks__/fs.ts"],"names":[],"mappings":";;AACA,IAAI,aAAa,GAAU,EAAE,CAAC;AAE9B,SAAgB,QAAQ,CAAC,GAAG,IAAW;IACpC,MAAO,IAAI,GAAG,aAAa,CAAC,KAAK,EAAE,CAAC;IACpC,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;QAC7B,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;KACnE;IAED,OAAO,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AACxB,CAAC;AAPD,4BAOC;AAED,SAAgB,eAAe,CAAC,EAAO;IACpC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC1B,CAAC;AAFD,0CAEC;AAED,SAAgB,eAAe;IAC5B,IAAI,aAAa,CAAC,MAAM,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,8BAA8B,aAAa,CAAC,MAAM,eAAe,CAAC,CAAC;KACrF;AACJ,CAAC;AAJD,0CAIC;AAED,MAAM,MAAM,GAAG;IACZ,QAAQ;CACV,CAAA;AAED,kBAAe,MAAM,CAAC"}
+1
View File
@@ -0,0 +1 @@
export {};
+77
View File
@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
jest.mock('fs');
//@ts-ignore
const fs_1 = require("fs");
const src_1 = require("../src");
describe(`exists`, () => {
let statSync;
let statSyncMock;
let path;
beforeEach(() => {
path = `./path/${Math.random()}`;
fs_1.addStatSyncMock(statSyncMock = jest.fn(() => statSync()));
});
afterEach(() => {
fs_1.assertMocksUsed();
statSync = statSyncMock = undefined;
});
describe('known errors', () => {
beforeEach(() => givenStatSyncThrows({ code: 'ENOENT' }));
it('with type', () => {
expect(src_1.exists(path, src_1.READABLE)).toBe(false);
});
it('with type omitted', () => {
expect(src_1.exists(path)).toBe(false);
});
});
describe('unknown errors', () => {
let err;
beforeEach(() => err = givenStatSyncThrows(new Error('something')));
it('with type', () => {
expect(() => src_1.exists(path, src_1.READABLE)).toThrow(err);
});
it('with type omitted', () => {
expect(() => src_1.exists(path)).toThrow(err);
});
});
describe('path is a file', () => {
beforeEach(() => givenStatSyncIsA('file'));
existsReturns(true, false, true);
});
describe('path is a folder', () => {
beforeEach(() => givenStatSyncIsA('folder'));
existsReturns(false, true, true);
});
describe('path is unknown', () => {
beforeEach(() => givenStatSyncIsA('unknown'));
existsReturns(false, false, false);
});
function existsReturns(file, folder, readable) {
it('when searching for a file', () => {
expect(src_1.exists(path, src_1.FILE)).toBe(file);
});
it('when searching for a folder', () => {
expect(src_1.exists(path, src_1.FOLDER)).toBe(folder);
});
it('when searching for either', () => {
expect(src_1.exists(path, src_1.READABLE)).toBe(readable);
});
it('when searching without a type', () => {
expect(src_1.exists(path)).toBe(readable);
});
}
function givenStatSyncThrows(err) {
statSync = () => { throw err; };
return err;
}
function givenStatSyncIsA(type) {
const mockStat = {
isFile() { return type === 'file'; },
isDirectory() { return type === 'folder'; },
};
statSync = () => mockStat;
return mockStat;
}
});
//# sourceMappingURL=exists.spec.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"exists.spec.js","sourceRoot":"","sources":["../../test/exists.spec.ts"],"names":[],"mappings":";;AACA,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEhB,YAAY;AACZ,2BAAsD;AACtD,gCAAwD;AAExD,QAAQ,CAAC,QAAQ,EAAE,GAAG,EAAE;IAErB,IAAI,QAAa,CAAC;IAClB,IAAI,YAAiB,CAAC;IACtB,IAAI,IAAY,CAAC;IAEjB,UAAU,CAAC,GAAG,EAAE;QACb,IAAI,GAAG,UAAU,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;QACjC,oBAAe,CAAC,YAAY,GAAG,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;IAEH,SAAS,CAAC,GAAG,EAAE;QACZ,oBAAe,EAAE,CAAC;QAClB,QAAQ,GAAG,YAAY,GAAG,SAAS,CAAC;IACvC,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,cAAc,EAAE,GAAG,EAAE;QAC3B,UAAU,CAAC,GAAG,EAAE,CAAC,mBAAmB,CAAC,EAAC,IAAI,EAAE,QAAQ,EAAC,CAAC,CAAC,CAAC;QAExD,EAAE,CAAC,WAAW,EAAE,GAAG,EAAE;YAClB,MAAM,CAAC,YAAM,CAAC,IAAI,EAAE,cAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;QAEH,EAAE,CAAC,mBAAmB,EAAE,GAAG,EAAE;YAC1B,MAAM,CAAC,YAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,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
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"license": "MIT",
"repository": "git@github.com:kwsites/file-exists.git",
"author": "Steve King <steve@mydev.co>",
"contributors": [
{
"name": "Steve King",
"email": "steve@mydev.co"
}
],
"files": [
"dist/**/*.*"
],
"scripts": {
"clean": "rimraf ./dist",
"build": "yarn run clean && tsc",
"preversion": "yarn run clean && yarn run build && yarn test",
"postversion": "npm publish --access=public && git push && git push --tags",
"test": "jest --coverage",
"tsc": "tsc"
},
"devDependencies": {
"@babel/core": "^7.10.1",
"@babel/preset-env": "^7.10.1",
"@babel/preset-typescript": "^7.10.1",
"@types/debug": "^4.1.5",
"@types/jest": "^26.0.0",
"@types/node": "^10.12.0",
"babel-jest": "^26.0.1",
"jest": "^25.3.0",
"rimraf": "^2.6.2",
"ts-node": "^8.10.2",
"typescript": "^3.1.3"
},
"dependencies": {
"debug": "^4.1.1"
}
}
+41
View File
@@ -0,0 +1,41 @@
# @kwsites/file-exists
Synchronous validation of a path existing either as a file or as a directory.
```
const { exists, FILE, FOLDER, READABLE } = require('@kwsites/file-exists');
// check for a folder existing
assert(exists(__dirname, FOLDER));
assert(!exists(__filename, FOLDER));
// check for a file existing
assert(!exists(__filename, FILE));
assert(exists(__filename, FILE));
// when no type is specified, both folders and files are allowed
assert(exists(__dirname));
assert(exists(__filename));
// alternatively specify both files and folders
assert(exists(__dirname, FILE + FOLDER));
// or just that the path is readable (can be either a file or folder)
assert(exists(__filename, READABLE));
```
## Troubleshooting
This library uses [debug](https://www.npmjs.com/package/debug) to handle logging,
to enable logging, use either the environment variable:
```
"DEBUG=@kwsites/file-exists" node ./your-app.js
```
Or explicitly enable logging using the `debug` library itself:
```javascript
require('debug').enable('@kwsites/file-exists');
```
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 kwsites
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+49
View File
@@ -0,0 +1,49 @@
/**
* The `DeferredPromise` has a `promise` property in an initially pending state,
* that will be resolved when the `done` method is called or rejected when the
* `fail` method is called.
*/
export interface DeferredPromise<RESOLVES, REJECTS extends Error = Error> {
done(result: RESOLVES): void;
fail(error: REJECTS): void;
readonly status: DeferredPromiseStatus;
readonly fulfilled: boolean;
promise: Promise<RESOLVES>;
}
/**
* The three states the DeferredPromise can be in - initially pending then either
* resolved or rejected when it is fulfilled.
*
* ```typescript
import {createDeferred, DeferredPromiseStatus} from '@kwsites/promise-deferred`;
const pending: DeferredPromiseStatus = 'pending';
expect(createDeferred()).toHaveProperty('status', pending);
```
*/
export declare type DeferredPromiseStatus = 'pending' | 'resolved' | 'rejected';
/**
* Creates a new `DeferredPromise`
*
* ```typescript
import {deferred} from '@kwsites/promise-deferred`;
```
*/
export declare function deferred<T extends any = void, E extends Error = Error>(): DeferredPromise<T, E>;
/**
* Alias of the exported `deferred` function, to help consumers wanting to use `deferred` as the
* local variable name rather than the factory import name, without needing to rename on import.
*
* ```typescript
import {createDeferred} from '@kwsites/promise-deferred`;
```
*/
export declare const createDeferred: typeof deferred;
/**
* Default export allows use as:
*
* ```typescript
import deferred from '@kwsites/promise-deferred`;
```
*/
export default deferred;
+59
View File
@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDeferred = exports.deferred = void 0;
/**
* Creates a new `DeferredPromise`
*
* ```typescript
import {deferred} from '@kwsites/promise-deferred`;
```
*/
function deferred() {
let done;
let fail;
let status = 'pending';
const promise = new Promise((_done, _fail) => {
done = _done;
fail = _fail;
});
return {
promise,
done(result) {
if (status === 'pending') {
status = 'resolved';
done(result);
}
},
fail(error) {
if (status === 'pending') {
status = 'rejected';
fail(error);
}
},
get fulfilled() {
return status !== 'pending';
},
get status() {
return status;
},
};
}
exports.deferred = deferred;
/**
* Alias of the exported `deferred` function, to help consumers wanting to use `deferred` as the
* local variable name rather than the factory import name, without needing to rename on import.
*
* ```typescript
import {createDeferred} from '@kwsites/promise-deferred`;
```
*/
exports.createDeferred = deferred;
/**
* Default export allows use as:
*
* ```typescript
import deferred from '@kwsites/promise-deferred`;
```
*/
exports.default = deferred;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AA0BA;;;;;;GAMG;AACH,SAAgB,QAAQ;IACrB,IAAI,IAAyB,CAAC;IAC9B,IAAI,IAAwB,CAAC;IAC7B,IAAI,MAAM,GAA0B,SAAS,CAAC;IAE9C,MAAM,OAAO,GAAe,IAAI,OAAO,CAAI,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QACzD,IAAI,GAAG,KAAK,CAAC;QACb,IAAI,GAAG,KAAK,CAAC;IAChB,CAAC,CAAC,CAAC;IAEH,OAAO;QACJ,OAAO;QACP,IAAI,CAAE,MAAM;YACT,IAAI,MAAM,KAAK,SAAS,EAAE;gBACvB,MAAM,GAAG,UAAU,CAAC;gBACpB,IAAI,CAAC,MAAM,CAAC,CAAC;aACf;QACJ,CAAC;QACD,IAAI,CAAE,KAAK;YACR,IAAI,MAAM,KAAK,SAAS,EAAE;gBACvB,MAAM,GAAG,UAAU,CAAC;gBACpB,IAAI,CAAC,KAAK,CAAC,CAAC;aACd;QACJ,CAAC;QACD,IAAI,SAAS;YACV,OAAO,MAAM,KAAK,SAAS,CAAC;QAC/B,CAAC;QACD,IAAI,MAAM;YACP,OAAO,MAAM,CAAC;QACjB,CAAC;KACH,CAAC;AACL,CAAC;AA/BD,4BA+BC;AAED;;;;;;;GAOG;AACU,QAAA,cAAc,GAAG,QAAQ,CAAC;AAEvC;;;;;;GAMG;AACH,kBAAe,QAAQ,CAAC"}
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@kwsites/promise-deferred",
"description": "Minimalist creation of promise wrappers, exposing the ability to resolve or reject the inner promise",
"version": "1.1.1",
"private": false,
"author": "Steve King <steve@mydev.co>",
"contributors": [
{
"name": "Steve King",
"email": "steve@mydev.co"
}
],
"main": "./dist/index",
"types": "./dist/index",
"license": "MIT",
"repository": "git://github.com/kwsites/promise-deferred.git",
"devDependencies": {
"@babel/core": "^7.10.3",
"@babel/preset-env": "^7.10.3",
"@babel/preset-typescript": "^7.10.1",
"@types/jest": "^26.0.0",
"@types/node": "^14.0.13",
"babel-jest": "^26.1.0",
"babel-preset-env": "^1.7.0",
"jest": "^26.1.0",
"ts-node": "^8.10.2",
"typescript": "^3.9.5"
},
"files": [
"LICENSE",
"dist/**/*.*"
],
"scripts": {
"clean": "git clean -fxd -e .idea -e node_modules",
"clean:modules": "git clean -fxd node_modules",
"build": "tsc --build",
"build:clean": "yarn run clean && tsc",
"preversion": "yarn run build:clean && yarn test",
"postversion": "npm publish --access=public && git push && git push --tags",
"test": "jest --coverage",
"tsc": "tsc"
}
}
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+27
View File
@@ -0,0 +1,27 @@
# `@malept/cross-spawn-promise`
> A promisified version of [`cross-spawn`](https://npm.im/cross-spawn) with slightly different behavior & extra options.
[![CI](https://github.com/malept/cross-spawn-promise/workflows/CI/badge.svg)](https://github.com/malept/cross-spawn-promise/actions?query=workflow%3ACI)
[![NPM package](https://img.shields.io/npm/v/@malept/cross-spawn-promise.svg)](https://www.npmjs.com/package/@malept/cross-spawn-promise)
[![codecov](https://codecov.io/gh/malept/cross-spawn-promise/branch/main/graph/badge.svg)](https://codecov.io/gh/malept/cross-spawn-promise)
## Different Behavior
If the spawned process exits with a non-zero code, an `ExitCodeError` is thrown with the original
command, code, `stdout`, and `stderr` as properties.
If the spawned process is terminated by a signal on non-Windows platforms, an `ExitSignalError` is
thrown with the original command, signal name, `stdout`, and `stderr` as properties.
## Extra Options
- `logger`: a `Function` such as `console.log` or `debug(name)` to log some information
about the spawned process.
- `updateErrorCallback`: a callback which mutates the error before it is re-thrown. Most commonly,
this is used to augment the error message of `ENOENT` error to provide a more human-friendly
message as to how to install the missing executable.
## Legal
This module is licensed under the Apache 2.0 license.
+61
View File
@@ -0,0 +1,61 @@
/// <reference types="node" />
import { SpawnOptions } from "child_process";
export declare type LoggerFunction = (message: string) => void;
/**
* List of string arguments.
*/
export declare type CrossSpawnArgs = ReadonlyArray<string> | undefined;
export declare type CrossSpawnOptions = SpawnOptions & {
/**
* A `Function` such as `console.log` or `debug(name)` to log some information about the
* spawned process.
*/
logger?: LoggerFunction;
/**
* A callback which mutates the error before it is rethrown. Most commonly, this is used to
* augment the error message of `ENOENT` errors to provide a more human-friendly message as to
* how to install the missing executable.
*
* @param error - The error thrown from the `spawn` function
* @param hasLogger - Whether `logger` was set
*/
updateErrorCallback?: (error: Error, hasLogger: boolean) => void;
};
/**
* Wrapper error for when the spawn function itself emits an error.
*/
export declare class CrossSpawnError extends Error {
originalError: Error;
constructor(cmd: string, args: CrossSpawnArgs, originalError: Error, stderr: string);
}
/**
* Base error class for when a process does not exit with a status code of zero.
*/
export declare abstract class ExitError extends Error {
cmd: string;
args: CrossSpawnArgs;
stdout: string;
stderr: string;
constructor(cmd: string, args: CrossSpawnArgs, message: string, stdout: string, stderr: string);
}
/**
* The error thrown when a process emits a non-zero exit code.
*/
export declare class ExitCodeError extends ExitError {
code: number;
constructor(cmd: string, args: CrossSpawnArgs, code: number, stdout: string, stderr: string);
}
/**
* The error thrown when a process exits via a signal.
*/
export declare class ExitSignalError extends ExitError {
signal: string;
constructor(cmd: string, args: CrossSpawnArgs, signal: string, stdout: string, stderr: string);
}
/**
* A wrapper around `cross-spawn`'s `spawn` function which can optionally log the command executed
* and/or change the error object via a callback.
*
* @param cmd - The command to run
*/
export declare function spawn(cmd: string, args?: CrossSpawnArgs, options?: CrossSpawnOptions): Promise<string>;
+113
View File
@@ -0,0 +1,113 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.spawn = exports.ExitSignalError = exports.ExitCodeError = exports.ExitError = exports.CrossSpawnError = void 0;
const cross_spawn_1 = __importDefault(require("cross-spawn"));
function stringifyCommand(cmd, args) {
if (args && Array.isArray(args) && args.length > 0) {
return `${cmd} ${args.join(" ")}`;
}
else {
return cmd;
}
}
/**
* Wrapper error for when the spawn function itself emits an error.
*/
class CrossSpawnError extends Error {
constructor(cmd, args, originalError, stderr) {
const fullCommand = stringifyCommand(cmd, args);
const errorMessage = originalError.message || originalError;
super(`Error executing command (${fullCommand}):\n${errorMessage}\n${stderr}`.trim());
this.originalError = originalError;
}
}
exports.CrossSpawnError = CrossSpawnError;
/**
* Base error class for when a process does not exit with a status code of zero.
*/
class ExitError extends Error {
constructor(cmd, args, message, stdout, stderr) {
super(message);
this.cmd = cmd;
this.args = args;
this.stdout = stdout;
this.stderr = stderr;
}
}
exports.ExitError = ExitError;
/**
* The error thrown when a process emits a non-zero exit code.
*/
class ExitCodeError extends ExitError {
constructor(cmd, args, code, stdout, stderr) {
const fullCommand = stringifyCommand(cmd, args);
super(cmd, args, `Command failed with a non-zero return code (${code}):\n${fullCommand}\n${stdout}\n${stderr}`.trim(), stdout, stderr);
this.code = code;
}
}
exports.ExitCodeError = ExitCodeError;
/**
* The error thrown when a process exits via a signal.
*/
class ExitSignalError extends ExitError {
constructor(cmd, args, signal, stdout, stderr) {
const fullCommand = stringifyCommand(cmd, args);
super(cmd, args, `Command terminated via a signal (${signal}):\n${fullCommand}\n${stdout}\n${stderr}`.trim(), stdout, stderr);
this.signal = signal;
}
}
exports.ExitSignalError = ExitSignalError;
/**
* A wrapper around `cross-spawn`'s `spawn` function which can optionally log the command executed
* and/or change the error object via a callback.
*
* @param cmd - The command to run
*/
async function spawn(cmd, args, options) {
if (!options) {
options = {};
}
const { logger, updateErrorCallback, ...spawnOptions } = options;
if (logger)
logger(`Executing command ${stringifyCommand(cmd, args)}`);
return new Promise((resolve, reject) => {
let stdout = "";
let stderr = "";
const process = cross_spawn_1.default(cmd, args, spawnOptions);
if (process.stdout) {
process.stdout.on("data", (data) => {
stdout += data.toString();
});
}
if (process.stderr) {
process.stderr.on("data",
/* istanbul ignore next */ (data) => {
stderr += data.toString();
});
}
process.on("close", (code, signal) => {
if (code === 0) {
resolve(stdout);
}
else if (code === null) {
// Why: assume signal is not null if code is null
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
reject(new ExitSignalError(cmd, args, signal, stdout, stderr));
}
else {
reject(new ExitCodeError(cmd, args, code, stdout, stderr));
}
});
process.on("error", (err) => {
if (updateErrorCallback) {
updateErrorCallback(err, !!logger);
}
reject(new CrossSpawnError(cmd, args, err, stderr));
});
});
}
exports.spawn = spawn;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceR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": "Promisified version of cross-spawn",
"main": "dist/src/index.js",
"repository": "https://github.com/malept/cross-spawn-promise",
"author": "Mark Lee",
"license": "Apache-2.0",
"engines": {
"node": ">= 12.13.0"
},
"scripts": {
"ava": "ava",
"build": "tsc",
"coverage": "nyc --reporter=lcov --reporter=text ava",
"docs": "typedoc src/index.ts",
"lint": "prettier --check . && eslint --ext .ts .",
"prepare": "husky install && yarn build",
"test": "yarn lint && yarn ava"
},
"files": [
"dist"
],
"dependencies": {
"cross-spawn": "^7.0.1"
},
"devDependencies": {
"@istanbuljs/nyc-config-typescript": "^1.0.1",
"@types/cross-spawn": "^6.0.1",
"@types/node": "^15.14.0",
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"ava": "^3.3.0",
"eslint": "^7.0.0",
"eslint-config-prettier": "^8.0.0",
"eslint-plugin-ava": "^12.0.0",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-prettier": "^3.1.2",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-tsdoc": "^0.2.5",
"husky": "^7.0.0",
"lint-staged": "^11.0.0",
"nyc": "^15.0.0",
"prettier": "^2.0.1",
"source-map-support": "^0.5.16",
"ts-node": "^10.0.0",
"typedoc": "^0.21.2",
"typescript": "~4.3.5"
},
"ava": {
"extensions": [
"ts"
],
"require": [
"ts-node/register"
]
},
"eslintConfig": {
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "2019",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint",
"eslint-plugin-tsdoc"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:ava/recommended",
"plugin:import/errors",
"plugin:import/warnings",
"plugin:import/typescript",
"plugin:prettier/recommended",
"plugin:promise/recommended",
"prettier"
],
"rules": {
"strict": "error",
"tsdoc/syntax": "warn"
}
},
"eslintIgnore": [
"dist"
],
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/malept"
},
{
"type": "tidelift",
"url": "https://tidelift.com/subscription/pkg/npm-.malept-cross-spawn-promise?utm_medium=referral&utm_source=npm_fund"
}
],
"lint-staged": {
"*.{json,md,yml}": "prettier --write",
"*.ts": [
"prettier --write",
"eslint --fix"
]
},
"nyc": {
"extends": "@istanbuljs/nyc-config-typescript"
}
}
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2016 Endless Mobile, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+210
View File
@@ -0,0 +1,210 @@
# @malept/flatpak-bundler [![Version](https://img.shields.io/npm/v/@malept/flatpak-bundler.svg)](https://www.npmjs.com/package/@malept/flatpak-bundler) [![Build Status](https://github.com/malept/flatpak-bundler/workflows/CI/badge.svg)](https://github.com/malept/flatpak-bundler/actions?query=workflow%3ACI)
Build [flatpaks](https://flatpak.org/) from Node.js.
# Quick Start
Install `@malept/flatpak-bundler`.
```shell
$ npm install @malept/flatpak-bundler
```
[Build a flatpak with a Node script](#hello-world).
Install and run it!
```shell
$ flatpak install --user --bundle hello.flatpak
$ flatpak run org.world.Hello
Hello, world!
```
## Overview
This modules allows building flatpaks programmatically from Node. It requires
Node 10 or above and flatpak >= 0.6.13 to be installed on your system.
Under the hood, this is just a wrapper for the [flatpak-builder](https://docs.flatpak.org/en/latest/flatpak-builder.html)
tool with some extra sugar added.
With `flatpak-builder`, you specify a runtime, sandbox permissions and software
modules to build into your application, and build a flatpak from start to finish.
This module provides a few additional features:
- Supports auto installing flatpak runtime and app dependencies
- Supports exporting directly to the a single file flatpak bundle
- Supports easy copying files and creating symlinks directly in `/app`
The latter is particularly useful for [Electron](https://electronjs.org/) and
[nw.js](http://nwjs.io/) style Node applications, which often create packages
from prebuilt binaries and do not attempt to follow an autotools-like
[build api](https://github.com/cgwalters/build-api).
This module should make it easy to plug flatpak support into an Electron or nw.js
app packaging phase.
## Usage
### translateArch(arch)
Used to translate a Node-style arch (e.g., `x64`) into a Flatpak-compatible arch (e.g., `x86_64`).
If the arch is unknown, it will pass through the input value.
### bundle(manifest, buildOptions)
Takes an [app manifest](#manifest) and a build options object. It returns a Promise.
Both the manifest and options objects support both camelCase and dash-separated
variants of any option.
The promise is returned with a `finalBuildOptions` value. It contains the build
options after default values have been applied. Useful to read out the
`workingDir`, for example.
#### Manifest
This matches the format for [`flatpak-builder` app
manifests](https://docs.flatpak.org/en/latest/manifests.html), with a few extra
options added and camelCase variants supported.
- **id**: Required. The application id.
- **runtime**: Required. The runtime for your flatpak application.
- **sdk**: Required. The sdk for your flatpak application.
- **base**: An app to inherit from. Use the app as a "base" for `/app`
contents.
- **finishArgs**: The arguments to pass to `flatpak build-finish`. Use this to
add sandbox permissions. See the [Electron app example](#electron-app) for
some common app permissions.
- **modules**: If you need to build other software modules into you flatpak app
(anything not already in your runtime or base app), you can specify them
here.
#### Build Options
- **bundlePath**: Output location for a single file version of the flatpak. If
non supplied, the single file flatpak will not be created.
- **arch**: The architecture for the flatpak bundle. x86_64, i386 or arm.
- **workingDir**: The working directory to call `flatpak-builder` from.
Defaults to a new tmp directory.
- **buildDir**: The directory to build the application in. Defaults to
`${workingDir}/build`
- **repoDir**: The directory for a flatpak repo, can be used to publish to an
existing repo. Defaults to `${workingDir}/repo`
- **cleanTmpdirs**: Cleanup any tmp directories created during the build on
process exit. Defaults to true. Set false for easier debugging.
- **autoInstallRuntime**: Install/update the runtime while building. Defaults
to true if runtimeFlatpakref is set in the manifest.
- **autoInstallSdk**: Install/update the sdk while building. Defaults
to true if sdkFlatpakref is set in the manifest.
- **autoInstallBase**: Install/update the base app while building. Defaults
to true if baseFlatpakref is set in the manifest.
- **gpgSign**: The gpg key to use to sign the flatpak repo and bundle file.
- **gpgHomedir**: The gpg homedir to use when signing.
- **subject**: The single line subject to use for the flatpak repo commit
message.
- **body**: The description to use for the flatpak repo commit message.
- **files**: Files to copy directly into the app. Should be a list of [source,
dest] tuples. Source should be a relative/absolute path to a file/directory
to copy into the flatpak, and dest should be the path inside the app install
prefix (e.g. `/share/applications/`)
- **symlinks**: Symlinks to create in the app files. Should be a list of
[target, location] symlink tuples. Target can be either a relative or
absolute path inside the app install prefix, and location should be a
absolute path inside the prefix to create the symlink at.
- **extraExports**: Files to export outside of the flatpak sandbox, in addition
to the application desktop file, icons and appstream. File basename *must*
be prefixed with the app id. Should not be needed for common use.
- **runtimeFlatpakref**: A pathname or url to a flatpakref file to use to auto
install the runtime.
- **sdkFlatpakref**: A pathname or url to a flatpakref file to use to auto
install the sdk.
- **baseFlatpakref**: A pathname or url to a flatpakref file to use to auto
install the base app.
- **bundleRepoUrl**: Repo url for the single file bundle. Installing the bundle
will automatically configure a remote for this URL.
- **extraFlatpakBuilderArgs**: List of extra arguments to pass to the
[flatpak-builder](https://docs.flatpak.org/en/latest/flatpak-builder-command-reference.html) command.
- **extraFlatpakBuildExportArgs**: List of extra arguments to pass to the
[flatpak build-export](https://docs.flatpak.org/en/latest/flatpak-command-reference.html#flatpak-build-export) command.
- **extraFlatpakBuildBundleArgs**: List of extra arguments to pass to the
[flatpak build-bundle](https://docs.flatpak.org/en/latest/flatpak-command-reference.html#flatpak-build-bundle) command.
### Logging
To turn on debugging output, set the DEBUG environment variable:
```shell
DEBUG=flatpak-bundler npm run my-flatpak-command
```
## Examples
### Hello world
```javascript
const flatpakBundler = require('@malept/flatpak-bundler')
const fs = require('fs-extra')
// Write a hello world script to disk
await fs.writeFile('hello',
`#!/bin/bash
echo "Hello, world!"`, { mode: 0o755 })
// Make a flatpak with it!
try {
await flatpakBundler.bundle({
id: 'org.world.Hello',
runtime: 'org.freedesktop.Platform',
runtimeVersion: '1.4',
sdk: 'org.freedesktop.Sdk',
}, {
bundlePath: 'hello.flatpak',
files: [
['hello', '/bin/hello']
],
runtimeFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref'
})
console.log('Flatpak built successfully')
} catch (error) {
console.error('Error building flatpak', error)
}
```
### Electron App
```javascript
const flatpakBundler = require('@malept/flatpak-bundler')
try {
const finalBuildOptions = await flatpakBundler.bundle({ // Manifest
id: 'org.world.Hello',
base: 'io.atom.electron.BaseApp', // Electron base application
runtime: 'org.freedesktop.Platform', // Use the freedesktop runtime
runtimeVersion: '1.4',
sdk: 'org.freedesktop.Sdk',
finishArgs: [
'--share=ipc', '--socket=x11', // Allow app to show windows with X11
'--socket=pulseaudio', // Allow audio output
'--filesystem=home', // Allow access to users home directory
'--share=network', // Allow network access
'--device=dri' // Allow OpenGL rendering
],
renameDesktopFile: 'hello.desktop', // Rename the desktop file to agree with the app ID so flatpak will export it
renameIcon: 'hello' // Rename the icon to agree with the app ID so flatpak will export it
}, { // Build options
arch: 'x86_64',
baseFlatpakref: 'https://s3-us-west-2.amazonaws.com/electron-flatpak.endlessm.com/electron-base-app-master.flatpakref', // So we can auto install the runtime
bundlePath: 'dist/hello_x86_64.flatpak',
files: [
[ 'static/linux', '/share/' ], // Desktop file and icons
[ packagedFileDir, '/share/bar' ] // Application binaries and assets
],
gpgSign: '1234ABCD', // GPG key to sign with
runtimeFlatpakref: 'https://raw.githubusercontent.com/endlessm/flatpak-bundler/master/refs/freedesktop-runtime-1.4.flatpakref',
symlinks: [
[ '/share/bar/Bar', '/bin/Bar' ] // Create a symlink in /bin to to app executable
]
})
console.log('Flatpak built successfully.')
console.log(`Build dir and repo in ${finalBuildOptions.workingDir}`)
} catch (error) {
console.error('Error building flatpak', error)
}
```
+318
View File
@@ -0,0 +1,318 @@
'use strict'
const _ = require('lodash')
const childProcess = require('child_process')
const fs = require('fs-extra')
const path = require('path')
const { promisify } = require('util')
const tmp = require('tmp-promise')
const pkg = require('./package.json')
const logger = require('debug')(pkg.name)
const exec = promisify(childProcess.exec)
function kebabify (object) {
return _.cloneDeepWith(object, (value) => {
if (!value || typeof value !== 'object') return value
return Object.keys(value).reduce((newValue, key) => {
newValue[_.kebabCase(key)] = value[key]
return newValue
}, {})
})
}
function translateArch (arch) {
if (arch === 'ia32') return 'i386'
if (arch === 'x64') return 'x86_64'
if (arch === 'amd64') return 'x86_64'
if (arch === 'armv7l') return 'arm'
return arch
}
function getOptionsWithDefaults (options, manifest) {
const defaults = {
'build-dir': path.join(options['working-dir'], 'build'),
'repo-dir': path.join(options['working-dir'], 'repo'),
'manifest-path': path.join(options['working-dir'], 'manifest.json'),
'extra-flatpak-builder-args': [],
'extra-flatpak-build-bundle-args': [],
'extra-flatpak-build-export-args': [],
'clean-tmpdirs': true,
'auto-install-runtime': typeof options['runtime-flatpakref'] !== 'undefined',
'auto-install-sdk': typeof options['sdk-flatpakref'] !== 'undefined',
'auto-install-base': typeof options['base-flatpakref'] !== 'undefined'
}
options = _.defaults({}, options, defaults)
options['working-dir'] = path.resolve(options['working-dir'])
options['build-dir'] = path.resolve(options['build-dir'])
options['repo-dir'] = path.resolve(options['repo-dir'])
options['manifest-path'] = path.resolve(options['manifest-path'])
if (options['bundle-path']) options['bundle-path'] = path.resolve(options['bundle-path'])
return options
}
async function spawnWithLogging (options, command, args, allowFail) {
return new Promise((resolve, reject) => {
logger(`$ ${command} ${args.join(' ')}`)
const child = childProcess.spawn(command, args, { cwd: options['working-dir'] })
child.stdout.on('data', (data) => {
logger(`1> ${data}`)
})
child.stderr.on('data', (data) => {
logger(`2> ${data}`)
})
child.on('error', (error) => {
reject(error)
})
child.on('close', (code) => {
if (!allowFail && code !== 0) {
reject(new Error(`${command} failed with status code ${code}`))
}
resolve(code === 0)
})
})
}
function addCommandLineOption (args, name, value) {
if (!value) return
args.push(`--${name}`)
if (value !== true) args.push(value)
}
async function checkInstalled (id, options, version, checkUser) {
const args = ['info']
addCommandLineOption(args, 'show-commit', true)
addCommandLineOption(args, checkUser ? 'user' : 'system', true)
args.push([id, options.arch, version].join('/'))
return spawnWithLogging(options, 'flatpak', args, true)
}
let _flatpakBuilderVersion
/**
* Get the flatpak-builder version in a comparable form (Array of Numbers).
*/
async function flatpakBuilderVersion () {
if (!_flatpakBuilderVersion) {
const versionString = _.last((await exec('flatpak-builder --version')).toString().split(' '))
_flatpakBuilderVersion = versionString.split('.').map(part => parseInt(part, 10))
}
return _flatpakBuilderVersion
}
async function addAssumeYesArg (args) {
if ((await flatpakBuilderVersion()) >= [0, 9, 9]) {
logger('flatpak-builder is new enough, adding --assumeyes')
addCommandLineOption(args, 'assumeyes', true)
}
}
async function ensureRef (options, manifest, type, version) {
const flatpakref = options[`${type}-flatpakref`]
const id = manifest[type]
if (!options[`auto-install-${type}`]) {
return
}
logger(`Ensuring ${type} is up to date`)
logger(`Checking for install of ${id}`)
const [userInstall, systemInstall] = await Promise.all([
checkInstalled(id, options, version, true),
checkInstalled(id, options, version, false)
])
if (!userInstall && !systemInstall) {
logger(`No install of ${id} found, trying to install from ${flatpakref}`)
if (!flatpakref) {
throw new Error(`Cannot install ${id} without flatpakref`)
}
const args = ['install']
addCommandLineOption(args, 'user', true)
addCommandLineOption(args, 'no-deps', true)
addCommandLineOption(args, 'arch', options.arch)
await addAssumeYesArg(args)
if (flatpakref.startsWith('app/') || flatpakref.startsWith('runtime/')) {
args.push(flatpakref)
} else {
addCommandLineOption(args, 'from', flatpakref)
}
return spawnWithLogging(options, 'flatpak', args)
}
logger(`Found install of ${id}, trying to update`)
const args = ['update']
addCommandLineOption(args, 'user', userInstall)
addCommandLineOption(args, 'no-deps', true)
addCommandLineOption(args, 'arch', options.arch)
await addAssumeYesArg(args)
args.push(id)
if (version) {
args.push(version)
}
return spawnWithLogging(options, 'flatpak', args)
}
async function ensureRuntime (options, manifest) {
return ensureRef(options, manifest, 'runtime', manifest['runtime-version'])
}
async function ensureSdk (options, manifest) {
return ensureRef(options, manifest, 'sdk', manifest['runtime-version'])
}
async function ensureBase (options, manifest) {
return ensureRef(options, manifest, 'base', manifest['base-version'])
}
async function ensureWorkingDir (options) {
if (!options['working-dir']) {
const dir = await tmp.dir({ prefix: 'flatpak-bundler', unsafeCleanup: options['clean-tmpdirs'] })
options['working-dir'] = dir.path
} else {
return fs.ensureDir(options['working-dir'])
}
}
async function writeJsonFile (options, manifest) {
return fs.writeJson(options['manifest-path'], manifest, { space: ' ' })
}
async function copyFiles (options, manifest) {
if (!options.files) {
return
}
return Promise.all(options.files.map(async sourceDest => {
const source = path.resolve(sourceDest[0])
const dest = path.join(options['build-dir'], 'files', sourceDest[1])
let dir = dest
if (!dir.endsWith(path.sep)) {
dir = path.dirname(dir)
}
logger(`Copying ${source} to ${dest}`)
await fs.ensureDir(dir)
await fs.copy(source, dest)
}))
}
async function createSymlinks (options, manifest) {
if (!options.symlinks) {
return
}
return Promise.all(options.symlinks.map(async ([targetPath, location]) => {
const target = path.join('/app', targetPath)
const dest = path.join(options['build-dir'], 'files', location)
logger(`Symlinking ${target} at ${dest}`)
await fs.ensureDir(path.dirname(dest))
await fs.symlink(target, dest)
}))
}
async function copyExports (options, manifest) {
if (!options['extra-exports']) {
return
}
return Promise.all(options['extra-exports'].map(async source => {
const dest = path.join(options['build-dir'], 'export', source)
const dir = path.dirname(dest)
source = path.join(options['build-dir'], 'files', source)
logger(`Exporting ${source} to ${dest}`)
await fs.ensureDir(dir)
await fs.copy(source, dest)
}))
}
async function flatpakBuilder (options, manifest, finish) {
const args = []
addCommandLineOption(args, 'arch', options.arch)
addCommandLineOption(args, 'force-clean', true)
// If we are not compiling anything, allow building without the platform and sdk
// installed. Allows automated builds on a minimal environment, for example.
if (!manifest.modules || manifest.modules.length === 0) {
addCommandLineOption(args, 'allow-missing-runtimes', true)
}
if (!finish) {
addCommandLineOption(args, 'build-only', true)
} else {
addCommandLineOption(args, 'finish-only', true)
}
await addAssumeYesArg(args)
args.push.apply(args, options['extra-flatpak-builder-args'])
args.push(options['build-dir'])
args.push(options['manifest-path'])
return spawnWithLogging(options, 'flatpak-builder', args)
}
async function flatpakBuildExport (options, manifest) {
const args = ['build-export']
addCommandLineOption(args, 'arch', options.arch)
addCommandLineOption(args, 'gpg-sign', options['gpg-sign'])
addCommandLineOption(args, 'gpg-homedir', options['gpg-homedir'])
addCommandLineOption(args, 'subject', options.subject)
addCommandLineOption(args, 'body', options.body)
if (options['build-runtime']) addCommandLineOption(args, 'runtime', true)
args.push.apply(args, options['extra-flatpak-build-export-args'])
args.push(options['repo-dir'])
args.push(options['build-dir'])
if (manifest.branch) args.push(manifest.branch)
return spawnWithLogging(options, 'flatpak', args)
}
async function flatpakBuildBundle (options, manifest) {
if (!options['bundle-path']) {
return
}
const args = ['build-bundle']
addCommandLineOption(args, 'arch', options.arch)
addCommandLineOption(args, 'gpg-keys', options['gpg-keys'])
addCommandLineOption(args, 'gpg-homedir', options['gpg-homedir'])
addCommandLineOption(args, 'repo-url', options['bundle-repo-url'])
if (options['build-runtime']) addCommandLineOption(args, 'runtime', true)
args.push.apply(args, options['extra-flatpak-build-bundle-args'])
args.push(options['repo-dir'])
args.push(options['bundle-path'])
args.push(manifest.id)
if (manifest.branch) args.push(manifest.branch)
await fs.ensureDir(path.dirname(options['bundle-path']))
return spawnWithLogging(options, 'flatpak', args)
}
exports.bundle = async function (manifest, options) {
manifest = kebabify(manifest)
options = kebabify(options)
if (manifest['app-id']) manifest.id = manifest['app-id']
await ensureWorkingDir(options)
options = getOptionsWithDefaults(options, manifest)
options.arch = translateArch(options.arch)
logger(`Using manifest...\n${JSON.stringify(manifest, null, ' ')}`)
logger(`Using options...\n${JSON.stringify(options, null, ' ')}`)
await ensureRuntime(options, manifest)
await ensureSdk(options, manifest)
await ensureBase(options, manifest)
await writeJsonFile(options, manifest)
await flatpakBuilder(options, manifest, false)
await copyFiles(options, manifest)
await createSymlinks(options, manifest)
await flatpakBuilder(options, manifest, true)
await copyExports(options, manifest)
await flatpakBuildExport(options, manifest)
await flatpakBuildBundle(options, manifest)
return options
}
exports.translateArch = translateArch
+46
View File
@@ -0,0 +1,46 @@
{
"name": "@malept/flatpak-bundler",
"version": "0.4.0",
"description": "A small utility for packing files in a flatpak.",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/malept/flatpak-bundler.git"
},
"keywords": [
"flatpak"
],
"author": "Matt Watson <mattdangerw@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/malept/flatpak-bundler/issues"
},
"files": [],
"homepage": "https://github.com/malept/flatpak-bundler#readme",
"engines": {
"node": ">= 10.0.0"
},
"dependencies": {
"debug": "^4.1.1",
"fs-extra": "^9.0.0",
"lodash": "^4.17.15",
"tmp-promise": "^3.0.2"
},
"devDependencies": {
"husky": "^4.2.5",
"lint-staged": "^10.2.9",
"mocha": "^7.0.0",
"standard": "^14.0.0"
},
"scripts": {
"lint": "standard",
"mocha": "mocha",
"test": "standard && mocha"
},
"husky": {
"pre-commit": "lint-staged"
},
"lint-staged": {
"*.js": "standard --fix"
}
}
+32
View File
@@ -0,0 +1,32 @@
import { type KDFInput } from './utils.ts';
/**
* Argon2 options.
* * t: time cost, m: mem cost in kb, p: parallelization.
* * key: optional key. personalization: arbitrary extra data.
* * dkLen: desired number of output bytes.
*/
export type ArgonOpts = {
t: number;
m: number;
p: number;
version?: number;
key?: KDFInput;
personalization?: KDFInput;
dkLen?: number;
asyncTick?: number;
maxmem?: number;
onProgress?: (progress: number) => void;
};
/** argon2d GPU-resistant version. */
export declare const argon2d: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2i side-channel-resistant version. */
export declare const argon2i: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2id, combining i+d, the most popular version from RFC 9106 */
export declare const argon2id: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Uint8Array;
/** argon2d async GPU-resistant version. */
export declare const argon2dAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
/** argon2i async side-channel-resistant version. */
export declare const argon2iAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
/** argon2id async, combining i+d, the most popular version from RFC 9106 */
export declare const argon2idAsync: (password: KDFInput, salt: KDFInput, opts: ArgonOpts) => Promise<Uint8Array>;
//# sourceMappingURL=argon2.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"argon2.d.ts","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":"AAYA,OAAO,EAAqD,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAkK9F;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,GAAG,CAAC,EAAE,QAAQ,CAAC;IACf,eAAe,CAAC,EAAE,QAAQ,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAuNF,qCAAqC;AACrC,eAAO,MAAM,OAAO,GAAI,UAAU,QAAQ,EAAE,MAAM,QAAQ,EAAE,MAAM,SAAS,KAAG,UACnC,CAAC;AAC5C,8CAA8C;AAC9C,eAAO,MAAM,OAAO,GAAI,U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