@private.me/xbind 3.0.0 → 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 (217) hide show
  1. package/README.md +55 -7
  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.d.ts +84 -0
  174. package/dist-standalone/plugins/logging.js +163 -0
  175. package/dist-standalone/plugins/metrics.d.ts +111 -0
  176. package/dist-standalone/plugins/metrics.js +176 -0
  177. package/dist-standalone/plugins/validation.d.ts +104 -0
  178. package/dist-standalone/plugins/validation.js +297 -0
  179. package/dist-standalone/policy.js +315 -1
  180. package/dist-standalone/progress-callbacks.js +576 -1
  181. package/dist-standalone/redis-nonce-store.js +72 -1
  182. package/dist-standalone/registry-middleware.js +47 -1
  183. package/dist-standalone/retry-strategies.js +534 -1
  184. package/dist-standalone/retry-transport.js +98 -1
  185. package/dist-standalone/runtime/browser.d.ts +311 -0
  186. package/dist-standalone/runtime/browser.js +516 -0
  187. package/dist-standalone/runtime/edge.d.ts +282 -0
  188. package/dist-standalone/runtime/edge.js +511 -0
  189. package/dist-standalone/runtime/react-native.d.ts +157 -0
  190. package/dist-standalone/runtime/react-native.js +383 -0
  191. package/dist-standalone/security-policy.js +239 -1
  192. package/dist-standalone/serialization.js +1031 -1
  193. package/dist-standalone/split-channel.js +219 -1
  194. package/dist-standalone/subscription-proof.js +224 -1
  195. package/dist-standalone/succession.js +142 -1
  196. package/dist-standalone/timeouts.js +398 -1
  197. package/dist-standalone/trace-context.js +414 -1
  198. package/dist-standalone/trace-spans.js +488 -1
  199. package/dist-standalone/transport.js +59 -1
  200. package/dist-standalone/trust-registry.js +950 -1
  201. package/dist-standalone/types/error-response.d.ts +209 -0
  202. package/dist-standalone/types/error-response.js +52 -0
  203. package/dist-standalone/vault-auth.js +174 -1
  204. package/dist-standalone/vault-store-loader.js +187 -1
  205. package/dist-standalone/verify.js +16 -1
  206. package/dist-standalone/version-info.js +530 -1
  207. package/dist-standalone/xfetch.js +335 -1
  208. package/package.json +4 -10
  209. package/share1.dat +0 -0
  210. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  211. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  212. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  213. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  214. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  215. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  216. package/dist-standalone/cjs/package.json +0 -3
  217. package/dist-standalone/package.json +0 -10
@@ -1 +1,336 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createHealthChecker=createHealthChecker,exports.healthEndpoint=healthEndpoint;class HealthCheckerImpl{startTime;registry;transport;serviceName;version;environment;timeoutMs;enableStartupProbe;startupComplete=!1;constructor(t={}){this.startTime=Date.now(),this.registry=t.registry,this.transport=t.transport,this.serviceName=t.serviceName,this.version=t.version,this.environment=t.environment,this.timeoutMs=t.timeoutMs??5e3,this.enableStartupProbe=t.enableStartupProbe??!0}markStartupComplete(){this.startupComplete=!0}isStartupComplete(){return this.startupComplete}async check(t="readiness"){const e=(new Date).toISOString(),s=Math.floor((Date.now()-this.startTime)/1e3);if("startup"===t&&this.enableStartupProbe){const t=[{name:"startup",status:this.startupComplete?"healthy":"unhealthy",message:this.startupComplete?"Initialization complete":"Waiting for startup completion (call markStartupComplete())",lastCheck:e}];return{healthy:this.startupComplete,timestamp:e,uptimeSeconds:s,components:t,metadata:this.buildMetadata()}}if("liveness"===t){return{healthy:!0,timestamp:e,uptimeSeconds:s,components:[{name:"self",status:"healthy",message:"Service responsive",lastCheck:e}],metadata:this.buildMetadata()}}const a=[];if(this.registry){const t=await this.checkRegistry();a.push(t)}if(this.transport){const t=await this.checkTransport();a.push(t)}0===a.length&&a.push({name:"self",status:"healthy",message:"No dependencies configured",lastCheck:e});return{healthy:a.every(t=>"healthy"===t.status),timestamp:e,uptimeSeconds:s,components:a,metadata:this.buildMetadata()}}buildMetadata(){const t={};return this.serviceName&&(t.service=this.serviceName),this.version&&(t.version=this.version),this.environment&&(t.environment=this.environment),Object.keys(t).length>0?t:void 0}async checkRegistry(){const t=Date.now(),e=(new Date).toISOString();try{if(!this.registry)return{name:"registry",status:"unhealthy",message:"Registry not configured",lastCheck:e};const s=await this.withTimeout(this.registry.resolve("did:xail:health_check_probe"),this.timeoutMs),a=Date.now()-t;if(s&&"object"==typeof s&&"ok"in s){if(s.ok)return{name:"registry",status:"healthy",message:"Registry responding",latencyMs:a,lastCheck:e};{const t="string"==typeof s.error?s.error:"UNKNOWN";return t.includes("NOT_FOUND")?{name:"registry",status:"healthy",message:"Registry responding",latencyMs:a,lastCheck:e}:{name:"registry",status:"unhealthy",message:`Registry error: ${t}`,latencyMs:a,lastCheck:e}}}return{name:"registry",status:"healthy",message:"Registry responding",latencyMs:a,lastCheck:e}}catch(s){const a=Date.now()-t,r=s instanceof Error?s.message:"Unknown error";return r.toLowerCase().includes("timeout")?{name:"registry",status:"degraded",message:`Registry slow (>${this.timeoutMs}ms)`,latencyMs:a,lastCheck:e}:{name:"registry",status:"unhealthy",message:`Registry error: ${r}`,latencyMs:a,lastCheck:e}}}async checkTransport(){const t=Date.now(),e=(new Date).toISOString();try{if(!this.transport)return{name:"transport",status:"unhealthy",message:"Transport not configured",lastCheck:e};return{name:"transport",status:"healthy",message:"Transport adapter available",latencyMs:Date.now()-t,lastCheck:e}}catch(s){const a=Date.now()-t;return{name:"transport",status:"unhealthy",message:`Transport error: ${s instanceof Error?s.message:"Unknown error"}`,latencyMs:a,lastCheck:e}}}async withTimeout(t,e){return Promise.race([t,new Promise((t,s)=>setTimeout(()=>s(new Error("Health check timeout")),e))])}}function createHealthChecker(t){return new HealthCheckerImpl(t)}function healthEndpoint(t,e="readiness"){return async(s,a)=>{try{const s=await t.check(e),r=s.healthy?200:503;a.status(r).json(s)}catch(t){const e=t instanceof Error?t.message:"Unknown error";a.status(503).json({healthy:!1,timestamp:(new Date).toISOString(),uptimeSeconds:0,components:[{name:"health-check",status:"unhealthy",message:`Health check failed: ${e}`,lastCheck:(new Date).toISOString()}]})}}}
1
+ "use strict";
2
+ /**
3
+ * @module health-check
4
+ * Health check endpoint for operational monitoring and load balancer probes.
5
+ *
6
+ * Provides three probe types following Kubernetes health check patterns:
7
+ * - **Startup probe**: Verify initialization complete (one-time check)
8
+ * - **Readiness probe**: Verify dependencies ready (registry, transport)
9
+ * - **Liveness probe**: Verify service responsive (self-check)
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { createHealthChecker } from '@private.me/xbind';
14
+ *
15
+ * const checker = createHealthChecker({
16
+ * registry: myTrustRegistry,
17
+ * transport: myTransport
18
+ * });
19
+ *
20
+ * // Load balancer endpoint
21
+ * app.get('/health', async (req, res) => {
22
+ * const status = await checker.check();
23
+ * res.status(status.healthy ? 200 : 503).json(status);
24
+ * });
25
+ * ```
26
+ */
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.createHealthChecker = createHealthChecker;
29
+ exports.healthEndpoint = healthEndpoint;
30
+ /* ── Implementation ── */
31
+ class HealthCheckerImpl {
32
+ startTime;
33
+ registry;
34
+ transport;
35
+ serviceName;
36
+ version;
37
+ environment;
38
+ timeoutMs;
39
+ enableStartupProbe;
40
+ startupComplete = false;
41
+ constructor(options = {}) {
42
+ this.startTime = Date.now();
43
+ this.registry = options.registry;
44
+ this.transport = options.transport;
45
+ this.serviceName = options.serviceName;
46
+ this.version = options.version;
47
+ this.environment = options.environment;
48
+ this.timeoutMs = options.timeoutMs ?? 5000;
49
+ this.enableStartupProbe = options.enableStartupProbe ?? true;
50
+ }
51
+ markStartupComplete() {
52
+ this.startupComplete = true;
53
+ }
54
+ isStartupComplete() {
55
+ return this.startupComplete;
56
+ }
57
+ async check(probe = 'readiness') {
58
+ const timestamp = new Date().toISOString();
59
+ const uptimeSeconds = Math.floor((Date.now() - this.startTime) / 1000);
60
+ // Startup probe: Check if initialization complete
61
+ if (probe === 'startup' && this.enableStartupProbe) {
62
+ const components = [
63
+ {
64
+ name: 'startup',
65
+ status: this.startupComplete ? 'healthy' : 'unhealthy',
66
+ message: this.startupComplete
67
+ ? 'Initialization complete'
68
+ : 'Waiting for startup completion (call markStartupComplete())',
69
+ lastCheck: timestamp,
70
+ },
71
+ ];
72
+ return {
73
+ healthy: this.startupComplete,
74
+ timestamp,
75
+ uptimeSeconds,
76
+ components,
77
+ metadata: this.buildMetadata(),
78
+ };
79
+ }
80
+ // Liveness probe: Basic self-check (service responsive)
81
+ if (probe === 'liveness') {
82
+ const components = [
83
+ {
84
+ name: 'self',
85
+ status: 'healthy',
86
+ message: 'Service responsive',
87
+ lastCheck: timestamp,
88
+ },
89
+ ];
90
+ return {
91
+ healthy: true,
92
+ timestamp,
93
+ uptimeSeconds,
94
+ components,
95
+ metadata: this.buildMetadata(),
96
+ };
97
+ }
98
+ // Readiness probe: Check all dependencies
99
+ const components = [];
100
+ // Check registry if configured
101
+ if (this.registry) {
102
+ const registryHealth = await this.checkRegistry();
103
+ components.push(registryHealth);
104
+ }
105
+ // Check transport if configured
106
+ if (this.transport) {
107
+ const transportHealth = await this.checkTransport();
108
+ components.push(transportHealth);
109
+ }
110
+ // If no components configured, return basic health
111
+ if (components.length === 0) {
112
+ components.push({
113
+ name: 'self',
114
+ status: 'healthy',
115
+ message: 'No dependencies configured',
116
+ lastCheck: timestamp,
117
+ });
118
+ }
119
+ // Overall health: healthy if all components healthy
120
+ const healthy = components.every((c) => c.status === 'healthy');
121
+ return {
122
+ healthy,
123
+ timestamp,
124
+ uptimeSeconds,
125
+ components,
126
+ metadata: this.buildMetadata(),
127
+ };
128
+ }
129
+ buildMetadata() {
130
+ const metadata = {};
131
+ if (this.serviceName)
132
+ metadata.service = this.serviceName;
133
+ if (this.version)
134
+ metadata.version = this.version;
135
+ if (this.environment)
136
+ metadata.environment = this.environment;
137
+ return Object.keys(metadata).length > 0 ? metadata : undefined;
138
+ }
139
+ async checkRegistry() {
140
+ const startTime = Date.now();
141
+ const lastCheck = new Date().toISOString();
142
+ try {
143
+ if (!this.registry) {
144
+ return {
145
+ name: 'registry',
146
+ status: 'unhealthy',
147
+ message: 'Registry not configured',
148
+ lastCheck,
149
+ };
150
+ }
151
+ // Use timeout wrapper
152
+ const result = await this.withTimeout(this.registry.resolve('did:xail:health_check_probe'), this.timeoutMs);
153
+ const latencyMs = Date.now() - startTime;
154
+ // Registry returns Result<Uint8Array, RegistryError>
155
+ // For non-existent DIDs, it returns err with NOT_FOUND code (this is healthy behavior)
156
+ // For registry errors, it returns err with other error codes (unhealthy)
157
+ if (result && typeof result === 'object' && 'ok' in result) {
158
+ // Result type - check if ok or err
159
+ if (result.ok) {
160
+ // Registry found the DID (healthy)
161
+ return {
162
+ name: 'registry',
163
+ status: 'healthy',
164
+ message: 'Registry responding',
165
+ latencyMs,
166
+ lastCheck,
167
+ };
168
+ }
169
+ else {
170
+ // Registry returned an error
171
+ const errorCode = typeof result.error === 'string' ? result.error : 'UNKNOWN';
172
+ // NOT_FOUND is healthy (registry works, DID doesn't exist)
173
+ if (errorCode.includes('NOT_FOUND')) {
174
+ return {
175
+ name: 'registry',
176
+ status: 'healthy',
177
+ message: 'Registry responding',
178
+ latencyMs,
179
+ lastCheck,
180
+ };
181
+ }
182
+ // Other errors are unhealthy
183
+ return {
184
+ name: 'registry',
185
+ status: 'unhealthy',
186
+ message: `Registry error: ${errorCode}`,
187
+ latencyMs,
188
+ lastCheck,
189
+ };
190
+ }
191
+ }
192
+ // Fallback: if result is anything else, assume healthy
193
+ return {
194
+ name: 'registry',
195
+ status: 'healthy',
196
+ message: 'Registry responding',
197
+ latencyMs,
198
+ lastCheck,
199
+ };
200
+ }
201
+ catch (error) {
202
+ const latencyMs = Date.now() - startTime;
203
+ const message = error instanceof Error ? error.message : 'Unknown error';
204
+ // Timeout is degraded (slow but responsive)
205
+ if (message.toLowerCase().includes('timeout')) {
206
+ return {
207
+ name: 'registry',
208
+ status: 'degraded',
209
+ message: `Registry slow (>${this.timeoutMs}ms)`,
210
+ latencyMs,
211
+ lastCheck,
212
+ };
213
+ }
214
+ // Other errors are unhealthy
215
+ return {
216
+ name: 'registry',
217
+ status: 'unhealthy',
218
+ message: `Registry error: ${message}`,
219
+ latencyMs,
220
+ lastCheck,
221
+ };
222
+ }
223
+ }
224
+ async checkTransport() {
225
+ const startTime = Date.now();
226
+ const lastCheck = new Date().toISOString();
227
+ try {
228
+ if (!this.transport) {
229
+ return {
230
+ name: 'transport',
231
+ status: 'unhealthy',
232
+ message: 'Transport not configured',
233
+ lastCheck,
234
+ };
235
+ }
236
+ // Transport doesn't expose a health check method, so we check if it's instantiated
237
+ // In production, you might want to add a ping() method to XailTransportAdapter
238
+ const latencyMs = Date.now() - startTime;
239
+ return {
240
+ name: 'transport',
241
+ status: 'healthy',
242
+ message: 'Transport adapter available',
243
+ latencyMs,
244
+ lastCheck,
245
+ };
246
+ }
247
+ catch (error) {
248
+ const latencyMs = Date.now() - startTime;
249
+ const message = error instanceof Error ? error.message : 'Unknown error';
250
+ return {
251
+ name: 'transport',
252
+ status: 'unhealthy',
253
+ message: `Transport error: ${message}`,
254
+ latencyMs,
255
+ lastCheck,
256
+ };
257
+ }
258
+ }
259
+ async withTimeout(promise, timeoutMs) {
260
+ return Promise.race([
261
+ promise,
262
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Health check timeout')), timeoutMs)),
263
+ ]);
264
+ }
265
+ }
266
+ /* ── Public API ── */
267
+ /**
268
+ * Create a health checker instance.
269
+ *
270
+ * @param options - Configuration options
271
+ * @returns Health checker instance
272
+ *
273
+ * @example
274
+ * ```typescript
275
+ * const checker = createHealthChecker({
276
+ * registry: agent.registry,
277
+ * transport: agent.transport,
278
+ * serviceName: 'my-service',
279
+ * version: '1.0.0'
280
+ * });
281
+ *
282
+ * // Mark startup complete after initialization
283
+ * await agent.register();
284
+ * checker.markStartupComplete();
285
+ *
286
+ * // Check health
287
+ * const status = await checker.check('readiness');
288
+ * console.log(status.healthy ? 'Ready' : 'Not ready');
289
+ * ```
290
+ */
291
+ function createHealthChecker(options) {
292
+ return new HealthCheckerImpl(options);
293
+ }
294
+ /**
295
+ * Express/Fastify middleware helper for health endpoint.
296
+ *
297
+ * @param checker - Health checker instance
298
+ * @param probe - Probe type (default: 'readiness')
299
+ * @returns Request handler
300
+ *
301
+ * @example
302
+ * ```typescript
303
+ * const checker = createHealthChecker({ registry, transport });
304
+ *
305
+ * // Express
306
+ * app.get('/health', healthEndpoint(checker));
307
+ * app.get('/health/startup', healthEndpoint(checker, 'startup'));
308
+ * app.get('/health/liveness', healthEndpoint(checker, 'liveness'));
309
+ * app.get('/health/readiness', healthEndpoint(checker, 'readiness'));
310
+ * ```
311
+ */
312
+ function healthEndpoint(checker, probe = 'readiness') {
313
+ return async (_req, res) => {
314
+ try {
315
+ const status = await checker.check(probe);
316
+ const statusCode = status.healthy ? 200 : 503;
317
+ res.status(statusCode).json(status);
318
+ }
319
+ catch (error) {
320
+ const message = error instanceof Error ? error.message : 'Unknown error';
321
+ res.status(503).json({
322
+ healthy: false,
323
+ timestamp: new Date().toISOString(),
324
+ uptimeSeconds: 0,
325
+ components: [
326
+ {
327
+ name: 'health-check',
328
+ status: 'unhealthy',
329
+ message: `Health check failed: ${message}`,
330
+ lastCheck: new Date().toISOString(),
331
+ },
332
+ ],
333
+ });
334
+ }
335
+ };
336
+ }
@@ -1 +1,272 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createAxiosCompat=createAxiosCompat,exports.createGotCompat=createGotCompat,exports.wrapFetch=wrapFetch;const xfetch_js_1=require("./xfetch.js");function createAxiosCompat(){async function t(t){const e="string"==typeof t?{url:t}:t,a=e.method?.toUpperCase()??"GET",r=e.baseURL?new URL(e.url??"",e.baseURL).toString():e.url??"",o={...e.headers};let s,n=r;if(e.params){const t=new URLSearchParams;for(const[a,r]of Object.entries(e.params))t.append(a,String(r));n=`${r}?${t.toString()}`}e.data&&("string"==typeof e.data?s=e.data:(s=JSON.stringify(e.data),o["Content-Type"]="application/json"));const c={method:a,headers:o,body:s,timeout:e.timeout,forceXBind:e.forceXBind,disableXBind:e.disableXBind},i=await(0,xfetch_js_1.xfetch)(n,c);let u;switch(e.responseType??"json"){case"json":default:u=await i.json();break;case"text":u=await i.text();break;case"blob":u=await i.blob();break;case"arraybuffer":u=await i.arrayBuffer()}if(e.validateStatus&&!e.validateStatus(i.status))throw new Error(`Request failed with status ${i.status}`);const d={};return i.headers.forEach((t,e)=>{d[e]=t}),{data:u,status:i.status,statusText:i.statusText,headers:d,config:e,xbind:{used:i.usedXBind,protocol:i.transport.protocol,latency:i.transport.latency,peerDID:i.transport.peerDID}}}return{request:t,get:async function(e,a){return t({...a,url:e,method:"GET"})},post:async function(e,a,r){return t({...r,url:e,method:"POST",data:a})},put:async function(e,a,r){return t({...r,url:e,method:"PUT",data:a})},patch:async function(e,a,r){return t({...r,url:e,method:"PATCH",data:a})},delete:async function(e,a){return t({...a,url:e,method:"DELETE"})}}}function createGotCompat(){async function t(t,e){const a="string"==typeof t?{...e,url:t}:t,r=a.method?.toUpperCase()??"GET",o=a.url??"",s={...a.headers};let n,c=o;if(a.searchParams){const t=new URLSearchParams;for(const[e,r]of Object.entries(a.searchParams))t.append(e,String(r));c=`${o}?${t.toString()}`}a.json?(n=JSON.stringify(a.json),s["Content-Type"]="application/json"):a.body&&(n=a.body instanceof Buffer?a.body.toString():a.body);const i={method:r,headers:s,body:n,timeout:"number"==typeof a.timeout?a.timeout:a.timeout?.request,forceXBind:a.forceXBind,disableXBind:a.disableXBind},u=await(0,xfetch_js_1.xfetch)(c,i);let d;switch(a.responseType??"text"){case"json":d=await u.json();break;case"text":default:d=await u.text();break;case"buffer":const t=await u.arrayBuffer();d=Buffer.from(t)}const p={};return u.headers.forEach((t,e)=>{p[e]=t}),{body:d,statusCode:u.status,headers:p,url:u.url,requestUrl:c,xbind:{used:u.usedXBind,protocol:u.transport.protocol,latency:u.transport.latency,peerDID:u.transport.peerDID}}}return t.get=(e,a)=>t(e,{...a,method:"GET"}),t.post=(e,a)=>t(e,{...a,method:"POST"}),t.put=(e,a)=>t(e,{...a,method:"PUT"}),t.patch=(e,a)=>t(e,{...a,method:"PATCH"}),t.delete=(e,a)=>t(e,{...a,method:"DELETE"}),t}function wrapFetch(){return xfetch_js_1.xfetch}
1
+ "use strict";
2
+ /**
3
+ * @module http-compat
4
+ * HTTP client compatibility adapters for xBind auto-upgrade
5
+ *
6
+ * Provides drop-in replacements for popular HTTP clients (fetch, axios, got)
7
+ * that transparently upgrade to xBind when both parties support it.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.createAxiosCompat = createAxiosCompat;
11
+ exports.createGotCompat = createGotCompat;
12
+ exports.wrapFetch = wrapFetch;
13
+ const xfetch_js_1 = require("./xfetch.js");
14
+ /**
15
+ * Create axios-compatible HTTP client with xBind auto-upgrade
16
+ *
17
+ * Drop-in replacement for axios that transparently upgrades to xBind.
18
+ *
19
+ * @returns Axios-compatible client
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * import { createAxiosCompat } from '@private.me/xbind/http-compat';
24
+ *
25
+ * const axios = createAxiosCompat();
26
+ *
27
+ * // Auto-upgrades to xBind if supported
28
+ * const response = await axios.get('https://api.example.com/data');
29
+ * console.log('Used xBind?', response.xbind?.used);
30
+ * console.log('Data:', response.data);
31
+ * ```
32
+ */
33
+ function createAxiosCompat() {
34
+ async function request(config) {
35
+ // Normalize config
36
+ const cfg = typeof config === 'string' ? { url: config } : config;
37
+ const method = cfg.method?.toUpperCase() ?? 'GET';
38
+ const url = cfg.baseURL
39
+ ? new URL(cfg.url ?? '', cfg.baseURL).toString()
40
+ : cfg.url ?? '';
41
+ // Build headers
42
+ const headers = { ...cfg.headers };
43
+ // Build URL with query params
44
+ let finalUrl = url;
45
+ if (cfg.params) {
46
+ const params = new URLSearchParams();
47
+ for (const [key, value] of Object.entries(cfg.params)) {
48
+ params.append(key, String(value));
49
+ }
50
+ finalUrl = `${url}?${params.toString()}`;
51
+ }
52
+ // Build request body
53
+ let body;
54
+ if (cfg.data) {
55
+ if (typeof cfg.data === 'string') {
56
+ body = cfg.data;
57
+ }
58
+ else {
59
+ body = JSON.stringify(cfg.data);
60
+ headers['Content-Type'] = 'application/json';
61
+ }
62
+ }
63
+ // Convert to xfetch options
64
+ const xfetchOpts = {
65
+ method,
66
+ headers,
67
+ body,
68
+ timeout: cfg.timeout,
69
+ forceXBind: cfg.forceXBind,
70
+ disableXBind: cfg.disableXBind,
71
+ };
72
+ // Make request via xfetch
73
+ const response = await (0, xfetch_js_1.xfetch)(finalUrl, xfetchOpts);
74
+ // Parse response body based on responseType
75
+ let data;
76
+ const responseType = cfg.responseType ?? 'json';
77
+ switch (responseType) {
78
+ case 'json':
79
+ data = (await response.json());
80
+ break;
81
+ case 'text':
82
+ data = (await response.text());
83
+ break;
84
+ case 'blob':
85
+ data = (await response.blob());
86
+ break;
87
+ case 'arraybuffer':
88
+ data = (await response.arrayBuffer());
89
+ break;
90
+ default:
91
+ data = (await response.json());
92
+ }
93
+ // Validate status if custom validator provided
94
+ if (cfg.validateStatus && !cfg.validateStatus(response.status)) {
95
+ throw new Error(`Request failed with status ${response.status}`);
96
+ }
97
+ // Convert headers to object
98
+ const responseHeaders = {};
99
+ response.headers.forEach((value, key) => {
100
+ responseHeaders[key] = value;
101
+ });
102
+ return {
103
+ data,
104
+ status: response.status,
105
+ statusText: response.statusText,
106
+ headers: responseHeaders,
107
+ config: cfg,
108
+ xbind: {
109
+ used: response.usedXBind,
110
+ protocol: response.transport.protocol,
111
+ latency: response.transport.latency,
112
+ peerDID: response.transport.peerDID,
113
+ },
114
+ };
115
+ }
116
+ // Convenience methods
117
+ async function get(url, config) {
118
+ return request({ ...config, url, method: 'GET' });
119
+ }
120
+ async function post(url, data, config) {
121
+ return request({ ...config, url, method: 'POST', data });
122
+ }
123
+ async function put(url, data, config) {
124
+ return request({ ...config, url, method: 'PUT', data });
125
+ }
126
+ async function patch(url, data, config) {
127
+ return request({ ...config, url, method: 'PATCH', data });
128
+ }
129
+ async function del(url, config) {
130
+ return request({ ...config, url, method: 'DELETE' });
131
+ }
132
+ return {
133
+ request,
134
+ get,
135
+ post,
136
+ put,
137
+ patch,
138
+ delete: del,
139
+ };
140
+ }
141
+ /**
142
+ * Create got-compatible HTTP client with xBind auto-upgrade
143
+ *
144
+ * Drop-in replacement for got that transparently upgrades to xBind.
145
+ *
146
+ * @returns Got-compatible client
147
+ *
148
+ * @example
149
+ * ```typescript
150
+ * import { createGotCompat } from '@private.me/xbind/http-compat';
151
+ *
152
+ * const got = createGotCompat();
153
+ *
154
+ * // Auto-upgrades to xBind if supported
155
+ * const response = await got('https://api.example.com/data', {
156
+ * responseType: 'json',
157
+ * });
158
+ * console.log('Used xBind?', response.xbind?.used);
159
+ * console.log('Body:', response.body);
160
+ * ```
161
+ */
162
+ function createGotCompat() {
163
+ async function got(url, options) {
164
+ // Normalize options
165
+ const opts = typeof url === 'string' ? { ...options, url } : url;
166
+ const method = opts.method?.toUpperCase() ?? 'GET';
167
+ const finalUrl = opts.url ?? '';
168
+ // Build headers
169
+ const headers = { ...opts.headers };
170
+ // Build URL with search params
171
+ let urlWithParams = finalUrl;
172
+ if (opts.searchParams) {
173
+ const params = new URLSearchParams();
174
+ for (const [key, value] of Object.entries(opts.searchParams)) {
175
+ params.append(key, String(value));
176
+ }
177
+ urlWithParams = `${finalUrl}?${params.toString()}`;
178
+ }
179
+ // Build request body
180
+ let body;
181
+ if (opts.json) {
182
+ body = JSON.stringify(opts.json);
183
+ headers['Content-Type'] = 'application/json';
184
+ }
185
+ else if (opts.body) {
186
+ // Convert Buffer to string for compatibility with xfetch
187
+ // SAFETY: After instanceof check, both branches produce string type
188
+ body = (opts.body instanceof Buffer ? opts.body.toString() : opts.body);
189
+ }
190
+ // Extract timeout
191
+ const timeout = typeof opts.timeout === 'number'
192
+ ? opts.timeout
193
+ : opts.timeout?.request;
194
+ // Convert to xfetch options
195
+ const xfetchOpts = {
196
+ method,
197
+ headers,
198
+ body,
199
+ timeout,
200
+ forceXBind: opts.forceXBind,
201
+ disableXBind: opts.disableXBind,
202
+ };
203
+ // Make request via xfetch
204
+ const response = await (0, xfetch_js_1.xfetch)(urlWithParams, xfetchOpts);
205
+ // Parse response body based on responseType
206
+ let responseBody;
207
+ const responseType = opts.responseType ?? 'text';
208
+ switch (responseType) {
209
+ case 'json':
210
+ responseBody = (await response.json());
211
+ break;
212
+ case 'text':
213
+ responseBody = (await response.text());
214
+ break;
215
+ case 'buffer':
216
+ const arrayBuffer = await response.arrayBuffer();
217
+ responseBody = Buffer.from(arrayBuffer);
218
+ break;
219
+ default:
220
+ responseBody = (await response.text());
221
+ }
222
+ // Convert headers to object
223
+ const responseHeaders = {};
224
+ response.headers.forEach((value, key) => {
225
+ responseHeaders[key] = value;
226
+ });
227
+ return {
228
+ body: responseBody,
229
+ statusCode: response.status,
230
+ headers: responseHeaders,
231
+ url: response.url,
232
+ requestUrl: urlWithParams,
233
+ xbind: {
234
+ used: response.usedXBind,
235
+ protocol: response.transport.protocol,
236
+ latency: response.transport.latency,
237
+ peerDID: response.transport.peerDID,
238
+ },
239
+ };
240
+ }
241
+ // Convenience methods
242
+ got.get = (url, options) => got(url, { ...options, method: 'GET' });
243
+ got.post = (url, options) => got(url, { ...options, method: 'POST' });
244
+ got.put = (url, options) => got(url, { ...options, method: 'PUT' });
245
+ got.patch = (url, options) => got(url, { ...options, method: 'PATCH' });
246
+ got.delete = (url, options) => got(url, { ...options, method: 'DELETE' });
247
+ return got;
248
+ }
249
+ /**
250
+ * Wrap existing fetch implementation with xBind auto-upgrade
251
+ *
252
+ * Use this to upgrade an existing fetch instance (like node-fetch, cross-fetch, etc.)
253
+ *
254
+ * @param fetchImpl - Fetch implementation to wrap
255
+ * @returns Wrapped fetch with xBind support
256
+ *
257
+ * @example
258
+ * ```typescript
259
+ * import { wrapFetch } from '@private.me/xbind/http-compat';
260
+ * import nodeFetch from 'node-fetch';
261
+ *
262
+ * const fetch = wrapFetch(nodeFetch);
263
+ *
264
+ * // Uses xBind if supported, falls back to node-fetch
265
+ * const response = await fetch('https://api.example.com/data');
266
+ * ```
267
+ */
268
+ function wrapFetch(fetchImpl) {
269
+ // Return xfetch (which already handles auto-upgrade and fallback)
270
+ // The original fetchImpl is not used because xfetch uses global fetch
271
+ return xfetch_js_1.xfetch;
272
+ }