File size: 5,944 Bytes
4e23b01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { describe, expect, it } from 'vitest';

import { OrderedHookSlot, createHooks } from '#/hooks';

describe('OrderedHookSlot', () => {
  it('runs the terminal when no handlers are registered', async () => {
    const slot = new OrderedHookSlot<{ value: number }>();
    let terminalRan = false;
    await slot.run({ value: 0 }, async () => {
      terminalRan = true;
    });
    expect(terminalRan).toBe(true);
  });

  it('runs handlers in registration order and threads context', async () => {
    const slot = new OrderedHookSlot<{ value: number }>();
    const order: string[] = [];
    slot.register('a', async (ctx, next) => {
      order.push('a');
      ctx.value += 1;
      await next();
    });
    slot.register('b', async (ctx, next) => {
      order.push('b');
      ctx.value += 10;
      await next();
    });
    const ctx = { value: 0 };
    await slot.run(ctx);
    expect(order).toEqual(['a', 'b']);
    expect(ctx.value).toBe(11);
  });

  it('removes a handler with delete()', async () => {
    const slot = new OrderedHookSlot<Record<string, never>>();
    const order: string[] = [];
    slot.register('a', async (_ctx, next) => {
      order.push('a');
      await next();
    });
    slot.register('b', async (_ctx, next) => {
      order.push('b');
      await next();
    });
    expect(slot.delete('a')).toBe(true);
    await slot.run({});
    expect(order).toEqual(['b']);
  });

  it('honors before / after ordering', async () => {
    const slot = new OrderedHookSlot<Record<string, never>>();
    const order: string[] = [];
    const mk =
      (id: string) =>
      async (_ctx: Record<string, never>, next: () => Promise<void>) => {
        order.push(id);
        await next();
      };
    slot.register('a', mk('a'));
    slot.register('c', mk('c'));
    slot.register('b', mk('b'), { before: 'c' });
    await slot.run({});
    expect(order).toEqual(['a', 'b', 'c']);
  });

  it('re-runs the remaining chain when next() is called more than once', async () => {
    const slot = new OrderedHookSlot<Record<string, never>>();
    let terminalRuns = 0;
    slot.register('a', async (_ctx, next) => {
      await next();
      await next();
    });
    await slot.run({}, async () => {
      terminalRuns += 1;
    });
    expect(terminalRuns).toBe(2);
  });

  it('skips downstream handlers and the terminal when next() is not called', async () => {
    const slot = new OrderedHookSlot<{ value: number }>();
    const order: string[] = [];
    slot.register('veto', () => {
      order.push('veto');
    });
    slot.register('downstream', async (_ctx, next) => {
      order.push('downstream');
      await next();
    });
    let terminalRan = false;
    await slot.run({ value: 0 }, async () => {
      terminalRan = true;
    });
    expect(order).toEqual(['veto']);
    expect(terminalRan).toBe(false);
  });

  it('re-runs the remaining chain and terminal on each next() call', async () => {
    const slot = new OrderedHookSlot<{ attempt: number; result?: string }>();
    const attempts: number[] = [];
    slot.register('retry', async (ctx, next) => {
      ctx.attempt = 1;
      await next();
      if (ctx.result === 'fail') {
        ctx.attempt = 2;
        await next();
      }
    });
    slot.register('downstream', async (ctx, next) => {
      attempts.push(ctx.attempt);
      await next();
    });
    const ctx: { attempt: number; result?: string } = { attempt: 0 };
    await slot.run(ctx, async (current) => {
      current.result = current.attempt === 1 ? 'fail' : 'ok';
    });
    expect(attempts).toEqual([1, 2]);
    expect(ctx.result).toBe('ok');
  });

  it('resumes the remaining chain and terminal with a forked context', async () => {
    interface Ctx {
      readonly id: number;
      value: number;
      result?: number;
    }
    const slot = new OrderedHookSlot<Ctx>();
    const seen: number[] = [];
    slot.register('fork', async (ctx, next) => {
      const fork: Ctx = { ...ctx, value: 100 };
      await next(fork);
      ctx.result = fork.result;
    });
    slot.register('downstream', async (ctx, next) => {
      seen.push(ctx.value);
      await next();
    });
    const original: Ctx = { id: 1, value: 0 };
    await slot.run(original, async (current) => {
      current.result = current.value + 1;
    });
    expect(seen).toEqual([100]);
    expect(original.value).toBe(0);
    expect(original.result).toBe(101);
  });

  it('propagates a fork through nested next() calls without arguments', async () => {
    interface Ctx {
      value: number;
    }
    const slot = new OrderedHookSlot<Ctx>();
    slot.register('fork', async (ctx, next) => {
      await next({ ...ctx, value: 42 });
    });
    slot.register('middle', async (_ctx, next) => {
      await next();
    });
    let terminalValue: number | undefined;
    await slot.run({ value: 0 }, async (current) => {
      terminalValue = current.value;
    });
    expect(terminalValue).toBe(42);
  });

  it('runs forked branches concurrently', async () => {
    interface Ctx {
      input: number;
      output?: number;
    }
    const slot = new OrderedHookSlot<Ctx>();
    slot.register('race', async (ctx, next) => {
      const forks: Ctx[] = [
        { ...ctx, input: 1 },
        { ...ctx, input: 2 },
      ];
      await Promise.all(forks.map((fork) => next(fork)));
      ctx.output = Math.max(...forks.map((fork) => fork.output ?? 0));
    });
    const ctx: Ctx = { input: 0 };
    await slot.run(ctx, async (current) => {
      current.output = current.input * 10;
    });
    expect(ctx.output).toBe(20);
  });
});

describe('createHooks', () => {
  it('creates one slot per event key', () => {
    type HookEvents = { start: { x: number }; stop: { y: number } };
    const hooks = createHooks<HookEvents, keyof HookEvents>(['start', 'stop']);
    expect(hooks.start).toBeInstanceOf(OrderedHookSlot);
    expect(hooks.stop).toBeInstanceOf(OrderedHookSlot);
  });
});