Socket
Socket
Sign inDemoInstall

@feathersjs/hooks

Package Overview
Dependencies
0
Maintainers
4
Versions
22
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.5.0 to 0.6.0

lib/hooks.d.ts

11

CHANGELOG.md

@@ -6,2 +6,13 @@ # Change Log

# [0.6.0](https://github.com/feathersjs/hooks/compare/v0.5.0...v0.6.0) (2020-11-12)
### Features
* **hooks:** Revert refactoring into separate hooks (PR [#37](https://github.com/feathersjs/hooks/issues/37)) ([#57](https://github.com/feathersjs/hooks/issues/57)) ([56a44be](https://github.com/feathersjs/hooks/commit/56a44beb3388873f7bef12ac640f115beffceb95))
# [0.5.0](https://github.com/feathersjs/hooks/compare/v0.5.0-alpha.0...v0.5.0) (2020-06-01)

@@ -8,0 +19,0 @@

149

deno/base.ts
import { Middleware } from './compose.ts';
import { copyToSelf } from './utils';

@@ -7,2 +8,5 @@ export const HOOKS: string = Symbol('@feathersjs/hooks') as any;

/**
* The base hook context.
*/
export class HookContext<T = any, C = any> {

@@ -22,7 +26,10 @@ result?: T;

export type HookDefaultsInitializer = (context: HookContext) => HookContextData;
export type HookDefaultsInitializer = (self?: any, args?: any[], context?: HookContext) => HookContextData;
export class HookManager {
_parent?: this|null = null;
_middleware: Middleware[] = [];
_params: string[]|null = null;
_middleware: Middleware[]|null = null;
_props: HookContextData|null = null;
_defaults: HookDefaultsInitializer;

@@ -35,4 +42,4 @@ parent (parent: this) {

middleware (middleware: Middleware[]) {
this._middleware = middleware;
middleware (middleware?: Middleware[]) {
this._middleware = middleware?.length ? middleware : null;

@@ -42,21 +49,119 @@ return this;

getContextClass (): HookContextConstructor {
return HookContext;
}
getMiddleware (): Middleware[]|null {
const previous = this._parent?.getMiddleware();
getMiddleware (): Middleware[] {
const previous = this._parent ? this._parent.getMiddleware() : [];
if (previous) {
if (this._middleware) {
return previous.concat(this._middleware);
}
return previous.concat(this._middleware);
return previous;
}
return this._middleware;
}
collectMiddleware (self: any, _args: any[]): Middleware[] {
collectMiddleware (self: any, _args: any[]): Middleware[] {
const otherMiddleware = getMiddleware(self);
const middleware = this.getMiddleware();
return otherMiddleware.concat(this.getMiddleware());
if (otherMiddleware) {
if (middleware) {
return otherMiddleware.concat(middleware);
}
return otherMiddleware;
}
return this.getMiddleware();
}
props (props: HookContextData) {
if (!this._props) {
this._props = {};
}
Object.assign(this._props, props);
return this;
}
getProps (): HookContextData {
const previous = this._parent?.getProps();
if (previous) {
return Object.assign({}, previous, this._props);
}
return this._props;
}
params (...params: string[]) {
this._params = params;
return this;
}
getParams (): string[] {
const previous = this._parent?.getParams();
return previous || this._params;
}
defaults (defaults: HookDefaultsInitializer) {
this._defaults = defaults;
return this;
}
getDefaults (self: any, args: any[], context: HookContext): HookContextData {
const defaults = typeof this._defaults === 'function' ? this._defaults(self, args, context) : null;
const previous = this._parent?.getDefaults(self, args, context);
if (previous) {
return Object.assign({}, previous, this._props);
}
return defaults;
}
getContextClass (Base: HookContextConstructor = HookContext): HookContextConstructor {
const ContextClass = class ContextClass extends Base {
constructor (data: any) {
super(data);
copyToSelf(this);
}
};
const params = this.getParams();
const props = this.getProps();
if (params) {
params.forEach((name, index) => {
if (props?.[name]) {
throw new Error(`Hooks can not have a property and param named '${name}'. Use .defaults instead.`);
}
Object.defineProperty(ContextClass.prototype, name, {
enumerable: true,
get () {
return this?.arguments[index];
},
set (value: any) {
this.arguments[index] = value;
}
});
});
}
if (props) {
Object.assign(ContextClass.prototype, props);
}
return ContextClass;
}
initializeContext (self: any, args: any[], context: HookContext): HookContext {
const ctx = this._parent ? this._parent.initializeContext(self, args, context) : context;
const defaults = this.getDefaults(self, args, ctx);

@@ -69,2 +174,10 @@ if (self) {

if (defaults) {
for (const name of Object.keys(defaults)) {
if (ctx[name] === undefined) {
ctx[name] = defaults[name];
}
}
}
return ctx;

@@ -74,5 +187,9 @@ }

export type HookOptions = HookManager|Middleware[];
export type HookOptions = HookManager|Middleware[]|null;
export function convertOptions (options: HookOptions = []) {
export function convertOptions (options: HookOptions = null) {
if (!options) {
return new HookManager()
}
return Array.isArray(options) ? new HookManager().middleware(options) : options;

@@ -93,6 +210,6 @@ }

export function getMiddleware (target: any): Middleware[] {
export function getMiddleware (target: any): Middleware[]|null {
const manager = getManager(target);
return manager ? manager.getMiddleware() : [];
return manager ? manager.getMiddleware() : null;
}

@@ -99,0 +216,0 @@

147

deno/hooks.ts

@@ -1,45 +0,128 @@

import { HookContext, HookContextData, HookDefaultsInitializer } from './base.ts'
import { NextFunction } from './compose.ts'
import { compose, Middleware } from './compose.ts';
import {
HookContext, setManager, HookContextData, HookOptions, convertOptions, setMiddleware
} from './base.ts';
export function params (...names: string[]) {
const descriptors = names.reduce((result, name, index) => {
result[name] = {
enumerable: true,
get (this: any) {
return this.arguments[index];
},
export function getOriginal (fn: any): any {
return typeof fn.original === 'function' ? getOriginal(fn.original) : fn;
}
set (this: any, value) {
this.arguments[index] = value;
}
function copyProperties <F> (target: F, original: any) {
const originalProps = (Object.keys(original) as any)
.concat(Object.getOwnPropertySymbols(original));
for (const prop of originalProps) {
const propDescriptor = Object.getOwnPropertyDescriptor(original, prop);
if (!target.hasOwnProperty(prop)) {
Object.defineProperty(target, prop, propDescriptor);
}
}
return target;
}
export function functionHooks <F> (fn: F, managerOrMiddleware: HookOptions) {
if (typeof fn !== 'function') {
throw new Error('Can not apply hooks to non-function');
}
const manager = convertOptions(managerOrMiddleware);
const wrapper: any = function (this: any, ...args: any[]) {
const { Context, original } = wrapper;
// If we got passed an existing HookContext instance, we want to return it as well
const returnContext = args[args.length - 1] instanceof Context;
// Use existing context or default
const base = returnContext ? (args.pop() as HookContext) : new Context();
// Initialize the context
const context = manager.initializeContext(this, args, base);
// Assemble the hook chain
const hookChain: Middleware[] = [
// Return `ctx.result` or the context
(ctx, next) => next().then(() => returnContext ? ctx : ctx.result)
];
// Create the hook chain by calling the `collectMiddleware function
const mw = manager.collectMiddleware(this, args);
if (mw) {
Array.prototype.push.apply(hookChain, mw);
}
// Runs the actual original method if `ctx.result` is not already set
hookChain.push((ctx, next) => {
if (ctx.result === undefined) {
return Promise.resolve(original.apply(this, ctx.arguments)).then(result => {
ctx.result = result;
return next();
});
}
return result;
}, {} as PropertyDescriptorMap);
return next();
});
return async function defineParams (context: HookContext, next: NextFunction) {
Object.defineProperties(context, descriptors);
await next();
return compose(hookChain).call(this, context);
};
copyProperties(wrapper, fn);
setManager(wrapper, manager);
return Object.assign(wrapper, {
original: getOriginal(fn),
Context: manager.getContextClass(),
createContext: (data: HookContextData = {}) => {
return new wrapper.Context(data);
}
});
};
export type HookMap<O = any> = {
[L in keyof O]?: HookOptions;
}
export function props (properties: HookContextData) {
return async function setProps (context: HookContext, next: NextFunction) {
Object.assign(context, properties);
await next();
export function objectHooks (_obj: any, hooks: HookMap|Middleware[]) {
const obj = typeof _obj === 'function' ? _obj.prototype : _obj;
if (Array.isArray(hooks)) {
return setMiddleware(obj, hooks);
}
}
export function defaults (initializer: HookDefaultsInitializer) {
return async function setDefaults (context: HookContext, next: NextFunction) {
const defaults = initializer(context);
return Object.keys(hooks).reduce((result, method) => {
const fn = obj[method];
for (const name of Object.keys(defaults)) {
if (context[name] === undefined) {
context[name] = defaults[name];
}
if (typeof fn !== 'function') {
throw new Error(`Can not apply hooks. '${method}' is not a function`);
}
await next();
}
}
const manager = convertOptions(hooks[method]);
result[method] = functionHooks(fn, manager.props({ method }));
return result;
}, obj);
};
export const hookDecorator = (managerOrMiddleware?: HookOptions) => {
const wrapper: any = (_target: any, method: string, descriptor: TypedPropertyDescriptor<any>): TypedPropertyDescriptor<any> => {
const manager = convertOptions(managerOrMiddleware);
if (!descriptor) {
setManager(_target.prototype, manager);
return _target;
}
const fn = descriptor.value;
if (typeof fn !== 'function') {
throw new Error(`Can not apply hooks. '${method}' is not a function`);
}
descriptor.value = functionHooks(fn, manager.props({ method }));
return descriptor;
};
return wrapper;
};

@@ -1,9 +0,8 @@

import { functionHooks } from './function.ts';
import { Middleware } from './compose.ts';
import { objectHooks, HookMap } from './object.ts';
import { hookDecorator } from './decorator.ts';
import { HookManager, HookContextData, HookContext, HookContextConstructor, HookOptions } from './base.ts';
import {
HookManager, HookContextData, HookContext, HookContextConstructor, HookOptions
} from './base.ts';
import { functionHooks, hookDecorator, objectHooks, HookMap } from './hooks';
export * as setContext from './context';
export * from './function.ts';
export * from './hooks';
export * from './compose.ts';

@@ -20,2 +19,8 @@ export * from './base.ts';

export type MiddlewareOptions = {
params?: any;
defaults?: any;
props?: any;
};
/**

@@ -25,6 +30,20 @@ * Initializes a hook settings object with the given middleware.

*/
export function middleware (mw: Middleware[] = []) {
const manager = new HookManager();
export function middleware (mw?: Middleware[], options?: MiddlewareOptions) {
const manager = new HookManager().middleware(mw);
return manager.middleware(mw);
if (options) {
if (options.params) {
manager.params(options.params);
}
if (options.defaults) {
manager.defaults(options.defaults);
}
if (options.props) {
manager.props(options.props);
}
}
return manager;
}

@@ -31,0 +50,0 @@

@@ -1,20 +0,1 @@

export function getOriginal (fn: any): any {
return typeof fn.original === 'function' ? getOriginal(fn.original) : fn;
}
export function copyProperties <F> (target: F, original: any) {
const originalProps = (Object.keys(original) as any)
.concat(Object.getOwnPropertySymbols(original));
for (const prop of originalProps) {
const propDescriptor = Object.getOwnPropertyDescriptor(original, prop);
if (!target.hasOwnProperty(prop)) {
Object.defineProperty(target, prop, propDescriptor);
}
}
return target;
}
const proto = Object.prototype as any;

@@ -21,0 +2,0 @@ // These are non-standard but offer a more reliable prototype based

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.hooks=t():e.hooks=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=4)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HOOKS=Symbol("@feathersjs/hooks");class r{constructor(e={}){Object.assign(this,e)}}t.HookContext=r;class o{constructor(){this._parent=null,this._middleware=[]}parent(e){return this._parent=e,this}middleware(e){return this._middleware=e,this}getContextClass(){return r}getMiddleware(){return(this._parent?this._parent.getMiddleware():[]).concat(this._middleware)}collectMiddleware(e,t){return c(e).concat(this.getMiddleware())}initializeContext(e,t,n){const r=this._parent?this._parent.initializeContext(e,t,n):n;return e&&(r.self=e),r.arguments=t,r}}function i(e){return e&&e[t.HOOKS]||null}function s(e,n){const r=i(e);return e[t.HOOKS]=n.parent(r),e}function c(e){const t=i(e);return t?t.getMiddleware():[]}t.HookManager=o,t.convertOptions=function(e=[]){return Array.isArray(e)?(new o).middleware(e):e},t.getManager=i,t.setManager=s,t.getMiddleware=c,t.setMiddleware=function(e,t){return s(e,(new o).middleware(t))}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(3),o=n(0);function i(e){return"function"==typeof e.original?i(e.original):e}t.getOriginal=i,t.functionHooks=function(e,t){if("function"!=typeof e)throw new Error("Can not apply hooks to non-function");const n=o.convertOptions(t),s=function(...e){const{Context:t,original:o}=s,i=e[e.length-1]instanceof t,c=i?e.pop():new t,u=n.initializeContext(this,e,c),a=[(e,t)=>t().then(()=>i?e:e.result),...n.collectMiddleware(this,e),(e,t)=>void 0===e.result?Promise.resolve(o.apply(this,e.arguments)).then(n=>(e.result=n,t())):t()];return r.compose(a).call(this,u)};return function(e,t){const n=Object.keys(t).concat(Object.getOwnPropertySymbols(t));for(const r of n){const n=Object.getOwnPropertyDescriptor(t,r);e.hasOwnProperty(r)||Object.defineProperty(e,r,n)}}(s,e),o.setManager(s,n),Object.assign(s,{original:i(e),Context:n.getContextClass(),createContext:(e={})=>new s.Context(e)})}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.params=function(...e){const t=e.reduce((e,t,n)=>(e[t]={enumerable:!0,get(){return this.arguments[n]},set(e){this.arguments[n]=e}},e),{});return async function(e,n){Object.defineProperties(e,t),await n()}},t.properties=function(e){return async function(t,n){Object.assign(t,e),await n()}},t.defaults=function(e){return async function(t,n){const r=await e(t);for(const e of Object.keys(r))void 0===t[e]&&(t[e]=r[e]);await n()}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.compose=function(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(const t of e)if("function"!=typeof t)throw new TypeError("Middleware must be composed of functions!");return function(t,n){let r=-1;return function o(i){if(i<=r)return Promise.reject(new Error("next() called multiple times"));r=i;let s=e[i];i===e.length&&(s=n);if(!s)return Promise.resolve();try{return Promise.resolve(s.call(this,t,o.bind(this,i+1)))}catch(e){return Promise.reject(e)}}.call(this,0)}}},function(e,t,n){"use strict";function r(e){for(var n in e)t.hasOwnProperty(n)||(t[n]=e[n])}var o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t};Object.defineProperty(t,"__esModule",{value:!0});const i=n(1),s=n(5),c=n(6),u=n(0);t.setContext=o(n(2)),r(n(1)),r(n(3)),r(n(0)),t.middleware=function(e=[]){return(new u.HookManager).middleware(e)},t.hooks=function(...e){const[t,n]=e;return"function"==typeof t&&(n instanceof u.HookManager||Array.isArray(n))?i.functionHooks(t,n):2===e.length?s.objectHooks(t,n):c.hookDecorator(t)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(1),o=n(0),i=n(2);t.objectHooks=function(e,t){const n="function"==typeof e?e.prototype:e;return Array.isArray(t)?o.setMiddleware(n,t):Object.keys(t).reduce((e,s)=>{const c=n[s];if("function"!=typeof c)throw new Error(`Can not apply hooks. '${s}' is not a function`);const u=o.convertOptions(t[s]);return u._middleware.unshift(i.properties({method:s})),e[s]=r.functionHooks(c,u),e},n)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=n(1),o=n(0),i=n(2);t.hookDecorator=e=>(t,n,s)=>{const c=o.convertOptions(e);if(!s)return o.setManager(t.prototype,c),t;const u=s.value;if("function"!=typeof u)throw new Error(`Can not apply hooks. '${n}' is not a function`);return c._middleware.unshift(i.properties({method:n})),s.value=r.functionHooks(u,c),s}}])}));
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.hooks=e():t.hooks=e()}(this,(function(){return(()=>{"use strict";var t={150:(t,e,o)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.setMiddleware=e.getMiddleware=e.setManager=e.getManager=e.convertOptions=e.HookManager=e.HookContext=e.HOOKS=void 0;const r=o(930);e.HOOKS=Symbol("@feathersjs/hooks");class n{constructor(t={}){Object.assign(this,t)}}e.HookContext=n;class s{constructor(){this._parent=null,this._params=null,this._middleware=null,this._props=null}parent(t){return this._parent=t,this}middleware(t){return this._middleware=(null==t?void 0:t.length)?t:null,this}getMiddleware(){var t;const e=null===(t=this._parent)||void 0===t?void 0:t.getMiddleware();return e?this._middleware?e.concat(this._middleware):e:this._middleware}collectMiddleware(t,e){const o=c(t),r=this.getMiddleware();return o?r?o.concat(r):o:this.getMiddleware()}props(t){return this._props||(this._props={}),Object.assign(this._props,t),this}getProps(){var t;const e=null===(t=this._parent)||void 0===t?void 0:t.getProps();return e?Object.assign({},e,this._props):this._props}params(...t){return this._params=t,this}getParams(){var t;return(null===(t=this._parent)||void 0===t?void 0:t.getParams())||this._params}defaults(t){return this._defaults=t,this}getDefaults(t,e,o){var r;const n="function"==typeof this._defaults?this._defaults(t,e,o):null,s=null===(r=this._parent)||void 0===r?void 0:r.getDefaults(t,e,o);return s?Object.assign({},s,this._props):n}getContextClass(t=n){const e=class extends t{constructor(t){super(t),r.copyToSelf(this)}},o=this.getParams(),s=this.getProps();return o&&o.forEach(((t,o)=>{if(null==s?void 0:s[t])throw new Error(`Hooks can not have a property and param named '${t}'. Use .defaults instead.`);Object.defineProperty(e.prototype,t,{enumerable:!0,get(){return null==this?void 0:this.arguments[o]},set(t){this.arguments[o]=t}})})),s&&Object.assign(e.prototype,s),e}initializeContext(t,e,o){const r=this._parent?this._parent.initializeContext(t,e,o):o,n=this.getDefaults(t,e,r);if(t&&(r.self=t),r.arguments=e,n)for(const t of Object.keys(n))void 0===r[t]&&(r[t]=n[t]);return r}}function i(t){return t&&t[e.HOOKS]||null}function a(t,o){const r=i(t);return t[e.HOOKS]=o.parent(r),t}function c(t){const e=i(t);return e?e.getMiddleware():null}e.HookManager=s,e.convertOptions=function(t=null){return t?Array.isArray(t)?(new s).middleware(t):t:new s},e.getManager=i,e.setManager=a,e.getMiddleware=c,e.setMiddleware=function(t,e){return a(t,(new s).middleware(e))}},85:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.compose=void 0,e.compose=function(t){if(!Array.isArray(t))throw new TypeError("Middleware stack must be an array!");for(const e of t)if("function"!=typeof e)throw new TypeError("Middleware must be composed of functions!");return function(e,o){let r=-1;return function n(s){if(s<=r)return Promise.reject(new Error("next() called multiple times"));r=s;let i=t[s];if(s===t.length&&(i=o),!i)return Promise.resolve();try{return Promise.resolve(i.call(this,e,n.bind(this,s+1)))}catch(t){return Promise.reject(t)}}.call(this,0)}}},460:(t,e,o)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.hookDecorator=e.objectHooks=e.functionHooks=e.getOriginal=void 0;const r=o(85),n=o(150);function s(t){return"function"==typeof t.original?s(t.original):t}function i(t,e){if("function"!=typeof t)throw new Error("Can not apply hooks to non-function");const o=n.convertOptions(e),i=function(...t){const{Context:e,original:n}=i,s=t[t.length-1]instanceof e,a=s?t.pop():new e,c=o.initializeContext(this,t,a),u=[(t,e)=>e().then((()=>s?t:t.result))],l=o.collectMiddleware(this,t);return l&&Array.prototype.push.apply(u,l),u.push(((t,e)=>void 0===t.result?Promise.resolve(n.apply(this,t.arguments)).then((o=>(t.result=o,e()))):e())),r.compose(u).call(this,c)};return function(t,e){const o=Object.keys(e).concat(Object.getOwnPropertySymbols(e));for(const r of o){const o=Object.getOwnPropertyDescriptor(e,r);t.hasOwnProperty(r)||Object.defineProperty(t,r,o)}}(i,t),n.setManager(i,o),Object.assign(i,{original:s(t),Context:o.getContextClass(),createContext:(t={})=>new i.Context(t)})}e.getOriginal=s,e.functionHooks=i,e.objectHooks=function(t,e){const o="function"==typeof t?t.prototype:t;return Array.isArray(e)?n.setMiddleware(o,e):Object.keys(e).reduce(((t,r)=>{const s=o[r];if("function"!=typeof s)throw new Error(`Can not apply hooks. '${r}' is not a function`);const a=n.convertOptions(e[r]);return t[r]=i(s,a.props({method:r})),t}),o)},e.hookDecorator=t=>(e,o,r)=>{const s=n.convertOptions(t);if(!r)return n.setManager(e.prototype,s),e;const a=r.value;if("function"!=typeof a)throw new Error(`Can not apply hooks. '${o}' is not a function`);return r.value=i(a,s.props({method:o})),r}},920:function(t,e,o){var r=this&&this.__createBinding||(Object.create?function(t,e,o,r){void 0===r&&(r=o),Object.defineProperty(t,r,{enumerable:!0,get:function(){return e[o]}})}:function(t,e,o,r){void 0===r&&(r=o),t[r]=e[o]}),n=this&&this.__exportStar||function(t,e){for(var o in t)"default"===o||Object.prototype.hasOwnProperty.call(e,o)||r(e,t,o)};Object.defineProperty(e,"__esModule",{value:!0}),e.hooks=e.middleware=void 0;const s=o(150),i=o(460);n(o(460),e),n(o(85),e),n(o(150),e),e.middleware=function(t,e){const o=(new s.HookManager).middleware(t);return e&&(e.params&&o.params(e.params),e.defaults&&o.defaults(e.defaults),e.props&&o.props(e.props)),o},e.hooks=function(...t){const[e,o]=t;return"function"==typeof e&&(o instanceof s.HookManager||Array.isArray(o))?i.functionHooks(e,o):2===t.length?i.objectHooks(e,o):i.hookDecorator(e)}},930:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.copyToSelf=void 0;const o=Object.prototype,r="function"==typeof o.__lookupGetter__&&"function"==typeof o.__defineGetter__&&"function"==typeof o.__defineSetter__;e.copyToSelf=function(t){for(const e in t)if(!t.hasOwnProperty(e)){const o=r?t.constructor.prototype.__lookupGetter__(e):Object.getOwnPropertyDescriptor(t,e);o&&r?(t.__defineGetter__(e,o),t.__defineSetter__(e,t.constructor.prototype.__lookupSetter__(e))):o?Object.defineProperty(t,e,o):t[e]=t[e]}}}},e={};return function o(r){if(e[r])return e[r].exports;var n=e[r]={exports:{}};return t[r].call(n.exports,n,n.exports,o),n.exports}(920)})()}));

@@ -6,2 +6,5 @@ import { Middleware } from './compose';

};
/**
* The base hook context.
*/
export declare class HookContext<T = any, C = any> {

@@ -18,18 +21,27 @@ result?: T;

}) => HookContext;
export declare type HookDefaultsInitializer = (context: HookContext) => HookContextData;
export declare type HookDefaultsInitializer = (self?: any, args?: any[], context?: HookContext) => HookContextData;
export declare class HookManager {
_parent?: this | null;
_middleware: Middleware[];
_params: string[] | null;
_middleware: Middleware[] | null;
_props: HookContextData | null;
_defaults: HookDefaultsInitializer;
parent(parent: this): this;
middleware(middleware: Middleware[]): this;
getContextClass(): HookContextConstructor;
getMiddleware(): Middleware[];
middleware(middleware?: Middleware[]): this;
getMiddleware(): Middleware[] | null;
collectMiddleware(self: any, _args: any[]): Middleware[];
props(props: HookContextData): this;
getProps(): HookContextData;
params(...params: string[]): this;
getParams(): string[];
defaults(defaults: HookDefaultsInitializer): this;
getDefaults(self: any, args: any[], context: HookContext): HookContextData;
getContextClass(Base?: HookContextConstructor): HookContextConstructor;
initializeContext(self: any, args: any[], context: HookContext): HookContext;
}
export declare type HookOptions = HookManager | Middleware[];
export declare type HookOptions = HookManager | Middleware[] | null;
export declare function convertOptions(options?: HookOptions): HookManager;
export declare function getManager(target: any): HookManager | null;
export declare function setManager<T>(target: T, manager: HookManager): T;
export declare function getMiddleware(target: any): Middleware[];
export declare function getMiddleware(target: any): Middleware[] | null;
export declare function setMiddleware<T>(target: T, middleware: Middleware[]): T;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setMiddleware = exports.getMiddleware = exports.setManager = exports.getManager = exports.convertOptions = exports.HookManager = exports.HookContext = exports.HOOKS = void 0;
const utils_1 = require("./utils");
exports.HOOKS = Symbol('@feathersjs/hooks');
/**
* The base hook context.
*/
class HookContext {

@@ -13,3 +18,5 @@ constructor(data = {}) {

this._parent = null;
this._middleware = [];
this._params = null;
this._middleware = null;
this._props = null;
}

@@ -21,18 +28,97 @@ parent(parent) {

middleware(middleware) {
this._middleware = middleware;
this._middleware = (middleware === null || middleware === void 0 ? void 0 : middleware.length) ? middleware : null;
return this;
}
getContextClass() {
return HookContext;
}
getMiddleware() {
const previous = this._parent ? this._parent.getMiddleware() : [];
return previous.concat(this._middleware);
var _a;
const previous = (_a = this._parent) === null || _a === void 0 ? void 0 : _a.getMiddleware();
if (previous) {
if (this._middleware) {
return previous.concat(this._middleware);
}
return previous;
}
return this._middleware;
}
collectMiddleware(self, _args) {
const otherMiddleware = getMiddleware(self);
return otherMiddleware.concat(this.getMiddleware());
const middleware = this.getMiddleware();
if (otherMiddleware) {
if (middleware) {
return otherMiddleware.concat(middleware);
}
return otherMiddleware;
}
return this.getMiddleware();
}
props(props) {
if (!this._props) {
this._props = {};
}
Object.assign(this._props, props);
return this;
}
getProps() {
var _a;
const previous = (_a = this._parent) === null || _a === void 0 ? void 0 : _a.getProps();
if (previous) {
return Object.assign({}, previous, this._props);
}
return this._props;
}
params(...params) {
this._params = params;
return this;
}
getParams() {
var _a;
const previous = (_a = this._parent) === null || _a === void 0 ? void 0 : _a.getParams();
return previous || this._params;
}
defaults(defaults) {
this._defaults = defaults;
return this;
}
getDefaults(self, args, context) {
var _a;
const defaults = typeof this._defaults === 'function' ? this._defaults(self, args, context) : null;
const previous = (_a = this._parent) === null || _a === void 0 ? void 0 : _a.getDefaults(self, args, context);
if (previous) {
return Object.assign({}, previous, this._props);
}
return defaults;
}
getContextClass(Base = HookContext) {
const ContextClass = class ContextClass extends Base {
constructor(data) {
super(data);
utils_1.copyToSelf(this);
}
};
const params = this.getParams();
const props = this.getProps();
if (params) {
params.forEach((name, index) => {
if (props === null || props === void 0 ? void 0 : props[name]) {
throw new Error(`Hooks can not have a property and param named '${name}'. Use .defaults instead.`);
}
Object.defineProperty(ContextClass.prototype, name, {
enumerable: true,
get() {
return this === null || this === void 0 ? void 0 : this.arguments[index];
},
set(value) {
this.arguments[index] = value;
}
});
});
}
if (props) {
Object.assign(ContextClass.prototype, props);
}
return ContextClass;
}
initializeContext(self, args, context) {
const ctx = this._parent ? this._parent.initializeContext(self, args, context) : context;
const defaults = this.getDefaults(self, args, ctx);
if (self) {

@@ -42,2 +128,9 @@ ctx.self = self;

ctx.arguments = args;
if (defaults) {
for (const name of Object.keys(defaults)) {
if (ctx[name] === undefined) {
ctx[name] = defaults[name];
}
}
}
return ctx;

@@ -47,3 +140,6 @@ }

exports.HookManager = HookManager;
function convertOptions(options = []) {
function convertOptions(options = null) {
if (!options) {
return new HookManager();
}
return Array.isArray(options) ? new HookManager().middleware(options) : options;

@@ -64,3 +160,3 @@ }

const manager = getManager(target);
return manager ? manager.getMiddleware() : [];
return manager ? manager.getMiddleware() : null;
}

@@ -67,0 +163,0 @@ exports.getMiddleware = getMiddleware;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compose = void 0;
function compose(middleware) {

@@ -4,0 +5,0 @@ if (!Array.isArray(middleware)) {

import { Middleware } from './compose';
import { HookMap } from './object';
import { HookManager, HookContextData, HookContext, HookContextConstructor, HookOptions } from './base';
export * as setContext from './context';
export * from './function';
import { HookMap } from './hooks';
export * from './hooks';
export * from './compose';

@@ -14,2 +13,7 @@ export * from './base';

export declare type WrappedFunction<F, T> = F & ((...rest: any[]) => Promise<T> | Promise<HookContext>) & WrapperAddon<F>;
export declare type MiddlewareOptions = {
params?: any;
defaults?: any;
props?: any;
};
/**

@@ -19,3 +23,3 @@ * Initializes a hook settings object with the given middleware.

*/
export declare function middleware(mw?: Middleware[]): HookManager;
export declare function middleware(mw?: Middleware[], options?: MiddlewareOptions): HookManager;
/**

@@ -22,0 +26,0 @@ * Returns a new function that wraps an existing async function

"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
const function_1 = require("./function");
const object_1 = require("./object");
const decorator_1 = require("./decorator");
exports.hooks = exports.middleware = void 0;
const base_1 = require("./base");
exports.setContext = __importStar(require("./context"));
__export(require("./function"));
__export(require("./compose"));
__export(require("./base"));
const hooks_1 = require("./hooks");
__exportStar(require("./hooks"), exports);
__exportStar(require("./compose"), exports);
__exportStar(require("./base"), exports);
/**

@@ -25,5 +23,16 @@ * Initializes a hook settings object with the given middleware.

*/
function middleware(mw = []) {
const manager = new base_1.HookManager();
return manager.middleware(mw);
function middleware(mw, options) {
const manager = new base_1.HookManager().middleware(mw);
if (options) {
if (options.params) {
manager.params(options.params);
}
if (options.defaults) {
manager.defaults(options.defaults);
}
if (options.props) {
manager.props(options.props);
}
}
return manager;
}

@@ -35,10 +44,10 @@ exports.middleware = middleware;

if (typeof target === 'function' && (_hooks instanceof base_1.HookManager || Array.isArray(_hooks))) {
return function_1.functionHooks(target, _hooks);
return hooks_1.functionHooks(target, _hooks);
}
if (args.length === 2) {
return object_1.objectHooks(target, _hooks);
return hooks_1.objectHooks(target, _hooks);
}
return decorator_1.hookDecorator(target);
return hooks_1.hookDecorator(target);
}
exports.hooks = hooks;
//# sourceMappingURL=index.js.map
{
"name": "@feathersjs/hooks",
"version": "0.5.0",
"version": "0.6.0",
"description": "Async middleware for JavaScript and TypeScript",

@@ -43,2 +43,11 @@ "homepage": "https://feathersjs.com",

},
"files": [
"CHANGELOG.md",
"LICENSE",
"README.md",
"src/**",
"lib/**",
"deno/**",
"dist/**"
],
"publishConfig": {

@@ -48,14 +57,14 @@ "access": "public"

"devDependencies": {
"@types/chai": "^4.2.7",
"@types/mocha": "^7.0.1",
"@types/node": "^13.1.2",
"mocha": "^7.0.1",
"shx": "^0.3.2",
"ts-loader": "^6.2.1",
"ts-node": "^8.5.4",
"typescript": "^3.7.4",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10"
"@types/chai": "^4.2.14",
"@types/mocha": "^8.0.3",
"@types/node": "^14.14.6",
"mocha": "^8.2.1",
"shx": "^0.3.3",
"ts-loader": "^8.0.10",
"ts-node": "^9.0.0",
"typescript": "^4.0.5",
"webpack": "^5.4.0",
"webpack-cli": "^4.2.0"
},
"gitHead": "740a8591176e0f66eb3c8ac1c6f5ac07172b4f88"
"gitHead": "84a9b4bb12114a391d464fbcde7ee95fecf57e53"
}
import { Middleware } from './compose';
import { copyToSelf } from './utils';

@@ -7,2 +8,5 @@ export const HOOKS: string = Symbol('@feathersjs/hooks') as any;

/**
* The base hook context.
*/
export class HookContext<T = any, C = any> {

@@ -22,7 +26,10 @@ result?: T;

export type HookDefaultsInitializer = (context: HookContext) => HookContextData;
export type HookDefaultsInitializer = (self?: any, args?: any[], context?: HookContext) => HookContextData;
export class HookManager {
_parent?: this|null = null;
_middleware: Middleware[] = [];
_params: string[]|null = null;
_middleware: Middleware[]|null = null;
_props: HookContextData|null = null;
_defaults: HookDefaultsInitializer;

@@ -35,4 +42,4 @@ parent (parent: this) {

middleware (middleware: Middleware[]) {
this._middleware = middleware;
middleware (middleware?: Middleware[]) {
this._middleware = middleware?.length ? middleware : null;

@@ -42,21 +49,119 @@ return this;

getContextClass (): HookContextConstructor {
return HookContext;
}
getMiddleware (): Middleware[]|null {
const previous = this._parent?.getMiddleware();
getMiddleware (): Middleware[] {
const previous = this._parent ? this._parent.getMiddleware() : [];
if (previous) {
if (this._middleware) {
return previous.concat(this._middleware);
}
return previous.concat(this._middleware);
return previous;
}
return this._middleware;
}
collectMiddleware (self: any, _args: any[]): Middleware[] {
collectMiddleware (self: any, _args: any[]): Middleware[] {
const otherMiddleware = getMiddleware(self);
const middleware = this.getMiddleware();
return otherMiddleware.concat(this.getMiddleware());
if (otherMiddleware) {
if (middleware) {
return otherMiddleware.concat(middleware);
}
return otherMiddleware;
}
return this.getMiddleware();
}
props (props: HookContextData) {
if (!this._props) {
this._props = {};
}
Object.assign(this._props, props);
return this;
}
getProps (): HookContextData {
const previous = this._parent?.getProps();
if (previous) {
return Object.assign({}, previous, this._props);
}
return this._props;
}
params (...params: string[]) {
this._params = params;
return this;
}
getParams (): string[] {
const previous = this._parent?.getParams();
return previous || this._params;
}
defaults (defaults: HookDefaultsInitializer) {
this._defaults = defaults;
return this;
}
getDefaults (self: any, args: any[], context: HookContext): HookContextData {
const defaults = typeof this._defaults === 'function' ? this._defaults(self, args, context) : null;
const previous = this._parent?.getDefaults(self, args, context);
if (previous) {
return Object.assign({}, previous, this._props);
}
return defaults;
}
getContextClass (Base: HookContextConstructor = HookContext): HookContextConstructor {
const ContextClass = class ContextClass extends Base {
constructor (data: any) {
super(data);
copyToSelf(this);
}
};
const params = this.getParams();
const props = this.getProps();
if (params) {
params.forEach((name, index) => {
if (props?.[name]) {
throw new Error(`Hooks can not have a property and param named '${name}'. Use .defaults instead.`);
}
Object.defineProperty(ContextClass.prototype, name, {
enumerable: true,
get () {
return this?.arguments[index];
},
set (value: any) {
this.arguments[index] = value;
}
});
});
}
if (props) {
Object.assign(ContextClass.prototype, props);
}
return ContextClass;
}
initializeContext (self: any, args: any[], context: HookContext): HookContext {
const ctx = this._parent ? this._parent.initializeContext(self, args, context) : context;
const defaults = this.getDefaults(self, args, ctx);

@@ -69,2 +174,10 @@ if (self) {

if (defaults) {
for (const name of Object.keys(defaults)) {
if (ctx[name] === undefined) {
ctx[name] = defaults[name];
}
}
}
return ctx;

@@ -74,5 +187,9 @@ }

export type HookOptions = HookManager|Middleware[];
export type HookOptions = HookManager|Middleware[]|null;
export function convertOptions (options: HookOptions = []) {
export function convertOptions (options: HookOptions = null) {
if (!options) {
return new HookManager()
}
return Array.isArray(options) ? new HookManager().middleware(options) : options;

@@ -93,6 +210,6 @@ }

export function getMiddleware (target: any): Middleware[] {
export function getMiddleware (target: any): Middleware[]|null {
const manager = getManager(target);
return manager ? manager.getMiddleware() : [];
return manager ? manager.getMiddleware() : null;
}

@@ -99,0 +216,0 @@

@@ -1,9 +0,8 @@

import { functionHooks } from './function';
import { Middleware } from './compose';
import { objectHooks, HookMap } from './object';
import { hookDecorator } from './decorator';
import { HookManager, HookContextData, HookContext, HookContextConstructor, HookOptions } from './base';
import {
HookManager, HookContextData, HookContext, HookContextConstructor, HookOptions
} from './base';
import { functionHooks, hookDecorator, objectHooks, HookMap } from './hooks';
export * as setContext from './context';
export * from './function';
export * from './hooks';
export * from './compose';

@@ -20,2 +19,8 @@ export * from './base';

export type MiddlewareOptions = {
params?: any;
defaults?: any;
props?: any;
};
/**

@@ -25,6 +30,20 @@ * Initializes a hook settings object with the given middleware.

*/
export function middleware (mw: Middleware[] = []) {
const manager = new HookManager();
export function middleware (mw?: Middleware[], options?: MiddlewareOptions) {
const manager = new HookManager().middleware(mw);
return manager.middleware(mw);
if (options) {
if (options.params) {
manager.params(options.params);
}
if (options.defaults) {
manager.defaults(options.defaults);
}
if (options.props) {
manager.props(options.props);
}
}
return manager;
}

@@ -31,0 +50,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc