repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
core | github_2023 | zen-fs | typescript | StoreFS.remove | protected async remove(path: string, isDir: boolean): Promise<void> {
const syscall = isDir ? 'rmdir' : 'unlink';
await using tx = this.transaction();
const { dir: parent, base: fileName } = parse(path),
parentNode = await this.findInode(tx, parent, syscall),
listing = decodeDirListing((await tx.get(parentNode.data)) ?? _throw(ErrnoError.With('ENOENT', parent, syscall)));
if (!listing[fileName]) {
throw ErrnoError.With('ENOENT', path, syscall);
}
const fileIno = listing[fileName];
// Get file inode.
const fileNode = new Inode((await tx.get(fileIno)) ?? _throw(ErrnoError.With('ENOENT', path, syscall)));
// Remove from directory listing of parent.
delete listing[fileName];
if (!isDir && fileNode.toStats().isDirectory()) throw ErrnoError.With('EISDIR', path, syscall);
await tx.set(parentNode.data, encodeDirListing(listing));
if (--fileNode.nlink < 1) {
// remove file
await tx.remove(fileNode.data);
await tx.remove(fileIno);
this._remove(fileIno);
}
// Success.
await tx.commit();
} | /**
* Remove all traces of `path` from the file system.
* @param path The path to remove from the file system.
* @param isDir Does the path belong to a directory, or a file?
* @todo Update mtime.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L792-L825 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | StoreFS.removeSync | protected removeSync(path: string, isDir: boolean): void {
const syscall = isDir ? 'rmdir' : 'unlink';
using tx = this.transaction();
const { dir: parent, base: fileName } = parse(path),
parentNode = this.findInodeSync(tx, parent, syscall),
listing = decodeDirListing(tx.getSync(parentNode.data) ?? _throw(ErrnoError.With('ENOENT', parent, syscall))),
fileIno: number = listing[fileName];
if (!fileIno) throw ErrnoError.With('ENOENT', path, syscall);
// Get file inode.
const fileNode = new Inode(tx.getSync(fileIno) ?? _throw(ErrnoError.With('ENOENT', path, syscall)));
// Remove from directory listing of parent.
delete listing[fileName];
if (!isDir && fileNode.toStats().isDirectory()) {
throw ErrnoError.With('EISDIR', path, syscall);
}
// Update directory listing.
tx.setSync(parentNode.data, encodeDirListing(listing));
if (--fileNode.nlink < 1) {
// remove file
tx.removeSync(fileNode.data);
tx.removeSync(fileIno);
this._remove(fileIno);
}
// Success.
tx.commitSync();
} | /**
* Remove all traces of `path` from the file system.
* @param path The path to remove from the file system.
* @param isDir Does the path belong to a directory, or a file?
* @todo Update mtime.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L833-L865 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | SyncMapTransaction.keys | public async keys(): Promise<Iterable<number>> {
return this.store.keys();
} | // eslint-disable-next-line @typescript-eslint/require-await | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/map.ts#L25-L27 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | WrappedTransaction.stash | protected stash(id: number, data?: Uint8Array, offset: number = 0): void {
if (!this.originalData.has(id)) this.originalData.set(id, []);
this.originalData.get(id)!.push({ data, offset });
} | /**
* Stashes given key value pair into `originalData` if it doesn't already exist.
* Allows us to stash values the program is requesting anyway to
* prevent needless `get` requests if the program modifies the data later
* on during the transaction.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/store.ts#L351-L354 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | WrappedTransaction.markModified | protected async markModified(id: number, offset: number, length?: number): Promise<void> {
this.modifiedKeys.add(id);
const end = length ? offset + length : undefined;
try {
this.stash(id, await this.raw.get(id, offset, end), offset);
} catch (e) {
if (!(this.raw instanceof AsyncTransaction)) throw e;
/*
async transaction has a quirk:
setting the buffer to a larger size doesn't work correctly due to cache ranges
so, we cache the existing sub-ranges
*/
const tx = this.raw as AsyncTransaction<AsyncStore>;
const resource = tx._cached(id);
if (!resource) throw e;
for (const range of resource.cached(offset, end ?? offset)) {
this.stash(id, await this.raw.get(id, range.start, range.end), range.start);
}
}
} | /**
* Marks an id as modified, and stashes its value if it has not been stashed already.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/store.ts#L359-L381 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | WrappedTransaction.markModifiedSync | protected markModifiedSync(id: number, offset: number, length?: number): void {
this.modifiedKeys.add(id);
const end = length ? offset + length : undefined;
try {
this.stash(id, this.raw.getSync(id, offset, end), offset);
} catch (e) {
if (!(this.raw instanceof AsyncTransaction)) throw e;
/*
async transaction has a quirk:
setting the buffer to a larger size doesn't work correctly due to cache ranges
so, we cache the existing sub-ranges
*/
const tx = this.raw as AsyncTransaction<AsyncStore>;
const resource = tx._cached(id);
if (!resource) throw e;
for (const range of resource.cached(offset, end ?? offset)) {
this.stash(id, this.raw.getSync(id, range.start, range.end), range.start);
}
}
} | /**
* Marks an id as modified, and stashes its value if it has not been stashed already.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/store.ts#L386-L409 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | DeviceFile.read | public async read<TBuffer extends ArrayBufferView>(buffer: TBuffer, offset?: number, length?: number): Promise<FileReadResult<TBuffer>> {
return { bytesRead: this.readSync(buffer, offset, length), buffer };
} | // eslint-disable-next-line @typescript-eslint/require-await | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/devices.ts#L192-L194 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | DeviceFile.write | public async write(buffer: Uint8Array, offset?: number, length?: number, position?: number): Promise<number> {
return this.writeSync(buffer, offset, length, position);
} | // eslint-disable-next-line @typescript-eslint/require-await | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/devices.ts#L212-L214 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | DeviceFS.createDevice | public createDevice<TData = any>(path: string, driver: DeviceDriver<TData>, options: object = {}): Device<TData | Record<string, never>> {
log_deprecated('DeviceFS#createDevice');
if (this.existsSync(path)) {
throw ErrnoError.With('EEXIST', path, 'mknod');
}
let ino = 1;
const silence = canary(ErrnoError.With('EDEADLK', path, 'mknod'));
while (this.store.has(ino)) ino++;
silence();
const dev = {
driver,
ino,
data: {},
minor: 0,
major: 0,
...driver.init?.(ino, options),
};
this.devices.set(path, dev);
return dev;
} | /**
* Creates a new device at `path` relative to the `DeviceFS` root.
* @deprecated
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/devices.ts#L287-L306 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | DeviceFS.devicesWithDriver | protected devicesWithDriver(driver: DeviceDriver<unknown> | string, forceIdentity?: boolean): Device[] {
if (forceIdentity && typeof driver == 'string') {
throw err(new ErrnoError(Errno.EINVAL, 'Can not fetch devices using only a driver name'), { fs: this });
}
const devs: Device[] = [];
for (const device of this.devices.values()) {
if (forceIdentity && device.driver != driver) continue;
const name = typeof driver == 'string' ? driver : driver.name;
if (name == device.driver.name) devs.push(device);
}
return devs;
} | /* node:coverage enable */ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/devices.ts#L309-L323 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | DeviceFS._createDevice | _createDevice<TData = any>(driver: DeviceDriver<TData>, options: object = {}): Device<TData | Record<string, never>> {
let ino = 1;
while (this.store.has(ino)) ino++;
const dev = {
driver,
ino,
data: {},
minor: 0,
major: 0,
...driver.init?.(ino, options),
};
const path = '/' + (dev.name || driver.name) + (driver.singleton ? '' : this.devicesWithDriver(driver).length);
if (this.existsSync(path)) throw ErrnoError.With('EEXIST', path, 'mknod');
this.devices.set(path, dev);
info('Initialized device: ' + this._mountPoint + path);
return dev;
} | /**
* @internal
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/devices.ts#L328-L348 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | DeviceFS.addDefaults | public addDefaults(): void {
this._createDevice(nullDevice);
this._createDevice(zeroDevice);
this._createDevice(fullDevice);
this._createDevice(randomDevice);
this._createDevice(consoleDevice);
debug('Added default devices.');
} | /**
* Adds default devices
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/devices.ts#L353-L360 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | ErrnoError.toString | public toString(): string {
return this.code + ': ' + this.message + (this.path ? `, '${this.path}'` : '');
} | /**
* @returns A friendly error message.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/error.ts#L291-L293 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | ErrnoError.bufferSize | public bufferSize(): number {
// 4 bytes for string length.
return 4 + JSON.stringify(this.toJSON()).length;
} | /**
* The size of the API error in buffer-form in bytes.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/error.ts#L309-L312 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.constructor | public constructor(
fs: FS,
path: string,
public readonly flag: string,
public readonly stats: Stats,
/**
* A buffer containing the entire contents of the file.
*/
protected _buffer: Uint8Array = new Uint8Array(new ArrayBuffer(0, fs.attributes.has('no_buffer_resize') ? {} : { maxByteLength }))
) {
super(fs, path);
/*
Note:
This invariant is *not* maintained once the file starts getting modified.
It only actually matters if file is readable, as writeable modes may truncate/append to file.
*/
if (this.stats.size == _buffer.byteLength) {
return;
}
if (!isWriteable(this.flag)) {
throw new ErrnoError(Errno.EIO, `Size mismatch: buffer length ${_buffer.byteLength}, stats size ${this.stats.size}`, path);
}
this.stats.size = _buffer.byteLength;
this.dirty = true;
} | /**
* Creates a file with `path` and, optionally, the given contents.
* Note that, if contents is specified, it will be mutated by the file.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L287-L314 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.buffer | public get buffer(): Uint8Array {
return this._buffer;
} | /**
* Get the underlying buffer for this file. Mutating not recommended and will mess up dirty tracking.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L319-L321 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.position | public get position(): number {
if (isAppendable(this.flag)) {
return this.stats.size;
}
return this._position;
} | /**
* Get the current file position.
*
* We emulate the following bug mentioned in the Node documentation:
*
* On Linux, positional writes don't work when the file is opened in append mode.
* The kernel ignores the position argument and always appends the data to the end of the file.
* @returns The current file position.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L332-L337 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.dispose | protected dispose(force?: boolean): void {
if (this.closed) throw ErrnoError.With('EBADF', this.path, 'dispose');
if (this.dirty && !force) {
throw ErrnoError.With('EBUSY', this.path, 'dispose');
}
this.closed = true;
} | /**
* Cleans up. This will *not* sync the file data to the FS
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L374-L381 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.write | public async write(buffer: Uint8Array, offset?: number, length?: number, position?: number): Promise<number> {
const bytesWritten = this._write(buffer, offset, length, position);
if (config.syncImmediately) await this.sync();
return bytesWritten;
} | /**
* Write buffer to the file.
* @param buffer Uint8Array containing the data to write to the file.
* @param offset Offset in the buffer to start reading data from.
* @param length The amount of bytes to write to the file.
* @param position Offset from the beginning of the file where this data should be written.
* If position is null, the data will be written at the current position.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L449-L453 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.writeSync | public writeSync(buffer: Uint8Array, offset?: number, length?: number, position?: number): number {
const bytesWritten = this._write(buffer, offset, length, position);
if (config.syncImmediately) this.syncSync();
return bytesWritten;
} | /**
* Write buffer to the file.
* @param buffer Uint8Array containing the data to write to the file.
* @param offset Offset in the buffer to start reading data from.
* @param length The amount of bytes to write to the file.
* @param position Offset from the beginning of the file where this data should be written.
* If position is null, the data will be written at the current position.
* @returns bytes written
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L464-L468 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.read | public async read<TBuffer extends ArrayBufferView>(
buffer: TBuffer,
offset?: number,
length?: number,
position?: number
): Promise<{ bytesRead: number; buffer: TBuffer }> {
const bytesRead = this._read(buffer, offset, length, position);
if (config.syncImmediately) await this.sync();
return { bytesRead, buffer };
} | /**
* Read data from the file.
* @param buffer The buffer that the data will be written to.
* @param offset The offset within the buffer where writing will start.
* @param length An integer specifying the number of bytes to read.
* @param position An integer specifying where to begin reading from in the file.
* If position is null, data will be read from the current file position.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L507-L516 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | PreloadFile.readSync | public readSync(buffer: ArrayBufferView, offset?: number, length?: number, position?: number): number {
const bytesRead = this._read(buffer, offset, length, position);
if (config.syncImmediately) this.syncSync();
return bytesRead;
} | /**
* Read data from the file.
* @param buffer The buffer that the data will be written to.
* @param offset The offset within the buffer where writing will start.
* @param length An integer specifying the number of bytes to read.
* @param position An integer specifying where to begin reading from in the file.
* If position is null, data will be read from the current file position.
* @returns number of bytes written
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L527-L531 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.position | public get position(): number {
return isAppendable(this.flag) ? this.stats.size : this._position;
} | /**
* Get the current file position.
*
* We emulate the following bug mentioned in the Node documentation:
*
* On Linux, positional writes don't work when the file is opened in append mode.
* The kernel ignores the position argument and always appends the data to the end of the file.
* @returns The current file position.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L625-L627 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.constructor | public constructor(
fs: FS,
path: string,
public readonly flag: string,
public readonly stats: StatsLike<number>
) {
super(fs, path);
this.dirty = true;
} | /**
* Creates a file with `path` and, optionally, the given contents.
* Note that, if contents is specified, it will be mutated by the file.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L647-L656 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.dispose | protected dispose(force?: boolean): void {
if (this.closed) throw ErrnoError.With('EBADF', this.path, 'dispose');
if (this.dirty && !force) throw ErrnoError.With('EBUSY', this.path, 'dispose');
this.closed = true;
} | /**
* Cleans up. This will *not* sync the file data to the FS
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L691-L697 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.write | public async write(
buffer: Uint8Array,
offset: number = 0,
length: number = buffer.byteLength - offset,
position: number = this.position
): Promise<number> {
const slice = this.prepareWrite(buffer, offset, length, position);
await this.fs.write(this.path, slice, position);
if (config.syncImmediately) await this.sync();
return slice.byteLength;
} | /**
* Write buffer to the file.
* @param buffer Uint8Array containing the data to write to the file.
* @param offset Offset in the buffer to start reading data from.
* @param length The amount of bytes to write to the file.
* @param position Offset from the beginning of the file where this data should be written.
* If position is null, the data will be written at the current position.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L761-L771 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.writeSync | public writeSync(buffer: Uint8Array, offset: number = 0, length: number = buffer.byteLength - offset, position: number = this.position): number {
const slice = this.prepareWrite(buffer, offset, length, position);
this.fs.writeSync(this.path, slice, position);
if (config.syncImmediately) this.syncSync();
return slice.byteLength;
} | /**
* Write buffer to the file.
* @param buffer Uint8Array containing the data to write to the file.
* @param offset Offset in the buffer to start reading data from.
* @param length The amount of bytes to write to the file.
* @param position Offset from the beginning of the file where this data should be written.
* If position is null, the data will be written at the current position.
* @returns bytes written
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L782-L787 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.prepareRead | protected prepareRead(length: number, position: number): number {
if (this.closed) throw ErrnoError.With('EBADF', this.path, 'read');
if (!isReadable(this.flag)) throw new ErrnoError(Errno.EPERM, 'File not opened with a readable mode.');
if (config.updateOnRead) this.dirty = true;
this.stats.atimeMs = Date.now();
let end = position + length;
if (end > this.stats.size) {
end = position + Math.max(this.stats.size - position, 0);
}
this._position = end;
return end;
} | /**
* Computes position information for reading
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L792-L807 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.read | public async read<TBuffer extends ArrayBufferView>(
buffer: TBuffer,
offset: number = 0,
length: number = buffer.byteLength - offset,
position: number = this.position
): Promise<{ bytesRead: number; buffer: TBuffer }> {
const end = this.prepareRead(length, position);
const uint8 = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
await this.fs.read(this.path, uint8.subarray(offset, offset + length), position, end);
if (config.syncImmediately) await this.sync();
return { bytesRead: end - position, buffer };
} | /**
* Read data from the file.
* @param buffer The buffer that the data will be written to.
* @param offset The offset within the buffer where writing will start.
* @param length An integer specifying the number of bytes to read.
* @param position An integer specifying where to begin reading from in the file.
* If position is unset, data will be read from the current file position.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L817-L828 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | LazyFile.readSync | public readSync(
buffer: ArrayBufferView,
offset: number = 0,
length: number = buffer.byteLength - offset,
position: number = this.position
): number {
const end = this.prepareRead(length, position);
const uint8 = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
this.fs.readSync(this.path, uint8.subarray(offset, offset + length), position, end);
if (config.syncImmediately) this.syncSync();
return end - position;
} | /**
* Read data from the file.
* @param buffer The buffer that the data will be written to.
* @param offset The offset within the buffer where writing will start.
* @param length An integer specifying the number of bytes to read.
* @param position An integer specifying where to begin reading from in the file.
* If position is null, data will be read from the current file position.
* @returns number of bytes written
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file.ts#L839-L850 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Index.toJSON | public toJSON(): IndexData {
return {
version,
entries: Object.fromEntries([...this].map(([k, v]) => [k, v.toJSON()])),
};
} | /**
* Converts the index to JSON
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file_index.ts#L30-L35 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Index.toString | public toString(): string {
return JSON.stringify(this.toJSON());
} | /**
* Converts the index to a string
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file_index.ts#L40-L42 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Index._alloc | _alloc(): number {
return Math.max(...[...this.values()].flatMap(i => [i.ino, i.data])) + 1;
} | /**
* Get the next available ID in the index
* @internal
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file_index.ts#L82-L84 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Index.directories | public directories(): Map<string, Record<string, number>> {
const dirs = new Map<string, Record<string, number>>();
for (const [path, node] of this) {
if ((node.mode & S_IFMT) != S_IFDIR) continue;
const entries: Record<string, number> = {};
for (const entry of this.keys()) {
if (dirname(entry) == path && entry != path) entries[basename(entry)] = this.get(entry)!.ino;
}
dirs.set(path, entries);
}
return dirs;
} | /**
* Gets a list of entries for each directory in the index.
* Use
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file_index.ts#L90-L105 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Index.fromJSON | public fromJSON(json: IndexData): this {
if (json.version != version) {
throw new ErrnoError(Errno.EINVAL, 'Index version mismatch');
}
this.clear();
for (const [path, node] of Object.entries(json.entries)) {
node.data ??= randomInt(1, size_max);
if (path == '/') node.ino = 0;
this.set(path, new Inode(node));
}
return this;
} | /**
* Loads the index from JSON data
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file_index.ts#L110-L126 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Index.parse | public static parse(data: string): Index {
if (!isJSON(data)) throw new ErrnoError(Errno.EINVAL, 'Invalid JSON');
const json = JSON.parse(data) as IndexData;
const index = new Index();
index.fromJSON(json);
return index;
} | /**
* Parses an index from a string
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/file_index.ts#L131-L138 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Inode.toStats | public toStats(): Stats {
return new Stats(this);
} | /**
* Handy function that converts the Inode to a Node Stats object.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/inode.ts#L93-L95 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Inode.update | public update(data?: Partial<Readonly<InodeLike>>): boolean {
if (!data) return false;
let hasChanged = false;
for (const key of _inode_fields) {
if (data[key] === undefined) continue;
// When multiple StoreFSes are used in a single stack, the differing IDs end up here.
if (key == 'ino' || key == 'data') continue;
if (this[key] === data[key]) continue;
this[key] = data[key];
hasChanged = true;
}
return hasChanged;
} | /**
* Updates the Inode using information from the stats object. Used by file
* systems at sync time, e.g.:
* - Program opens file and gets a File object.
* - Program mutates file. File object is responsible for maintaining
* metadata changes locally -- typically in a Stats object.
* - Program closes file. File object's metadata changes are synced with the
* file system.
* @returns whether any changes have occurred.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/inode.ts#L107-L125 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | ansi | function ansi(text: string, format: string): string {
return `\x1b[${format}m${text}\x1b[0m`;
} | // Formatting and output | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/internal/log.ts#L122-L124 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | _MutexedFS.addLock | protected addLock(): MutexLock {
const lock = new MutexLock(this.currentLock);
this.currentLock = lock;
return lock;
} | /**
* Adds a lock for a path
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/mixins/mutexed.ts#L90-L94 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | _MutexedFS.lock | public async lock(path: string, syscall: string): Promise<MutexLock> {
const previous = this.currentLock;
const lock = this.addLock();
const stack = new Error().stack;
setTimeout(() => {
if (lock.isLocked) {
const error = ErrnoError.With('EDEADLK', path, syscall);
error.stack += stack?.slice('Error'.length);
throw err(error, { fs: this });
}
}, 5000);
await previous?.done();
return lock;
} | /**
* Locks `path` asynchronously.
* If the path is currently locked, waits for it to be unlocked.
* @internal
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/mixins/mutexed.ts#L101-L114 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | _MutexedFS.lockSync | public lockSync(path: string, syscall: string): MutexLock {
if (this.currentLock?.isLocked) {
throw err(ErrnoError.With('EBUSY', path, syscall), { fs: this });
}
return this.addLock();
} | /**
* Locks `path` asynchronously.
* If the path is currently locked, an error will be thrown
* @internal
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/mixins/mutexed.ts#L121-L127 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | _MutexedFS.isLocked | public get isLocked(): boolean {
return !!this.currentLock?.isLocked;
} | /**
* Whether `path` is locked
* @internal
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/mixins/mutexed.ts#L133-L135 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | _MutexedFS.rename | public async rename(oldPath: string, newPath: string): Promise<void> {
using _ = await this.lock(oldPath, 'rename');
await this._fs.rename(oldPath, newPath);
} | /* eslint-disable @typescript-eslint/no-unused-vars */ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/mixins/mutexed.ts#L138-L141 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | collectAsyncIterator | async function collectAsyncIterator<T>(it: NodeJS.AsyncIterator<T>): Promise<T[]> {
const results: T[] = [];
for await (const result of it) {
results.push(result);
}
return results;
} | /**
* Helper to collect an async iterator into an array
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/async.ts#L23-L29 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Dir.closeSync | public closeSync(): void {
this.closed = true;
} | /**
* Synchronously close the directory's underlying resource handle.
* Subsequent reads will result in errors.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/dir.ts#L85-L87 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Dir.readSync | public readSync(): Dirent | null {
this.checkClosed();
this._entries ??= readdirSync.call<V_Context, [string, any], Dirent[]>(this.context, this.path, { withFileTypes: true });
if (!this._entries.length) return null;
return this._entries.shift() ?? null;
} | /**
* Synchronously read the next directory entry via `readdir(3)` as a `Dirent`.
* If there are no more directory entries to read, null will be returned.
* Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/dir.ts#L118-L123 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.chown | public async chown(uid: number, gid: number): Promise<void> {
await this.file.chown(uid, gid);
this._emitChange();
} | /**
* Asynchronous fchown(2) - Change ownership of a file.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L57-L60 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.chmod | public async chmod(mode: fs.Mode): Promise<void> {
const numMode = normalizeMode(mode, -1);
if (numMode < 0) throw new ErrnoError(Errno.EINVAL, 'Invalid mode.');
await this.file.chmod(numMode);
this._emitChange();
} | /**
* Asynchronous fchmod(2) - Change permissions of a file.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L66-L71 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.datasync | public datasync(): Promise<void> {
return this.file.datasync();
} | /**
* Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L76-L78 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.sync | public sync(): Promise<void> {
return this.file.sync();
} | /**
* Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L83-L85 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.truncate | public async truncate(length?: number | null): Promise<void> {
length ||= 0;
if (length < 0) {
throw new ErrnoError(Errno.EINVAL);
}
await this.file.truncate(length);
this._emitChange();
} | /**
* Asynchronous ftruncate(2) - Truncate a file to a specified length.
* @param length If not specified, defaults to `0`.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L91-L98 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.utimes | public async utimes(atime: string | number | Date, mtime: string | number | Date): Promise<void> {
await this.file.utimes(normalizeTime(atime), normalizeTime(mtime));
this._emitChange();
} | /**
* Asynchronously change file timestamps of the file.
* @param atime The last access time. If a string is provided, it will be coerced to number.
* @param mtime The last modified time. If a string is provided, it will be coerced to number.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L105-L108 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.appendFile | public async appendFile(
data: string | Uint8Array,
_options: (fs.ObjectEncodingOptions & promises.FlagAndOpenMode) | BufferEncoding = {}
): Promise<void> {
const options = normalizeOptions(_options, 'utf8', 'a', 0o644);
const flag = parseFlag(options.flag);
if (!isAppendable(flag)) {
throw new ErrnoError(Errno.EINVAL, 'Flag passed to appendFile must allow for appending.');
}
if (typeof data != 'string' && !options.encoding) {
throw new ErrnoError(Errno.EINVAL, 'Encoding not specified');
}
const encodedData = typeof data == 'string' ? Buffer.from(data, options.encoding!) : data;
await this.file.write(encodedData, 0, encodedData.length);
this._emitChange();
} | /**
* Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically.
* The `FileHandle` must have been opened for appending.
* @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string.
* @param _options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
* - `encoding` defaults to `'utf8'`.
* - `mode` defaults to `0o666`.
* - `flag` defaults to `'a'`.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L119-L134 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.readableWebStream | public readableWebStream(options: promises.ReadableWebStreamOptions = {}): TReadableStream<Uint8Array> {
// Note: using an arrow function to preserve `this`
const start = async (controller: ReadableStreamController<Uint8Array>) => {
try {
const chunkSize = 64 * 1024,
maxChunks = 1e7;
let i = 0,
position = 0,
bytesRead = NaN;
while (bytesRead > 0) {
const result = await this.read(new Uint8Array(chunkSize), 0, chunkSize, position);
if (!result.bytesRead) {
controller.close();
return;
}
controller.enqueue(result.buffer.subarray(0, result.bytesRead));
position += result.bytesRead;
if (++i >= maxChunks) {
throw new ErrnoError(Errno.EFBIG, 'Too many iterations on readable stream', this.file.path, 'FileHandle.readableWebStream');
}
bytesRead = result.bytesRead;
}
} catch (e) {
controller.error(e);
}
};
const _gt = globalThis;
if (!('ReadableStream' in _gt)) {
throw new ErrnoError(Errno.ENOSYS, 'ReadableStream is missing on globalThis');
}
return new (_gt as { ReadableStream: new (...args: unknown[]) => TReadableStream<Uint8Array> }).ReadableStream({
start,
type: options.type,
});
} | /**
* Returns a `ReadableStream` that may be used to read the files data.
*
* An error will be thrown if this method is called more than once or is called after the `FileHandle` is closed or closing.
*
* While the `ReadableStream` will read the file to completion,
* it will not close the `FileHandle` automatically.
* User code must still call the `fileHandle.close()` method.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L211-L247 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | start | const start = async (controller: ReadableStreamController<Uint8Array>) => {
try {
const chunkSize = 64 * 1024,
maxChunks = 1e7;
let i = 0,
position = 0,
bytesRead = NaN;
while (bytesRead > 0) {
const result = await this.read(new Uint8Array(chunkSize), 0, chunkSize, position);
if (!result.bytesRead) {
controller.close();
return;
}
controller.enqueue(result.buffer.subarray(0, result.bytesRead));
position += result.bytesRead;
if (++i >= maxChunks) {
throw new ErrnoError(Errno.EFBIG, 'Too many iterations on readable stream', this.file.path, 'FileHandle.readableWebStream');
}
bytesRead = result.bytesRead;
}
} catch (e) {
controller.error(e);
}
}; | // Note: using an arrow function to preserve `this` | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L213-L237 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.readLines | public readLines(options?: promises.CreateReadStreamOptions): ReadlineInterface {
throw ErrnoError.With('ENOSYS', this.file.path, 'FileHandle.readLines');
} | /**
* @todo Implement
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L252-L254 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.write | public async write<T extends FileContents>(
data: T,
options?: number | null | { offset?: number; length?: number; position?: number },
lenOrEnc?: BufferEncoding | number | null,
position?: number | null
): Promise<{ bytesWritten: number; buffer: T }> {
let buffer: Uint8Array, offset: number | null | undefined, length: number;
if (typeof options == 'object') {
lenOrEnc = options?.length;
position = options?.position;
options = options?.offset;
}
if (typeof data === 'string') {
position = typeof options === 'number' ? options : null;
const encoding = typeof lenOrEnc === 'string' ? lenOrEnc : ('utf8' as BufferEncoding);
offset = 0;
buffer = Buffer.from(data, encoding);
length = buffer.length;
} else {
buffer = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
offset = options;
length = lenOrEnc as number;
position = typeof position === 'number' ? position : null;
}
position ??= this.file.position;
const bytesWritten = await this.file.write(buffer, offset, length, position);
this._emitChange();
return { buffer: data, bytesWritten };
} | /**
* Asynchronously writes `string` to the file.
* The `FileHandle` must have been opened for writing.
* It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise`
* to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L279-L307 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.writeFile | public async writeFile(data: string | Uint8Array, _options: fs.WriteFileOptions = {}): Promise<void> {
const options = normalizeOptions(_options, 'utf8', 'w', 0o644);
const flag = parseFlag(options.flag);
if (!isWriteable(flag)) {
throw new ErrnoError(Errno.EINVAL, 'Flag passed must allow for writing.');
}
if (typeof data != 'string' && !options.encoding) {
throw new ErrnoError(Errno.EINVAL, 'Encoding not specified');
}
const encodedData = typeof data == 'string' ? Buffer.from(data, options.encoding!) : data;
await this.file.write(encodedData, 0, encodedData.length, 0);
this._emitChange();
} | /**
* Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically.
* The `FileHandle` must have been opened for writing.
* It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected).
* @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string.
* @param _options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
* - `encoding` defaults to `'utf8'`.
* - `mode` defaults to `0o666`.
* - `flag` defaults to `'w'`.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L319-L331 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.close | public async close(): Promise<void> {
await this.file.close();
fdMap.delete(this.fd);
} | /**
* Asynchronous close(2) - close a `FileHandle`.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L336-L339 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.writev | public async writev(buffers: Uint8Array[], position?: number): Promise<fs.WriteVResult> {
let bytesWritten = 0;
for (const buffer of buffers) {
bytesWritten += (await this.write(buffer, 0, buffer.length, position! + bytesWritten)).bytesWritten;
}
return { bytesWritten, buffers };
} | /**
* Asynchronous `writev`. Writes from multiple buffers.
* @param buffers An array of Uint8Array buffers.
* @param position The position in the file where to begin writing.
* @returns The number of bytes written.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L347-L355 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.readv | public async readv(buffers: NodeJS.ArrayBufferView[], position?: number): Promise<fs.ReadVResult> {
let bytesRead = 0;
for (const buffer of buffers) {
bytesRead += (await this.read(buffer, 0, buffer.byteLength, position! + bytesRead)).bytesRead;
}
return { bytesRead, buffers };
} | /**
* Asynchronous `readv`. Reads into multiple buffers.
* @param buffers An array of Uint8Array buffers.
* @param position The position in the file where to begin reading.
* @returns The number of bytes read.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L363-L371 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.createReadStream | public createReadStream(options?: promises.CreateReadStreamOptions): ReadStream {
const stream = new ReadStream({
highWaterMark: options?.highWaterMark || 64 * 1024,
encoding: options!.encoding!,
// eslint-disable-next-line @typescript-eslint/no-misused-promises
read: async (size: number) => {
try {
const result = await this.read(new Uint8Array(size), 0, size, this.file.position);
stream.push(!result.bytesRead ? null : result.buffer.subarray(0, result.bytesRead)); // Push data or null for EOF
this.file.position += result.bytesRead;
} catch (error) {
stream.destroy(error as Error);
}
},
});
stream.path = this.file.path;
return stream;
} | /**
* Creates a stream for reading from the file.
* @param options Options for the readable stream
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L377-L396 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | FileHandle.createWriteStream | public createWriteStream(options?: promises.CreateWriteStreamOptions): WriteStream {
const streamOptions = {
highWaterMark: options?.highWaterMark,
encoding: options?.encoding,
write: async (chunk: Uint8Array, encoding: BufferEncoding, callback: (error?: Error | null) => void) => {
try {
const { bytesWritten } = await this.write(chunk, null, encoding);
callback(bytesWritten == chunk.length ? null : new Error('Failed to write full chunk'));
} catch (error) {
callback(error as Error);
}
},
};
const stream = new WriteStream(streamOptions);
stream.path = this.file.path;
return stream;
} | /**
* Creates a stream for writing to the file.
* @param options Options for the writeable stream.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/promises.ts#L402-L420 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | _isParentOf | function _isParentOf(parent: string, child: string): boolean {
if (parent === '/' || parent === child) return true;
if (!parent.endsWith('/')) parent += '/';
return child.startsWith(parent);
} | /**
* @internal @hidden
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/shared.ts#L216-L222 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | applySetId | function applySetId(file: File, uid: number, gid: number) {
if (file.fs.attributes.has('setid')) return;
const parent = file.fs.statSync(dirname(file.path));
file.chownSync(
parent.mode & constants.S_ISUID ? parent.uid : uid, // manually apply setuid/setgid
parent.mode & constants.S_ISGID ? parent.gid : gid
);
} | /**
* Manually apply setuid/setgid.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/sync.ts#L128-L136 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | _resolveSync | function _resolveSync($: V_Context, path: string, preserveSymlinks?: boolean): ResolvedPath {
if (preserveSymlinks) {
const resolved = resolveMount(path, $);
const stats = resolved.fs.statSync(resolved.path);
return { ...resolved, fullPath: path, stats };
}
/* Try to resolve it directly. If this works,
that means we don't need to perform any resolution for parent directories. */
try {
const resolved = resolveMount(path, $);
// Stat it to make sure it exists
const stats = resolved.fs.statSync(resolved.path);
if (!stats.isSymbolicLink()) {
return { ...resolved, fullPath: path, stats };
}
const target = resolve(dirname(path), readlinkSync.call($, path).toString());
return _resolveSync($, target);
} catch {
// Go the long way
}
const { base, dir } = parse(path);
const realDir = dir == '/' ? '/' : realpathSync.call($, dir);
const maybePath = join(realDir, base);
const resolved = resolveMount(maybePath, $);
try {
const stats = resolved.fs.statSync(resolved.path);
if (!stats.isSymbolicLink()) {
return { ...resolved, fullPath: maybePath, stats };
}
const target = resolve(realDir, readlinkSync.call($, maybePath).toString());
return _resolveSync($, target);
} catch (e) {
if ((e as ErrnoError).code == 'ENOENT') {
return { ...resolved, fullPath: path };
}
throw fixError(e as ErrnoError, { [resolved.path]: maybePath });
}
} | /**
* Resolves the mount and real path for a path.
* Additionally, any stats fetched will be returned for de-duplication
* @internal @hidden
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/sync.ts#L707-L751 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Watcher.off | public off<T extends EventEmitter.EventNames<TEvents>>(event: T, fn?: (...args: any[]) => void, context?: any, once?: boolean): this {
return super.off<T>(event, fn as EventEmitter.EventListener<TEvents, T>, context, once);
} | /* eslint-disable @typescript-eslint/no-explicit-any */ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/watchers.ts#L20-L22 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | Watcher.constructor | public constructor(
/**
* @internal
*/
public readonly _context: V_Context,
public readonly path: string
) {
super();
} | /* eslint-enable @typescript-eslint/no-explicit-any */ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/watchers.ts#L29-L37 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | StatWatcher.stop | public stop() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
this.removeAllListeners();
} | /**
* @internal
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/vfs/watchers.ts#L159-L165 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | populate | async function populate(dir: string) {
await fs.promises.mkdir(dir + '/_rename_me');
await fs.promises.writeFile(dir + '/file.dat', 'filedata');
await fs.promises.writeFile(dir + '/_rename_me/lol.txt', 'lololol');
} | /**
* Creates the following directory structure within `dir`:
* - _rename_me
* - lol.txt
* - file.dat
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/tests/fs/rename.test.ts#L13-L17 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
core | github_2023 | zen-fs | typescript | check_directory | async function check_directory(dir: string) {
const contents = await fs.promises.readdir(dir);
assert.equal(contents.length, 2);
const subContents = await fs.promises.readdir(dir + '/_rename_me');
assert.equal(subContents.length, 1);
assert(await fs.promises.exists(dir + '/file.dat'));
assert(await fs.promises.exists(dir + '/_rename_me/lol.txt'));
} | /**
* Check that the directory structure created in populate_directory remains.
*/ | https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/tests/fs/rename.test.ts#L22-L31 | fea47188b8827aa31de2fc14974444c0d2b8fa9f |
scrapecomfort | github_2023 | Indie-Platforms | typescript | Extractor.findMostSimilarEmbedding | findMostSimilarEmbedding(targetEmbedding: number[], embeddings: number[][]) {
let mostSimilarIndex = 0;
let secondMostSimilarIndex = 0;
let highestSimilarity = -Infinity;
let secondHighestSimilarity = -Infinity;
for (let i = 0; i < embeddings.length; i++) {
const similarity = this.calculateSimilarity(
targetEmbedding,
embeddings[i]
);
if (similarity > highestSimilarity) {
highestSimilarity = similarity;
mostSimilarIndex = i;
}
if (
similarity > secondHighestSimilarity &&
similarity < highestSimilarity
) {
secondHighestSimilarity = similarity;
secondMostSimilarIndex = i;
}
}
return [mostSimilarIndex, secondMostSimilarIndex];
} | // Helper function to find the most similar embedding in a list | https://github.com/Indie-Platforms/scrapecomfort/blob/75c5d351954b34e6ba0057bba7295cd4285d5394/src/main/workers.ts#L395-L420 | 75c5d351954b34e6ba0057bba7295cd4285d5394 |
LynxHub | github_2023 | KindaBrazy | typescript | getArgumentProperty | function getArgumentProperty<K extends keyof ArgumentItem>(
name: string,
args: ArgumentsData | undefined,
property: K,
): ArgumentItem[K] | undefined {
if (!args) return undefined;
const arg = getArgumentByName(args, name);
return arg ? arg[property] : undefined;
} | /**
* Gets a specific property of an argument by its name.
* @param name - The name of the argument.
* @param args - The Arguments data structure to search in.
* @param property - The property to retrieve from the argument.
* @returns The value of the specified property, or undefined if not found.
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/cross/GetArgumentsData.ts#L76-L84 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | AppInitializer.checkGitAvailable | private async checkGitAvailable(): Promise<string> {
return new Promise((resolve, reject) => {
const commandProcess = spawn('git', ['--version']);
commandProcess.stdout.on('data', data => {
const versionParts = data.toString().trim().split(' ');
resolve(`V${versionParts.slice(2).join('.').trim()}`);
});
commandProcess.on('error', err => {
console.error('Failed to check version: ', err);
reject();
});
commandProcess.stderr.on('data', data => {
console.error('Failed to check version: ', data);
reject();
});
});
} | //#region Private Methods | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/AppInitializer.ts#L42-L59 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | AppInitializer.listenToChannels | private listenToChannels(): void {
// Handle app restart
ipcMain.on(initializerChannels.startApp, () => {
storageManager.updateData('app', {initialized: true});
app.relaunch();
app.exit();
});
// Handle window controls
ipcMain.on(initializerChannels.minimize, () => this.window?.minimize());
ipcMain.on(initializerChannels.close, () => this.window?.close());
// Handle version checks
ipcMain.handle(initializerChannels.gitAvailable, () => this.checkGitAvailable());
// Handle AI module installation
ipcMain.on(initializerChannels.installAIModule, this.handleInstallAIModule.bind(this));
} | /** Sets up IPC channel listeners for various initializing actions. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/AppInitializer.ts#L62-L79 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | AppInitializer.handleInstallAIModule | private async handleInstallAIModule(): Promise<void> {
const modulesPath = ModuleManager.getModulesPath();
const {repo} = extractGitUrl(MAIN_MODULE_URL);
const installPath = path.join(modulesPath, repo);
try {
// Remove existing installation if any
await fs.promises.rm(installPath, {recursive: true, force: true});
const gitManager = new GitManager();
gitManager.onProgress = progress => {
this.window?.webContents.send(initializerChannels.onInstallAIModule, '', 'Progress', progress);
};
gitManager.onError = (reason: string) => {
this.window?.webContents.send(initializerChannels.onInstallAIModule, '', 'Failed', reason);
};
gitManager.onComplete = () => {
this.window?.webContents.send(initializerChannels.onInstallAIModule, '', 'Completed', '');
};
await gitManager.clone(MAIN_MODULE_URL, installPath);
} catch (error) {
console.error('Failed to install AI module:', error);
this.window?.webContents.send(initializerChannels.onInstallAIModule, 'Failed');
}
} | /**
* Handles the installation of the AI module.
* Clone the repository and manage the installation process.
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/AppInitializer.ts#L85-L111 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | AppInitializer.createInitializer | public async createInitializer(): Promise<void> {
electronApp.setAppUserModelId(APP_NAME);
app.on('browser-window-created', (_, window) => {
optimizer.watchWindowShortcuts(window);
});
await app.whenReady();
this.window = new BrowserWindow(AppInitializer.WINDOW_CONFIG);
this.window.on('ready-to-show', () => {
this.window?.show();
});
this.listenToChannels();
this.window.webContents.setWindowOpenHandler(details => {
shell.openExternal(details.url);
return {action: 'deny'};
});
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
await this.window.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/initializer.html`);
} else {
await this.window.loadFile(path.join(__dirname, `../renderer/initializer.html`));
}
} | //#region Public Methods | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/AppInitializer.ts#L117-L144 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ValidateCards.startWatching | private startWatching(): void {
this.dirs.forEach(dir => {
const watcher = watch(dir, {depth: 0, persistent: true});
watcher.on('unlinkDir', this.handleUnlinkedDir);
this.watchers.push(watcher);
});
} | /**
* Starts watching the directories of the given cards for changes.
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DataValidator.ts#L31-L37 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ValidateCards.handleUnlinkedDir | private handleUnlinkedDir = (unlinkedPath: string): void => {
storageManager.removeInstalledCardByPath(unlinkedPath);
} | /**
* Handles the event when a watched directory is unlinked (removed).
* @param {string} unlinkedPath - The path of the unlinked directory
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DataValidator.ts | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ValidateCards.stopWatching | private stopWatching(): void {
this.watchers.forEach(watcher => watcher.close());
this.watchers = [];
} | /** Stops all active directory watchers. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DataValidator.ts#L48-L51 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ValidateCards.validateCards | private async validateCards(cards: InstalledCards): Promise<InstalledCards> {
const pathCards: PathCards[] = [];
const moduleCards: InstalledCards = [];
const onInstalledDirExist = async (card: InstalledCard) => {
if (card.dir) {
pathCards.push({id: card.id, dir: card.dir});
return await this.dirExist(card.dir);
}
return false;
};
for (const card of cards) {
const isInstalledMethod = moduleManager.getMethodsById(card.id)?.isInstalled;
if (isInstalledMethod) {
const lynxApi: LynxApiInstalled = {
installedDirExistAndWatch: onInstalledDirExist(card),
storage: {get: storageManager.getCustomData, set: storageManager.setCustomRun},
pty,
};
const installed = await isInstalledMethod(lynxApi);
if (installed) moduleCards.push(card);
} else if (card.dir && !path.basename(card.dir).startsWith('.')) {
const exist = await this.dirExist(card.dir);
if (exist) {
pathCards.push({id: card.id, dir: card.dir!});
}
}
}
this.dirs = new Set(pathCards.map(card => path.resolve(path.dirname(card.dir!))));
this.startWatching();
return [...pathCards, ...moduleCards];
} | /**
* Validates the given cards by checking if their directories are Git repositories.
* @param {InstalledCards} cards - The cards to validate
* @returns {Promise<InstalledCards>} Resolves to an array of valid cards
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DataValidator.ts#L69-L106 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ValidateCards.checkAndWatch | public async checkAndWatch(): Promise<void> {
const installedCards: InstalledCards = storageManager.getData('cards').installedCards;
const validCards = await this.validateCards(installedCards);
if (!lodash.isEqual(installedCards, validCards)) {
storageManager.updateData('cards', {installedCards: validCards});
}
} | /**
* Checks the validity of installed cards and sets up watchers for valid directories.
* @returns {Promise<void>}
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DataValidator.ts#L114-L122 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ValidateCards.changedCards | public changedCards(): void {
this.stopWatching();
this.checkAndWatch();
} | /** Restarts the watching process when cards have changed. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DataValidator.ts#L125-L128 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | DiscordRpcManager.constructor | constructor() {
this.startAppTimestamp = new Date();
this.client = new Client({clientId: ''});
this.client.on('ready', this.handleClientReady);
this.client.login().catch(console.error);
} | //#region Constructor | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DiscordRpcManager.ts#L35-L41 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | DiscordRpcManager.handleClientReady | private handleClientReady = (): void => {
this.isReadyToActivity = true;
} | //#region Private Methods | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DiscordRpcManager.ts | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | DiscordRpcManager.start | public start(): void {
this.updateDiscordRP();
if (this.discordRP?.LynxHub.Enabled) {
this.setActivity();
this.updateActivityLoop();
}
} | /**
* Starts the Discord RPC manager.
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DiscordRpcManager.ts#L135-L141 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | DiscordRpcManager.updateDiscordRP | public updateDiscordRP(): void {
this.discordRP = storageManager.getData('app').discordRP;
this.resetToDefaultActivity();
if (this.isReadyToActivity) {
if (!this.discordRP.LynxHub.Enabled) {
this.clearActivity();
} else if (!this.intervalRepeatActivity) {
this.updateActivityLoop();
}
}
} | /**
* Updates the Discord Rich Presence settings.
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DiscordRpcManager.ts#L146-L157 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | DiscordRpcManager.runningAI | public runningAI(status: DiscordRunningAI): void {
if (!this.discordRP?.LynxHub.Enabled && !status.running) {
this.clearActivity();
return;
}
if (!this.discordRP?.RunningAI.Enabled) {
return;
}
if (!status.running) {
this.resetToDefaultActivity();
return;
}
this.startAITimestamp = new Date();
this.activity = this.createActivityForStatus(status);
if (!this.intervalRepeatActivity) {
this.setActivity();
this.updateActivityLoop();
}
} | /**
* Updates the activity based on the AI running status.
* @param status - The current AI running status
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/DiscordRpcManager.ts#L163-L185 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.getMainWindow | public getMainWindow(): BrowserWindow | undefined {
return this.mainWindow;
} | //#region Getters | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L61-L63 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.createLoadingWindow | private createLoadingWindow(): void {
this.loadingWindow = new BrowserWindow(ElectronAppManager.LOADING_WINDOW_CONFIG);
this.setupLoadingWindowEventListeners();
this.loadAppropriateURL(this.loadingWindow, 'loading.html');
} | /** Creates and configures the loading window. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L74-L78 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.setupLoadingWindowEventListeners | private setupLoadingWindowEventListeners(): void {
this.loadingWindow?.on('close', () => {
this.loadingWindow = undefined;
});
this.loadingWindow?.on('ready-to-show', () => {
this.loadingWindow?.show();
this.isLoading = true;
});
} | /** Sets up event listeners for the loading window. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L81-L90 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.createMainWindow | private createMainWindow(): void {
this.mainWindow = new BrowserWindow(ElectronAppManager.MAIN_WINDOW_CONFIG);
this.setupMainWindowEventListeners();
this.loadAppropriateURL(this.mainWindow, 'index.html');
this.onCreateWindow?.();
} | /** Creates and configures the main application window. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L93-L98 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.setupMainWindowEventListeners | private setupMainWindowEventListeners(): void {
this.mainWindow?.on('ready-to-show', (): void => {
setTimeout(() => {
this.loadingWindow?.close();
this.onReadyToShow?.();
}, 1000);
});
this.mainWindow?.webContents.setWindowOpenHandler(({url}) => {
shell.openExternal(url).catch(e => {
console.error('Error on openExternal: ', e);
});
return {action: 'deny'};
});
this.mainWindow?.on('minimize', this.handleMinimize);
this.mainWindow?.on('focus', this.handleFocus);
const webContent = this.mainWindow?.webContents;
if (!webContent) return;
this.mainWindow?.on('focus', (): void => webContent.send(winChannels.onChangeState, {name: 'focus', value: true}));
this.mainWindow?.on('blur', (): void => webContent.send(winChannels.onChangeState, {name: 'focus', value: false}));
this.mainWindow?.on('maximize', (): void =>
webContent.send(winChannels.onChangeState, {
name: 'maximize',
value: true,
}),
);
this.mainWindow?.on('unmaximize', (): void =>
webContent.send(winChannels.onChangeState, {
name: 'maximize',
value: false,
}),
);
this.mainWindow?.on('enter-full-screen', (): void =>
webContent.send(winChannels.onChangeState, {
name: 'full-screen',
value: true,
}),
);
this.mainWindow?.on('leave-full-screen', (): void =>
webContent.send(winChannels.onChangeState, {
name: 'full-screen',
value: false,
}),
);
} | /** Sets up event listeners for the main window. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L101-L150 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.handleMinimize | private handleMinimize = (): void => {
if (storageManager.getData('app').taskbarStatus === 'tray-minimized') {
trayManager.createTrayIcon();
if (platform() === 'linux') {
this.mainWindow?.hide();
} else if (platform() === 'darwin' && app.dock.isVisible()) {
app.dock.hide();
} else {
this.mainWindow?.setSkipTaskbar(true);
}
}
} | /** Handles the minimized event for the main window. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.loadAppropriateURL | private loadAppropriateURL(window: BrowserWindow, htmlFile: string): void {
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
window.loadURL(`${process.env['ELECTRON_RENDERER_URL']}/${htmlFile}`);
} else {
window.loadFile(path.join(__dirname, `../renderer/${htmlFile}`));
}
} | /**
* Loads the appropriate URL based on the environment.
* @param window - The BrowserWindow to load the URL into.
* @param htmlFile - The HTML file to load in production mode.
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L183-L189 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.setupAppEventListeners | private setupAppEventListeners(): void {
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
} | /** Sets up global application event listeners. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L192-L198 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.restart | public restart(): void {
app.relaunch();
app.exit();
} | /** Restarts the application. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L205-L208 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | ElectronAppManager.startLoading | public startLoading(): void {
this.createLoadingWindow();
this.setupAppEventListeners();
} | /** Creates and initializes the application windows. */ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/ElectronAppManager.ts#L211-L214 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
LynxHub | github_2023 | KindaBrazy | typescript | GitManager.locateCard | public static async locateCard(url: string, dir?: string): Promise<string | undefined> {
let resultPath: string | undefined;
if (dir) {
resultPath = dir;
} else {
resultPath = await openDialog({properties: ['openDirectory']});
}
if (!resultPath) return undefined;
const remote = await this.remoteUrlFromDir(resultPath);
if (!remote) return undefined;
return validateGitRepoUrl(remote) === validateGitRepoUrl(url) ? resultPath : undefined;
} | /**
* Locates a card based on the repository URL.
* @param url - The URL of the repository.
* @param dir - Optional directory instead of user choosing
* @returns A promise that resolves to the path of the card or undefined.
*/ | https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L47-L62 | 16a4717552cc939cabefa69048c04a6d66380aa9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.