Skip to content

Commit

Permalink
fix: separate error emit from regular events
Browse files Browse the repository at this point in the history
Separates the error event arguments from the regular event arguments.

Before, we had a merged tuple of `[Path | Error, Stats?]` to account for
the fact that some events can be `[Path, Stats?]` and some can be
`[Error, Stats?]`.

However, this results in incorrect types since nothing will ever pass
`Path | Error` as a type (only one or the other).

This separates them and uses a union instead, such that event handlers
other than `error` only ever have a `Path`.
  • Loading branch information
43081j committed Dec 18, 2024
1 parent 3fa04b5 commit 322e851
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ export type FSWInstanceOptions = BasicOpts & {
};

export type ThrottleType = 'readdir' | 'watch' | 'add' | 'remove' | 'change';
export type EmitArgs = [Path | Error, Stats?];
export type EmitArgsWithName = [EventName, ...EmitArgs];
export type EmitArgs = [path: Path, stats?: Stats];
export type EmitErrorArgs = [error: Error, stats?: Stats];
export type EmitArgsWithName = [event: EventName, ...EmitArgs];
export type MatchFunction = (val: string, stats?: Stats) => boolean;
export interface MatcherObject {
path: string;
Expand Down Expand Up @@ -302,9 +303,7 @@ export interface FSWatcherKnownEventMap {
[EV.READY]: [];
[EV.RAW]: Parameters<WatchHandlers['rawEmitter']>;
[EV.ERROR]: Parameters<WatchHandlers['errHandler']>;
[EV.ALL]: [EventName, ...EmitArgs];
[EV.UNLINK]: [path: string];
[EV.UNLINK_DIR]: [path: string];
[EV.ALL]: [event: EventName, ...EmitArgs];
}

export type FSWatcherEventMap = FSWatcherKnownEventMap & {
Expand Down Expand Up @@ -604,7 +603,7 @@ export class FSWatcher extends EventEmitter<FSWatcherEventMap> {
const opts = this.options;
if (isWindows) path = sysPath.normalize(path);
if (opts.cwd) path = sysPath.relative(opts.cwd, path);
const args: EmitArgs = [path];
const args: EmitArgs | EmitErrorArgs = [path];
if (stats != null) args.push(stats);

const awf = opts.awaitWriteFinish;
Expand Down Expand Up @@ -639,7 +638,7 @@ export class FSWatcher extends EventEmitter<FSWatcherEventMap> {
const awfEmit = (err?: Error, stats?: Stats) => {
if (err) {
event = EV.ERROR;
args[0] = err;
(args as unknown as EmitErrorArgs)[0] = err;
this.emitWithAll(event, args);
} else if (stats) {
// if stats doesn't exist the file must have been deleted
Expand Down

0 comments on commit 322e851

Please sign in to comment.