@logosdx/hooks 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,830 @@
1
+ function _array_like_to_array(arr, len) {
2
+ if (len == null || len > arr.length) len = arr.length;
3
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
+ return arr2;
5
+ }
6
+ function _array_with_holes(arr) {
7
+ if (Array.isArray(arr)) return arr;
8
+ }
9
+ function _assert_this_initialized(self) {
10
+ if (self === void 0) {
11
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
12
+ }
13
+ return self;
14
+ }
15
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
16
+ try {
17
+ var info = gen[key](arg);
18
+ var value = info.value;
19
+ } catch (error) {
20
+ reject(error);
21
+ return;
22
+ }
23
+ if (info.done) {
24
+ resolve(value);
25
+ } else {
26
+ Promise.resolve(value).then(_next, _throw);
27
+ }
28
+ }
29
+ function _async_to_generator(fn) {
30
+ return function() {
31
+ var self = this, args = arguments;
32
+ return new Promise(function(resolve, reject) {
33
+ var gen = fn.apply(self, args);
34
+ function _next(value) {
35
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
36
+ }
37
+ function _throw(err) {
38
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
39
+ }
40
+ _next(undefined);
41
+ });
42
+ };
43
+ }
44
+ function _call_super(_this, derived, args) {
45
+ derived = _get_prototype_of(derived);
46
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
47
+ }
48
+ function _check_private_redeclaration(obj, privateCollection) {
49
+ if (privateCollection.has(obj)) {
50
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
51
+ }
52
+ }
53
+ function _class_apply_descriptor_get(receiver, descriptor) {
54
+ if (descriptor.get) {
55
+ return descriptor.get.call(receiver);
56
+ }
57
+ return descriptor.value;
58
+ }
59
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
60
+ if (descriptor.set) {
61
+ descriptor.set.call(receiver, value);
62
+ } else {
63
+ if (!descriptor.writable) {
64
+ throw new TypeError("attempted to set read only private field");
65
+ }
66
+ descriptor.value = value;
67
+ }
68
+ }
69
+ function _class_call_check(instance, Constructor) {
70
+ if (!(instance instanceof Constructor)) {
71
+ throw new TypeError("Cannot call a class as a function");
72
+ }
73
+ }
74
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
75
+ if (!privateMap.has(receiver)) {
76
+ throw new TypeError("attempted to " + action + " private field on non-instance");
77
+ }
78
+ return privateMap.get(receiver);
79
+ }
80
+ function _class_private_field_get(receiver, privateMap) {
81
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
82
+ return _class_apply_descriptor_get(receiver, descriptor);
83
+ }
84
+ function _class_private_field_init(obj, privateMap, value) {
85
+ _check_private_redeclaration(obj, privateMap);
86
+ privateMap.set(obj, value);
87
+ }
88
+ function _class_private_field_set(receiver, privateMap, value) {
89
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
90
+ _class_apply_descriptor_set(receiver, descriptor, value);
91
+ return value;
92
+ }
93
+ function _construct(Parent, args, Class) {
94
+ if (_is_native_reflect_construct()) {
95
+ _construct = Reflect.construct;
96
+ } else {
97
+ _construct = function construct(Parent, args, Class) {
98
+ var a = [
99
+ null
100
+ ];
101
+ a.push.apply(a, args);
102
+ var Constructor = Function.bind.apply(Parent, a);
103
+ var instance = new Constructor();
104
+ if (Class) _set_prototype_of(instance, Class.prototype);
105
+ return instance;
106
+ };
107
+ }
108
+ return _construct.apply(null, arguments);
109
+ }
110
+ function _defineProperties(target, props) {
111
+ for(var i = 0; i < props.length; i++){
112
+ var descriptor = props[i];
113
+ descriptor.enumerable = descriptor.enumerable || false;
114
+ descriptor.configurable = true;
115
+ if ("value" in descriptor) descriptor.writable = true;
116
+ Object.defineProperty(target, descriptor.key, descriptor);
117
+ }
118
+ }
119
+ function _create_class(Constructor, protoProps, staticProps) {
120
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
121
+ if (staticProps) _defineProperties(Constructor, staticProps);
122
+ return Constructor;
123
+ }
124
+ function _define_property(obj, key, value) {
125
+ if (key in obj) {
126
+ Object.defineProperty(obj, key, {
127
+ value: value,
128
+ enumerable: true,
129
+ configurable: true,
130
+ writable: true
131
+ });
132
+ } else {
133
+ obj[key] = value;
134
+ }
135
+ return obj;
136
+ }
137
+ function _get_prototype_of(o) {
138
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
139
+ return o.__proto__ || Object.getPrototypeOf(o);
140
+ };
141
+ return _get_prototype_of(o);
142
+ }
143
+ function _inherits(subClass, superClass) {
144
+ if (typeof superClass !== "function" && superClass !== null) {
145
+ throw new TypeError("Super expression must either be null or a function");
146
+ }
147
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
148
+ constructor: {
149
+ value: subClass,
150
+ writable: true,
151
+ configurable: true
152
+ }
153
+ });
154
+ if (superClass) _set_prototype_of(subClass, superClass);
155
+ }
156
+ function _instanceof(left, right) {
157
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
158
+ return !!right[Symbol.hasInstance](left);
159
+ } else {
160
+ return left instanceof right;
161
+ }
162
+ }
163
+ function _is_native_function(fn) {
164
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
165
+ }
166
+ function _iterable_to_array_limit(arr, i) {
167
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
168
+ if (_i == null) return;
169
+ var _arr = [];
170
+ var _n = true;
171
+ var _d = false;
172
+ var _s, _e;
173
+ try {
174
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
175
+ _arr.push(_s.value);
176
+ if (i && _arr.length === i) break;
177
+ }
178
+ } catch (err) {
179
+ _d = true;
180
+ _e = err;
181
+ } finally{
182
+ try {
183
+ if (!_n && _i["return"] != null) _i["return"]();
184
+ } finally{
185
+ if (_d) throw _e;
186
+ }
187
+ }
188
+ return _arr;
189
+ }
190
+ function _non_iterable_rest() {
191
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
192
+ }
193
+ function _object_spread(target) {
194
+ for(var i = 1; i < arguments.length; i++){
195
+ var source = arguments[i] != null ? arguments[i] : {};
196
+ var ownKeys = Object.keys(source);
197
+ if (typeof Object.getOwnPropertySymbols === "function") {
198
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
199
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
200
+ }));
201
+ }
202
+ ownKeys.forEach(function(key) {
203
+ _define_property(target, key, source[key]);
204
+ });
205
+ }
206
+ return target;
207
+ }
208
+ function _possible_constructor_return(self, call) {
209
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
210
+ return call;
211
+ }
212
+ return _assert_this_initialized(self);
213
+ }
214
+ function _set_prototype_of(o, p) {
215
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
216
+ o.__proto__ = p;
217
+ return o;
218
+ };
219
+ return _set_prototype_of(o, p);
220
+ }
221
+ function _sliced_to_array(arr, i) {
222
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
223
+ }
224
+ function _type_of(obj) {
225
+ "@swc/helpers - typeof";
226
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
227
+ }
228
+ function _unsupported_iterable_to_array(o, minLen) {
229
+ if (!o) return;
230
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
231
+ var n = Object.prototype.toString.call(o).slice(8, -1);
232
+ if (n === "Object" && o.constructor) n = o.constructor.name;
233
+ if (n === "Map" || n === "Set") return Array.from(n);
234
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
235
+ }
236
+ function _wrap_native_super(Class) {
237
+ var _cache = typeof Map === "function" ? new Map() : undefined;
238
+ _wrap_native_super = function wrapNativeSuper(Class) {
239
+ if (Class === null || !_is_native_function(Class)) return Class;
240
+ if (typeof Class !== "function") {
241
+ throw new TypeError("Super expression must either be null or a function");
242
+ }
243
+ if (typeof _cache !== "undefined") {
244
+ if (_cache.has(Class)) return _cache.get(Class);
245
+ _cache.set(Class, Wrapper);
246
+ }
247
+ function Wrapper() {
248
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
249
+ }
250
+ Wrapper.prototype = Object.create(Class.prototype, {
251
+ constructor: {
252
+ value: Wrapper,
253
+ enumerable: false,
254
+ writable: true,
255
+ configurable: true
256
+ }
257
+ });
258
+ return _set_prototype_of(Wrapper, Class);
259
+ };
260
+ return _wrap_native_super(Class);
261
+ }
262
+ function _is_native_reflect_construct() {
263
+ try {
264
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
265
+ } catch (_) {}
266
+ return (_is_native_reflect_construct = function() {
267
+ return !!result;
268
+ })();
269
+ }
270
+ function _ts_generator(thisArg, body) {
271
+ var f, y, t, _ = {
272
+ label: 0,
273
+ sent: function() {
274
+ if (t[0] & 1) throw t[1];
275
+ return t[1];
276
+ },
277
+ trys: [],
278
+ ops: []
279
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
280
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
281
+ return this;
282
+ }), g;
283
+ function verb(n) {
284
+ return function(v) {
285
+ return step([
286
+ n,
287
+ v
288
+ ]);
289
+ };
290
+ }
291
+ function step(op) {
292
+ if (f) throw new TypeError("Generator is already executing.");
293
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
294
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
295
+ if (y = 0, t) op = [
296
+ op[0] & 2,
297
+ t.value
298
+ ];
299
+ switch(op[0]){
300
+ case 0:
301
+ case 1:
302
+ t = op;
303
+ break;
304
+ case 4:
305
+ _.label++;
306
+ return {
307
+ value: op[1],
308
+ done: false
309
+ };
310
+ case 5:
311
+ _.label++;
312
+ y = op[1];
313
+ op = [
314
+ 0
315
+ ];
316
+ continue;
317
+ case 7:
318
+ op = _.ops.pop();
319
+ _.trys.pop();
320
+ continue;
321
+ default:
322
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
323
+ _ = 0;
324
+ continue;
325
+ }
326
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
327
+ _.label = op[1];
328
+ break;
329
+ }
330
+ if (op[0] === 6 && _.label < t[1]) {
331
+ _.label = t[1];
332
+ t = op;
333
+ break;
334
+ }
335
+ if (t && _.label < t[2]) {
336
+ _.label = t[2];
337
+ _.ops.push(op);
338
+ break;
339
+ }
340
+ if (t[2]) _.ops.pop();
341
+ _.trys.pop();
342
+ continue;
343
+ }
344
+ op = body.call(thisArg, _);
345
+ } catch (e) {
346
+ op = [
347
+ 6,
348
+ e
349
+ ];
350
+ y = 0;
351
+ } finally{
352
+ f = t = 0;
353
+ }
354
+ if (op[0] & 5) throw op[1];
355
+ return {
356
+ value: op[0] ? op[1] : void 0,
357
+ done: true
358
+ };
359
+ }
360
+ }
361
+ function _ts_values(o) {
362
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
363
+ if (m) return m.call(o);
364
+ if (o && typeof o.length === "number") return {
365
+ next: function() {
366
+ if (o && i >= o.length) o = void 0;
367
+ return {
368
+ value: o && o[i++],
369
+ done: !o
370
+ };
371
+ }
372
+ };
373
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
374
+ }
375
+ import { assert, attempt, isFunction, isObject } from '@logosdx/utils';
376
+ /**
377
+ * Error thrown when a hook extension calls `fail()` or when hook execution fails.
378
+ *
379
+ * @example
380
+ * engine.extend('save', 'before', async (ctx) => {
381
+ * if (!ctx.args[0].isValid) {
382
+ * ctx.fail('Validation failed');
383
+ * }
384
+ * });
385
+ *
386
+ * const [, err] = await attempt(() => app.save(data));
387
+ * if (isHookError(err)) {
388
+ * console.log(err.hookName); // 'save'
389
+ * console.log(err.extPoint); // 'before'
390
+ * }
391
+ */ export var HookError = /*#__PURE__*/ function(Error1) {
392
+ "use strict";
393
+ _inherits(HookError, Error1);
394
+ function HookError(message) {
395
+ _class_call_check(this, HookError);
396
+ var _this;
397
+ _this = _call_super(this, HookError, [
398
+ message
399
+ ]), /** Name of the hook where the error occurred */ _define_property(_this, "hookName", void 0), /** Extension point where the error occurred: 'before', 'after', or 'error' */ _define_property(_this, "extPoint", void 0), /** Original error if `fail()` was called with an Error instance */ _define_property(_this, "originalError", void 0), /** Whether the hook was explicitly aborted via `fail()` */ _define_property(_this, "aborted", false);
400
+ return _this;
401
+ }
402
+ return HookError;
403
+ }(_wrap_native_super(Error));
404
+ /**
405
+ * Type guard to check if an error is a HookError.
406
+ *
407
+ * @example
408
+ * const [result, err] = await attempt(() => app.save(data));
409
+ * if (isHookError(err)) {
410
+ * console.log(`Hook "${err.hookName}" failed at "${err.extPoint}"`);
411
+ * }
412
+ */ export var isHookError = function(error) {
413
+ var _error_constructor;
414
+ return (error === null || error === void 0 ? void 0 : (_error_constructor = error.constructor) === null || _error_constructor === void 0 ? void 0 : _error_constructor.name) === HookError.name;
415
+ };
416
+ var Hook = function Hook() {
417
+ "use strict";
418
+ _class_call_check(this, Hook);
419
+ _define_property(this, "before", new Set());
420
+ _define_property(this, "after", new Set());
421
+ _define_property(this, "error", new Set());
422
+ };
423
+ var allowedExtPoints = new Set([
424
+ 'before',
425
+ 'after',
426
+ 'error'
427
+ ]);
428
+ var _registered = /*#__PURE__*/ new WeakMap(), _hooks = /*#__PURE__*/ new WeakMap(), _hookFnOpts = /*#__PURE__*/ new WeakMap(), _wrapped = /*#__PURE__*/ new WeakMap();
429
+ /**
430
+ * A lightweight, type-safe hook system for extending function behavior.
431
+ *
432
+ * HookEngine allows you to wrap functions and add extensions that run
433
+ * before, after, or on error. Extensions can modify arguments, change
434
+ * results, or abort execution entirely.
435
+ *
436
+ * @example
437
+ * interface MyApp {
438
+ * save(data: Data): Promise<Result>;
439
+ * load(id: string): Promise<Data>;
440
+ * }
441
+ *
442
+ * const app = new MyAppImpl();
443
+ * const hooks = new HookEngine<MyApp>();
444
+ *
445
+ * // Wrap a method to make it hookable
446
+ * hooks.wrap(app, 'save');
447
+ *
448
+ * // Add a validation extension
449
+ * hooks.extend('save', 'before', async (ctx) => {
450
+ * if (!ctx.args[0].isValid) {
451
+ * ctx.fail('Validation failed');
452
+ * }
453
+ * });
454
+ *
455
+ * // Add logging extension
456
+ * hooks.extend('save', 'after', async (ctx) => {
457
+ * console.log('Saved:', ctx.results);
458
+ * });
459
+ *
460
+ * @typeParam Shape - Interface defining the hookable functions
461
+ */ export var HookEngine = /*#__PURE__*/ function() {
462
+ "use strict";
463
+ function HookEngine() {
464
+ _class_call_check(this, HookEngine);
465
+ _class_private_field_init(this, _registered, {
466
+ writable: true,
467
+ value: new Set()
468
+ });
469
+ _class_private_field_init(this, _hooks, {
470
+ writable: true,
471
+ value: new Map()
472
+ });
473
+ _class_private_field_init(this, _hookFnOpts, {
474
+ writable: true,
475
+ value: new WeakMap()
476
+ });
477
+ _class_private_field_init(this, _wrapped, {
478
+ writable: true,
479
+ value: new WeakMap()
480
+ });
481
+ }
482
+ _create_class(HookEngine, [
483
+ {
484
+ /**
485
+ * Add an extension to a registered hook.
486
+ *
487
+ * Extensions run at specific points in the hook lifecycle:
488
+ * - `before`: Runs before the original function. Can modify args or return early.
489
+ * - `after`: Runs after successful execution. Can modify the result.
490
+ * - `error`: Runs when the original function throws. Can handle or transform errors.
491
+ *
492
+ * @param name - Name of the registered hook to extend
493
+ * @param extensionPoint - When to run: 'before', 'after', or 'error'
494
+ * @param cbOrOpts - Extension callback or options object
495
+ * @returns Cleanup function to remove the extension
496
+ *
497
+ * @example
498
+ * // Simple callback
499
+ * const cleanup = hooks.extend('save', 'before', async (ctx) => {
500
+ * console.log('About to save:', ctx.args);
501
+ * });
502
+ *
503
+ * // With options
504
+ * hooks.extend('save', 'after', {
505
+ * callback: async (ctx) => { console.log('Saved!'); },
506
+ * once: true, // Remove after first run
507
+ * ignoreOnFail: true // Don't throw if this extension fails
508
+ * });
509
+ *
510
+ * // Later: remove the extension
511
+ * cleanup();
512
+ */ key: "extend",
513
+ value: function extend(name, extensionPoint, cbOrOpts) {
514
+ var callback = typeof cbOrOpts === 'function' ? cbOrOpts : cbOrOpts === null || cbOrOpts === void 0 ? void 0 : cbOrOpts.callback;
515
+ var opts = typeof cbOrOpts === 'function' ? {} : cbOrOpts;
516
+ assert(typeof name === 'string', '"name" must be a string');
517
+ assert(_class_private_field_get(this, _registered).has(name), "'".concat(name.toString(), "' is not a registered hook"));
518
+ assert(typeof extensionPoint === 'string', '"extensionPoint" must be a string');
519
+ assert(allowedExtPoints.has(extensionPoint), "'".concat(extensionPoint, "' is not a valid extension point"));
520
+ assert(isFunction(callback) || isObject(cbOrOpts), '"cbOrOpts" must be a extension callback or options');
521
+ assert(isFunction(callback), 'callback must be a function');
522
+ var _class_private_field_get_get;
523
+ var hook = (_class_private_field_get_get = _class_private_field_get(this, _hooks).get(name)) !== null && _class_private_field_get_get !== void 0 ? _class_private_field_get_get : new Hook();
524
+ hook[extensionPoint].add(callback);
525
+ _class_private_field_get(this, _hooks).set(name, hook);
526
+ _class_private_field_get(this, _hookFnOpts).set(callback, opts);
527
+ /**
528
+ * Removes the registered hook extension
529
+ */ return function() {
530
+ hook[extensionPoint].delete(callback);
531
+ };
532
+ }
533
+ },
534
+ {
535
+ /**
536
+ * Register a function as a hookable and return the wrapped version.
537
+ *
538
+ * The wrapped function behaves identically to the original but allows
539
+ * extensions to be added via `extend()`. Use `wrap()` for a simpler API
540
+ * when working with object methods.
541
+ *
542
+ * @param name - Unique name for this hook (must match a key in Shape)
543
+ * @param cb - The original function to wrap
544
+ * @param opts - Options for the wrapped function
545
+ * @returns Wrapped function with hook support
546
+ *
547
+ * @example
548
+ * const hooks = new HookEngine<{ fetch: typeof fetch }>();
549
+ *
550
+ * const hookedFetch = hooks.make('fetch', fetch);
551
+ *
552
+ * hooks.extend('fetch', 'before', async (ctx) => {
553
+ * console.log('Fetching:', ctx.args[0]);
554
+ * });
555
+ *
556
+ * await hookedFetch('/api/data');
557
+ */ key: "make",
558
+ value: function make(name, cb) {
559
+ var opts = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
560
+ var _this = this;
561
+ assert(typeof name === 'string', '"name" must be a string');
562
+ assert(!_class_private_field_get(this, _registered).has(name), "'".concat(name.toString(), "' hook is already registered"));
563
+ assert(isFunction(cb), '"cb" must be a function');
564
+ assert(isObject(opts), '"opts" must be an object');
565
+ _class_private_field_get(this, _registered).add(name);
566
+ if (_class_private_field_get(this, _wrapped).has(cb)) {
567
+ return _class_private_field_get(this, _wrapped).get(cb);
568
+ }
569
+ var callback = function() {
570
+ for(var _len = arguments.length, origArgs = new Array(_len), _key = 0; _key < _len; _key++){
571
+ origArgs[_key] = arguments[_key];
572
+ }
573
+ return _async_to_generator(function() {
574
+ var _this, returnEarly, hook, context, _ref, before, after, errorFns, handleSet, _ref1, res, err;
575
+ return _ts_generator(this, function(_state) {
576
+ switch(_state.label){
577
+ case 0:
578
+ _this = this;
579
+ returnEarly = false;
580
+ hook = _class_private_field_get(this, _hooks).get(name);
581
+ context = {
582
+ args: origArgs,
583
+ point: 'before',
584
+ removeHook: function removeHook() {},
585
+ returnEarly: function returnEarly1() {
586
+ returnEarly = true;
587
+ },
588
+ setArgs: function setArgs(next) {
589
+ assert(Array.isArray(next), "setArgs: next args for '".concat(context.point, "' '").concat(name.toString(), "' must be an array of arguments"));
590
+ context.args = next;
591
+ },
592
+ setResult: function setResult(next) {
593
+ context.results = next;
594
+ },
595
+ fail: function fail(reason) {
596
+ var error = new HookError("Hook Aborted: ".concat(reason !== null && reason !== void 0 ? reason : 'unknown'));
597
+ if (_instanceof(reason, Error)) {
598
+ error.originalError = reason;
599
+ }
600
+ error.extPoint = context.point;
601
+ error.hookName = name;
602
+ throw error;
603
+ }
604
+ };
605
+ _ref = hook !== null && hook !== void 0 ? hook : new Hook(), before = _ref.before, after = _ref.after, errorFns = _ref.error;
606
+ handleSet = function(which, point) {
607
+ return _async_to_generator(function() {
608
+ var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _this, _loop, _iterator, _step, _ret, err;
609
+ return _ts_generator(this, function(_state) {
610
+ switch(_state.label){
611
+ case 0:
612
+ context.point = point;
613
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
614
+ _state.label = 1;
615
+ case 1:
616
+ _state.trys.push([
617
+ 1,
618
+ 6,
619
+ 7,
620
+ 8
621
+ ]);
622
+ _loop = function() {
623
+ var fn, opts, _ref, _$err;
624
+ return _ts_generator(this, function(_state) {
625
+ switch(_state.label){
626
+ case 0:
627
+ fn = _step.value;
628
+ context.removeHook = function() {
629
+ return which.delete(fn);
630
+ };
631
+ opts = _class_private_field_get(_this, _hookFnOpts).get(fn);
632
+ return [
633
+ 4,
634
+ attempt(function() {
635
+ return fn(_object_spread({}, context));
636
+ })
637
+ ];
638
+ case 1:
639
+ _ref = _sliced_to_array.apply(void 0, [
640
+ _state.sent(),
641
+ 2
642
+ ]), _$err = _ref[1];
643
+ if (opts.once) context.removeHook();
644
+ if (_$err && opts.ignoreOnFail !== true) {
645
+ throw _$err;
646
+ }
647
+ if (returnEarly) return [
648
+ 2,
649
+ "break"
650
+ ];
651
+ return [
652
+ 2
653
+ ];
654
+ }
655
+ });
656
+ };
657
+ _iterator = which[Symbol.iterator]();
658
+ _state.label = 2;
659
+ case 2:
660
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
661
+ 3,
662
+ 5
663
+ ];
664
+ _this = this;
665
+ return [
666
+ 5,
667
+ _ts_values(_loop())
668
+ ];
669
+ case 3:
670
+ _ret = _state.sent();
671
+ if (_ret === "break") return [
672
+ 3,
673
+ 5
674
+ ];
675
+ _state.label = 4;
676
+ case 4:
677
+ _iteratorNormalCompletion = true;
678
+ return [
679
+ 3,
680
+ 2
681
+ ];
682
+ case 5:
683
+ return [
684
+ 3,
685
+ 8
686
+ ];
687
+ case 6:
688
+ err = _state.sent();
689
+ _didIteratorError = true;
690
+ _iteratorError = err;
691
+ return [
692
+ 3,
693
+ 8
694
+ ];
695
+ case 7:
696
+ try {
697
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
698
+ _iterator.return();
699
+ }
700
+ } finally{
701
+ if (_didIteratorError) {
702
+ throw _iteratorError;
703
+ }
704
+ }
705
+ return [
706
+ 7
707
+ ];
708
+ case 8:
709
+ return [
710
+ 2
711
+ ];
712
+ }
713
+ });
714
+ }).call(_this);
715
+ };
716
+ return [
717
+ 4,
718
+ handleSet(before, 'before')
719
+ ];
720
+ case 1:
721
+ _state.sent();
722
+ if (returnEarly) return [
723
+ 2,
724
+ context.results
725
+ ];
726
+ return [
727
+ 4,
728
+ attempt(function() {
729
+ return cb.apply((opts === null || opts === void 0 ? void 0 : opts.bindTo) || cb, context.args);
730
+ })
731
+ ];
732
+ case 2:
733
+ _ref1 = _sliced_to_array.apply(void 0, [
734
+ _state.sent(),
735
+ 2
736
+ ]), res = _ref1[0], err = _ref1[1];
737
+ context.results = res;
738
+ context.error = err;
739
+ if (!err) return [
740
+ 3,
741
+ 4
742
+ ];
743
+ context.point = 'error';
744
+ return [
745
+ 4,
746
+ handleSet(errorFns, 'error')
747
+ ];
748
+ case 3:
749
+ _state.sent();
750
+ throw err;
751
+ case 4:
752
+ return [
753
+ 4,
754
+ handleSet(after, 'after')
755
+ ];
756
+ case 5:
757
+ _state.sent();
758
+ return [
759
+ 2,
760
+ context.results
761
+ ];
762
+ }
763
+ });
764
+ }).call(_this);
765
+ };
766
+ return callback;
767
+ }
768
+ },
769
+ {
770
+ /**
771
+ * Wrap an object method in-place to make it hookable.
772
+ *
773
+ * This is a convenience method that combines `make()` with automatic
774
+ * binding and reassignment. The method is replaced on the instance
775
+ * with the wrapped version.
776
+ *
777
+ * @param instance - Object containing the method to wrap
778
+ * @param name - Name of the method to wrap
779
+ * @param opts - Additional options
780
+ *
781
+ * @example
782
+ * class UserService {
783
+ * async save(user: User) { ... }
784
+ * }
785
+ *
786
+ * const service = new UserService();
787
+ * const hooks = new HookEngine<UserService>();
788
+ *
789
+ * hooks.wrap(service, 'save');
790
+ *
791
+ * // Now service.save() is hookable
792
+ * hooks.extend('save', 'before', async (ctx) => {
793
+ * console.log('Saving user:', ctx.args[0]);
794
+ * });
795
+ */ key: "wrap",
796
+ value: function wrap(instance, name, opts) {
797
+ assert(isObject(instance), '"instance" must be an object');
798
+ var wrapped = this.make(name, instance[name], _object_spread({
799
+ bindTo: instance
800
+ }, opts));
801
+ _class_private_field_get(this, _wrapped).set(wrapped, instance[name]);
802
+ instance[name] = wrapped;
803
+ }
804
+ },
805
+ {
806
+ /**
807
+ * Clear all registered hooks and extensions.
808
+ *
809
+ * After calling this method, all hooks are unregistered and all
810
+ * extensions are removed. Previously wrapped functions will continue
811
+ * to work but without any extensions.
812
+ *
813
+ * @example
814
+ * hooks.wrap(app, 'save');
815
+ * hooks.extend('save', 'before', validator);
816
+ *
817
+ * // Reset for testing
818
+ * hooks.clear();
819
+ *
820
+ * // app.save() still works, but validator no longer runs
821
+ */ key: "clear",
822
+ value: function clear() {
823
+ _class_private_field_get(this, _registered).clear();
824
+ _class_private_field_get(this, _hooks).clear();
825
+ _class_private_field_set(this, _hookFnOpts, new WeakMap());
826
+ }
827
+ }
828
+ ]);
829
+ return HookEngine;
830
+ }();