@private.me/xbind 3.0.1 → 3.0.2

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 (210) hide show
  1. package/README.md +55 -14
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.js +163 -1
  174. package/dist-standalone/plugins/metrics.js +176 -1
  175. package/dist-standalone/plugins/validation.js +297 -1
  176. package/dist-standalone/policy.js +315 -1
  177. package/dist-standalone/progress-callbacks.js +576 -1
  178. package/dist-standalone/redis-nonce-store.js +72 -1
  179. package/dist-standalone/registry-middleware.js +47 -1
  180. package/dist-standalone/retry-strategies.js +534 -1
  181. package/dist-standalone/retry-transport.js +98 -1
  182. package/dist-standalone/runtime/browser.js +516 -1
  183. package/dist-standalone/runtime/edge.js +511 -1
  184. package/dist-standalone/runtime/react-native.js +383 -1
  185. package/dist-standalone/security-policy.js +239 -1
  186. package/dist-standalone/serialization.js +1031 -1
  187. package/dist-standalone/split-channel.js +219 -1
  188. package/dist-standalone/subscription-proof.js +224 -1
  189. package/dist-standalone/succession.js +142 -1
  190. package/dist-standalone/timeouts.js +398 -1
  191. package/dist-standalone/trace-context.js +414 -1
  192. package/dist-standalone/trace-spans.js +488 -1
  193. package/dist-standalone/transport.js +59 -1
  194. package/dist-standalone/trust-registry.js +950 -1
  195. package/dist-standalone/types/error-response.js +52 -1
  196. package/dist-standalone/vault-auth.js +174 -1
  197. package/dist-standalone/vault-store-loader.js +187 -1
  198. package/dist-standalone/verify.js +16 -1
  199. package/dist-standalone/version-info.js +530 -1
  200. package/dist-standalone/xfetch.js +335 -1
  201. package/package.json +4 -13
  202. package/share1.dat +0 -0
  203. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  204. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  205. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  206. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  207. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  208. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  209. package/dist-standalone/cjs/package.json +0 -3
  210. package/dist-standalone/package.json +0 -10
@@ -1 +1,488 @@
1
- import{TraceContext,generateSpanId}from"./trace-context.js";export var SpanStatusCode;!function(t){t[t.OK=0]="OK",t[t.ERROR=1]="ERROR",t[t.UNSET=2]="UNSET"}(SpanStatusCode||(SpanStatusCode={}));export var SpanKind;!function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"}(SpanKind||(SpanKind={}));export class TraceSpan{spanId;traceContext;name;kind;parentSpanId;startTime;endTime;status;attributes;events;ended;constructor(t,e,n={}){this.spanId=generateSpanId(),this.traceContext=e,this.name=t,this.kind=n.kind??SpanKind.INTERNAL,this.parentSpanId=n.parentSpanId,this.startTime=Date.now(),this.status={code:SpanStatusCode.UNSET},this.attributes=n.attributes??{},this.events=[],this.ended=!1}setAttribute(t,e){if(this.ended)throw new Error("Cannot set attribute on ended span");return this.attributes[t]=e,this}setAttributes(t){if(this.ended)throw new Error("Cannot set attributes on ended span");return Object.assign(this.attributes,t),this}addEvent(t,e){if(this.ended)throw new Error("Cannot add event to ended span");return this.events.push({name:t,timestamp:Date.now(),attributes:e}),this}setStatus(t,e){if(this.ended)throw new Error("Cannot set status on ended span");return this.status={code:t,message:e},this}recordException(t){if(this.ended)throw new Error("Cannot record exception on ended span");this.setStatus(SpanStatusCode.ERROR);const e={};return t instanceof Error?(e["exception.type"]=t.name,e["exception.message"]=t.message,t.stack&&(e["exception.stacktrace"]=t.stack)):e["exception.message"]=String(t),this.addEvent("exception",e),this}end(t){this.ended||(this.endTime=t??Date.now(),this.ended=!0,this.status.code===SpanStatusCode.UNSET&&(this.status={code:SpanStatusCode.OK}))}isEnded(){return this.ended}getDuration(){return this.ended&&this.endTime?this.endTime-this.startTime:null}toData(){if(!this.ended||!this.endTime)throw new Error("Cannot export data from active span. Call end() first.");return{spanId:this.spanId,traceId:this.traceContext.traceId,parentSpanId:this.parentSpanId,name:this.name,kind:this.kind,startTime:this.startTime,endTime:this.endTime,duration:this.endTime-this.startTime,status:{...this.status},attributes:{...this.attributes},events:this.events.map(t=>({name:t.name,timestamp:t.timestamp,attributes:t.attributes?{...t.attributes}:void 0}))}}createChild(t,e={}){return new TraceSpan(t,this.traceContext,{...e,parentSpanId:this.spanId})}}export class SpanRecorder{activeSpans;completedSpans;maxSpans;rootContext;constructor(t={}){this.activeSpans=new Map,this.completedSpans=[],this.maxSpans=t.maxSpans??1e3,this.rootContext=t.traceContext}startSpan(t,e={}){const n=e.traceContext??e.parentSpan?.traceContext??this.rootContext??TraceContext.create(),a=new TraceSpan(t,n,{kind:e.kind,attributes:e.attributes,parentSpanId:e.parentSpan?.spanId});this.activeSpans.set(a.spanId,a);const s=setTimeout(()=>{a.isEnded()||(a.setStatus(SpanStatusCode.ERROR,"Span not ended (auto-ended by recorder)"),this.endSpan(a))},6e4),r=a.end.bind(a);return a.end=t=>{clearTimeout(s),r(t),this.endSpan(a)},a}endSpan(t){t.isEnded()||t.end(),this.activeSpans.delete(t.spanId);const e=t.toData();this.completedSpans.push(e),this.completedSpans.length>this.maxSpans&&this.completedSpans.shift()}getCompletedSpans(){return[...this.completedSpans]}getActiveSpans(){return Array.from(this.activeSpans.values())}clearCompletedSpans(){this.completedSpans=[]}getSpanCount(){return{active:this.activeSpans.size,completed:this.completedSpans.length}}findSpansByTraceId(t){return this.completedSpans.filter(e=>e.traceId===t)}buildTraceTree(t){const e=this.findSpansByTraceId(t);if(0===e.length)return null;const n=e.find(t=>!t.parentSpanId);return n?buildSpanTreeNode(n,e):null}}function buildSpanTreeNode(t,e){const n=e.filter(e=>e.parentSpanId===t.spanId).map(t=>buildSpanTreeNode(t,e));return{span:t,children:n}}export async function measureAsync(t,e,n,a){const s=t.startSpan(e,a);try{const t=await n();return s.setStatus(SpanStatusCode.OK),t}catch(t){throw s.recordException(t),t}finally{s.end()}}export function measureSync(t,e,n,a){const s=t.startSpan(e,a);try{const t=n();return s.setStatus(SpanStatusCode.OK),t}catch(t){throw s.recordException(t),t}finally{s.end()}}
1
+ /**
2
+ * @module trace-spans
3
+ * Distributed tracing spans with parent-child relationships
4
+ *
5
+ * Provides span tracking for distributed tracing with automatic timing,
6
+ * attribute collection, and integration with W3C Trace Context.
7
+ *
8
+ * Performance target: <1ms overhead per operation
9
+ *
10
+ * Usage:
11
+ * ```typescript
12
+ * import { TraceSpan, SpanRecorder } from '@private.me/xbind';
13
+ *
14
+ * // Create a span recorder
15
+ * const recorder = new SpanRecorder();
16
+ *
17
+ * // Start a span
18
+ * const span = recorder.startSpan('operation-name', { attr: 'value' });
19
+ *
20
+ * // Do work...
21
+ *
22
+ * // End the span
23
+ * span.end();
24
+ *
25
+ * // Get completed spans
26
+ * const spans = recorder.getCompletedSpans();
27
+ * ```
28
+ */
29
+ import { TraceContext, generateSpanId } from './trace-context.js';
30
+ /**
31
+ * Span status codes (aligned with OpenTelemetry)
32
+ */
33
+ export var SpanStatusCode;
34
+ (function (SpanStatusCode) {
35
+ /** Operation completed successfully */
36
+ SpanStatusCode[SpanStatusCode["OK"] = 0] = "OK";
37
+ /** Operation encountered an error */
38
+ SpanStatusCode[SpanStatusCode["ERROR"] = 1] = "ERROR";
39
+ /** Status is unset (default) */
40
+ SpanStatusCode[SpanStatusCode["UNSET"] = 2] = "UNSET";
41
+ })(SpanStatusCode || (SpanStatusCode = {}));
42
+ /**
43
+ * Span kind (aligned with OpenTelemetry)
44
+ */
45
+ export var SpanKind;
46
+ (function (SpanKind) {
47
+ /** Internal span (default) */
48
+ SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL";
49
+ /** Server span (handling incoming request) */
50
+ SpanKind[SpanKind["SERVER"] = 1] = "SERVER";
51
+ /** Client span (outgoing request) */
52
+ SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT";
53
+ /** Producer span (message queue producer) */
54
+ SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER";
55
+ /** Consumer span (message queue consumer) */
56
+ SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER";
57
+ })(SpanKind || (SpanKind = {}));
58
+ /**
59
+ * Trace span for distributed tracing
60
+ *
61
+ * Represents a single unit of work in a distributed trace with automatic timing.
62
+ */
63
+ export class TraceSpan {
64
+ /** Span ID (unique within trace) */
65
+ spanId;
66
+ /** Trace context */
67
+ traceContext;
68
+ /** Span name */
69
+ name;
70
+ /** Span kind */
71
+ kind;
72
+ /** Parent span ID */
73
+ parentSpanId;
74
+ /** Start timestamp (milliseconds since epoch) */
75
+ startTime;
76
+ /** End timestamp (milliseconds since epoch, undefined if not ended) */
77
+ endTime;
78
+ /** Span status */
79
+ status;
80
+ /** Span attributes */
81
+ attributes;
82
+ /** Span events */
83
+ events;
84
+ /** Whether span has ended */
85
+ ended;
86
+ /**
87
+ * Create a trace span
88
+ *
89
+ * @param name - Span name
90
+ * @param traceContext - Trace context
91
+ * @param options - Span options
92
+ */
93
+ constructor(name, traceContext, options = {}) {
94
+ this.spanId = generateSpanId();
95
+ this.traceContext = traceContext;
96
+ this.name = name;
97
+ this.kind = options.kind ?? SpanKind.INTERNAL;
98
+ this.parentSpanId = options.parentSpanId;
99
+ this.startTime = Date.now();
100
+ this.status = { code: SpanStatusCode.UNSET };
101
+ this.attributes = options.attributes ?? {};
102
+ this.events = [];
103
+ this.ended = false;
104
+ }
105
+ /**
106
+ * Set span attribute
107
+ *
108
+ * @param key - Attribute key
109
+ * @param value - Attribute value
110
+ * @returns This span (for chaining)
111
+ */
112
+ setAttribute(key, value) {
113
+ if (this.ended) {
114
+ throw new Error('Cannot set attribute on ended span');
115
+ }
116
+ this.attributes[key] = value;
117
+ return this;
118
+ }
119
+ /**
120
+ * Set multiple span attributes
121
+ *
122
+ * @param attributes - Attributes to set
123
+ * @returns This span (for chaining)
124
+ */
125
+ setAttributes(attributes) {
126
+ if (this.ended) {
127
+ throw new Error('Cannot set attributes on ended span');
128
+ }
129
+ Object.assign(this.attributes, attributes);
130
+ return this;
131
+ }
132
+ /**
133
+ * Add an event to the span
134
+ *
135
+ * Events are timestamped log entries within a span.
136
+ *
137
+ * @param name - Event name
138
+ * @param attributes - Optional event attributes
139
+ * @returns This span (for chaining)
140
+ */
141
+ addEvent(name, attributes) {
142
+ if (this.ended) {
143
+ throw new Error('Cannot add event to ended span');
144
+ }
145
+ this.events.push({
146
+ name,
147
+ timestamp: Date.now(),
148
+ attributes,
149
+ });
150
+ return this;
151
+ }
152
+ /**
153
+ * Set span status
154
+ *
155
+ * @param code - Status code
156
+ * @param message - Optional status message
157
+ * @returns This span (for chaining)
158
+ */
159
+ setStatus(code, message) {
160
+ if (this.ended) {
161
+ throw new Error('Cannot set status on ended span');
162
+ }
163
+ this.status = { code, message };
164
+ return this;
165
+ }
166
+ /**
167
+ * Record an exception in the span
168
+ *
169
+ * Automatically sets status to ERROR and adds exception event.
170
+ *
171
+ * @param error - Error to record
172
+ * @returns This span (for chaining)
173
+ */
174
+ recordException(error) {
175
+ if (this.ended) {
176
+ throw new Error('Cannot record exception on ended span');
177
+ }
178
+ this.setStatus(SpanStatusCode.ERROR);
179
+ const attributes = {};
180
+ if (error instanceof Error) {
181
+ attributes['exception.type'] = error.name;
182
+ attributes['exception.message'] = error.message;
183
+ if (error.stack) {
184
+ attributes['exception.stacktrace'] = error.stack;
185
+ }
186
+ }
187
+ else {
188
+ attributes['exception.message'] = String(error);
189
+ }
190
+ this.addEvent('exception', attributes);
191
+ return this;
192
+ }
193
+ /**
194
+ * End the span
195
+ *
196
+ * Records the end timestamp and marks the span as complete.
197
+ * If status is UNSET, automatically sets to OK.
198
+ *
199
+ * @param endTime - Optional end timestamp (defaults to now)
200
+ */
201
+ end(endTime) {
202
+ if (this.ended) {
203
+ return; // Idempotent
204
+ }
205
+ this.endTime = endTime ?? Date.now();
206
+ this.ended = true;
207
+ // Auto-set status to OK if unset
208
+ if (this.status.code === SpanStatusCode.UNSET) {
209
+ this.status = { code: SpanStatusCode.OK };
210
+ }
211
+ }
212
+ /**
213
+ * Check if span has ended
214
+ *
215
+ * @returns True if ended
216
+ */
217
+ isEnded() {
218
+ return this.ended;
219
+ }
220
+ /**
221
+ * Get span duration in milliseconds
222
+ *
223
+ * @returns Duration or null if not ended
224
+ */
225
+ getDuration() {
226
+ if (!this.ended || !this.endTime)
227
+ return null;
228
+ return this.endTime - this.startTime;
229
+ }
230
+ /**
231
+ * Export span data
232
+ *
233
+ * @returns Span data (throws if span not ended)
234
+ */
235
+ toData() {
236
+ if (!this.ended || !this.endTime) {
237
+ throw new Error('Cannot export data from active span. Call end() first.');
238
+ }
239
+ return {
240
+ spanId: this.spanId,
241
+ traceId: this.traceContext.traceId,
242
+ parentSpanId: this.parentSpanId,
243
+ name: this.name,
244
+ kind: this.kind,
245
+ startTime: this.startTime,
246
+ endTime: this.endTime,
247
+ duration: this.endTime - this.startTime,
248
+ status: { ...this.status },
249
+ attributes: { ...this.attributes },
250
+ events: this.events.map((e) => ({
251
+ name: e.name,
252
+ timestamp: e.timestamp,
253
+ attributes: e.attributes ? { ...e.attributes } : undefined,
254
+ })),
255
+ };
256
+ }
257
+ /**
258
+ * Create a child span
259
+ *
260
+ * The child span will have the same trace ID but a new span ID.
261
+ *
262
+ * @param name - Child span name
263
+ * @param options - Span options
264
+ * @returns New child span
265
+ */
266
+ createChild(name, options = {}) {
267
+ return new TraceSpan(name, this.traceContext, {
268
+ ...options,
269
+ parentSpanId: this.spanId,
270
+ });
271
+ }
272
+ }
273
+ /**
274
+ * Span recorder for collecting completed spans
275
+ *
276
+ * Manages span lifecycle and provides access to completed span data.
277
+ */
278
+ export class SpanRecorder {
279
+ /** Active spans (not yet ended) */
280
+ activeSpans;
281
+ /** Completed spans */
282
+ completedSpans;
283
+ /** Maximum number of completed spans to keep (prevent memory leak) */
284
+ maxSpans;
285
+ /** Trace context for root spans */
286
+ rootContext;
287
+ /**
288
+ * Create a span recorder
289
+ *
290
+ * @param options - Recorder options
291
+ */
292
+ constructor(options = {}) {
293
+ this.activeSpans = new Map();
294
+ this.completedSpans = [];
295
+ this.maxSpans = options.maxSpans ?? 1000;
296
+ this.rootContext = options.traceContext;
297
+ }
298
+ /**
299
+ * Start a new span
300
+ *
301
+ * @param name - Span name
302
+ * @param options - Span options
303
+ * @returns New span
304
+ */
305
+ startSpan(name, options = {}) {
306
+ const context = options.traceContext ??
307
+ options.parentSpan?.traceContext ??
308
+ this.rootContext ??
309
+ TraceContext.create();
310
+ const span = new TraceSpan(name, context, {
311
+ kind: options.kind,
312
+ attributes: options.attributes,
313
+ parentSpanId: options.parentSpan?.spanId,
314
+ });
315
+ this.activeSpans.set(span.spanId, span);
316
+ // Auto-end on next tick if forgotten (safety measure)
317
+ // This prevents memory leaks from forgotten spans
318
+ const timeout = setTimeout(() => {
319
+ if (!span.isEnded()) {
320
+ span.setStatus(SpanStatusCode.ERROR, 'Span not ended (auto-ended by recorder)');
321
+ this.endSpan(span);
322
+ }
323
+ }, 60000); // 60 second timeout
324
+ // Clear timeout if span ends normally
325
+ const originalEnd = span.end.bind(span);
326
+ span.end = (endTime) => {
327
+ clearTimeout(timeout);
328
+ originalEnd(endTime);
329
+ this.endSpan(span);
330
+ };
331
+ return span;
332
+ }
333
+ /**
334
+ * End a span and record its data
335
+ *
336
+ * @param span - Span to end
337
+ */
338
+ endSpan(span) {
339
+ if (!span.isEnded()) {
340
+ span.end();
341
+ }
342
+ // Remove from active spans
343
+ this.activeSpans.delete(span.spanId);
344
+ // Add to completed spans
345
+ const data = span.toData();
346
+ this.completedSpans.push(data);
347
+ // Enforce max spans limit (FIFO)
348
+ if (this.completedSpans.length > this.maxSpans) {
349
+ this.completedSpans.shift();
350
+ }
351
+ }
352
+ /**
353
+ * Get all completed spans
354
+ *
355
+ * @returns Array of completed span data
356
+ */
357
+ getCompletedSpans() {
358
+ return [...this.completedSpans];
359
+ }
360
+ /**
361
+ * Get active spans
362
+ *
363
+ * @returns Array of active spans
364
+ */
365
+ getActiveSpans() {
366
+ return Array.from(this.activeSpans.values());
367
+ }
368
+ /**
369
+ * Clear all completed spans
370
+ */
371
+ clearCompletedSpans() {
372
+ this.completedSpans = [];
373
+ }
374
+ /**
375
+ * Get span count
376
+ *
377
+ * @returns Object with active and completed span counts
378
+ */
379
+ getSpanCount() {
380
+ return {
381
+ active: this.activeSpans.size,
382
+ completed: this.completedSpans.length,
383
+ };
384
+ }
385
+ /**
386
+ * Find completed spans by trace ID
387
+ *
388
+ * @param traceId - Trace ID to search for
389
+ * @returns Array of matching spans
390
+ */
391
+ findSpansByTraceId(traceId) {
392
+ return this.completedSpans.filter((span) => span.traceId === traceId);
393
+ }
394
+ /**
395
+ * Build trace tree from completed spans
396
+ *
397
+ * Groups spans by trace ID and builds parent-child relationships.
398
+ *
399
+ * @param traceId - Trace ID to build tree for
400
+ * @returns Tree structure
401
+ */
402
+ buildTraceTree(traceId) {
403
+ const spans = this.findSpansByTraceId(traceId);
404
+ if (spans.length === 0)
405
+ return null;
406
+ // Find root span (no parent)
407
+ const root = spans.find((s) => !s.parentSpanId);
408
+ if (!root)
409
+ return null;
410
+ // Build tree recursively
411
+ return buildSpanTreeNode(root, spans);
412
+ }
413
+ }
414
+ /**
415
+ * Build span tree node recursively
416
+ *
417
+ * @param span - Current span
418
+ * @param allSpans - All spans in trace
419
+ * @returns Tree node
420
+ */
421
+ function buildSpanTreeNode(span, allSpans) {
422
+ const children = allSpans
423
+ .filter((s) => s.parentSpanId === span.spanId)
424
+ .map((child) => buildSpanTreeNode(child, allSpans));
425
+ return { span, children };
426
+ }
427
+ /**
428
+ * Helper function to measure async operation with automatic span tracking
429
+ *
430
+ * @param recorder - Span recorder
431
+ * @param name - Span name
432
+ * @param fn - Async function to measure
433
+ * @param options - Span options
434
+ * @returns Result of async function
435
+ *
436
+ * @example
437
+ * ```typescript
438
+ * const result = await measureAsync(recorder, 'database-query', async () => {
439
+ * return await db.query('SELECT * FROM users');
440
+ * });
441
+ * ```
442
+ */
443
+ export async function measureAsync(recorder, name, fn, options) {
444
+ const span = recorder.startSpan(name, options);
445
+ try {
446
+ const result = await fn();
447
+ span.setStatus(SpanStatusCode.OK);
448
+ return result;
449
+ }
450
+ catch (error) {
451
+ span.recordException(error);
452
+ throw error;
453
+ }
454
+ finally {
455
+ span.end();
456
+ }
457
+ }
458
+ /**
459
+ * Helper function to measure sync operation with automatic span tracking
460
+ *
461
+ * @param recorder - Span recorder
462
+ * @param name - Span name
463
+ * @param fn - Sync function to measure
464
+ * @param options - Span options
465
+ * @returns Result of sync function
466
+ *
467
+ * @example
468
+ * ```typescript
469
+ * const result = measureSync(recorder, 'encryption', () => {
470
+ * return encrypt(data, key);
471
+ * });
472
+ * ```
473
+ */
474
+ export function measureSync(recorder, name, fn, options) {
475
+ const span = recorder.startSpan(name, options);
476
+ try {
477
+ const result = fn();
478
+ span.setStatus(SpanStatusCode.OK);
479
+ return result;
480
+ }
481
+ catch (error) {
482
+ span.recordException(error);
483
+ throw error;
484
+ }
485
+ finally {
486
+ span.end();
487
+ }
488
+ }
@@ -1 +1,59 @@
1
- import{ok,err}from"./_deps/shared/index.js";export class HttpsTransportAdapter{baseUrl;timeoutMs;fetchFn;handlers=[];constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,""),this.timeoutMs=t.timeoutMs??1e4,this.fetchFn=t.fetch??globalThis.fetch.bind(globalThis)}async send(t,e){const s=`${this.baseUrl}/deliver/${encodeURIComponent(e)}`;try{const e=new AbortController,r=setTimeout(()=>e.abort(),this.timeoutMs),o=await this.fetchFn(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:e.signal});return clearTimeout(r),o.ok?ok(void 0):err(404===o.status?"RECIPIENT_UNREACHABLE":"SEND_FAILED")}catch(t){return t instanceof DOMException&&"AbortError"===t.name?err("TIMEOUT"):err("NETWORK_ERROR")}}onReceive(t){this.handlers.push(t)}dispatch(t){for(const e of this.handlers)e(t)}dispose(){this.handlers=[]}}
1
+ import { ok, err } from"./_deps/shared/index.js";
2
+ /**
3
+ * HTTPS transport adapter — sends envelopes as JSON POST requests.
4
+ *
5
+ * Recipient URL resolved as: baseUrl/deliver/{recipientDid}
6
+ * This is the SDK's default transport for server-to-server delivery.
7
+ */
8
+ export class HttpsTransportAdapter {
9
+ baseUrl;
10
+ timeoutMs;
11
+ fetchFn;
12
+ handlers = [];
13
+ constructor(opts) {
14
+ this.baseUrl = opts.baseUrl.replace(/\/$/, '');
15
+ this.timeoutMs = opts.timeoutMs ?? 10_000;
16
+ this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
17
+ }
18
+ async send(envelope, recipientDid) {
19
+ const url = `${this.baseUrl}/deliver/${encodeURIComponent(recipientDid)}`;
20
+ try {
21
+ const controller = new AbortController();
22
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
23
+ const response = await this.fetchFn(url, {
24
+ method: 'POST',
25
+ headers: { 'Content-Type': 'application/json' },
26
+ body: JSON.stringify(envelope),
27
+ signal: controller.signal,
28
+ });
29
+ clearTimeout(timer);
30
+ if (!response.ok) {
31
+ return err(response.status === 404
32
+ ? 'RECIPIENT_UNREACHABLE'
33
+ : 'SEND_FAILED');
34
+ }
35
+ return ok(undefined);
36
+ }
37
+ catch (e) {
38
+ if (e instanceof DOMException && e.name === 'AbortError') {
39
+ return err('TIMEOUT');
40
+ }
41
+ return err('NETWORK_ERROR');
42
+ }
43
+ }
44
+ onReceive(handler) {
45
+ this.handlers.push(handler);
46
+ }
47
+ /**
48
+ * Dispatch a received envelope to all handlers.
49
+ * Called by the server when an incoming POST is received.
50
+ */
51
+ dispatch(envelope) {
52
+ for (const handler of this.handlers) {
53
+ handler(envelope);
54
+ }
55
+ }
56
+ dispose() {
57
+ this.handlers = [];
58
+ }
59
+ }