@imqueue/rpc 2.1.0 → 3.0.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.
Files changed (62) hide show
  1. package/.github/workflows/build.yml +49 -5
  2. package/.oxfmtrc.json +9 -0
  3. package/.oxlintrc.json +37 -0
  4. package/README.md +68 -0
  5. package/package.json +21 -58
  6. package/scripts/strip-comment-coverage.mjs +464 -0
  7. package/src/IMQCache.d.ts +10 -9
  8. package/src/IMQCache.js +16 -22
  9. package/src/IMQClient.d.ts +21 -16
  10. package/src/IMQClient.js +407 -271
  11. package/src/IMQDelay.d.ts +14 -0
  12. package/src/IMQDelay.js +26 -5
  13. package/src/IMQLock.d.ts +17 -15
  14. package/src/IMQLock.js +36 -36
  15. package/src/IMQMetadata.d.ts +8 -0
  16. package/src/IMQMetadata.js +8 -0
  17. package/src/IMQRPCDescription.d.ts +2 -2
  18. package/src/IMQRPCDescription.js +2 -2
  19. package/src/IMQRPCError.d.ts +7 -7
  20. package/src/IMQRPCError.js +7 -8
  21. package/src/IMQRPCOptions.d.ts +27 -3
  22. package/src/IMQRPCOptions.js +17 -3
  23. package/src/IMQRPCRequest.d.ts +1 -1
  24. package/src/IMQRPCResponse.d.ts +1 -1
  25. package/src/IMQRequestContext.js +1 -2
  26. package/src/IMQService.d.ts +3 -4
  27. package/src/IMQService.js +302 -220
  28. package/src/cache/ICache.d.ts +53 -0
  29. package/src/cache/RedisCache.d.ts +30 -25
  30. package/src/cache/RedisCache.js +104 -61
  31. package/src/decorators/cache.d.ts +12 -0
  32. package/src/decorators/cache.js +56 -41
  33. package/src/decorators/classType.d.ts +43 -0
  34. package/src/decorators/classType.js +83 -0
  35. package/src/decorators/expose.d.ts +5 -31
  36. package/src/decorators/expose.js +118 -134
  37. package/src/decorators/index.d.ts +2 -0
  38. package/src/decorators/index.js +4 -0
  39. package/src/decorators/indexed.d.ts +23 -0
  40. package/src/decorators/indexed.js +22 -13
  41. package/src/decorators/lock.d.ts +10 -11
  42. package/src/decorators/lock.js +63 -56
  43. package/src/decorators/logged.d.ts +11 -9
  44. package/src/decorators/logged.js +47 -40
  45. package/src/decorators/metadata.d.ts +24 -0
  46. package/src/decorators/metadata.js +45 -0
  47. package/src/decorators/property.d.ts +7 -57
  48. package/src/decorators/property.js +112 -83
  49. package/src/decorators/remote.d.ts +7 -7
  50. package/src/decorators/remote.js +19 -13
  51. package/src/helpers/fs.d.ts +13 -13
  52. package/src/helpers/fs.js +19 -19
  53. package/src/helpers/os-uuid.d.ts +2 -1
  54. package/src/helpers/os-uuid.js +86 -3
  55. package/src/helpers/pid.d.ts +19 -9
  56. package/src/helpers/pid.js +33 -33
  57. package/src/helpers/signature.d.ts +9 -7
  58. package/src/helpers/signature.js +80 -10
  59. package/src/index.d.ts +0 -1
  60. package/src/index.js +0 -1
  61. package/tsconfig.json +18 -14
  62. package/typedoc.json +19 -0
@@ -1,34 +1,8 @@
1
- /*!
2
- * IMQ-RPC Decorators: expose
3
- *
4
- * I'm Queue Software Project
5
- * Copyright (C) 2025 imqueue.com <support@imqueue.com>
6
- *
7
- * This program is free software: you can redistribute it and/or modify
8
- * it under the terms of the GNU General Public License as published by
9
- * the Free Software Foundation, either version 3 of the License, or
10
- * (at your option) any later version.
11
- *
12
- * This program is distributed in the hope that it will be useful,
13
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- * GNU General Public License for more details.
16
- *
17
- * You should have received a copy of the GNU General Public License
18
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
- *
20
- * If you want to use this code in a closed source (commercial) project, you can
21
- * purchase a proprietary commercial license. Please contact us at
22
- * <support@imqueue.com> to get commercial licensing options.
23
- */
24
- import 'reflect-metadata';
25
1
  /**
26
- * Expose decorator factory
2
+ * Expose decorator factory. Applied to a service method, it registers that
3
+ * method in the RPC service description. (Complex argument/return types are
4
+ * registered separately via the '@classType' decorator on those classes.)
27
5
  *
28
- * @return {(
29
- * target: object,
30
- * methodName: (string),
31
- * descriptor: TypedPropertyDescriptor<(...args: any[]) => any>
32
- * ) => void} - decorator function
6
+ * @return {(value: any, context: ClassMethodDecoratorContext) => void}
33
7
  */
34
- export declare function expose(): (...args: any[]) => any;
8
+ export declare function expose(): any;
@@ -24,28 +24,17 @@ exports.expose = expose;
24
24
  * purchase a proprietary commercial license. Please contact us at
25
25
  * <support@imqueue.com> to get commercial licensing options.
26
26
  */
27
- require("reflect-metadata");
28
- const acorn = require("acorn");
27
+ const typescript_1 = require("typescript");
29
28
  const __1 = require("..");
30
- const TS_TYPES = [
31
- 'object',
32
- 'string',
33
- 'number',
34
- 'boolean',
35
- 'null',
36
- 'undefined',
37
- ];
38
29
  const descriptions = {};
39
30
  const RX_ARG_NAMES = /^(\S+)([=\s]+.*?)?$/;
40
31
  const RX_COMMA_SPLIT = /\s*,\s*/;
41
32
  const RX_MULTILINE_CLEANUP = /\*?\n +\* ?/g;
42
33
  const RX_DESCRIPTION = /^([\s\S]*?)@/;
43
34
  const RX_TAG = /(@[^@]+)/g;
44
- // noinspection RegExpRedundantEscape
45
35
  const RX_TYPE = /\{([\s\S]+)\}/;
46
36
  const RX_LI_CLEANUP = /^\s*-\s*/;
47
37
  const RX_SPACE_SPLIT = / /;
48
- // noinspection RegExpRedundantEscape
49
38
  const RX_OPTIONAL = /^\[(.*?)\]$/;
50
39
  /**
51
40
  * Lookup and returns a list of argument names for a given function
@@ -55,7 +44,11 @@ const RX_OPTIONAL = /^\[(.*?)\]$/;
55
44
  */
56
45
  function argumentNames(fn) {
57
46
  let src = fn.toString();
58
- return src.slice(src.indexOf('(') + 1, src.indexOf(')')).split(RX_COMMA_SPLIT).map(arg => arg.trim().replace(RX_ARG_NAMES, '$1')).filter(arg => arg);
47
+ return src
48
+ .slice(src.indexOf('(') + 1, src.indexOf(')'))
49
+ .split(RX_COMMA_SPLIT)
50
+ .map(arg => arg.trim().replace(RX_ARG_NAMES, '$1'))
51
+ .filter(arg => arg);
59
52
  }
60
53
  /**
61
54
  * Parses given multi-line comment block
@@ -72,10 +65,9 @@ function parseComment(src) {
72
65
  description: '',
73
66
  type: '',
74
67
  tsType: '',
75
- }
68
+ },
76
69
  };
77
70
  let match, tags = [];
78
- // istanbul ignore next
79
71
  data.description = String((cleanSrc.match(RX_DESCRIPTION) || [])[1] || '').trim();
80
72
  while ((match = RX_TAG.exec(cleanSrc))) {
81
73
  tags.push(match[1].trim());
@@ -121,7 +113,6 @@ function parseComment(src) {
121
113
  }
122
114
  return data;
123
115
  }
124
- // codebeat:disable[LOC,ABC]
125
116
  /**
126
117
  * Finds and parses methods and their comment blocks for a given class
127
118
  *
@@ -129,77 +120,43 @@ function parseComment(src) {
129
120
  * @param {string} src - class source code
130
121
  */
131
122
  function parseDescriptions(name, src) {
132
- const comments = [];
133
- const options = {
134
- ecmaVersion: 8,
135
- locations: true,
136
- ranges: true,
137
- allowReserved: true,
138
- onComment: comments,
139
- };
140
- const nodes = acorn.parse(src, options).body;
123
+ // parsed with the TypeScript compiler, which is already a runtime
124
+ // dependency (used for client generation) — no parent pointers needed,
125
+ // only class members and their leading comment trivia are read
126
+ const sourceFile = (0, typescript_1.createSourceFile)(`${name}.js`, src, typescript_1.ScriptTarget.Latest, false, typescript_1.ScriptKind.JS);
127
+ // the local `inherits` is a placeholder only: the public description's
128
+ // `inherits` is derived from the runtime prototype chain in
129
+ // buildMethodDescription(), never from the parsed source
141
130
  descriptions[name] = {
142
- inherits: 'Function'
131
+ inherits: 'Function',
143
132
  };
144
- for (let node of nodes) {
145
- // istanbul ignore if
146
- if (!(node && node.type === 'ClassDeclaration' &&
147
- node.id && node.id.name === name &&
148
- node.body.type === 'ClassBody')) {
133
+ for (const statement of sourceFile.statements) {
134
+ if (!(0, typescript_1.isClassDeclaration)(statement) ||
135
+ !statement.name ||
136
+ statement.name.text !== name) {
149
137
  continue;
150
138
  }
151
- if (node.superClass) {
152
- // istanbul ignore next
153
- if (node.superClass.type === 'MemberExpression') {
154
- descriptions[name].inherits =
155
- node.superClass.property.name;
156
- }
157
- else if (node.superClass.type === 'Identifier') {
158
- descriptions[name].inherits = node.superClass.name;
159
- }
160
- }
161
- const methods = node.body.body.filter((f) => f.type === 'MethodDefinition');
162
- for (let method of node.body.body) {
163
- // istanbul ignore if
164
- if (method.type !== 'MethodDefinition') {
139
+ for (const member of statement.members) {
140
+ if (!(0, typescript_1.isMethodDeclaration)(member) ||
141
+ !member.name ||
142
+ !(0, typescript_1.isIdentifier)(member.name)) {
165
143
  continue;
166
144
  }
167
- const methodName = method.key.name;
168
- const blocks = comments.filter(comment => comment.type === 'Block');
145
+ // the method's doc is the last block comment in its leading
146
+ // trivia; member.pos starts right after the previous token, so
147
+ // comments belonging to earlier members can never match
148
+ const blocks = ((0, typescript_1.getLeadingCommentRanges)(src, member.pos) || []).filter(range => range.kind === typescript_1.SyntaxKind.MultiLineCommentTrivia);
169
149
  if (!blocks.length) {
170
150
  continue;
171
151
  }
172
- const methodStart = method.start;
173
- let lastDif = methodStart - blocks[0].end;
174
- let foundBlock = blocks[0];
175
- for (let comment of blocks) {
176
- const dif = methodStart - comment.end;
177
- if (dif < 0) {
178
- break;
179
- }
180
- if (dif >= lastDif) {
181
- continue;
182
- }
183
- lastDif = dif;
184
- foundBlock = comment;
185
- }
186
- if (!method.range || foundBlock.start > method.range[1]) {
187
- continue;
188
- }
189
- const index = methods.indexOf(method);
190
- const prev = index && methods[index - 1];
191
- const prevBeforeComment = !prev
192
- || (prev && prev.range && prev.range[1] <= foundBlock.start);
193
- if (prevBeforeComment) {
194
- // it's a method comment block!!!!
195
- descriptions[name][methodName] = {
196
- comment: parseComment(foundBlock.value),
197
- };
198
- }
152
+ const block = blocks[blocks.length - 1];
153
+ descriptions[name][member.name.text] = {
154
+ // comment body without the enclosing /* and */ delimiters
155
+ comment: parseComment(src.slice(block.pos + 2, block.end - 2)),
156
+ };
199
157
  }
200
158
  }
201
159
  }
202
- // codebeat:enable[LOC,ABC]
203
160
  /**
204
161
  * Helper function to make easy descriptions parts extractions
205
162
  *
@@ -211,8 +168,8 @@ function parseDescriptions(name, src) {
211
168
  */
212
169
  function get(prop, className, method, defaults) {
213
170
  if (descriptions[className] && descriptions[className][method]) {
214
- let comment = descriptions[className][method].comment;
215
- // istanbul ignore else
171
+ let comment = descriptions[className][method]
172
+ .comment;
216
173
  if (comment[prop]) {
217
174
  return comment[prop];
218
175
  }
@@ -220,74 +177,101 @@ function get(prop, className, method, defaults) {
220
177
  return defaults;
221
178
  }
222
179
  /**
223
- * Converts JavaScript type to most close possible TypeScript type
180
+ * Builds and registers the RPC description for a single exposed method.
224
181
  *
225
- * @param type
226
- * @returns {string}
182
+ * Types are taken from the method's JSDoc (parsed from the class source,
183
+ * preserved by `removeComments: false`); standard decorators provide no
184
+ * runtime `design:type` metadata, so JSDoc is the sole type source.
185
+ *
186
+ * @param {Function} ctor - class that declares the method
187
+ * @param {string} methodName - exposed method name
188
+ * @param {(...args: any[]) => any} fn - the method implementation
227
189
  */
228
- function cast(type) {
229
- let tsType = String(type).toLowerCase();
230
- if (tsType === 'undefined') {
231
- tsType = 'void';
190
+ function buildMethodDescription(ctor, methodName, fn) {
191
+ const className = ctor.name;
192
+ const argNames = argumentNames(fn);
193
+ if (!descriptions[className]) {
194
+ parseDescriptions(className, ctor.toString());
232
195
  }
233
- else if (tsType === 'array') {
234
- tsType = 'any[]';
196
+ const args = get('params', className, methodName, []);
197
+ const ret = get('returns', className, methodName, {
198
+ description: '',
199
+ type: '',
200
+ tsType: '',
201
+ });
202
+ if (!args || !args.length) {
203
+ for (let i = 0, s = argNames.length; i < s; i++) {
204
+ args[i] = {
205
+ description: '',
206
+ name: argNames[i],
207
+ type: '',
208
+ tsType: '',
209
+ isOptional: false,
210
+ };
211
+ }
235
212
  }
236
- else if (!~TS_TYPES.indexOf(tsType)) {
237
- tsType = type;
213
+ // JSDoc is the sole type source; mirror the parsed tsType into `type`
214
+ // (the only consumer of `type` is the client generator's
215
+ // IMQDelay/IMQMetadata stripping) and default any undocumented type to
216
+ // 'any' so generated clients are always valid TypeScript
217
+ for (const arg of args) {
218
+ arg.tsType = arg.tsType || 'any';
219
+ arg.type = arg.type || arg.tsType;
238
220
  }
239
- return tsType;
221
+ ret.tsType = ret.tsType || 'any';
222
+ ret.type = ret.type || ret.tsType;
223
+ // derive the parent from the runtime prototype chain rather than the
224
+ // parsed source: standard-decorator output aliases the `extends` clause
225
+ // to a helper (e.g. `extends _classSuper`), so the source name is unusable
226
+ const parent = Object.getPrototypeOf(ctor);
227
+ const inherits = parent && parent.name ? parent.name : 'Function';
228
+ __1.IMQRPCDescription.serviceDescription[className] = __1.IMQRPCDescription
229
+ .serviceDescription[className] || {
230
+ inherits,
231
+ methods: {},
232
+ };
233
+ __1.IMQRPCDescription.serviceDescription[className].methods[methodName] = {
234
+ description: get('description', className, methodName, ''),
235
+ arguments: args,
236
+ returns: ret,
237
+ };
240
238
  }
241
239
  /**
242
- * Expose decorator factory
240
+ * Expose decorator factory. Applied to a service method, it registers that
241
+ * method in the RPC service description. (Complex argument/return types are
242
+ * registered separately via the '@classType' decorator on those classes.)
243
243
  *
244
- * @return {(
245
- * target: object,
246
- * methodName: (string),
247
- * descriptor: TypedPropertyDescriptor<(...args: any[]) => any>
248
- * ) => void} - decorator function
244
+ * @return {(value: any, context: ClassMethodDecoratorContext) => void}
249
245
  */
250
246
  function expose() {
251
- return function exposeDecorator(target, methodName, descriptor) {
252
- let className = target.constructor.name;
253
- let argNames = argumentNames(descriptor.value);
254
- let retType = Reflect.getMetadata('design:returntype', target, methodName);
255
- let retTypeName = retType ? retType.name : String(retType);
256
- if (!descriptions[className]) {
257
- parseDescriptions(className, target.constructor.toString());
258
- }
259
- let args = get('params', className, methodName, []);
260
- let ret = get('returns', className, methodName, {
261
- description: '',
262
- type: retTypeName,
263
- tsType: cast(retTypeName),
264
- });
265
- ret.type = retTypeName;
266
- if (!args || !args.length) {
267
- for (let i = 0, s = argNames.length; i < s; i++) {
268
- args[i] = {
269
- description: '',
270
- name: argNames[i],
271
- type: '',
272
- tsType: '',
273
- isOptional: false,
274
- };
275
- }
247
+ // Dual-mode: standard (TC39) invocations pass a context object with a
248
+ // `kind` property; legacy ones pass (target, propertyKey, descriptor).
249
+ return function exposeDecorator(target, context, descriptor) {
250
+ if (context && typeof context === 'object' && 'kind' in context) {
251
+ const value = target;
252
+ const methodName = String(context.name);
253
+ // the class is not available at decoration time, so defer to an
254
+ // initializer that runs at construction, where `this` is known
255
+ context.addInitializer(function () {
256
+ // register the method under the class that actually declares
257
+ // it (inherited methods are described under the base class,
258
+ // matching decoration-time behavior)
259
+ let proto = this.constructor.prototype;
260
+ while (proto &&
261
+ !Object.prototype.hasOwnProperty.call(proto, methodName)) {
262
+ proto = Object.getPrototypeOf(proto);
263
+ }
264
+ const ctor = proto
265
+ ? proto.constructor
266
+ : this.constructor;
267
+ buildMethodDescription(ctor, methodName, value);
268
+ });
269
+ return;
276
270
  }
277
- Reflect.getMetadata('design:paramtypes', target, methodName).forEach((typeConstructor, i) => {
278
- args[i].type = args[i].type || typeConstructor.name;
279
- args[i].tsType = args[i].tsType || cast(args[i].type);
280
- });
281
- __1.IMQRPCDescription.serviceDescription[className] =
282
- __1.IMQRPCDescription.serviceDescription[className] || {
283
- inherits: descriptions[className].inherits,
284
- methods: {},
285
- };
286
- __1.IMQRPCDescription.serviceDescription[className].methods[methodName] = {
287
- description: get('description', className, methodName, ''),
288
- arguments: args,
289
- returns: ret,
290
- };
271
+ // legacy: `target` is the prototype, so its constructor is the class
272
+ // that declares the method — available immediately at decoration time
273
+ buildMethodDescription(target.constructor, String(context), descriptor.value);
274
+ return descriptor;
291
275
  };
292
276
  }
293
277
  //# sourceMappingURL=expose.js.map
@@ -21,7 +21,9 @@
21
21
  * purchase a proprietary commercial license. Please contact us at
22
22
  * <support@imqueue.com> to get commercial licensing options.
23
23
  */
24
+ import './metadata';
24
25
  export * from './expose';
26
+ export * from './classType';
25
27
  export * from './remote';
26
28
  export * from './lock';
27
29
  export * from './cache';
@@ -37,7 +37,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
37
37
  * purchase a proprietary commercial license. Please contact us at
38
38
  * <support@imqueue.com> to get commercial licensing options.
39
39
  */
40
+ // must load first: installs the Symbol.metadata polyfill required by the
41
+ // standard-decorator metadata used across the decorators below
42
+ require("./metadata");
40
43
  __exportStar(require("./expose"), exports);
44
+ __exportStar(require("./classType"), exports);
41
45
  __exportStar(require("./remote"), exports);
42
46
  __exportStar(require("./lock"), exports);
43
47
  __exportStar(require("./cache"), exports);
@@ -1,3 +1,26 @@
1
+ /*!
2
+ * IMQ-RPC Decorators: property
3
+ *
4
+ * I'm Queue Software Project
5
+ * Copyright (C) 2025 imqueue.com <support@imqueue.com>
6
+ *
7
+ * This program is free software: you can redistribute it and/or modify
8
+ * it under the terms of the GNU General Public License as published by
9
+ * the Free Software Foundation, either version 3 of the License, or
10
+ * (at your option) any later version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ * GNU General Public License for more details.
16
+ *
17
+ * You should have received a copy of the GNU General Public License
18
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
+ *
20
+ * If you want to use this code in a closed source (commercial) project, you can
21
+ * purchase a proprietary commercial license. Please contact us at
22
+ * <support@imqueue.com> to get commercial licensing options.
23
+ */
1
24
  import { Thunk } from '..';
2
25
  /**
3
26
  * Implements '@indexed' decorator factory
@@ -25,6 +25,7 @@ exports.indexed = indexed;
25
25
  * <support@imqueue.com> to get commercial licensing options.
26
26
  */
27
27
  const __1 = require("..");
28
+ const property_1 = require("./property");
28
29
  /**
29
30
  * Implements '@indexed' decorator factory
30
31
  * This is used to specify complex service types which are need to expose
@@ -43,27 +44,35 @@ const __1 = require("..");
43
44
  * @return {(constructor: Function) => void}
44
45
  */
45
46
  function indexed(indexTypedef) {
46
- return function (constructor) {
47
- // istanbul ignore if
47
+ // Dual-mode: standard (TC39) class decorators pass a context object with a
48
+ // `kind` property; legacy ones pass only the constructor.
49
+ return function (value, context) {
50
+ const isStandard = context && typeof context === 'object' && 'kind' in context;
48
51
  if (!indexTypedef) {
49
- return; // nothing to do here
52
+ return isStandard ? undefined : value; // nothing to do here
50
53
  }
51
54
  if (typeof indexTypedef === 'function') {
52
55
  indexTypedef = indexTypedef();
53
56
  }
54
- // istanbul ignore if
55
57
  if (typeof indexTypedef !== 'string') {
56
58
  indexTypedef = String(indexTypedef);
57
59
  }
58
- const typeName = constructor.name;
59
- __1.IMQRPCDescription.typesDescription[typeName] =
60
- __1.IMQRPCDescription.typesDescription[typeName] || {
61
- indexType: indexTypedef,
62
- properties: {},
63
- inherits: Object.getPrototypeOf(constructor).name,
64
- };
65
- __1.IMQRPCDescription.typesDescription[typeName]
66
- .indexType = indexTypedef;
60
+ if (isStandard) {
61
+ // registers any @property fields on this class plus the index type
62
+ (0, property_1.registerType)(value, context.metadata, indexTypedef);
63
+ return;
64
+ }
65
+ // legacy: @property already registered the fields directly, so only
66
+ // the index type needs to be attached to the existing description
67
+ const typeName = value.name;
68
+ __1.IMQRPCDescription.typesDescription[typeName] = __1.IMQRPCDescription
69
+ .typesDescription[typeName] || {
70
+ properties: {},
71
+ inherits: Object.getPrototypeOf(value).name,
72
+ };
73
+ __1.IMQRPCDescription.typesDescription[typeName].indexType =
74
+ indexTypedef;
75
+ return value;
67
76
  };
68
77
  }
69
78
  //# sourceMappingURL=indexed.js.map
@@ -3,16 +3,15 @@ export interface LockOptions {
3
3
  skipArgs?: number[];
4
4
  }
5
5
  /**
6
- * \@lock() decorator implementation
7
- * Will make all simultaneous similar method calls locked to be resolved with
8
- * the first obtained values. Similarity is identified by a bypassed method
9
- * argument values.
6
+ * Creates a `@lock()` method decorator. Concurrent calls to the decorated
7
+ * method that share the same arguments are coalesced: only the first call is
8
+ * executed, and all the others resolve with its result. Call similarity is
9
+ * determined by the method's argument values. The returned decorator is
10
+ * dual-mode: it works both as a standard (TC39) and as a legacy method
11
+ * decorator.
10
12
  *
11
- * @param {boolean|LockOptions} enabledOrOptions - whether to enable locks or not
12
- * @return {(
13
- * target: any,
14
- * methodName: (string),
15
- * descriptor: TypedPropertyDescriptor<(...args: any[]) => any>
16
- * ) => void}
13
+ * @param {boolean | LockOptions} enabledOrOptions - whether locking is enabled,
14
+ * or the lock options
15
+ * @return {Function} - a dual-mode method decorator
17
16
  */
18
- export declare function lock(enabledOrOptions?: boolean | LockOptions): (target: any, methodName: string | symbol, descriptor: TypedPropertyDescriptor<(...args: any[]) => any>) => void;
17
+ export declare function lock(enabledOrOptions?: boolean | LockOptions): any;
@@ -25,69 +25,76 @@ exports.lock = lock;
25
25
  * <support@imqueue.com> to get commercial licensing options.
26
26
  */
27
27
  const __1 = require("..");
28
+ const helpers_1 = require("../helpers");
28
29
  /**
29
- * \@lock() decorator implementation
30
- * Will make all simultaneous similar method calls locked to be resolved with
31
- * the first obtained values. Similarity is identified by a bypassed method
32
- * argument values.
30
+ * Creates a `@lock()` method decorator. Concurrent calls to the decorated
31
+ * method that share the same arguments are coalesced: only the first call is
32
+ * executed, and all the others resolve with its result. Call similarity is
33
+ * determined by the method's argument values. The returned decorator is
34
+ * dual-mode: it works both as a standard (TC39) and as a legacy method
35
+ * decorator.
33
36
  *
34
- * @param {boolean|LockOptions} enabledOrOptions - whether to enable locks or not
35
- * @return {(
36
- * target: any,
37
- * methodName: (string),
38
- * descriptor: TypedPropertyDescriptor<(...args: any[]) => any>
39
- * ) => void}
37
+ * @param {boolean | LockOptions} enabledOrOptions - whether locking is enabled,
38
+ * or the lock options
39
+ * @return {Function} - a dual-mode method decorator
40
40
  */
41
41
  function lock(enabledOrOptions = true) {
42
- return function (target, methodName, descriptor) {
43
- const enabled = typeof enabledOrOptions === 'boolean'
44
- ? enabledOrOptions
45
- : !enabledOrOptions.disabled;
46
- const skipArgs = typeof enabledOrOptions === 'boolean'
47
- ? undefined
48
- : enabledOrOptions.skipArgs;
49
- const original = descriptor.value;
50
- const className = typeof target === 'function'
51
- ? target.name // static
52
- : target.constructor.name; // dynamic
53
- descriptor.value = async function (...args) {
54
- const withLocks = !parseInt(process.env['DISABLE_LOCKS'] + '') && enabled;
55
- let lock;
56
- let sig = '';
57
- if (withLocks) {
58
- sig = (0, __1.signature)(className, methodName, skipArgs ? args.filter((_, index) => !~skipArgs.indexOf(index)) : args);
59
- lock = await __1.IMQLock.acquire(sig, undefined, {
60
- className,
61
- methodName,
62
- args,
63
- });
64
- if (!__1.IMQLock.locked(sig)) {
65
- return lock;
66
- }
42
+ const enabled = typeof enabledOrOptions === 'boolean'
43
+ ? enabledOrOptions
44
+ : !enabledOrOptions.disabled;
45
+ const skipArgs = typeof enabledOrOptions === 'boolean'
46
+ ? undefined
47
+ : enabledOrOptions.skipArgs;
48
+ const wrap = (original, methodName, isStatic) => async function (...args) {
49
+ const className = isStatic
50
+ ? this.name // static: `this` is the class
51
+ : this.constructor.name; // dynamic: `this` is the instance
52
+ const withLocks = !parseInt(process.env['DISABLE_LOCKS'] + '') && enabled;
53
+ let lock;
54
+ let sig = '';
55
+ if (withLocks) {
56
+ sig = (0, helpers_1.signature)(className, methodName, skipArgs
57
+ ? args.filter((_, index) => !~skipArgs.indexOf(index))
58
+ : args);
59
+ lock = await __1.IMQLock.acquire(sig, undefined, {
60
+ className,
61
+ methodName,
62
+ args,
63
+ });
64
+ if (!__1.IMQLock.locked(sig)) {
65
+ return lock;
67
66
  }
68
- try {
69
- // istanbul ignore next
70
- let result = original
71
- ? original.apply(this, args)
72
- : undefined;
73
- if (result && result.then &&
74
- typeof result.then === 'function') {
75
- result = await result;
76
- }
77
- if (withLocks) {
78
- __1.IMQLock.release(sig, result);
79
- }
80
- return result;
67
+ }
68
+ try {
69
+ let result = original
70
+ ? original.apply(this, args)
71
+ : undefined;
72
+ if (result &&
73
+ result.then &&
74
+ typeof result.then === 'function') {
75
+ result = await result;
81
76
  }
82
- catch (err) {
83
- // istanbul ignore next
84
- if (withLocks) {
85
- __1.IMQLock.release(sig, null, err);
86
- }
87
- // istanbul ignore next
88
- throw err;
77
+ if (withLocks) {
78
+ __1.IMQLock.release(sig, result);
89
79
  }
90
- };
80
+ return result;
81
+ }
82
+ catch (err) {
83
+ if (withLocks) {
84
+ __1.IMQLock.release(sig, null, err);
85
+ }
86
+ throw err;
87
+ }
88
+ };
89
+ // Dual-mode: standard (TC39) invocations pass a context object with a
90
+ // `kind` property; legacy ones pass (target, propertyKey, descriptor).
91
+ return function (target, context, descriptor) {
92
+ if (context && typeof context === 'object' && 'kind' in context) {
93
+ return wrap(target, context.name, context.static);
94
+ }
95
+ const isStatic = typeof target === 'function';
96
+ descriptor.value = wrap(descriptor.value, context, isStatic);
97
+ return descriptor;
91
98
  };
92
99
  }
93
100
  //# sourceMappingURL=lock.js.map