@twin.org/tracing-facades 0.9.3-next.3

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 IOTA Stiftung.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # TWIN Tracing Facades
2
+
3
+ Applies tracing to factory produced components using a facade, without modifying them.
4
+
5
+ ## Installation
6
+
7
+ ```shell
8
+ npm install @twin.org/tracing-facades
9
+ ```
10
+
11
+ ## Examples
12
+
13
+ Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
14
+
15
+ ## Reference
16
+
17
+ Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
18
+
19
+ ## Changelog
20
+
21
+ The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
@@ -0,0 +1,7 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export * from "./models/ITracingFacadeConfig.js";
4
+ export * from "./models/ITracingFacadeConstructorOptions.js";
5
+ export * from "./models/tracingFacadeAttributes.js";
6
+ export * from "./tracingFacade.js";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,kCAAkC,CAAC;AACjD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,qCAAqC,CAAC;AACpD,cAAc,oBAAoB,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./models/ITracingFacadeConfig.js\";\nexport * from \"./models/ITracingFacadeConstructorOptions.js\";\nexport * from \"./models/tracingFacadeAttributes.js\";\nexport * from \"./tracingFacade.js\";\n"]}
@@ -0,0 +1,4 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ export {};
4
+ //# sourceMappingURL=ITracingFacadeConfig.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITracingFacadeConfig.js","sourceRoot":"","sources":["../../../src/models/ITracingFacadeConfig.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * Configuration for the tracing facade.\n *\n * The method and parameter patterns are dot separated and matched from the right, so `password`\n * and `*.*.password` both match a parameter of that name on any method of any class, while\n * `NotarizationService.create.controllerIdentity` matches only that one. A `*` matches any single\n * segment.\n */\nexport interface ITracingFacadeConfig {\n\t/**\n\t * Patterns for parameters whose values are never recorded, whatever their type, matched\n\t * against `class.method.parameter`. Supplying this replaces TracingFacade.DEFAULT_EXCLUDE_PARAMS.\n\t */\n\texcludeParams?: string[];\n\n\t/**\n\t * Patterns for methods which are not intercepted at all, matched against `class.method`.\n\t * Supplying this replaces TracingFacade.DEFAULT_EXCLUDE_METHODS.\n\t */\n\texcludeMethods?: string[];\n\n\t/**\n\t * Patterns for parameters to record even when the value is not primitive, matched against\n\t * `class.method.parameter`. A further segment selects a single property, so\n\t * `NotarizationService.create.notarization.mode` records only the mode. Any other non\n\t * primitive parameter is not recorded.\n\t */\n\tincludeObjects?: string[];\n\n\t/**\n\t * The maximum length of a recorded string, longer values are truncated.\n\t * @default 256\n\t */\n\tmaxStringLength?: number;\n\n\t/**\n\t * The maximum number of entries recorded for an array.\n\t * @default 10\n\t */\n\tmaxArrayLength?: number;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ITracingFacadeConstructorOptions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ITracingFacadeConstructorOptions.js","sourceRoot":"","sources":["../../../src/models/ITracingFacadeConstructorOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { ITracingFacadeConfig } from \"./ITracingFacadeConfig.js\";\n\n/**\n * Options for the tracing facade constructor.\n */\nexport interface ITracingFacadeConstructorOptions {\n\t/**\n\t * The component type for the optional tracing component used for spans. When it does not\n\t * resolve the facade passes every call straight through.\n\t */\n\ttracingComponentType?: string;\n\n\t/**\n\t * The component type for the optional logging component, used to report a tracing failure.\n\t */\n\tloggingComponentType?: string;\n\n\t/**\n\t * The configuration for the facade.\n\t */\n\tconfig?: ITracingFacadeConfig;\n}\n"]}
@@ -0,0 +1,21 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ /**
4
+ * The span attribute keys recorded by the tracing facade.
5
+ */
6
+ // eslint-disable-next-line @typescript-eslint/naming-convention
7
+ export const TracingFacadeAttributes = {
8
+ /**
9
+ * The name of the method the span covers.
10
+ */
11
+ Method: "method.name",
12
+ /**
13
+ * The prefix for the recorded parameter values.
14
+ */
15
+ ParamPrefix: "param.",
16
+ /**
17
+ * The returned value.
18
+ */
19
+ Result: "method.result"
20
+ };
21
+ //# sourceMappingURL=tracingFacadeAttributes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracingFacadeAttributes.js","sourceRoot":"","sources":["../../../src/models/tracingFacadeAttributes.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AAEvC;;GAEG;AACH,gEAAgE;AAChE,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC;;OAEG;IACH,MAAM,EAAE,aAAa;IAErB;;OAEG;IACH,WAAW,EAAE,QAAQ;IAErB;;OAEG;IACH,MAAM,EAAE,eAAe;CACd,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * The span attribute keys recorded by the tracing facade.\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const TracingFacadeAttributes = {\n\t/**\n\t * The name of the method the span covers.\n\t */\n\tMethod: \"method.name\",\n\n\t/**\n\t * The prefix for the recorded parameter values.\n\t */\n\tParamPrefix: \"param.\",\n\n\t/**\n\t * The returned value.\n\t */\n\tResult: \"method.result\"\n} as const;\n\n/**\n * Union type of all tracing facade attribute string values.\n */\nexport type TracingFacadeAttributes =\n\t(typeof TracingFacadeAttributes)[keyof typeof TracingFacadeAttributes];\n"]}
@@ -0,0 +1,371 @@
1
+ // Copyright 2026 IOTA Stiftung.
2
+ // SPDX-License-Identifier: Apache-2.0.
3
+ import { ComponentFactory, Is } from "@twin.org/core";
4
+ import { TracingHelper } from "@twin.org/tracing-models";
5
+ import { TracingFacadeAttributes } from "./models/tracingFacadeAttributes.js";
6
+ /**
7
+ * Facade which records a span for each external call to an async method on the component it wraps,
8
+ * so a component can be traced without being modified.
9
+ *
10
+ * Only methods declared async are traced. A span cannot be opened synchronously, so wrapping a
11
+ * synchronous method would make it return a promise and break the contract of the wrapped
12
+ * component.
13
+ */
14
+ export class TracingFacade {
15
+ /**
16
+ * Runtime name for the class.
17
+ */
18
+ static CLASS_NAME = "TracingFacade";
19
+ /**
20
+ * The methods that are excluded from tracing by default.
21
+ */
22
+ static DEFAULT_EXCLUDE_METHODS = [
23
+ "start",
24
+ "stop",
25
+ "bootstrap",
26
+ "teardown"
27
+ ];
28
+ /**
29
+ * The parameters that are excluded from recording by default.
30
+ */
31
+ static DEFAULT_EXCLUDE_PARAMS = [
32
+ "password",
33
+ "token",
34
+ "apiKey",
35
+ "mnemonic"
36
+ ];
37
+ /**
38
+ * The default maximum length of a recorded string.
39
+ */
40
+ static DEFAULT_MAX_STRING_LENGTH = 256;
41
+ /**
42
+ * The default maximum number of entries recorded for an array.
43
+ */
44
+ static DEFAULT_MAX_ARRAY_LENGTH = 10;
45
+ /**
46
+ * The name a returned value is matched under, so it can be excluded or have a property
47
+ * selected with the same patterns as a parameter.
48
+ */
49
+ static RESULT_NAME = "resolved";
50
+ /**
51
+ * A camel case parameter name, used to check the names read from the source are trustworthy.
52
+ * @internal
53
+ */
54
+ static _IDENTIFIER = /^[a-z][A-Za-z0-9]*$/;
55
+ /**
56
+ * The result of Object.prototype.toString for a method declared async. Used in preference to
57
+ * the constructor name, which throws for a function with no prototype.
58
+ * @internal
59
+ */
60
+ static _ASYNC_FUNCTION_TAG = "[object AsyncFunction]";
61
+ /**
62
+ * The component recording the spans, when absent every call passes straight through.
63
+ * @internal
64
+ */
65
+ _tracingComponent;
66
+ /**
67
+ * The component for logging a tracing failure.
68
+ * @internal
69
+ */
70
+ _loggingComponent;
71
+ /**
72
+ * Patterns for parameters whose values are never recorded.
73
+ * @internal
74
+ */
75
+ _excludeParams;
76
+ /**
77
+ * Patterns for methods which are not intercepted.
78
+ * @internal
79
+ */
80
+ _excludeMethods;
81
+ /**
82
+ * Patterns for parameters to record even when the value is not primitive.
83
+ * @internal
84
+ */
85
+ _includeObjects;
86
+ /**
87
+ * The maximum length of a recorded string.
88
+ * @internal
89
+ */
90
+ _maxStringLength;
91
+ /**
92
+ * The maximum number of entries recorded for an array.
93
+ * @internal
94
+ */
95
+ _maxArrayLength;
96
+ /**
97
+ * The wrapper for each method, held against the target as well as the method.
98
+ * @internal
99
+ */
100
+ _wrappers;
101
+ /**
102
+ * The parameter names of each method, parsed once on first use.
103
+ * @internal
104
+ */
105
+ _paramNames;
106
+ /**
107
+ * Create a new instance of TracingFacade.
108
+ * @param options The options for the facade.
109
+ */
110
+ constructor(options) {
111
+ this._tracingComponent = ComponentFactory.getIfExists(options?.tracingComponentType);
112
+ this._loggingComponent = ComponentFactory.getIfExists(options?.loggingComponentType);
113
+ this._excludeParams = (options?.config?.excludeParams ?? TracingFacade.DEFAULT_EXCLUDE_PARAMS).map(pattern => pattern.split("."));
114
+ this._excludeMethods = (options?.config?.excludeMethods ?? TracingFacade.DEFAULT_EXCLUDE_METHODS).map(pattern => pattern.split("."));
115
+ this._includeObjects = (options?.config?.includeObjects ?? []).map(pattern => {
116
+ const segments = pattern.split(".");
117
+ return {
118
+ path: segments,
119
+ root: segments.slice(0, -1),
120
+ last: segments[segments.length - 1]
121
+ };
122
+ });
123
+ this._maxStringLength =
124
+ options?.config?.maxStringLength ?? TracingFacade.DEFAULT_MAX_STRING_LENGTH;
125
+ this._maxArrayLength =
126
+ options?.config?.maxArrayLength ?? TracingFacade.DEFAULT_MAX_ARRAY_LENGTH;
127
+ this._wrappers = new WeakMap();
128
+ this._paramNames = new WeakMap();
129
+ }
130
+ /**
131
+ * Wrap the target so its method calls are recorded as spans.
132
+ * @param target The component to wrap.
133
+ * @returns The wrapped component, or the target itself when there is no tracing component.
134
+ */
135
+ wrap(target) {
136
+ if (Is.empty(this._tracingComponent)) {
137
+ return target;
138
+ }
139
+ return new Proxy(target, {
140
+ get: (t, prop, receiver) => this.interceptGet(t, prop, receiver)
141
+ });
142
+ }
143
+ /**
144
+ * Intercept a property read, returning a replacement function for a method which should be
145
+ * traced, and the value itself for anything else.
146
+ * @param target The component being wrapped.
147
+ * @param prop The property being read.
148
+ * @param receiver The proxy the read was made through.
149
+ * @returns The value for the property.
150
+ * @internal
151
+ */
152
+ interceptGet(target, prop, receiver) {
153
+ const value = Reflect.get(target, prop, receiver);
154
+ if (!Is.function(value) || !Is.string(prop)) {
155
+ return value;
156
+ }
157
+ // Wrapping a synchronous method would make it return a promise. The declaration is tested
158
+ // rather than the return value, which would open the span too late to nest inner calls.
159
+ if (Object.prototype.toString.call(value) !== TracingFacade._ASYNC_FUNCTION_TAG) {
160
+ return value;
161
+ }
162
+ const className = this.className(target);
163
+ if (this.matchesAny(this._excludeMethods, [className, prop])) {
164
+ return value;
165
+ }
166
+ return this.tracedMethod(target, className, prop, value);
167
+ }
168
+ /**
169
+ * Get the wrapper for a method, building it on first use.
170
+ * @param target The component being wrapped.
171
+ * @param className The name of the component class.
172
+ * @param name The name of the method.
173
+ * @param method The method to wrap.
174
+ * @returns The wrapper, which is the same function for every read of that method.
175
+ * @internal
176
+ */
177
+ tracedMethod(target, className, name, method) {
178
+ let wrappers = this._wrappers.get(target);
179
+ if (Is.undefined(wrappers)) {
180
+ wrappers = new WeakMap();
181
+ this._wrappers.set(target, wrappers);
182
+ }
183
+ let wrapper = wrappers.get(method);
184
+ if (Is.undefined(wrapper)) {
185
+ wrapper = async (...args) => TracingHelper.withSpan(this._tracingComponent, Is.stringValue(className) ? `method:${className}.${name}` : `method:${name}`, { attributes: this.callAttributes(className, name, method, args) }, async (span) => {
186
+ const resolved = await method.apply(target, args);
187
+ if (!Is.empty(span)) {
188
+ const recorded = this.attributeValue([className, name, TracingFacade.RESULT_NAME], resolved);
189
+ if (!Is.undefined(recorded)) {
190
+ span.attributes = {
191
+ ...span.attributes,
192
+ [TracingFacadeAttributes.Result]: recorded
193
+ };
194
+ }
195
+ }
196
+ return resolved;
197
+ }, this._loggingComponent);
198
+ wrappers.set(method, wrapper);
199
+ }
200
+ return wrapper;
201
+ }
202
+ /**
203
+ * Build the attributes describing a call.
204
+ * @param className The name of the component class.
205
+ * @param name The name of the method.
206
+ * @param method The method being called.
207
+ * @param args The arguments the method was called with.
208
+ * @returns The attributes.
209
+ * @internal
210
+ */
211
+ callAttributes(className, name, method, args) {
212
+ const attributes = {
213
+ [TracingFacadeAttributes.Method]: Is.stringValue(className) ? `${className}.${name}` : name
214
+ };
215
+ const paramNames = this.paramNames(method);
216
+ for (let i = 0; i < args.length; i++) {
217
+ const paramName = paramNames[i];
218
+ if (Is.stringValue(paramName)) {
219
+ const recorded = this.attributeValue([className, name, paramName], args[i]);
220
+ if (!Is.undefined(recorded)) {
221
+ attributes[`${TracingFacadeAttributes.ParamPrefix}${paramName}`] = recorded;
222
+ }
223
+ }
224
+ }
225
+ return attributes;
226
+ }
227
+ /**
228
+ * Decide what is recorded for a value, applying the exclusions, the object selection and the
229
+ * length limits.
230
+ * @param path The class, method and parameter name the value belongs to.
231
+ * @param value The value to record.
232
+ * @returns The value to record, or undefined when nothing is recorded.
233
+ * @internal
234
+ */
235
+ attributeValue(path, value) {
236
+ if (this.matchesAny(this._excludeParams, path)) {
237
+ return undefined;
238
+ }
239
+ const primitive = this.primitiveValue(value);
240
+ if (!Is.undefined(primitive)) {
241
+ return primitive;
242
+ }
243
+ const included = this.included(path);
244
+ if (!included.record) {
245
+ return undefined;
246
+ }
247
+ if (Is.arrayValue(included.properties)) {
248
+ if (!Is.object(value)) {
249
+ return undefined;
250
+ }
251
+ const selected = {};
252
+ for (const property of included.properties) {
253
+ selected[property] = value[property];
254
+ }
255
+ return selected;
256
+ }
257
+ return Is.array(value) ? value.slice(0, this._maxArrayLength) : value;
258
+ }
259
+ /**
260
+ * Convert a value which can be recorded as a span attribute directly.
261
+ * @param value The value to convert.
262
+ * @returns The value to record, or undefined when it is not a primitive.
263
+ * @internal
264
+ */
265
+ primitiveValue(value) {
266
+ if (Is.string(value)) {
267
+ return value.length > this._maxStringLength ? value.slice(0, this._maxStringLength) : value;
268
+ }
269
+ // A bigint cannot be serialised by JSON.stringify, so it is converted here.
270
+ if (Is.bigint(value)) {
271
+ return String(value);
272
+ }
273
+ if (Is.number(value) || Is.boolean(value) || Is.null(value)) {
274
+ return value;
275
+ }
276
+ return undefined;
277
+ }
278
+ /**
279
+ * Decide whether a non primitive value is recorded, and which of its properties are.
280
+ * @param path The class, method and parameter name the value belongs to.
281
+ * @returns Whether to record the value, and the properties to record when the patterns select
282
+ * them rather than the whole value.
283
+ * @internal
284
+ */
285
+ included(path) {
286
+ const properties = [];
287
+ for (const pattern of this._includeObjects) {
288
+ // The parameter itself is named, so the whole value is recorded.
289
+ if (this.matches(pattern.path, path)) {
290
+ return { record: true };
291
+ }
292
+ if (pattern.root.length > 0 && this.matches(pattern.root, path)) {
293
+ properties.push(pattern.last);
294
+ }
295
+ }
296
+ return properties.length > 0 ? { record: true, properties } : { record: false };
297
+ }
298
+ /**
299
+ * Does any of the patterns match the path.
300
+ * @param patterns The patterns to test.
301
+ * @param path The path to test them against.
302
+ * @returns True when one of the patterns matches.
303
+ * @internal
304
+ */
305
+ matchesAny(patterns, path) {
306
+ return patterns.some(pattern => this.matches(pattern, path));
307
+ }
308
+ /**
309
+ * Does a dot separated pattern match a path. The pattern is matched from the right, so a
310
+ * pattern shorter than the path leaves the leading segments unconstrained, and a `*` matches
311
+ * any single segment.
312
+ * @param segments The segments of the pattern to test.
313
+ * @param path The path to test it against.
314
+ * @returns True when the pattern matches.
315
+ * @internal
316
+ */
317
+ matches(segments, path) {
318
+ if (segments.length > path.length) {
319
+ return false;
320
+ }
321
+ const offset = path.length - segments.length;
322
+ return segments.every((segment, index) => segment === "*" || segment === path[offset + index]);
323
+ }
324
+ /**
325
+ * Get the name of the component class, which every IComponent implementation provides.
326
+ * @param target The component to get the name of.
327
+ * @returns The class name, or an empty string when the component does not provide one.
328
+ * @internal
329
+ */
330
+ className(target) {
331
+ const method = target.className;
332
+ if (Is.function(method)) {
333
+ const name = method.call(target);
334
+ if (Is.stringValue(name)) {
335
+ return name;
336
+ }
337
+ }
338
+ return "";
339
+ }
340
+ /**
341
+ * Get the parameter names of a method, read from its source and held for reuse. An empty list
342
+ * is returned when the names cannot be read reliably, so no parameter values are recorded
343
+ * rather than being recorded against a name which may be wrong.
344
+ * @param method The method to read the parameter names of.
345
+ * @returns The parameter names in order, or an empty list when they cannot be trusted.
346
+ * @internal
347
+ */
348
+ paramNames(method) {
349
+ let names = this._paramNames.get(method);
350
+ if (Is.undefined(names)) {
351
+ const source = method.toString();
352
+ const open = source.indexOf("(");
353
+ const close = source.indexOf(")", open);
354
+ names =
355
+ open === -1 || close === -1
356
+ ? []
357
+ : source
358
+ .slice(open + 1, close)
359
+ .split(",")
360
+ .map(param => param.trim())
361
+ .filter(param => param.length > 0);
362
+ // Anything which is not a plain identifier means the whole list is suspect, so nothing is trusted.
363
+ if (!names.every(name => TracingFacade._IDENTIFIER.test(name))) {
364
+ names = [];
365
+ }
366
+ this._paramNames.set(method, names);
367
+ }
368
+ return names;
369
+ }
370
+ }
371
+ //# sourceMappingURL=tracingFacade.js.map
@@ -0,0 +1 @@
1
+ {"version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CAAC,CAAC;oBAC1B,CAAC,CAAC,EAAE;oBACJ,CAAC,CAAC,MAAM;yBACL,KAAK,CAAC,IAAI,GAAG,CAAC,EAAE,KAAK,CAAC;yBACtB,KAAK,CAAC,GAAG,CAAC;yBACV,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;yBAC1B,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAEvC,mGAAmG;YACnG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,aAAa,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;gBAChE,KAAK,GAAG,EAAE,CAAC;YACZ,CAAC;YAED,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QACrC,CAAC;QAED,OAAO,KAAK,CAAC;IACd,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { ComponentFactory, Is, type IFacade } from \"@twin.org/core\";\nimport type { ILoggingComponent } from \"@twin.org/logging-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { TracingHelper, type ITracingComponent } from \"@twin.org/tracing-models\";\nimport type { ITracingFacadeConstructorOptions } from \"./models/ITracingFacadeConstructorOptions.js\";\nimport { TracingFacadeAttributes } from \"./models/tracingFacadeAttributes.js\";\n\n/**\n * Facade which records a span for each external call to an async method on the component it wraps,\n * so a component can be traced without being modified.\n *\n * Only methods declared async are traced. A span cannot be opened synchronously, so wrapping a\n * synchronous method would make it return a promise and break the contract of the wrapped\n * component.\n */\nexport class TracingFacade implements IFacade {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<TracingFacade>();\n\n\t/**\n\t * The methods that are excluded from tracing by default.\n\t */\n\tpublic static readonly DEFAULT_EXCLUDE_METHODS: string[] = [\n\t\t\"start\",\n\t\t\"stop\",\n\t\t\"bootstrap\",\n\t\t\"teardown\"\n\t];\n\n\t/**\n\t * The parameters that are excluded from recording by default.\n\t */\n\tpublic static readonly DEFAULT_EXCLUDE_PARAMS: string[] = [\n\t\t\"password\",\n\t\t\"token\",\n\t\t\"apiKey\",\n\t\t\"mnemonic\"\n\t];\n\n\t/**\n\t * The default maximum length of a recorded string.\n\t */\n\tpublic static readonly DEFAULT_MAX_STRING_LENGTH: number = 256;\n\n\t/**\n\t * The default maximum number of entries recorded for an array.\n\t */\n\tpublic static readonly DEFAULT_MAX_ARRAY_LENGTH: number = 10;\n\n\t/**\n\t * The name a returned value is matched under, so it can be excluded or have a property\n\t * selected with the same patterns as a parameter.\n\t */\n\tpublic static readonly RESULT_NAME: string = \"resolved\";\n\n\t/**\n\t * A camel case parameter name, used to check the names read from the source are trustworthy.\n\t * @internal\n\t */\n\tprivate static readonly _IDENTIFIER: RegExp = /^[a-z][A-Za-z0-9]*$/;\n\n\t/**\n\t * The result of Object.prototype.toString for a method declared async. Used in preference to\n\t * the constructor name, which throws for a function with no prototype.\n\t * @internal\n\t */\n\tprivate static readonly _ASYNC_FUNCTION_TAG: string = \"[object AsyncFunction]\";\n\n\t/**\n\t * The component recording the spans, when absent every call passes straight through.\n\t * @internal\n\t */\n\tprivate readonly _tracingComponent?: ITracingComponent;\n\n\t/**\n\t * The component for logging a tracing failure.\n\t * @internal\n\t */\n\tprivate readonly _loggingComponent?: ILoggingComponent;\n\n\t/**\n\t * Patterns for parameters whose values are never recorded.\n\t * @internal\n\t */\n\tprivate readonly _excludeParams: string[][];\n\n\t/**\n\t * Patterns for methods which are not intercepted.\n\t * @internal\n\t */\n\tprivate readonly _excludeMethods: string[][];\n\n\t/**\n\t * Patterns for parameters to record even when the value is not primitive.\n\t * @internal\n\t */\n\tprivate readonly _includeObjects: { path: string[]; root: string[]; last: string }[];\n\n\t/**\n\t * The maximum length of a recorded string.\n\t * @internal\n\t */\n\tprivate readonly _maxStringLength: number;\n\n\t/**\n\t * The maximum number of entries recorded for an array.\n\t * @internal\n\t */\n\tprivate readonly _maxArrayLength: number;\n\n\t/**\n\t * The wrapper for each method, held against the target as well as the method.\n\t * @internal\n\t */\n\tprivate readonly _wrappers: WeakMap<\n\t\tobject,\n\t\tWeakMap<object, (...args: unknown[]) => Promise<unknown>>\n\t>;\n\n\t/**\n\t * The parameter names of each method, parsed once on first use.\n\t * @internal\n\t */\n\tprivate readonly _paramNames: WeakMap<object, string[]>;\n\n\t/**\n\t * Create a new instance of TracingFacade.\n\t * @param options The options for the facade.\n\t */\n\tconstructor(options?: ITracingFacadeConstructorOptions) {\n\t\tthis._tracingComponent = ComponentFactory.getIfExists(options?.tracingComponentType);\n\t\tthis._loggingComponent = ComponentFactory.getIfExists(options?.loggingComponentType);\n\t\tthis._excludeParams = (\n\t\t\toptions?.config?.excludeParams ?? TracingFacade.DEFAULT_EXCLUDE_PARAMS\n\t\t).map(pattern => pattern.split(\".\"));\n\t\tthis._excludeMethods = (\n\t\t\toptions?.config?.excludeMethods ?? TracingFacade.DEFAULT_EXCLUDE_METHODS\n\t\t).map(pattern => pattern.split(\".\"));\n\t\tthis._includeObjects = (options?.config?.includeObjects ?? []).map(pattern => {\n\t\t\tconst segments = pattern.split(\".\");\n\n\t\t\treturn {\n\t\t\t\tpath: segments,\n\t\t\t\troot: segments.slice(0, -1),\n\t\t\t\tlast: segments[segments.length - 1]\n\t\t\t};\n\t\t});\n\t\tthis._maxStringLength =\n\t\t\toptions?.config?.maxStringLength ?? TracingFacade.DEFAULT_MAX_STRING_LENGTH;\n\t\tthis._maxArrayLength =\n\t\t\toptions?.config?.maxArrayLength ?? TracingFacade.DEFAULT_MAX_ARRAY_LENGTH;\n\t\tthis._wrappers = new WeakMap();\n\t\tthis._paramNames = new WeakMap();\n\t}\n\n\t/**\n\t * Wrap the target so its method calls are recorded as spans.\n\t * @param target The component to wrap.\n\t * @returns The wrapped component, or the target itself when there is no tracing component.\n\t */\n\tpublic wrap<T>(target: T): T {\n\t\tif (Is.empty(this._tracingComponent)) {\n\t\t\treturn target;\n\t\t}\n\n\t\treturn new Proxy(target as { [key: string]: unknown }, {\n\t\t\tget: (t, prop, receiver): unknown => this.interceptGet(t, prop, receiver)\n\t\t}) as T;\n\t}\n\n\t/**\n\t * Intercept a property read, returning a replacement function for a method which should be\n\t * traced, and the value itself for anything else.\n\t * @param target The component being wrapped.\n\t * @param prop The property being read.\n\t * @param receiver The proxy the read was made through.\n\t * @returns The value for the property.\n\t * @internal\n\t */\n\tprivate interceptGet(\n\t\ttarget: { [key: string]: unknown },\n\t\tprop: string | symbol,\n\t\treceiver: unknown\n\t): unknown {\n\t\tconst value = Reflect.get(target, prop, receiver);\n\n\t\tif (!Is.function(value) || !Is.string(prop)) {\n\t\t\treturn value;\n\t\t}\n\n\t\t// Wrapping a synchronous method would make it return a promise. The declaration is tested\n\t\t// rather than the return value, which would open the span too late to nest inner calls.\n\t\tif (Object.prototype.toString.call(value) !== TracingFacade._ASYNC_FUNCTION_TAG) {\n\t\t\treturn value;\n\t\t}\n\n\t\tconst className = this.className(target);\n\n\t\tif (this.matchesAny(this._excludeMethods, [className, prop])) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn this.tracedMethod(target, className, prop, value);\n\t}\n\n\t/**\n\t * Get the wrapper for a method, building it on first use.\n\t * @param target The component being wrapped.\n\t * @param className The name of the component class.\n\t * @param name The name of the method.\n\t * @param method The method to wrap.\n\t * @returns The wrapper, which is the same function for every read of that method.\n\t * @internal\n\t */\n\tprivate tracedMethod(\n\t\ttarget: { [key: string]: unknown },\n\t\tclassName: string,\n\t\tname: string,\n\t\tmethod: (...args: unknown[]) => unknown\n\t): (...args: unknown[]) => Promise<unknown> {\n\t\tlet wrappers = this._wrappers.get(target);\n\n\t\tif (Is.undefined(wrappers)) {\n\t\t\twrappers = new WeakMap();\n\t\t\tthis._wrappers.set(target, wrappers);\n\t\t}\n\n\t\tlet wrapper = wrappers.get(method);\n\n\t\tif (Is.undefined(wrapper)) {\n\t\t\twrapper = async (...args: unknown[]): Promise<unknown> =>\n\t\t\t\tTracingHelper.withSpan(\n\t\t\t\t\tthis._tracingComponent,\n\t\t\t\t\tIs.stringValue(className) ? `method:${className}.${name}` : `method:${name}`,\n\t\t\t\t\t{ attributes: this.callAttributes(className, name, method, args) },\n\t\t\t\t\tasync span => {\n\t\t\t\t\t\tconst resolved = await method.apply(target, args);\n\n\t\t\t\t\t\tif (!Is.empty(span)) {\n\t\t\t\t\t\t\tconst recorded = this.attributeValue(\n\t\t\t\t\t\t\t\t[className, name, TracingFacade.RESULT_NAME],\n\t\t\t\t\t\t\t\tresolved\n\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\tif (!Is.undefined(recorded)) {\n\t\t\t\t\t\t\t\tspan.attributes = {\n\t\t\t\t\t\t\t\t\t...span.attributes,\n\t\t\t\t\t\t\t\t\t[TracingFacadeAttributes.Result]: recorded\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn resolved;\n\t\t\t\t\t},\n\t\t\t\t\tthis._loggingComponent\n\t\t\t\t);\n\n\t\t\twrappers.set(method, wrapper);\n\t\t}\n\n\t\treturn wrapper;\n\t}\n\n\t/**\n\t * Build the attributes describing a call.\n\t * @param className The name of the component class.\n\t * @param name The name of the method.\n\t * @param method The method being called.\n\t * @param args The arguments the method was called with.\n\t * @returns The attributes.\n\t * @internal\n\t */\n\tprivate callAttributes(\n\t\tclassName: string,\n\t\tname: string,\n\t\tmethod: (...args: unknown[]) => unknown,\n\t\targs: unknown[]\n\t): { [key: string]: unknown } {\n\t\tconst attributes: { [key: string]: unknown } = {\n\t\t\t[TracingFacadeAttributes.Method]: Is.stringValue(className) ? `${className}.${name}` : name\n\t\t};\n\n\t\tconst paramNames = this.paramNames(method);\n\n\t\tfor (let i = 0; i < args.length; i++) {\n\t\t\tconst paramName = paramNames[i];\n\n\t\t\tif (Is.stringValue(paramName)) {\n\t\t\t\tconst recorded = this.attributeValue([className, name, paramName], args[i]);\n\n\t\t\t\tif (!Is.undefined(recorded)) {\n\t\t\t\t\tattributes[`${TracingFacadeAttributes.ParamPrefix}${paramName}`] = recorded;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn attributes;\n\t}\n\n\t/**\n\t * Decide what is recorded for a value, applying the exclusions, the object selection and the\n\t * length limits.\n\t * @param path The class, method and parameter name the value belongs to.\n\t * @param value The value to record.\n\t * @returns The value to record, or undefined when nothing is recorded.\n\t * @internal\n\t */\n\tprivate attributeValue(path: string[], value: unknown): unknown {\n\t\tif (this.matchesAny(this._excludeParams, path)) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst primitive = this.primitiveValue(value);\n\n\t\tif (!Is.undefined(primitive)) {\n\t\t\treturn primitive;\n\t\t}\n\n\t\tconst included = this.included(path);\n\n\t\tif (!included.record) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (Is.arrayValue(included.properties)) {\n\t\t\tif (!Is.object<{ [key: string]: unknown }>(value)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tconst selected: { [key: string]: unknown } = {};\n\t\t\tfor (const property of included.properties) {\n\t\t\t\tselected[property] = value[property];\n\t\t\t}\n\n\t\t\treturn selected;\n\t\t}\n\n\t\treturn Is.array(value) ? value.slice(0, this._maxArrayLength) : value;\n\t}\n\n\t/**\n\t * Convert a value which can be recorded as a span attribute directly.\n\t * @param value The value to convert.\n\t * @returns The value to record, or undefined when it is not a primitive.\n\t * @internal\n\t */\n\tprivate primitiveValue(value: unknown): unknown {\n\t\tif (Is.string(value)) {\n\t\t\treturn value.length > this._maxStringLength ? value.slice(0, this._maxStringLength) : value;\n\t\t}\n\n\t\t// A bigint cannot be serialised by JSON.stringify, so it is converted here.\n\t\tif (Is.bigint(value)) {\n\t\t\treturn String(value);\n\t\t}\n\n\t\tif (Is.number(value) || Is.boolean(value) || Is.null(value)) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Decide whether a non primitive value is recorded, and which of its properties are.\n\t * @param path The class, method and parameter name the value belongs to.\n\t * @returns Whether to record the value, and the properties to record when the patterns select\n\t * them rather than the whole value.\n\t * @internal\n\t */\n\tprivate included(path: string[]): { record: boolean; properties?: string[] } {\n\t\tconst properties: string[] = [];\n\n\t\tfor (const pattern of this._includeObjects) {\n\t\t\t// The parameter itself is named, so the whole value is recorded.\n\t\t\tif (this.matches(pattern.path, path)) {\n\t\t\t\treturn { record: true };\n\t\t\t}\n\n\t\t\tif (pattern.root.length > 0 && this.matches(pattern.root, path)) {\n\t\t\t\tproperties.push(pattern.last);\n\t\t\t}\n\t\t}\n\n\t\treturn properties.length > 0 ? { record: true, properties } : { record: false };\n\t}\n\n\t/**\n\t * Does any of the patterns match the path.\n\t * @param patterns The patterns to test.\n\t * @param path The path to test them against.\n\t * @returns True when one of the patterns matches.\n\t * @internal\n\t */\n\tprivate matchesAny(patterns: string[][], path: string[]): boolean {\n\t\treturn patterns.some(pattern => this.matches(pattern, path));\n\t}\n\n\t/**\n\t * Does a dot separated pattern match a path. The pattern is matched from the right, so a\n\t * pattern shorter than the path leaves the leading segments unconstrained, and a `*` matches\n\t * any single segment.\n\t * @param segments The segments of the pattern to test.\n\t * @param path The path to test it against.\n\t * @returns True when the pattern matches.\n\t * @internal\n\t */\n\tprivate matches(segments: string[], path: string[]): boolean {\n\t\tif (segments.length > path.length) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst offset = path.length - segments.length;\n\n\t\treturn segments.every((segment, index) => segment === \"*\" || segment === path[offset + index]);\n\t}\n\n\t/**\n\t * Get the name of the component class, which every IComponent implementation provides.\n\t * @param target The component to get the name of.\n\t * @returns The class name, or an empty string when the component does not provide one.\n\t * @internal\n\t */\n\tprivate className(target: { [key: string]: unknown }): string {\n\t\tconst method = target.className;\n\n\t\tif (Is.function(method)) {\n\t\t\tconst name = method.call(target);\n\n\t\t\tif (Is.stringValue(name)) {\n\t\t\t\treturn name;\n\t\t\t}\n\t\t}\n\n\t\treturn \"\";\n\t}\n\n\t/**\n\t * Get the parameter names of a method, read from its source and held for reuse. An empty list\n\t * is returned when the names cannot be read reliably, so no parameter values are recorded\n\t * rather than being recorded against a name which may be wrong.\n\t * @param method The method to read the parameter names of.\n\t * @returns The parameter names in order, or an empty list when they cannot be trusted.\n\t * @internal\n\t */\n\tprivate paramNames(method: (...args: unknown[]) => unknown): string[] {\n\t\tlet names = this._paramNames.get(method);\n\n\t\tif (Is.undefined(names)) {\n\t\t\tconst source = method.toString();\n\t\t\tconst open = source.indexOf(\"(\");\n\t\t\tconst close = source.indexOf(\")\", open);\n\n\t\t\tnames =\n\t\t\t\topen === -1 || close === -1\n\t\t\t\t\t? []\n\t\t\t\t\t: source\n\t\t\t\t\t\t\t.slice(open + 1, close)\n\t\t\t\t\t\t\t.split(\",\")\n\t\t\t\t\t\t\t.map(param => param.trim())\n\t\t\t\t\t\t\t.filter(param => param.length > 0);\n\n\t\t\t// Anything which is not a plain identifier means the whole list is suspect, so nothing is trusted.\n\t\t\tif (!names.every(name => TracingFacade._IDENTIFIER.test(name))) {\n\t\t\t\tnames = [];\n\t\t\t}\n\n\t\t\tthis._paramNames.set(method, names);\n\t\t}\n\n\t\treturn names;\n\t}\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export * from "./models/ITracingFacadeConfig.js";
2
+ export * from "./models/ITracingFacadeConstructorOptions.js";
3
+ export * from "./models/tracingFacadeAttributes.js";
4
+ export * from "./tracingFacade.js";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Configuration for the tracing facade.
3
+ *
4
+ * The method and parameter patterns are dot separated and matched from the right, so `password`
5
+ * and `*.*.password` both match a parameter of that name on any method of any class, while
6
+ * `NotarizationService.create.controllerIdentity` matches only that one. A `*` matches any single
7
+ * segment.
8
+ */
9
+ export interface ITracingFacadeConfig {
10
+ /**
11
+ * Patterns for parameters whose values are never recorded, whatever their type, matched
12
+ * against `class.method.parameter`. Supplying this replaces TracingFacade.DEFAULT_EXCLUDE_PARAMS.
13
+ */
14
+ excludeParams?: string[];
15
+ /**
16
+ * Patterns for methods which are not intercepted at all, matched against `class.method`.
17
+ * Supplying this replaces TracingFacade.DEFAULT_EXCLUDE_METHODS.
18
+ */
19
+ excludeMethods?: string[];
20
+ /**
21
+ * Patterns for parameters to record even when the value is not primitive, matched against
22
+ * `class.method.parameter`. A further segment selects a single property, so
23
+ * `NotarizationService.create.notarization.mode` records only the mode. Any other non
24
+ * primitive parameter is not recorded.
25
+ */
26
+ includeObjects?: string[];
27
+ /**
28
+ * The maximum length of a recorded string, longer values are truncated.
29
+ * @default 256
30
+ */
31
+ maxStringLength?: number;
32
+ /**
33
+ * The maximum number of entries recorded for an array.
34
+ * @default 10
35
+ */
36
+ maxArrayLength?: number;
37
+ }
@@ -0,0 +1,19 @@
1
+ import type { ITracingFacadeConfig } from "./ITracingFacadeConfig.js";
2
+ /**
3
+ * Options for the tracing facade constructor.
4
+ */
5
+ export interface ITracingFacadeConstructorOptions {
6
+ /**
7
+ * The component type for the optional tracing component used for spans. When it does not
8
+ * resolve the facade passes every call straight through.
9
+ */
10
+ tracingComponentType?: string;
11
+ /**
12
+ * The component type for the optional logging component, used to report a tracing failure.
13
+ */
14
+ loggingComponentType?: string;
15
+ /**
16
+ * The configuration for the facade.
17
+ */
18
+ config?: ITracingFacadeConfig;
19
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The span attribute keys recorded by the tracing facade.
3
+ */
4
+ export declare const TracingFacadeAttributes: {
5
+ /**
6
+ * The name of the method the span covers.
7
+ */
8
+ readonly Method: "method.name";
9
+ /**
10
+ * The prefix for the recorded parameter values.
11
+ */
12
+ readonly ParamPrefix: "param.";
13
+ /**
14
+ * The returned value.
15
+ */
16
+ readonly Result: "method.result";
17
+ };
18
+ /**
19
+ * Union type of all tracing facade attribute string values.
20
+ */
21
+ export type TracingFacadeAttributes = (typeof TracingFacadeAttributes)[keyof typeof TracingFacadeAttributes];
@@ -0,0 +1,48 @@
1
+ import { type IFacade } from "@twin.org/core";
2
+ import type { ITracingFacadeConstructorOptions } from "./models/ITracingFacadeConstructorOptions.js";
3
+ /**
4
+ * Facade which records a span for each external call to an async method on the component it wraps,
5
+ * so a component can be traced without being modified.
6
+ *
7
+ * Only methods declared async are traced. A span cannot be opened synchronously, so wrapping a
8
+ * synchronous method would make it return a promise and break the contract of the wrapped
9
+ * component.
10
+ */
11
+ export declare class TracingFacade implements IFacade {
12
+ /**
13
+ * Runtime name for the class.
14
+ */
15
+ static readonly CLASS_NAME: string;
16
+ /**
17
+ * The methods that are excluded from tracing by default.
18
+ */
19
+ static readonly DEFAULT_EXCLUDE_METHODS: string[];
20
+ /**
21
+ * The parameters that are excluded from recording by default.
22
+ */
23
+ static readonly DEFAULT_EXCLUDE_PARAMS: string[];
24
+ /**
25
+ * The default maximum length of a recorded string.
26
+ */
27
+ static readonly DEFAULT_MAX_STRING_LENGTH: number;
28
+ /**
29
+ * The default maximum number of entries recorded for an array.
30
+ */
31
+ static readonly DEFAULT_MAX_ARRAY_LENGTH: number;
32
+ /**
33
+ * The name a returned value is matched under, so it can be excluded or have a property
34
+ * selected with the same patterns as a parameter.
35
+ */
36
+ static readonly RESULT_NAME: string;
37
+ /**
38
+ * Create a new instance of TracingFacade.
39
+ * @param options The options for the facade.
40
+ */
41
+ constructor(options?: ITracingFacadeConstructorOptions);
42
+ /**
43
+ * Wrap the target so its method calls are recorded as spans.
44
+ * @param target The component to wrap.
45
+ * @returns The wrapped component, or the target itself when there is no tracing component.
46
+ */
47
+ wrap<T>(target: T): T;
48
+ }
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## [0.9.3-next.3](https://github.com/iotaledger/twin-tracing/compare/tracing-processors-v0.9.3-next.2...tracing-processors-v0.9.3-next.3) (2026-09-08)
4
+
5
+
6
+ ### Features
7
+
8
+ * tracing facade ([#43](https://github.com/iotaledger/twin-tracing/issues/43)) ([83f23ef](https://github.com/iotaledger/twin-tracing/commit/83f23eff032cc8be235ebfb33c5582bfa1c95ddf))
9
+
10
+
11
+ ### Dependencies
12
+
13
+ * The following workspace dependencies were updated
14
+ * dependencies
15
+ * @twin.org/tracing-models bumped from 0.9.3-next.2 to 0.9.3-next.3
16
+
17
+ ## Changelog
@@ -0,0 +1,124 @@
1
+ # Tracing Facades Examples
2
+
3
+ A facade wraps the components a factory produces, so tracing is applied without the component
4
+ being modified. Registering one and activating it on a factory traces everything that factory
5
+ hands out.
6
+
7
+ ## Setup
8
+
9
+ ```typescript
10
+ import { ComponentFactory, FacadeFactory } from '@twin.org/core';
11
+ import { TracingFacade } from '@twin.org/tracing-facades';
12
+
13
+ FacadeFactory.register(
14
+ 'tracing',
15
+ () => new TracingFacade({ tracingComponentType: 'tracing', loggingComponentType: 'logging' })
16
+ );
17
+
18
+ ComponentFactory.useFacade('tracing');
19
+ ```
20
+
21
+ Every component the factory produces from that point on records a span named
22
+ `method:<class>.<name>` for each method called on it. With no tracing component registered the target is returned unwrapped,
23
+ so this is safe to activate unconditionally. A tracing connector which fails does not interrupt
24
+ the call it was recording, and the failure is reported to the logging component when one is
25
+ configured.
26
+
27
+ ## What is recorded
28
+
29
+ The span carries the method name, the arguments by parameter name, and the returned value when it
30
+ is primitive. A failure records the error message and ends the span with an error status.
31
+
32
+ ```text
33
+ method:NotarizationService.create
34
+ { "method.name": "NotarizationService.create", "method.result": "urn:..." }
35
+ ```
36
+
37
+ A parameter whose value is not primitive is recorded as present but without its value, so the
38
+ shape of the call is visible without serialising a payload into the trace.
39
+
40
+ ## Keeping values out of a span
41
+
42
+ Patterns are dot separated and matched from the right, so a bare name applies everywhere and a
43
+ fully qualified one applies to a single method.
44
+
45
+ ```typescript
46
+ config: {
47
+ excludeParams: [
48
+ ...TracingFacade.DEFAULT_EXCLUDE_PARAMS,
49
+ 'NotarizationService.create.controllerIdentity'
50
+ ];
51
+ }
52
+ ```
53
+
54
+ `DEFAULT_EXCLUDE_PARAMS` covers `password`, `token`, `apiKey` and `mnemonic`, and applies when
55
+ `excludeParams` is not supplied. Spread it into a custom list to keep it.
56
+
57
+ `includeObjects` records a parameter whose value is not primitive. A further segment selects a
58
+ single property, so only that is recorded.
59
+
60
+ ```typescript
61
+ config: {
62
+ includeObjects: [
63
+ 'NotarizationService.create.notarization.mode',
64
+ 'BlobStorageService.create.options'
65
+ ];
66
+ }
67
+ ```
68
+
69
+ Any other non primitive parameter is not recorded, so a payload never reaches the trace unless it
70
+ is named.
71
+
72
+ ## Limiting what is recorded
73
+
74
+ A recorded string is truncated to `maxStringLength`, which defaults to 256, since some methods are
75
+ passed base64 content. An included array is limited to `maxArrayLength` entries, which defaults
76
+ to 10.
77
+
78
+ ```typescript
79
+ config: {
80
+ maxStringLength: 128,
81
+ maxArrayLength: 5;
82
+ }
83
+ ```
84
+
85
+ The returned value is recorded under the name `resolved`, so it is excluded or property selected
86
+ with the same patterns.
87
+
88
+ ```typescript
89
+ config: {
90
+ excludeParams: ['IdentityService.verifiableCredentialCreate.resolved'];
91
+ }
92
+ ```
93
+
94
+ ## Methods which are not traced
95
+
96
+ `excludeMethods` passes the named methods straight through, with no span recorded.
97
+ `DEFAULT_EXCLUDE_METHODS` covers `start`, `stop`, `bootstrap` and `teardown`, the lifecycle
98
+ methods which are called once and carry no request context.
99
+
100
+ ```typescript
101
+ config: {
102
+ excludeMethods: [...TracingFacade.DEFAULT_EXCLUDE_METHODS, 'IdentityService.identityResolve'];
103
+ }
104
+ ```
105
+
106
+ Only external calls to methods declared `async` are recorded. Opening a span is asynchronous, so
107
+ wrapping a synchronous method would make it return a promise and break the contract of the
108
+ component being wrapped.
109
+
110
+ ## Choosing what gets traced
111
+
112
+ Facades are activated per factory, so the granularity is yours.
113
+
114
+ ```typescript
115
+ ComponentFactory.useFacade('tracing'); // every service
116
+ EntityStorageConnectorFactory.useFacade('tracing'); // every storage operation
117
+ ```
118
+
119
+ Deactivating applies to instances produced from that point on, since an instance already handed
120
+ out cannot be unwrapped.
121
+
122
+ ```typescript
123
+ ComponentFactory.unuseFacade('tracing');
124
+ ```
@@ -0,0 +1,113 @@
1
+ # Class: TracingFacade
2
+
3
+ Facade which records a span for each external call to an async method on the component it wraps,
4
+ so a component can be traced without being modified.
5
+
6
+ Only methods declared async are traced. A span cannot be opened synchronously, so wrapping a
7
+ synchronous method would make it return a promise and break the contract of the wrapped
8
+ component.
9
+
10
+ ## Implements
11
+
12
+ - `IFacade`
13
+
14
+ ## Constructors
15
+
16
+ ### Constructor
17
+
18
+ > **new TracingFacade**(`options?`): `TracingFacade`
19
+
20
+ Create a new instance of TracingFacade.
21
+
22
+ #### Parameters
23
+
24
+ ##### options?
25
+
26
+ [`ITracingFacadeConstructorOptions`](../interfaces/ITracingFacadeConstructorOptions.md)
27
+
28
+ The options for the facade.
29
+
30
+ #### Returns
31
+
32
+ `TracingFacade`
33
+
34
+ ## Properties
35
+
36
+ ### CLASS\_NAME {#class_name}
37
+
38
+ > `readonly` `static` **CLASS\_NAME**: `string`
39
+
40
+ Runtime name for the class.
41
+
42
+ ***
43
+
44
+ ### DEFAULT\_EXCLUDE\_METHODS {#default_exclude_methods}
45
+
46
+ > `readonly` `static` **DEFAULT\_EXCLUDE\_METHODS**: `string`[]
47
+
48
+ The methods that are excluded from tracing by default.
49
+
50
+ ***
51
+
52
+ ### DEFAULT\_EXCLUDE\_PARAMS {#default_exclude_params}
53
+
54
+ > `readonly` `static` **DEFAULT\_EXCLUDE\_PARAMS**: `string`[]
55
+
56
+ The parameters that are excluded from recording by default.
57
+
58
+ ***
59
+
60
+ ### DEFAULT\_MAX\_STRING\_LENGTH {#default_max_string_length}
61
+
62
+ > `readonly` `static` **DEFAULT\_MAX\_STRING\_LENGTH**: `number` = `256`
63
+
64
+ The default maximum length of a recorded string.
65
+
66
+ ***
67
+
68
+ ### DEFAULT\_MAX\_ARRAY\_LENGTH {#default_max_array_length}
69
+
70
+ > `readonly` `static` **DEFAULT\_MAX\_ARRAY\_LENGTH**: `number` = `10`
71
+
72
+ The default maximum number of entries recorded for an array.
73
+
74
+ ***
75
+
76
+ ### RESULT\_NAME {#result_name}
77
+
78
+ > `readonly` `static` **RESULT\_NAME**: `string` = `"resolved"`
79
+
80
+ The name a returned value is matched under, so it can be excluded or have a property
81
+ selected with the same patterns as a parameter.
82
+
83
+ ## Methods
84
+
85
+ ### wrap() {#wrap}
86
+
87
+ > **wrap**\<`T`\>(`target`): `T`
88
+
89
+ Wrap the target so its method calls are recorded as spans.
90
+
91
+ #### Type Parameters
92
+
93
+ ##### T
94
+
95
+ `T`
96
+
97
+ #### Parameters
98
+
99
+ ##### target
100
+
101
+ `T`
102
+
103
+ The component to wrap.
104
+
105
+ #### Returns
106
+
107
+ `T`
108
+
109
+ The wrapped component, or the target itself when there is no tracing component.
110
+
111
+ #### Implementation of
112
+
113
+ `IFacade.wrap`
@@ -0,0 +1,18 @@
1
+ # @twin.org/tracing-facades
2
+
3
+ ## Classes
4
+
5
+ - [TracingFacade](classes/TracingFacade.md)
6
+
7
+ ## Interfaces
8
+
9
+ - [ITracingFacadeConfig](interfaces/ITracingFacadeConfig.md)
10
+ - [ITracingFacadeConstructorOptions](interfaces/ITracingFacadeConstructorOptions.md)
11
+
12
+ ## Type Aliases
13
+
14
+ - [TracingFacadeAttributes](type-aliases/TracingFacadeAttributes.md)
15
+
16
+ ## Variables
17
+
18
+ - [TracingFacadeAttributes](variables/TracingFacadeAttributes.md)
@@ -0,0 +1,65 @@
1
+ # Interface: ITracingFacadeConfig
2
+
3
+ Configuration for the tracing facade.
4
+
5
+ The method and parameter patterns are dot separated and matched from the right, so `password`
6
+ and `*.*.password` both match a parameter of that name on any method of any class, while
7
+ `NotarizationService.create.controllerIdentity` matches only that one. A `*` matches any single
8
+ segment.
9
+
10
+ ## Properties
11
+
12
+ ### excludeParams? {#excludeparams}
13
+
14
+ > `optional` **excludeParams?**: `string`[]
15
+
16
+ Patterns for parameters whose values are never recorded, whatever their type, matched
17
+ against `class.method.parameter`. Supplying this replaces TracingFacade.DEFAULT_EXCLUDE_PARAMS.
18
+
19
+ ***
20
+
21
+ ### excludeMethods? {#excludemethods}
22
+
23
+ > `optional` **excludeMethods?**: `string`[]
24
+
25
+ Patterns for methods which are not intercepted at all, matched against `class.method`.
26
+ Supplying this replaces TracingFacade.DEFAULT_EXCLUDE_METHODS.
27
+
28
+ ***
29
+
30
+ ### includeObjects? {#includeobjects}
31
+
32
+ > `optional` **includeObjects?**: `string`[]
33
+
34
+ Patterns for parameters to record even when the value is not primitive, matched against
35
+ `class.method.parameter`. A further segment selects a single property, so
36
+ `NotarizationService.create.notarization.mode` records only the mode. Any other non
37
+ primitive parameter is not recorded.
38
+
39
+ ***
40
+
41
+ ### maxStringLength? {#maxstringlength}
42
+
43
+ > `optional` **maxStringLength?**: `number`
44
+
45
+ The maximum length of a recorded string, longer values are truncated.
46
+
47
+ #### Default
48
+
49
+ ```ts
50
+ 256
51
+ ```
52
+
53
+ ***
54
+
55
+ ### maxArrayLength? {#maxarraylength}
56
+
57
+ > `optional` **maxArrayLength?**: `number`
58
+
59
+ The maximum number of entries recorded for an array.
60
+
61
+ #### Default
62
+
63
+ ```ts
64
+ 10
65
+ ```
@@ -0,0 +1,28 @@
1
+ # Interface: ITracingFacadeConstructorOptions
2
+
3
+ Options for the tracing facade constructor.
4
+
5
+ ## Properties
6
+
7
+ ### tracingComponentType? {#tracingcomponenttype}
8
+
9
+ > `optional` **tracingComponentType?**: `string`
10
+
11
+ The component type for the optional tracing component used for spans. When it does not
12
+ resolve the facade passes every call straight through.
13
+
14
+ ***
15
+
16
+ ### loggingComponentType? {#loggingcomponenttype}
17
+
18
+ > `optional` **loggingComponentType?**: `string`
19
+
20
+ The component type for the optional logging component, used to report a tracing failure.
21
+
22
+ ***
23
+
24
+ ### config? {#config}
25
+
26
+ > `optional` **config?**: [`ITracingFacadeConfig`](ITracingFacadeConfig.md)
27
+
28
+ The configuration for the facade.
@@ -0,0 +1,5 @@
1
+ # Type Alias: TracingFacadeAttributes
2
+
3
+ > **TracingFacadeAttributes** = *typeof* [`TracingFacadeAttributes`](../variables/TracingFacadeAttributes.md)\[keyof *typeof* [`TracingFacadeAttributes`](../variables/TracingFacadeAttributes.md)\]
4
+
5
+ Union type of all tracing facade attribute string values.
@@ -0,0 +1,25 @@
1
+ # Variable: TracingFacadeAttributes
2
+
3
+ > `const` **TracingFacadeAttributes**: `object`
4
+
5
+ The span attribute keys recorded by the tracing facade.
6
+
7
+ ## Type Declaration
8
+
9
+ ### Method {#method}
10
+
11
+ > `readonly` **Method**: `"method.name"` = `"method.name"`
12
+
13
+ The name of the method the span covers.
14
+
15
+ ### ParamPrefix {#paramprefix}
16
+
17
+ > `readonly` **ParamPrefix**: `"param."` = `"param."`
18
+
19
+ The prefix for the recorded parameter values.
20
+
21
+ ### Result {#result}
22
+
23
+ > `readonly` **Result**: `"method.result"` = `"method.result"`
24
+
25
+ The returned value.
@@ -0,0 +1 @@
1
+ {}
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@twin.org/tracing-facades",
3
+ "version": "0.9.3-next.3",
4
+ "description": "Applies tracing to factory produced components using a facade, without modifying them.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/iotaledger/twin-tracing.git",
8
+ "directory": "packages/tracing-facades"
9
+ },
10
+ "author": "martyn.janes@iota.org",
11
+ "license": "Apache-2.0",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=20.0.0"
15
+ },
16
+ "dependencies": {
17
+ "@twin.org/core": "^0.9.3-next.3",
18
+ "@twin.org/logging-models": "next",
19
+ "@twin.org/nameof": "next",
20
+ "@twin.org/tracing-models": "0.9.3-next.3"
21
+ },
22
+ "main": "./dist/es/index.js",
23
+ "types": "./dist/types/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/types/index.d.ts",
27
+ "import": "./dist/es/index.js",
28
+ "default": "./dist/es/index.js"
29
+ },
30
+ "./locales/*.json": "./locales/*.json"
31
+ },
32
+ "files": [
33
+ "dist/es",
34
+ "dist/types",
35
+ "locales",
36
+ "docs"
37
+ ],
38
+ "keywords": [
39
+ "twin",
40
+ "trade",
41
+ "iota",
42
+ "framework",
43
+ "blockchain",
44
+ "tracing",
45
+ "spans",
46
+ "facade",
47
+ "proxy",
48
+ "instrumentation",
49
+ "observability"
50
+ ],
51
+ "bugs": {
52
+ "url": "git+https://github.com/iotaledger/twin-tracing/issues"
53
+ },
54
+ "homepage": "https://twindev.org"
55
+ }