@burdenoff/be-sdk 2026.1111.1 → 2026.1113.1

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 (83) hide show
  1. package/dist/activity/index.d.ts +2 -2
  2. package/dist/ai-credits/index.d.ts +1 -1
  3. package/dist/auth/index.d.ts +1 -1
  4. package/dist/bootstrap/index.d.ts +1 -1
  5. package/dist/bun-runtime-metrics-CPy5D6NT.js +58 -0
  6. package/dist/bun-runtime-metrics-CPy5D6NT.js.map +1 -0
  7. package/dist/cache/index.d.ts +1 -1
  8. package/dist/context/index.d.ts +1 -1
  9. package/dist/event-queue/index.d.ts +1 -1
  10. package/dist/export/index.d.ts +1 -1
  11. package/dist/export/index.js +1 -1
  12. package/dist/{export-DJXE3Osa.js → export-lqKewsuF.js} +2 -2
  13. package/dist/{export-DJXE3Osa.js.map → export-lqKewsuF.js.map} +1 -1
  14. package/dist/files/index.d.ts +1 -1
  15. package/dist/gateway/index.d.ts +3 -3
  16. package/dist/gateway/index.js +2 -2
  17. package/dist/gateway-2en8Gx_a.js +274 -0
  18. package/dist/gateway-2en8Gx_a.js.map +1 -0
  19. package/dist/graph/index.d.ts +1 -1
  20. package/dist/{graphql-CUDyhibV.d.ts → graphql-C8jKLLel.d.ts} +1 -1
  21. package/dist/{index-B2LCaK0R.d.ts → index-479i3w77.d.ts} +1 -1
  22. package/dist/{index-BGzMYJsm.d.ts → index-8pUSoT85.d.ts} +1 -1
  23. package/dist/{index-ADmsX0BI.d.ts → index-9MJVKzWA.d.ts} +3 -3
  24. package/dist/{index-FbXPfen7.d.ts → index-BJwHEzpN.d.ts} +1 -1
  25. package/dist/{index-CTTwo9av.d.ts → index-BTaQMEgB.d.ts} +1 -1
  26. package/dist/{index-CDOqxSIi.d.ts → index-Base-sg5.d.ts} +1 -1
  27. package/dist/{index-C_GXXF32.d.ts → index-Bh6W5JO4.d.ts} +3 -3
  28. package/dist/{index-BeVtqGO-.d.ts → index-Bwn5Z1h-.d.ts} +1 -1
  29. package/dist/{index-FRRaa6h2.d.ts → index-CEtULfb_.d.ts} +3 -3
  30. package/dist/{index-DqbGqfAy.d.ts → index-Cwu5Mpji.d.ts} +1 -1
  31. package/dist/{index-CaM9JUcc.d.ts → index-DSynXDRD.d.ts} +1 -1
  32. package/dist/{index-CVCyKzhB.d.ts → index-DWER4-_x.d.ts} +3 -3
  33. package/dist/{index-cmR9k9ga.d.ts → index-DhFP_AIB.d.ts} +1 -1
  34. package/dist/{index-zd_NPGJo.d.ts → index-DqpCL9kD.d.ts} +4 -4
  35. package/dist/{index-U_tu3zUl.d.ts → index-Dw_0wE4q.d.ts} +2 -2
  36. package/dist/{index-3KOZ1zN9.d.ts → index-HeUeEsMU.d.ts} +1 -1
  37. package/dist/{index-Cot73bdh.d.ts → index-KlrnELrN.d.ts} +1 -1
  38. package/dist/{index-MArCb8Aq.d.ts → index-SvWwlTUC.d.ts} +1 -1
  39. package/dist/{index-CHwMhK6v.d.ts → index-YMGOJins.d.ts} +2 -2
  40. package/dist/index-oJMtR3nl.d.ts +88 -0
  41. package/dist/index.d.ts +21 -21
  42. package/dist/index.js +5 -5
  43. package/dist/init/index.d.ts +1 -1
  44. package/dist/init/index.js +1 -1
  45. package/dist/{init-CQPFmOOe.js → init-D814LeLF.js} +2 -2
  46. package/dist/{init-CQPFmOOe.js.map → init-D814LeLF.js.map} +1 -1
  47. package/dist/instrumentation/index.d.ts +2 -2
  48. package/dist/layer/index.d.ts +2 -2
  49. package/dist/layer-Bcix-WCl.js.map +1 -1
  50. package/dist/{layer-BZBZZWeV.d.ts → layer-C0zxAUgR.d.ts} +1 -0
  51. package/dist/logger/index.d.ts +1 -1
  52. package/dist/notifications/index.d.ts +1 -1
  53. package/dist/payments/index.d.ts +2 -2
  54. package/dist/rbac/index.d.ts +1 -1
  55. package/dist/resource-caps/index.d.ts +1 -1
  56. package/dist/{sdk-B62itAH1.js → sdk-DqIqX-Ue.js} +33 -2
  57. package/dist/sdk-DqIqX-Ue.js.map +1 -0
  58. package/dist/search/index.d.ts +2 -2
  59. package/dist/security/index.d.ts +1 -1
  60. package/dist/security/rate-limit/index.d.ts +1 -1
  61. package/dist/server/index.js +2 -3
  62. package/dist/server/index.js.map +1 -1
  63. package/dist/tags/index.d.ts +1 -1
  64. package/dist/telemetry/index.d.ts +2 -2
  65. package/dist/telemetry/index.js +8 -4
  66. package/dist/telemetry/index.js.map +1 -1
  67. package/dist/temporal/index.d.ts +1 -1
  68. package/dist/tracker/index.d.ts +2 -2
  69. package/dist/tracker/index.js +2 -2
  70. package/dist/{tracker-PQztSlhJ.js → tracker-Cl3cGKe-.js} +2 -2
  71. package/dist/{tracker-PQztSlhJ.js.map → tracker-Cl3cGKe-.js.map} +1 -1
  72. package/dist/translation/index.d.ts +2 -2
  73. package/dist/types/index.d.ts +2 -2
  74. package/dist/{types-C6EKaS3V.d.ts → types-gJ9Qqi9E.d.ts} +1 -1
  75. package/dist/usage/index.d.ts +1 -1
  76. package/dist/usage/index.js +1 -1
  77. package/dist/{usage-BRqVP3CJ.js → usage-ygkKsxdd.js} +2 -2
  78. package/dist/{usage-BRqVP3CJ.js.map → usage-ygkKsxdd.js.map} +1 -1
  79. package/package.json +1 -1
  80. package/dist/gateway-ByVo-n37.js +0 -50
  81. package/dist/gateway-ByVo-n37.js.map +0 -1
  82. package/dist/index-YOShAwkq.d.ts +0 -45
  83. package/dist/sdk-B62itAH1.js.map +0 -1
package/dist/index.d.ts CHANGED
@@ -1,43 +1,43 @@
1
- import { a as DEFAULT_LAYER_RESOURCES, c as GatewayRetryConfig, d as LayerFullConfig, f as LayerGatewayConfig, i as DEFAULT_GATEWAY_ROUTING, l as GatewayRoutingConfig, m as ServiceLayer, n as DEFAULT_CIRCUIT_BREAKER_CONFIG, o as DEFAULT_LAYER_STREAMS, p as LayerResourceUrls, r as DEFAULT_GATEWAY_RETRY_CONFIG, s as GatewayRequestHeaders, t as CircuitBreakerConfig, u as LayerConfig } from "./layer-BZBZZWeV.js";
2
- import { _ as TemporalHealthStatus, a as EventQueueSDKConfig, f as SDKConfig, g as SDKShutdownOptions, h as SDKHealthStatus, i as EventQueueHealthStatus, o as LoggerConfig, p as SDKContext, s as LoggerTransport } from "./index-CTTwo9av.js";
3
- import { c as index_d_exports$17, r as Logger } from "./index-Cot73bdh.js";
1
+ import { a as DEFAULT_LAYER_RESOURCES, c as GatewayRetryConfig, d as LayerFullConfig, f as LayerGatewayConfig, i as DEFAULT_GATEWAY_ROUTING, l as GatewayRoutingConfig, m as ServiceLayer, n as DEFAULT_CIRCUIT_BREAKER_CONFIG, o as DEFAULT_LAYER_STREAMS, p as LayerResourceUrls, r as DEFAULT_GATEWAY_RETRY_CONFIG, s as GatewayRequestHeaders, t as CircuitBreakerConfig, u as LayerConfig } from "./layer-C0zxAUgR.js";
2
+ import { _ as TemporalHealthStatus, a as EventQueueSDKConfig, f as SDKConfig, g as SDKShutdownOptions, h as SDKHealthStatus, i as EventQueueHealthStatus, o as LoggerConfig, p as SDKContext, s as LoggerTransport } from "./index-BTaQMEgB.js";
3
+ import { c as index_d_exports$17, r as Logger } from "./index-KlrnELrN.js";
4
4
  import { ContextManager } from "./context/index.js";
5
- import { t as AuthModule } from "./index-CHwMhK6v.js";
6
- import { _ as TenantNotificationsModule, o as NotificationsModule, v as tenant_notifications_d_exports } from "./index-U_tu3zUl.js";
7
- import { f as RBACDirectiveConfig, h as createRBACDirectiveFromEnv, m as createRBACDirectiveForLayer, o as RBACModule, p as createRBACDirective, u as LayerAwareRBACConfig } from "./index-C_GXXF32.js";
5
+ import { t as AuthModule } from "./index-YMGOJins.js";
6
+ import { _ as TenantNotificationsModule, o as NotificationsModule, v as tenant_notifications_d_exports } from "./index-Dw_0wE4q.js";
7
+ import { f as RBACDirectiveConfig, h as createRBACDirectiveFromEnv, m as createRBACDirectiveForLayer, o as RBACModule, p as createRBACDirective, u as LayerAwareRBACConfig } from "./index-Bh6W5JO4.js";
8
8
  import { Activity, ActivityActorType, ActivityModule, ActivityOperationUnsupportedError, GetActivitiesOptions, LogActivityOptions } from "./activity/index.js";
9
- import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, b as BillingUsageClient, m as UsageModule, w as QuotaLimit, x as BillingUsageClientConfig } from "./index-CVCyKzhB.js";
10
- import { r as TrackerModule } from "./index-zd_NPGJo.js";
9
+ import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, b as BillingUsageClient, m as UsageModule, w as QuotaLimit, x as BillingUsageClientConfig } from "./index-DWER4-_x.js";
10
+ import { r as TrackerModule } from "./index-DqpCL9kD.js";
11
11
  import { DatabaseModule } from "./database/index.js";
12
- import { Zt as IEventPublisher, t as index_d_exports$5, yt as EventsModule } from "./index-FRRaa6h2.js";
13
- import { i as GraphModule, u as index_d_exports$10 } from "./index-ADmsX0BI.js";
12
+ import { Zt as IEventPublisher, t as index_d_exports$5, yt as EventsModule } from "./index-CEtULfb_.js";
13
+ import { i as GraphModule, u as index_d_exports$10 } from "./index-9MJVKzWA.js";
14
14
  import { SearchModule } from "./search/index.js";
15
15
  import { ExportProductTranslationsOptions, ProductTranslationTree, ProductTranslationsExportResult, TranslationExportFormat, TranslationModule, UpsertProductTranslationsOptions, UpsertProductTranslationsResult } from "./translation/index.js";
16
16
  import { PaymentsModule } from "./payments/index.js";
17
17
  import { BootstrapModule, createBootstrap } from "./bootstrap/index.js";
18
- import { a as TemporalWorkerManager, c as TemporalClientFactory, i as TemporalWorkerFactory, l as WorkflowStartOptions, n as TemporalWorker, o as TemporalClient, r as TemporalWorkerConfig, s as TemporalClientConfig, t as TemporalModule } from "./index-CaM9JUcc.js";
19
- import { t as BurdenoffGraphQLClient } from "./graphql-CUDyhibV.js";
18
+ import { a as TemporalWorkerManager, c as TemporalClientFactory, i as TemporalWorkerFactory, l as WorkflowStartOptions, n as TemporalWorker, o as TemporalClient, r as TemporalWorkerConfig, s as TemporalClientConfig, t as TemporalModule } from "./index-DSynXDRD.js";
19
+ import { t as BurdenoffGraphQLClient } from "./graphql-C8jKLLel.js";
20
20
  import { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from "./client/internal-client.js";
21
21
  import { a as registerDisposable, i as getRegisteredDisposableCount, n as ShutdownDisposable, o as unregisterDisposable, r as disposeAll, t as index_d_exports$16 } from "./index-Dt1HJPTX.js";
22
22
  import { BillingPlanTransport, PlanTier, RESOURCE_CAP_DEFAULTS, ResourceCap, ResourceCapDefaults, ResourceCapExceededError, ResourceCapsConfig, ResourceCapsModule, ResourceName, WorkspaceResourceCapScope, configureResourceCaps, getResourceCaps } from "./resource-caps/index.js";
23
23
  import { t as index_d_exports$23 } from "./index-CliOgq6L.js";
24
- import { t as index_d_exports$24 } from "./index-3KOZ1zN9.js";
25
- import { t as index_d_exports$8 } from "./index-BGzMYJsm.js";
26
- import { t as index_d_exports } from "./index-FbXPfen7.js";
27
- import { o as index_d_exports$1 } from "./index-MArCb8Aq.js";
24
+ import { t as index_d_exports$24 } from "./index-HeUeEsMU.js";
25
+ import { t as index_d_exports$8 } from "./index-8pUSoT85.js";
26
+ import { t as index_d_exports } from "./index-BJwHEzpN.js";
27
+ import { o as index_d_exports$1 } from "./index-SvWwlTUC.js";
28
28
  import { t as index_d_exports$18 } from "./index-BMIMnp6T.js";
29
29
  import { t as index_d_exports$19 } from "./index-C5uEKchX.js";
30
30
  import { t as index_d_exports$11 } from "./index-CSRcgkVi.js";
31
31
  import { t as index_d_exports$21 } from "./index-BiTzGUZP.js";
32
32
  import { s as index_d_exports$25 } from "./index-FKohsiex.js";
33
33
  import { C as getLocale, S as getLanguage, T as t, b as Translator, r as index_d_exports$12, w as hasI18n, x as createTranslator, y as I18nCapableContext } from "./index-CPQDMSFS.js";
34
- import { t as index_d_exports$6 } from "./index-BeVtqGO-.js";
35
- import { n as index_d_exports$13 } from "./index-DqbGqfAy.js";
34
+ import { t as index_d_exports$6 } from "./index-Bwn5Z1h-.js";
35
+ import { n as index_d_exports$13 } from "./index-Cwu5Mpji.js";
36
36
  import { p as index_d_exports$4 } from "./index-DGgh9DWn.js";
37
- import { a as index_d_exports$14 } from "./index-B2LCaK0R.js";
38
- import { a as index_d_exports$15 } from "./index-CDOqxSIi.js";
37
+ import { a as index_d_exports$14 } from "./index-479i3w77.js";
38
+ import { a as index_d_exports$15 } from "./index-Base-sg5.js";
39
39
  import { t as index_d_exports$3 } from "./index-BVOL7458.js";
40
- import { t as index_d_exports$9 } from "./index-YOShAwkq.js";
40
+ import { t as index_d_exports$9 } from "./index-oJMtR3nl.js";
41
41
  import { t as index_d_exports$7 } from "./index-BcqQs-Uq.js";
42
42
  import { a as index_d_exports$2, c as verifyCaptchaIfEnabled, n as RecaptchaVerifyResult, o as isCaptchaEnabled, s as verifyCaptcha, t as RecaptchaVerifyOptions } from "./index-yBSjMY32.js";
43
43
  import { t as index_d_exports$20 } from "./index-DY3dNhMN.js";
package/dist/index.js CHANGED
@@ -8,8 +8,8 @@ import { t as AuthModule } from "./auth-C5ctwSLp.js";
8
8
  import { c as tenant_notifications_exports, r as NotificationsModule, s as TenantNotificationsModule } from "./notifications-DY_i37WN.js";
9
9
  import { a as createRBACDirectiveForLayer, i as createRBACDirective, o as createRBACDirectiveFromEnv, t as RBACModule } from "./rbac-Dvz0YzEt.js";
10
10
  import { ActivityModule, ActivityOperationUnsupportedError } from "./activity/index.js";
11
- import { a as UsageModule, c as BillingUsageClient } from "./usage-BRqVP3CJ.js";
12
- import { t as TrackerModule } from "./tracker-PQztSlhJ.js";
11
+ import { a as UsageModule, c as BillingUsageClient } from "./usage-ygkKsxdd.js";
12
+ import { t as TrackerModule } from "./tracker-Cl3cGKe-.js";
13
13
  import { DatabaseModule } from "./database/index.js";
14
14
  import { T as EventsModule, t as event_queue_exports } from "./event-queue-Cw-YJPY_.js";
15
15
  import { a as unregisterDisposable, i as registerDisposable, n as disposeAll, r as getRegisteredDisposableCount, t as lifecycle_exports } from "./lifecycle-DeoLSX0U.js";
@@ -34,13 +34,13 @@ import { t as graphql_exports } from "./graphql-DHAHHcww.js";
34
34
  import { t as prisma_exports } from "./prisma-BzOOdt79.js";
35
35
  import { _ as utils_exports } from "./utils-DL85Tnbn.js";
36
36
  import { a as getLanguage, c as t, i as createTranslator, o as getLocale, r as i18n_exports, s as hasI18n } from "./i18n-BBMYFd0P.js";
37
- import { t as export_exports } from "./export-DJXE3Osa.js";
38
- import { n as init_exports } from "./init-CQPFmOOe.js";
37
+ import { t as export_exports } from "./export-lqKewsuF.js";
38
+ import { n as init_exports } from "./init-D814LeLF.js";
39
39
  import { s as dataloader_exports } from "./dataloader-DwpT3YoS.js";
40
40
  import { r as instrumentation_exports } from "./instrumentation-xkkmDgJ0.js";
41
41
  import { a as layer_exports } from "./layer-CEKy6cm8.js";
42
42
  import { t as crypto_exports } from "./crypto-DO9fM0FO.js";
43
- import { t as gateway_exports } from "./gateway-ByVo-n37.js";
43
+ import { t as gateway_exports } from "./gateway-2en8Gx_a.js";
44
44
  import { t as feature_flags_exports } from "./feature-flags-CP1KRgwD.js";
45
45
  import { i as verifyCaptchaIfEnabled, n as isCaptchaEnabled, r as verifyCaptcha, t as captcha_exports } from "./captcha-BT7yh1YS.js";
46
46
  import { t as platform_exports } from "./platform-DZwczW7v.js";
@@ -1,2 +1,2 @@
1
- import { _ as OpenTelemetryConfig, a as resetSDK, c as ClickHouseConfig, d as GraphSyncConfig, f as InitializedSDKState, g as ObservabilityConfig, h as MetricsConfig, i as isSDKInitialized, l as DatabaseConfig, m as LoggingConfig, o as AnalyticsConfig, p as LayerInitConfig, r as initializeBurdenoffSDK, s as BurdenoffSDKInitConfig, t as getSDKState, u as EventQueueConfig, v as SDKCacheConfig, y as SDKValkeyCacheConfig } from "../index-DqbGqfAy.js";
1
+ import { _ as OpenTelemetryConfig, a as resetSDK, c as ClickHouseConfig, d as GraphSyncConfig, f as InitializedSDKState, g as ObservabilityConfig, h as MetricsConfig, i as isSDKInitialized, l as DatabaseConfig, m as LoggingConfig, o as AnalyticsConfig, p as LayerInitConfig, r as initializeBurdenoffSDK, s as BurdenoffSDKInitConfig, t as getSDKState, u as EventQueueConfig, v as SDKCacheConfig, y as SDKValkeyCacheConfig } from "../index-Cwu5Mpji.js";
2
2
  export { type AnalyticsConfig, type BurdenoffSDKInitConfig, type ClickHouseConfig, type DatabaseConfig, type EventQueueConfig, type GraphSyncConfig, type InitializedSDKState, type LayerInitConfig, type LoggingConfig, type MetricsConfig, type ObservabilityConfig, type OpenTelemetryConfig, type SDKCacheConfig, type SDKValkeyCacheConfig, getSDKState, initializeBurdenoffSDK, isSDKInitialized, resetSDK };
@@ -1,4 +1,4 @@
1
- import { a as resetSDK, i as isSDKInitialized, r as initializeBurdenoffSDK, t as getSDKState } from "../init-CQPFmOOe.js";
1
+ import { a as resetSDK, i as isSDKInitialized, r as initializeBurdenoffSDK, t as getSDKState } from "../init-D814LeLF.js";
2
2
 
3
3
  export { getSDKState, initializeBurdenoffSDK, isSDKInitialized, resetSDK };
4
4
  //# sourceMappingURL=index.js.map
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
2
  import { a as logger } from "./logger-B6rCpb7D.js";
3
3
  import { t as LayerManager } from "./layer-CEKy6cm8.js";
4
4
  import { t as GatewayClient } from "./client-sAJTrb4i.js";
5
- import "./gateway-ByVo-n37.js";
5
+ import "./gateway-2en8Gx_a.js";
6
6
  import { configureResourceCaps } from "./resource-caps/index.js";
7
7
  import { n as createCounter } from "./metrics-collector-C2eShrlW.js";
8
8
 
@@ -322,4 +322,4 @@ async function initializeLayerStreams(config) {
322
322
  }
323
323
 
324
324
  export { resetSDK as a, isSDKInitialized as i, init_exports as n, initializeBurdenoffSDK as r, getSDKState as t };
325
- //# sourceMappingURL=init-CQPFmOOe.js.map
325
+ //# sourceMappingURL=init-D814LeLF.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"init-CQPFmOOe.js","names":[],"sources":["../src/init/index.ts"],"sourcesContent":["/**\n * Burdenoff SDK Initialization Module\n *\n * Provides a unified initialization function for all state services\n * including database, cache, analytics, event queue, and graph sync.\n *\n * @module init\n * @category Initialization\n */\n\nimport { logger } from '../logger/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { GatewayClient } from '../gateway/index.js';\nimport { configureResourceCaps } from '../resource-caps/index.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport type { BurdenoffSDKInitConfig, InitializedSDKState } from './types.js';\n\n/**\n * Global SDK state\n */\nlet sdkState: InitializedSDKState | null = null;\nlet isInitialized = false;\n\n/**\n * Initialize Burdenoff SDK with unified configuration\n *\n * This function initializes all configured state services in the correct order:\n * 1. Logging configuration\n * 2. Database (Prisma with PostgreSQL)\n * 3. Cache (Valkey)\n * 4. Event Queue (Redis Streams)\n * 5. Graph Sync (Redis Streams-based — Apache AGE writes happen inside wspace-graph-svc)\n * 6. Analytics (ClickHouse)\n * 7. Observability (Metrics, OpenTelemetry)\n *\n * @param config - SDK initialization configuration\n * @returns Initialized SDK state\n *\n * @example\n * ```typescript\n * import { initializeBurdenoffSDK } from '@burdenoff/be-sdk/init';\n *\n * const state = await initializeBurdenoffSDK({\n * database: {\n * url: process.env.DATABASE_URL!,\n * maxConnections: 20,\n * },\n * graph: {\n * enabled: true,\n * eventsEnabled: true,\n * },\n * cache: {\n * valkey: {\n * url: process.env.VALKEY_URL!,\n * },\n * },\n * });\n * ```\n */\nexport async function initializeBurdenoffSDK(config: BurdenoffSDKInitConfig): Promise<InitializedSDKState> {\n if (isInitialized && sdkState) {\n logger.warn('[SDK Init] SDK already initialized, returning existing state');\n return sdkState;\n }\n\n logger.info('[SDK Init] Starting SDK initialization...');\n const startTime = Date.now();\n\n try {\n // 1. Configure logging\n await initializeLogging(config);\n\n // 2. Initialize layer manager (if configured)\n const { layerManager, gatewayClient } = await initializeLayer(config);\n\n // 2b. Wire resource caps to billing so plan-based limits actually apply.\n // `userBillingPlan` lives in the GLOBAL layer: global services reach it\n // on their own internal gateway; wspace services go cross-layer via the\n // public global gateway (service JWT). Without this, every resource cap\n // silently collapses to the free-tier fallback regardless of the\n // customer's plan (BOFF-4805). Primes the process-wide singleton so all\n // existing `getResourceCaps()` call sites resolve real plans unchanged.\n if (gatewayClient && config.layer) {\n const layerType = config.layer.type;\n const fallbackCounter = createCounter(\n 'resource_caps.clientless_fallback_total',\n 'Total number of times resource caps fell back because no billing source was configured at bootstrap'\n );\n configureResourceCaps({\n transport: async (query, variables) => {\n // Cap checks run on entity-create paths and ALWAYS fall back to the\n // configured billing-failure tier on failure, so a billing outage\n // must degrade fast rather than stall writes. Bound the lookup with a\n // short timeout and no retries instead of the gateway defaults\n // (~30s × 3 ≈ 90s). Results are cached 60s, so healthy lookups rarely\n // hit the gateway anyway. `skipCircuitBreaker` keeps this best-effort\n // probe OUT of the shared gateway circuit: its failures already\n // degrade to the fallback here, so they must not count toward opening\n // the internal/cross-layer circuit and fail-fast unrelated M2M calls\n // during a billing outage.\n const options = { query, variables, timeout: 8000, skipRetry: true, skipCircuitBreaker: true };\n const response =\n layerType === 'global'\n ? await gatewayClient.internalQuery(options)\n : await gatewayClient.crossLayerQuery(options);\n return response?.data ?? null;\n },\n // Emitting a dedicated clientless-fallback counter at bootstrap means\n // a service that somehow starts without a billing transport is\n // immediately visible in metrics (BOFF-4809). The resource-caps module\n // itself also emits `resource_caps.plan_resolution_total`, but that\n // only fires on the first cap check; this counter fires at bootstrap.\n onFallback: () => fallbackCounter.inc(),\n });\n logger.info('[SDK Init] Resource caps wired to billing', { layer: layerType });\n } else {\n logger.warn('[SDK Init] No layer/gateway configured — resource caps will use free-tier fallbacks (BOFF-4805)');\n }\n\n // 3. Initialize database (required)\n const prisma = await initializeDatabase(config);\n\n // 4. Initialize cache (optional)\n const valkey = await initializeCache(config);\n\n // 5. Initialize event queue (optional) — Redis Streams via REDIS_URL\n const eventPublisher = await initializeEventQueue(config);\n\n // 6. Initialize layer streams (if layer configured)\n if (config.layer?.autoCreateStreams !== false && config.layer) {\n await initializeLayerStreams(config);\n }\n\n // 7. Initialize graph sync (optional) — publisher emits to Redis Streams,\n // never opens a graph-DB connection\n const graphSync = await initializeGraphSync(config);\n\n // 8. Initialize analytics (optional)\n const clickhouse = await initializeAnalytics(config);\n\n // 9. Initialize observability (optional)\n await initializeObservability(config);\n\n // Create SDK state\n // graphSync is a publisher-side placeholder; services emit Redis Streams\n // events and wspace-graph-svc owns the sole Apache AGE connection.\n void graphSync;\n sdkState = {\n prisma,\n valkey,\n clickhouse,\n eventPublisher,\n layerManager,\n gatewayClient,\n graphSyncEnabled: config.graph?.enabled ?? false,\n analyticsEnabled: !!config.analytics?.clickhouse,\n observabilityEnabled: config.observability?.metrics?.enabled ?? false,\n layerAwareEnabled: !!config.layer,\n };\n\n isInitialized = true;\n\n const duration = Date.now() - startTime;\n // sdkState is guaranteed non-null here since we just assigned it above\n const initializedState = sdkState;\n logger.info(`[SDK Init] SDK initialized successfully in ${duration}ms`, {\n graphSyncEnabled: initializedState.graphSyncEnabled,\n analyticsEnabled: initializedState.analyticsEnabled,\n observabilityEnabled: initializedState.observabilityEnabled,\n layerAwareEnabled: initializedState.layerAwareEnabled,\n layer: config.layer?.type,\n serviceName: config.layer?.serviceName,\n });\n\n return initializedState;\n } catch (error) {\n logger.error('[SDK Init] Failed to initialize SDK:', error);\n throw error;\n }\n}\n\n/**\n * Get current SDK state\n * @throws Error if SDK is not initialized\n */\nexport function getSDKState(): InitializedSDKState {\n if (!isInitialized || !sdkState) {\n throw new Error('SDK not initialized. Call initializeBurdenoffSDK() first.');\n }\n return sdkState;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isSDKInitialized(): boolean {\n return isInitialized;\n}\n\n/**\n * Reset SDK state (useful for testing)\n */\nexport async function resetSDK(): Promise<void> {\n logger.info('[SDK Init] Resetting SDK state...');\n\n if (sdkState) {\n // Cleanup resources\n // Note: Individual cleanup will be handled by service-specific shutdown handlers\n sdkState = null;\n }\n\n isInitialized = false;\n logger.info('[SDK Init] SDK state reset');\n}\n\n/**\n * Initialize logging configuration\n */\nasync function initializeLogging(config: BurdenoffSDKInitConfig): Promise<void> {\n logger.info('[SDK Init] Configuring logging...');\n\n const loggingConfig = config.logging ?? {};\n const isDevelopment = config.app?.nodeEnv === 'development';\n\n // Set log level\n const level = loggingConfig.level ?? 'info';\n logger.setLevel(level);\n\n // Set console logging\n const console = loggingConfig.console ?? true;\n logger.setConsoleEnabled(console);\n\n logger.info('[SDK Init] Logging configured', {\n level,\n console,\n format: loggingConfig.format ?? (isDevelopment ? 'pretty' : 'json'),\n });\n}\n\n/**\n * Initialize database (Prisma with PostgreSQL)\n */\nasync function initializeDatabase(config: BurdenoffSDKInitConfig): Promise<unknown> {\n logger.info('[SDK Init] Initializing database...');\n\n // Note: Database initialization is handled by createPrismaClient in prisma/client.ts\n // This is called by the application (e.g., workspaces-backend)\n // We just validate the config here\n if (!config.database?.url) {\n throw new Error('Database URL is required');\n }\n\n logger.info('[SDK Init] Database configuration validated', {\n maxConnections: config.database.maxConnections ?? 20,\n enableQueryLogging: config.database.enableQueryLogging ?? false,\n });\n\n // Return undefined as database client is created separately\n return undefined;\n}\n\n/**\n * Initialize cache (Valkey)\n */\nasync function initializeCache(config: BurdenoffSDKInitConfig): Promise<unknown> {\n const cacheConfig = config.cache?.valkey;\n\n if (!cacheConfig) {\n logger.info('[SDK Init] Cache not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing Valkey cache...');\n\n // Note: Valkey initialization is handled by cache module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] Valkey cache configuration validated', {\n url: cacheConfig.url ? '***' : undefined,\n defaultTTL: cacheConfig.defaultTTL ?? 3600,\n });\n\n return undefined;\n}\n\n/**\n * Initialize event queue (Redis Streams).\n *\n * NATS was retired on 2026-05-16. The publisher is created from\n * `REDIS_STREAMS_URL` when set, else `REDIS_URL` (set in every SM bundle). Legacy `config.eventQueue.nats`\n * values are ignored — kept on the type only as a back-compat shim.\n */\nasync function initializeEventQueue(_config: BurdenoffSDKInitConfig): Promise<unknown> {\n const { resolveEventStreamsUrl } = await import('../event-queue/env.js');\n if (!resolveEventStreamsUrl()) {\n logger.info('[SDK Init] REDIS_STREAMS_URL / REDIS_URL not set, skipping event queue init');\n return undefined;\n }\n\n try {\n const { EventQueueFactory } = await import('../event-queue/factory/EventQueueFactory.js');\n const publisher = EventQueueFactory.createPublisherFromEnv();\n await publisher.connect();\n\n logger.info('[SDK Init] Redis Streams event publisher connected');\n\n return publisher;\n } catch (error) {\n logger.warn('[SDK Init] Failed to connect Redis Streams event publisher (non-fatal)', {\n error: error instanceof Error ? error.message : String(error),\n note: 'Service will continue without event publishing. Use direct API calls as fallback.',\n });\n return undefined;\n }\n}\n\n/**\n * Initialize graph sync (Redis Streams publisher side).\n *\n * Services publish entity events to Redis Streams; the `wspace-graph-svc`\n * consumer (and only it) persists them into Apache AGE via Azure PG\n * sidecar. This SDK function does no DB work — it just validates that the\n * publisher-side config is sensible and logs it.\n */\nasync function initializeGraphSync(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.graph?.enabled) {\n logger.info('[SDK Init] Graph sync not enabled, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Graph sync enabled (publisher-only mode)', {\n eventsEnabled: config.graph.eventsEnabled ?? true,\n productSource: config.graph.productSource,\n streamName: config.graph.streamName ?? 'graph_events',\n syncInterval: config.graph.syncInterval ?? 1000,\n batchSize: config.graph.batchSize ?? 10,\n });\n\n return undefined;\n}\n\n/**\n * Initialize analytics (ClickHouse)\n */\nasync function initializeAnalytics(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.analytics?.clickhouse) {\n logger.info('[SDK Init] Analytics not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing ClickHouse for analytics...');\n\n // Note: ClickHouse initialization is handled by analytics module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] ClickHouse configuration validated', {\n url: config.analytics.clickhouse.url,\n database: config.analytics.clickhouse.database,\n requestTimeout: config.analytics.clickhouse.requestTimeout ?? 60000,\n });\n\n return undefined;\n}\n\n/**\n * Initialize observability (metrics, tracing)\n */\nasync function initializeObservability(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.observability?.metrics?.enabled && !config.observability?.openTelemetry?.enabled) {\n logger.info('[SDK Init] Observability not configured, skipping');\n return;\n }\n\n logger.info('[SDK Init] Initializing observability...');\n\n // Note: Observability initialization is handled by observability module\n // This is a placeholder for future implementation\n if (config.observability.metrics?.enabled) {\n logger.info('[SDK Init] Metrics configuration validated', {\n port: config.observability.metrics.port ?? 9090,\n endpoint: config.observability.metrics.endpoint ?? '/metrics',\n });\n }\n\n if (config.observability.openTelemetry?.enabled) {\n logger.info('[SDK Init] OpenTelemetry configuration validated', {\n serviceName: config.observability.openTelemetry.serviceName,\n samplingRate: config.observability.openTelemetry.samplingRate ?? 1.0,\n });\n }\n}\n\n/**\n * Initialize layer manager and gateway client\n */\nasync function initializeLayer(\n config: BurdenoffSDKInitConfig\n): Promise<{ layerManager?: LayerManager; gatewayClient?: GatewayClient }> {\n if (!config.layer) {\n logger.info('[SDK Init] Layer configuration not provided, skipping layer initialization');\n return {};\n }\n\n logger.info('[SDK Init] Initializing layer manager...', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n });\n\n // Create layer manager\n const layerManager = new LayerManager({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n });\n\n // Create gateway client\n const gatewayClient = new GatewayClient({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n logger.info('[SDK Init] Layer manager initialized', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n return { layerManager, gatewayClient };\n}\n\n/**\n * Initialize layer-specific Redis streams.\n *\n * No-op since the 2026-05-16 NATS retirement: Redis Streams are created\n * on demand by `XGROUP CREATE ... MKSTREAM` inside the consumer, so no\n * upfront connect-and-provision step is needed.\n */\nasync function initializeLayerStreams(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.layer) {\n return;\n }\n logger.debug('[SDK Init] Layer streams init is a no-op for Redis Streams (auto-created on first XADD/XGROUP)', {\n layer: config.layer.type,\n });\n}\n\n// Export types\nexport type * from './types.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAI,WAAuC;AAC3C,IAAI,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCpB,eAAsB,uBAAuB,QAA8D;CACzG,IAAI,iBAAiB,UAAU;EAC7B,OAAO,KAAK,8DAA8D;EAC1E,OAAO;CACT;CAEA,OAAO,KAAK,2CAA2C;CACvD,MAAM,YAAY,KAAK,IAAI;CAE3B,IAAI;EAEF,MAAM,kBAAkB,MAAM;EAG9B,MAAM,EAAE,cAAc,kBAAkB,MAAM,gBAAgB,MAAM;EASpE,IAAI,iBAAiB,OAAO,OAAO;GACjC,MAAM,YAAY,OAAO,MAAM;GAC/B,MAAM,kBAAkB,cACtB,2CACA,qGACF;GACA,sBAAsB;IACpB,WAAW,OAAO,OAAO,cAAc;KAWrC,MAAM,UAAU;MAAE;MAAO;MAAW,SAAS;MAAM,WAAW;MAAM,oBAAoB;KAAK;KAK7F,QAHE,cAAc,WACV,MAAM,cAAc,cAAc,OAAO,IACzC,MAAM,cAAc,gBAAgB,OAAO,EAClC,EAAE,QAAQ;IAC3B;IAMA,kBAAkB,gBAAgB,IAAI;GACxC,CAAC;GACD,OAAO,KAAK,6CAA6C,EAAE,OAAO,UAAU,CAAC;EAC/E,OACE,OAAO,KAAK,iGAAiG;EAI/G,MAAM,SAAS,MAAM,mBAAmB,MAAM;EAG9C,MAAM,SAAS,MAAM,gBAAg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B,IAAI,cAAc;EACtC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;EAC9B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO,KAAK,wCAAwC;EAClD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO;EAAE;EAAc;CAAc;AACvC;;;;;;;;AASA,eAAe,uBAAuB,QAA+C;CACnF,IAAI,CAAC,OAAO,OACV;CAEF,OAAO,MAAM,kGAAkG,EAC7G,OAAO,OAAO,MAAM,KACtB,CAAC;AACH"}
1
+ {"version":3,"file":"init-D814LeLF.js","names":[],"sources":["../src/init/index.ts"],"sourcesContent":["/**\n * Burdenoff SDK Initialization Module\n *\n * Provides a unified initialization function for all state services\n * including database, cache, analytics, event queue, and graph sync.\n *\n * @module init\n * @category Initialization\n */\n\nimport { logger } from '../logger/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { GatewayClient } from '../gateway/index.js';\nimport { configureResourceCaps } from '../resource-caps/index.js';\nimport { createCounter } from '../instrumentation/metrics-collector.js';\nimport type { BurdenoffSDKInitConfig, InitializedSDKState } from './types.js';\n\n/**\n * Global SDK state\n */\nlet sdkState: InitializedSDKState | null = null;\nlet isInitialized = false;\n\n/**\n * Initialize Burdenoff SDK with unified configuration\n *\n * This function initializes all configured state services in the correct order:\n * 1. Logging configuration\n * 2. Database (Prisma with PostgreSQL)\n * 3. Cache (Valkey)\n * 4. Event Queue (Redis Streams)\n * 5. Graph Sync (Redis Streams-based — Apache AGE writes happen inside wspace-graph-svc)\n * 6. Analytics (ClickHouse)\n * 7. Observability (Metrics, OpenTelemetry)\n *\n * @param config - SDK initialization configuration\n * @returns Initialized SDK state\n *\n * @example\n * ```typescript\n * import { initializeBurdenoffSDK } from '@burdenoff/be-sdk/init';\n *\n * const state = await initializeBurdenoffSDK({\n * database: {\n * url: process.env.DATABASE_URL!,\n * maxConnections: 20,\n * },\n * graph: {\n * enabled: true,\n * eventsEnabled: true,\n * },\n * cache: {\n * valkey: {\n * url: process.env.VALKEY_URL!,\n * },\n * },\n * });\n * ```\n */\nexport async function initializeBurdenoffSDK(config: BurdenoffSDKInitConfig): Promise<InitializedSDKState> {\n if (isInitialized && sdkState) {\n logger.warn('[SDK Init] SDK already initialized, returning existing state');\n return sdkState;\n }\n\n logger.info('[SDK Init] Starting SDK initialization...');\n const startTime = Date.now();\n\n try {\n // 1. Configure logging\n await initializeLogging(config);\n\n // 2. Initialize layer manager (if configured)\n const { layerManager, gatewayClient } = await initializeLayer(config);\n\n // 2b. Wire resource caps to billing so plan-based limits actually apply.\n // `userBillingPlan` lives in the GLOBAL layer: global services reach it\n // on their own internal gateway; wspace services go cross-layer via the\n // public global gateway (service JWT). Without this, every resource cap\n // silently collapses to the free-tier fallback regardless of the\n // customer's plan (BOFF-4805). Primes the process-wide singleton so all\n // existing `getResourceCaps()` call sites resolve real plans unchanged.\n if (gatewayClient && config.layer) {\n const layerType = config.layer.type;\n const fallbackCounter = createCounter(\n 'resource_caps.clientless_fallback_total',\n 'Total number of times resource caps fell back because no billing source was configured at bootstrap'\n );\n configureResourceCaps({\n transport: async (query, variables) => {\n // Cap checks run on entity-create paths and ALWAYS fall back to the\n // configured billing-failure tier on failure, so a billing outage\n // must degrade fast rather than stall writes. Bound the lookup with a\n // short timeout and no retries instead of the gateway defaults\n // (~30s × 3 ≈ 90s). Results are cached 60s, so healthy lookups rarely\n // hit the gateway anyway. `skipCircuitBreaker` keeps this best-effort\n // probe OUT of the shared gateway circuit: its failures already\n // degrade to the fallback here, so they must not count toward opening\n // the internal/cross-layer circuit and fail-fast unrelated M2M calls\n // during a billing outage.\n const options = { query, variables, timeout: 8000, skipRetry: true, skipCircuitBreaker: true };\n const response =\n layerType === 'global'\n ? await gatewayClient.internalQuery(options)\n : await gatewayClient.crossLayerQuery(options);\n return response?.data ?? null;\n },\n // Emitting a dedicated clientless-fallback counter at bootstrap means\n // a service that somehow starts without a billing transport is\n // immediately visible in metrics (BOFF-4809). The resource-caps module\n // itself also emits `resource_caps.plan_resolution_total`, but that\n // only fires on the first cap check; this counter fires at bootstrap.\n onFallback: () => fallbackCounter.inc(),\n });\n logger.info('[SDK Init] Resource caps wired to billing', { layer: layerType });\n } else {\n logger.warn('[SDK Init] No layer/gateway configured — resource caps will use free-tier fallbacks (BOFF-4805)');\n }\n\n // 3. Initialize database (required)\n const prisma = await initializeDatabase(config);\n\n // 4. Initialize cache (optional)\n const valkey = await initializeCache(config);\n\n // 5. Initialize event queue (optional) — Redis Streams via REDIS_URL\n const eventPublisher = await initializeEventQueue(config);\n\n // 6. Initialize layer streams (if layer configured)\n if (config.layer?.autoCreateStreams !== false && config.layer) {\n await initializeLayerStreams(config);\n }\n\n // 7. Initialize graph sync (optional) — publisher emits to Redis Streams,\n // never opens a graph-DB connection\n const graphSync = await initializeGraphSync(config);\n\n // 8. Initialize analytics (optional)\n const clickhouse = await initializeAnalytics(config);\n\n // 9. Initialize observability (optional)\n await initializeObservability(config);\n\n // Create SDK state\n // graphSync is a publisher-side placeholder; services emit Redis Streams\n // events and wspace-graph-svc owns the sole Apache AGE connection.\n void graphSync;\n sdkState = {\n prisma,\n valkey,\n clickhouse,\n eventPublisher,\n layerManager,\n gatewayClient,\n graphSyncEnabled: config.graph?.enabled ?? false,\n analyticsEnabled: !!config.analytics?.clickhouse,\n observabilityEnabled: config.observability?.metrics?.enabled ?? false,\n layerAwareEnabled: !!config.layer,\n };\n\n isInitialized = true;\n\n const duration = Date.now() - startTime;\n // sdkState is guaranteed non-null here since we just assigned it above\n const initializedState = sdkState;\n logger.info(`[SDK Init] SDK initialized successfully in ${duration}ms`, {\n graphSyncEnabled: initializedState.graphSyncEnabled,\n analyticsEnabled: initializedState.analyticsEnabled,\n observabilityEnabled: initializedState.observabilityEnabled,\n layerAwareEnabled: initializedState.layerAwareEnabled,\n layer: config.layer?.type,\n serviceName: config.layer?.serviceName,\n });\n\n return initializedState;\n } catch (error) {\n logger.error('[SDK Init] Failed to initialize SDK:', error);\n throw error;\n }\n}\n\n/**\n * Get current SDK state\n * @throws Error if SDK is not initialized\n */\nexport function getSDKState(): InitializedSDKState {\n if (!isInitialized || !sdkState) {\n throw new Error('SDK not initialized. Call initializeBurdenoffSDK() first.');\n }\n return sdkState;\n}\n\n/**\n * Check if SDK is initialized\n */\nexport function isSDKInitialized(): boolean {\n return isInitialized;\n}\n\n/**\n * Reset SDK state (useful for testing)\n */\nexport async function resetSDK(): Promise<void> {\n logger.info('[SDK Init] Resetting SDK state...');\n\n if (sdkState) {\n // Cleanup resources\n // Note: Individual cleanup will be handled by service-specific shutdown handlers\n sdkState = null;\n }\n\n isInitialized = false;\n logger.info('[SDK Init] SDK state reset');\n}\n\n/**\n * Initialize logging configuration\n */\nasync function initializeLogging(config: BurdenoffSDKInitConfig): Promise<void> {\n logger.info('[SDK Init] Configuring logging...');\n\n const loggingConfig = config.logging ?? {};\n const isDevelopment = config.app?.nodeEnv === 'development';\n\n // Set log level\n const level = loggingConfig.level ?? 'info';\n logger.setLevel(level);\n\n // Set console logging\n const console = loggingConfig.console ?? true;\n logger.setConsoleEnabled(console);\n\n logger.info('[SDK Init] Logging configured', {\n level,\n console,\n format: loggingConfig.format ?? (isDevelopment ? 'pretty' : 'json'),\n });\n}\n\n/**\n * Initialize database (Prisma with PostgreSQL)\n */\nasync function initializeDatabase(config: BurdenoffSDKInitConfig): Promise<unknown> {\n logger.info('[SDK Init] Initializing database...');\n\n // Note: Database initialization is handled by createPrismaClient in prisma/client.ts\n // This is called by the application (e.g., workspaces-backend)\n // We just validate the config here\n if (!config.database?.url) {\n throw new Error('Database URL is required');\n }\n\n logger.info('[SDK Init] Database configuration validated', {\n maxConnections: config.database.maxConnections ?? 20,\n enableQueryLogging: config.database.enableQueryLogging ?? false,\n });\n\n // Return undefined as database client is created separately\n return undefined;\n}\n\n/**\n * Initialize cache (Valkey)\n */\nasync function initializeCache(config: BurdenoffSDKInitConfig): Promise<unknown> {\n const cacheConfig = config.cache?.valkey;\n\n if (!cacheConfig) {\n logger.info('[SDK Init] Cache not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing Valkey cache...');\n\n // Note: Valkey initialization is handled by cache module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] Valkey cache configuration validated', {\n url: cacheConfig.url ? '***' : undefined,\n defaultTTL: cacheConfig.defaultTTL ?? 3600,\n });\n\n return undefined;\n}\n\n/**\n * Initialize event queue (Redis Streams).\n *\n * NATS was retired on 2026-05-16. The publisher is created from\n * `REDIS_STREAMS_URL` when set, else `REDIS_URL` (set in every SM bundle). Legacy `config.eventQueue.nats`\n * values are ignored — kept on the type only as a back-compat shim.\n */\nasync function initializeEventQueue(_config: BurdenoffSDKInitConfig): Promise<unknown> {\n const { resolveEventStreamsUrl } = await import('../event-queue/env.js');\n if (!resolveEventStreamsUrl()) {\n logger.info('[SDK Init] REDIS_STREAMS_URL / REDIS_URL not set, skipping event queue init');\n return undefined;\n }\n\n try {\n const { EventQueueFactory } = await import('../event-queue/factory/EventQueueFactory.js');\n const publisher = EventQueueFactory.createPublisherFromEnv();\n await publisher.connect();\n\n logger.info('[SDK Init] Redis Streams event publisher connected');\n\n return publisher;\n } catch (error) {\n logger.warn('[SDK Init] Failed to connect Redis Streams event publisher (non-fatal)', {\n error: error instanceof Error ? error.message : String(error),\n note: 'Service will continue without event publishing. Use direct API calls as fallback.',\n });\n return undefined;\n }\n}\n\n/**\n * Initialize graph sync (Redis Streams publisher side).\n *\n * Services publish entity events to Redis Streams; the `wspace-graph-svc`\n * consumer (and only it) persists them into Apache AGE via Azure PG\n * sidecar. This SDK function does no DB work — it just validates that the\n * publisher-side config is sensible and logs it.\n */\nasync function initializeGraphSync(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.graph?.enabled) {\n logger.info('[SDK Init] Graph sync not enabled, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Graph sync enabled (publisher-only mode)', {\n eventsEnabled: config.graph.eventsEnabled ?? true,\n productSource: config.graph.productSource,\n streamName: config.graph.streamName ?? 'graph_events',\n syncInterval: config.graph.syncInterval ?? 1000,\n batchSize: config.graph.batchSize ?? 10,\n });\n\n return undefined;\n}\n\n/**\n * Initialize analytics (ClickHouse)\n */\nasync function initializeAnalytics(config: BurdenoffSDKInitConfig): Promise<unknown> {\n if (!config.analytics?.clickhouse) {\n logger.info('[SDK Init] Analytics not configured, skipping');\n return undefined;\n }\n\n logger.info('[SDK Init] Initializing ClickHouse for analytics...');\n\n // Note: ClickHouse initialization is handled by analytics module\n // This is a placeholder for future implementation\n logger.info('[SDK Init] ClickHouse configuration validated', {\n url: config.analytics.clickhouse.url,\n database: config.analytics.clickhouse.database,\n requestTimeout: config.analytics.clickhouse.requestTimeout ?? 60000,\n });\n\n return undefined;\n}\n\n/**\n * Initialize observability (metrics, tracing)\n */\nasync function initializeObservability(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.observability?.metrics?.enabled && !config.observability?.openTelemetry?.enabled) {\n logger.info('[SDK Init] Observability not configured, skipping');\n return;\n }\n\n logger.info('[SDK Init] Initializing observability...');\n\n // Note: Observability initialization is handled by observability module\n // This is a placeholder for future implementation\n if (config.observability.metrics?.enabled) {\n logger.info('[SDK Init] Metrics configuration validated', {\n port: config.observability.metrics.port ?? 9090,\n endpoint: config.observability.metrics.endpoint ?? '/metrics',\n });\n }\n\n if (config.observability.openTelemetry?.enabled) {\n logger.info('[SDK Init] OpenTelemetry configuration validated', {\n serviceName: config.observability.openTelemetry.serviceName,\n samplingRate: config.observability.openTelemetry.samplingRate ?? 1.0,\n });\n }\n}\n\n/**\n * Initialize layer manager and gateway client\n */\nasync function initializeLayer(\n config: BurdenoffSDKInitConfig\n): Promise<{ layerManager?: LayerManager; gatewayClient?: GatewayClient }> {\n if (!config.layer) {\n logger.info('[SDK Init] Layer configuration not provided, skipping layer initialization');\n return {};\n }\n\n logger.info('[SDK Init] Initializing layer manager...', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n });\n\n // Create layer manager\n const layerManager = new LayerManager({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n });\n\n // Create gateway client\n const gatewayClient = new GatewayClient({\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n serviceIdentity: config.layer.serviceIdentity,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n logger.info('[SDK Init] Layer manager initialized', {\n layer: config.layer.type,\n serviceName: config.layer.serviceName,\n internalGatewayUrl: layerManager.getInternalGatewayUrl(),\n crossLayerGatewayUrl: layerManager.getCrossLayerGatewayUrl(),\n });\n\n return { layerManager, gatewayClient };\n}\n\n/**\n * Initialize layer-specific Redis streams.\n *\n * No-op since the 2026-05-16 NATS retirement: Redis Streams are created\n * on demand by `XGROUP CREATE ... MKSTREAM` inside the consumer, so no\n * upfront connect-and-provision step is needed.\n */\nasync function initializeLayerStreams(config: BurdenoffSDKInitConfig): Promise<void> {\n if (!config.layer) {\n return;\n }\n logger.debug('[SDK Init] Layer streams init is a no-op for Redis Streams (auto-created on first XADD/XGROUP)', {\n layer: config.layer.type,\n });\n}\n\n// Export types\nexport type * from './types.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAI,WAAuC;AAC3C,IAAI,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCpB,eAAsB,uBAAuB,QAA8D;CACzG,IAAI,iBAAiB,UAAU;EAC7B,OAAO,KAAK,8DAA8D;EAC1E,OAAO;CACT;CAEA,OAAO,KAAK,2CAA2C;CACvD,MAAM,YAAY,KAAK,IAAI;CAE3B,IAAI;EAEF,MAAM,kBAAkB,MAAM;EAG9B,MAAM,EAAE,cAAc,kBA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,cAAc,QAAQ,QAAQ;EAC3C,UAAU,OAAO,cAAc,QAAQ,YAAY;CACrD,CAAC;CAGH,IAAI,OAAO,cAAc,eAAe,SACtC,OAAO,KAAK,oDAAoD;EAC9D,aAAa,OAAO,cAAc,cAAc;EAChD,cAAc,OAAO,cAAc,cAAc,gBAAgB;CACnE,CAAC;AAEL;;;;AAKA,eAAe,gBACb,QACyE;CACzE,IAAI,CAAC,OAAO,OAAO;EACjB,OAAO,KAAK,4EAA4E;EACxF,OAAO,CAAC;CACV;CAEA,OAAO,KAAK,4CAA4C;EACtD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;CAC5B,CAAC;CAGD,MAAM,eAAe,IAAI,aAAa;EACpC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;CAChC,CAAC;CAGD,MAAM,gBAAgB,IAAI,cAAc;EACtC,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,iBAAiB,OAAO,MAAM;EAC9B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO,KAAK,wCAAwC;EAClD,OAAO,OAAO,MAAM;EACpB,aAAa,OAAO,MAAM;EAC1B,oBAAoB,aAAa,sBAAsB;EACvD,sBAAsB,aAAa,wBAAwB;CAC7D,CAAC;CAED,OAAO;EAAE;EAAc;CAAc;AACvC;;;;;;;;AASA,eAAe,uBAAuB,QAA+C;CACnF,IAAI,CAAC,OAAO,OACV;CAEF,OAAO,MAAM,kGAAkG,EAC7G,OAAO,OAAO,MAAM,KACtB,CAAC;AACH"}
@@ -1,3 +1,3 @@
1
- import { u as logger } from "../index-Cot73bdh.js";
2
- import { $ as Counter, A as buildMetricsConfig, At as HTTPInstrumentationConfig, B as GraphQLOperationType, Bt as TraceContext, C as DEFAULT_METRICS_CONFIG, Ct as isTracerInitialized, D as buildFeatureFlags, Dt as DatabaseInstrumentationConfig, E as buildDatabaseConfig, Et as CacheInstrumentationConfig, F as isInstrumentationConfigInitialized, Ft as MetricsConfig, G as createPrometheusPlugin, H as PrometheusPluginOptions, I as resetInstrumentationConfig, It as OperationContext, J as getGraphQLSpanFromContext, K as extractOperationInfo, L as updateInstrumentationConfig, Lt as STANDARD_METRICS, M as getInstrumentationConfig, Mt as InstrumentationFeatureFlags, N as initializeInstrumentationConfig, Nt as LoggingConfig, O as buildGraphQLConfig, Ot as EventQueueInstrumentationConfig, P as isFeatureEnabled, Pt as MetricDefinition, Q as isPrometheusAvailable, R as ApolloInlineTraceOptions, Rt as SpanAttributes, S as DEFAULT_LOGGING_CONFIG, St as injectTraceContext, T as ENV_VARS, Tt as withSpan, U as createApolloInlineTracePlugin, V as InstrumentationContextExtension, Vt as TracingConfig, W as createGraphQLInstrumentationPlugin, X as instrumentResolverMap, Y as instrumentResolver, Z as isApolloInlineTraceAvailable, _ as DEFAULT_DATABASE_CONFIG, _t as Tracer, at as createCounter, b as DEFAULT_GRAPHQL_CONFIG, bt as getTracer, c as resetInstrumentation, ct as createUpDownCounter, d as Log, dt as isMetricsRegistryInitialized, et as Gauge, f as Metric, ft as resetMetricsRegistry, g as DEFAULT_CACHE_CONFIG, gt as SpanStatus, h as traced, ht as SpanKind, i as getLogger, it as UpDownCounter, j as buildTracingConfig, jt as InstrumentationConfig, k as buildInstrumentationConfig, kt as GraphQLInstrumentationConfig, l as setupInstrumentation, lt as getMetricsRegistry, m as instrumented, mt as SpanEvent, n as InstrumentationSetupResult, nt as MetricLabels, o as initializeInstrumentation, ot as createGauge, p as Trace, pt as Span, q as getGraphQLOperationFromContext, r as SetupInstrumentationOptions, rt as MetricsRegistry, s as isInstrumentationInitialized, st as createHistogram, t as InitializeInstrumentationOptions, tt as Histogram, u as Instrument, ut as initializeMetricsRegistry, v as DEFAULT_EVENT_QUEUE_CONFIG, vt as extractTraceContext, w as DEFAULT_TRACING_CONFIG, wt as startSpan, x as DEFAULT_HTTP_CONFIG, xt as initializeTracer, y as DEFAULT_FEATURE_FLAGS, yt as getTraceContext, z as GraphQLOperationInfo, zt as SpanContext } from "../index-B2LCaK0R.js";
1
+ import { u as logger } from "../index-KlrnELrN.js";
2
+ import { $ as Counter, A as buildMetricsConfig, At as HTTPInstrumentationConfig, B as GraphQLOperationType, Bt as TraceContext, C as DEFAULT_METRICS_CONFIG, Ct as isTracerInitialized, D as buildFeatureFlags, Dt as DatabaseInstrumentationConfig, E as buildDatabaseConfig, Et as CacheInstrumentationConfig, F as isInstrumentationConfigInitialized, Ft as MetricsConfig, G as createPrometheusPlugin, H as PrometheusPluginOptions, I as resetInstrumentationConfig, It as OperationContext, J as getGraphQLSpanFromContext, K as extractOperationInfo, L as updateInstrumentationConfig, Lt as STANDARD_METRICS, M as getInstrumentationConfig, Mt as InstrumentationFeatureFlags, N as initializeInstrumentationConfig, Nt as LoggingConfig, O as buildGraphQLConfig, Ot as EventQueueInstrumentationConfig, P as isFeatureEnabled, Pt as MetricDefinition, Q as isPrometheusAvailable, R as ApolloInlineTraceOptions, Rt as SpanAttributes, S as DEFAULT_LOGGING_CONFIG, St as injectTraceContext, T as ENV_VARS, Tt as withSpan, U as createApolloInlineTracePlugin, V as InstrumentationContextExtension, Vt as TracingConfig, W as createGraphQLInstrumentationPlugin, X as instrumentResolverMap, Y as instrumentResolver, Z as isApolloInlineTraceAvailable, _ as DEFAULT_DATABASE_CONFIG, _t as Tracer, at as createCounter, b as DEFAULT_GRAPHQL_CONFIG, bt as getTracer, c as resetInstrumentation, ct as createUpDownCounter, d as Log, dt as isMetricsRegistryInitialized, et as Gauge, f as Metric, ft as resetMetricsRegistry, g as DEFAULT_CACHE_CONFIG, gt as SpanStatus, h as traced, ht as SpanKind, i as getLogger, it as UpDownCounter, j as buildTracingConfig, jt as InstrumentationConfig, k as buildInstrumentationConfig, kt as GraphQLInstrumentationConfig, l as setupInstrumentation, lt as getMetricsRegistry, m as instrumented, mt as SpanEvent, n as InstrumentationSetupResult, nt as MetricLabels, o as initializeInstrumentation, ot as createGauge, p as Trace, pt as Span, q as getGraphQLOperationFromContext, r as SetupInstrumentationOptions, rt as MetricsRegistry, s as isInstrumentationInitialized, st as createHistogram, t as InitializeInstrumentationOptions, tt as Histogram, u as Instrument, ut as initializeMetricsRegistry, v as DEFAULT_EVENT_QUEUE_CONFIG, vt as extractTraceContext, w as DEFAULT_TRACING_CONFIG, wt as startSpan, x as DEFAULT_HTTP_CONFIG, xt as initializeTracer, y as DEFAULT_FEATURE_FLAGS, yt as getTraceContext, z as GraphQLOperationInfo, zt as SpanContext } from "../index-479i3w77.js";
3
3
  export { type ApolloInlineTraceOptions, type CacheInstrumentationConfig, type Counter, DEFAULT_CACHE_CONFIG, DEFAULT_DATABASE_CONFIG, DEFAULT_EVENT_QUEUE_CONFIG, DEFAULT_FEATURE_FLAGS, DEFAULT_GRAPHQL_CONFIG, DEFAULT_HTTP_CONFIG, DEFAULT_LOGGING_CONFIG, DEFAULT_METRICS_CONFIG, DEFAULT_TRACING_CONFIG, type DatabaseInstrumentationConfig, ENV_VARS, type EventQueueInstrumentationConfig, type Gauge, type GraphQLInstrumentationConfig, type GraphQLOperationInfo, type GraphQLOperationType, type HTTPInstrumentationConfig, type Histogram, InitializeInstrumentationOptions, Instrument, type InstrumentationConfig, type InstrumentationContextExtension, type InstrumentationFeatureFlags, InstrumentationSetupResult, Log, type LoggingConfig, Metric, type MetricDefinition, type MetricLabels, type MetricsConfig, MetricsRegistry, type OperationContext, type PrometheusPluginOptions, STANDARD_METRICS, SetupInstrumentationOptions, type Span, type SpanAttributes, type SpanContext, type SpanEvent, SpanKind, SpanStatus, Trace, type TraceContext, Tracer, type TracingConfig, type UpDownCounter, buildDatabaseConfig, buildFeatureFlags, buildGraphQLConfig, buildInstrumentationConfig, buildMetricsConfig, buildTracingConfig, createApolloInlineTracePlugin, createCounter, createGauge, createGraphQLInstrumentationPlugin, createHistogram, createPrometheusPlugin, createUpDownCounter, extractOperationInfo, extractTraceContext, getGraphQLOperationFromContext, getGraphQLSpanFromContext, getInstrumentationConfig, getLogger, getMetricsRegistry, getTraceContext, getTracer, initializeInstrumentation, initializeInstrumentationConfig, initializeMetricsRegistry, initializeTracer, injectTraceContext, instrumentResolver, instrumentResolverMap, instrumented, isApolloInlineTraceAvailable, isFeatureEnabled, isInstrumentationConfigInitialized, isInstrumentationInitialized, isMetricsRegistryInitialized, isPrometheusAvailable, isTracerInitialized, logger, resetInstrumentation, resetInstrumentationConfig, resetMetricsRegistry, setupInstrumentation, startSpan, traced, updateInstrumentationConfig, withSpan };
@@ -1,3 +1,3 @@
1
- import { a as DEFAULT_LAYER_RESOURCES, d as LayerFullConfig, f as LayerGatewayConfig, i as DEFAULT_GATEWAY_ROUTING, l as GatewayRoutingConfig, m as ServiceLayer, o as DEFAULT_LAYER_STREAMS, p as LayerResourceUrls, u as LayerConfig } from "../layer-BZBZZWeV.js";
2
- import { i as getGatewayUrlForLayer, n as createLayerManagerFromEnv, o as validateLayerConfig, r as detectLayerFromServiceName, t as LayerManager } from "../index-CDOqxSIi.js";
1
+ import { a as DEFAULT_LAYER_RESOURCES, d as LayerFullConfig, f as LayerGatewayConfig, i as DEFAULT_GATEWAY_ROUTING, l as GatewayRoutingConfig, m as ServiceLayer, o as DEFAULT_LAYER_STREAMS, p as LayerResourceUrls, u as LayerConfig } from "../layer-C0zxAUgR.js";
2
+ import { i as getGatewayUrlForLayer, n as createLayerManagerFromEnv, o as validateLayerConfig, r as detectLayerFromServiceName, t as LayerManager } from "../index-Base-sg5.js";
3
3
  export { DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS, type GatewayRoutingConfig, type LayerConfig, type LayerFullConfig, type LayerGatewayConfig, LayerManager, type LayerResourceUrls, type ServiceLayer, createLayerManagerFromEnv, detectLayerFromServiceName, getGatewayUrlForLayer, validateLayerConfig };
@@ -1 +1 @@
1
- {"version":3,"file":"layer-Bcix-WCl.js","names":[],"sources":["../src/types/layer.ts"],"sourcesContent":["/**\n * Layer Type Definitions for Burdenoff Backend SDK\n *\n * This module defines types for the layer-aware architecture,\n * supporting wspace (workspace) and global (tenant) service layers.\n *\n * @module types/layer\n * @category Configuration\n */\n\n/**\n * Service layer types\n * - wspace: Workspace layer services (product-specific operations)\n * - global: Global/tenant layer services (cross-product services)\n */\nexport type ServiceLayer = 'wspace' | 'global';\n\n/**\n * Layer configuration for a service\n */\nexport interface LayerConfig {\n /**\n * Layer type this service belongs to\n * @example 'wspace' or 'global'\n */\n layer: ServiceLayer;\n\n /**\n * Service name (e.g., 'wspace-tags-svc', 'global-auth-svc')\n */\n serviceName: string;\n\n /**\n * Service identity for bypass headers\n * Used for M2M authentication\n * @default serviceName\n */\n serviceIdentity?: string;\n}\n\n/**\n * Gateway configuration per layer\n */\nexport interface LayerGatewayConfig {\n /**\n * Internal gateway URL (same layer int-gateway)\n * - wspace services use: wspace-int-gateway\n * - global services use: global-int-gateway\n */\n internalGatewayUrl: string;\n\n /**\n * Cross-layer gateway URL (cross layer public-gateway)\n * - wspace services use: global-public-gateway\n * - global services use: wspace-public-gateway\n */\n crossLayerGatewayUrl: string;\n}\n\n/**\n * Resource URLs per layer\n */\nexport interface LayerResourceUrls {\n /**\n * Event queue (Redis Streams) URL.\n *\n * Single fleet-shared Redis instance in every environment:\n * - ACA (prod/alpha): Azure Managed Redis — `REDIS_URL` injected from\n * KeyVault overrides this default.\n * - Local dev: self-hosted `shared-valkey` reachable via\n * docker-compose; the default below points at the same container\n * name used by `~/products/dev`'s compose graph.\n *\n * `LayerManager.resolveResourceConfig()` always prefers `REDIS_URL`\n * from the environment, so the layer-scoped default is only the\n * local-dev fallback.\n */\n eventQueueUrl: string;\n\n /**\n * Valkey/Redis URL for the layer\n */\n valkeyUrl: string;\n\n /**\n * Temporal server address for the layer\n */\n temporalAddress: string;\n\n /**\n * Temporal namespace for the layer\n */\n temporalNamespace: string;\n\n /**\n * RBAC gateway URL (for permission checks)\n */\n rbacGatewayUrl: string;\n}\n\n/**\n * Complete layer configuration including gateways and resources\n */\nexport interface LayerFullConfig extends LayerConfig {\n /**\n * Gateway configuration\n */\n gateways: LayerGatewayConfig;\n\n /**\n * Resource URLs\n */\n resources: LayerResourceUrls;\n}\n\n/**\n * Gateway routing rules by layer\n * Defines which gateway to use for same-layer vs cross-layer communication\n */\nexport interface GatewayRoutingConfig {\n /**\n * Layer this config applies to\n */\n layer: ServiceLayer;\n\n /**\n * Internal gateway for same-layer M2M calls\n */\n internalGateway: {\n /** Gateway host (without protocol) */\n host: string;\n /** Gateway port */\n port: number;\n /** GraphQL endpoint path */\n graphqlPath: string;\n };\n\n /**\n * Public gateway for cross-layer calls\n */\n crossLayerGateway: {\n /** Gateway host (without protocol) */\n host: string;\n /** Gateway port */\n port: number;\n /** GraphQL endpoint path */\n graphqlPath: string;\n };\n}\n\n/**\n * Default gateway routing configuration\n */\nexport const DEFAULT_GATEWAY_ROUTING: Record<ServiceLayer, GatewayRoutingConfig> = {\n wspace: {\n layer: 'wspace',\n internalGateway: {\n host: 'wspace-int-gateway',\n port: 4001,\n graphqlPath: '/workspaces/graphql',\n },\n crossLayerGateway: {\n host: 'global-public-gateway',\n port: 4000,\n graphqlPath: '/global/graphql',\n },\n },\n global: {\n layer: 'global',\n internalGateway: {\n host: 'global-int-gateway',\n port: 4002,\n graphqlPath: '/global/graphql',\n },\n crossLayerGateway: {\n host: 'wspace-public-gateway',\n port: 4003,\n graphqlPath: '/workspaces/graphql',\n },\n },\n};\n\n/**\n * Default stream configurations per layer\n */\nexport const DEFAULT_LAYER_STREAMS: Record<\n ServiceLayer,\n Array<{ name: string; subjects: string[]; description?: string }>\n> = {\n wspace: [\n {\n name: 'WSPACE_EVENTS',\n subjects: ['wspace.>'],\n description: 'Workspace layer events stream',\n },\n {\n name: 'WSPACE_GRAPH_EVENTS',\n subjects: ['graph.>'],\n description: 'Workspace layer graph events stream (captures all graph entity events)',\n },\n ],\n global: [\n {\n name: 'GLOBAL_EVENTS',\n subjects: ['global.>'],\n description: 'Global layer events stream',\n },\n {\n name: 'GLOBAL_GRAPH_EVENTS',\n subjects: ['graph.>'],\n description: 'Global layer graph events stream (captures all graph entity events)',\n },\n ],\n};\n\n/**\n * Build internal gateway URL for a layer\n * Uses HTTP for internal K8s communication (mTLS via Istio service mesh)\n */\nfunction buildInternalGatewayUrl(layer: ServiceLayer): string {\n const routing = DEFAULT_GATEWAY_ROUTING[layer];\n const { host, port, graphqlPath } = routing.internalGateway;\n // Internal K8s services use plain HTTP with mTLS handled by Istio\n const protocol = 'http';\n return `${protocol}://${host}:${port}${graphqlPath}`;\n}\n\n/**\n * Default resource URLs per layer\n *\n * Note: Internal K8s service communication uses plain HTTP with mTLS via Istio.\n * External traffic uses HTTPS via ingress gateway.\n */\nexport const DEFAULT_LAYER_RESOURCES: Record<ServiceLayer, LayerResourceUrls> = {\n // The event queue is a single fleet-shared Redis (Azure Managed Redis in\n // ACA, fed via REDIS_URL; self-hosted shared-valkey in local dev). The\n // layer-scoped default URL below is only the local-dev compose hostname —\n // production always overrides via REDIS_URL.\n wspace: {\n eventQueueUrl: 'redis://wspace-shared-valkey:6379',\n valkeyUrl: 'valkey://wspace-valkey:6379',\n temporalAddress: 'wspace-temporal:7233',\n temporalNamespace: 'wspace-default',\n rbacGatewayUrl: buildInternalGatewayUrl('wspace'),\n },\n global: {\n eventQueueUrl: 'redis://global-shared-valkey:6379',\n valkeyUrl: 'valkey://global-valkey:6379',\n temporalAddress: 'global-temporal:7233',\n temporalNamespace: 'global-default',\n rbacGatewayUrl: buildInternalGatewayUrl('global'),\n },\n};\n\n/**\n * Circuit breaker configuration for gateway client\n */\nexport interface CircuitBreakerConfig {\n /**\n * Number of failures before opening circuit\n * @default 5\n */\n failureThreshold: number;\n\n /**\n * Time in milliseconds to wait before attempting to close circuit\n * @default 30000 (30 seconds)\n */\n resetTimeout: number;\n\n /**\n * Time window in milliseconds for counting failures\n * @default 60000 (60 seconds)\n */\n failureWindow: number;\n}\n\n/**\n * Default circuit breaker configuration\n */\nexport const DEFAULT_CIRCUIT_BREAKER_CONFIG: CircuitBreakerConfig = {\n failureThreshold: 5,\n resetTimeout: 30000,\n failureWindow: 60000,\n};\n\n/**\n * Retry configuration for gateway client\n */\nexport interface GatewayRetryConfig {\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxAttempts: number;\n\n /**\n * Initial delay in milliseconds before first retry\n * @default 1000 (1 second)\n */\n initialDelay: number;\n\n /**\n * Maximum delay in milliseconds between retries\n * @default 10000 (10 seconds)\n */\n maxDelay: number;\n\n /**\n * Backoff multiplier for exponential backoff\n * @default 2\n */\n backoffMultiplier: number;\n}\n\n/**\n * Default retry configuration\n */\nexport const DEFAULT_GATEWAY_RETRY_CONFIG: GatewayRetryConfig = {\n maxAttempts: 3,\n initialDelay: 1000,\n maxDelay: 10000,\n backoffMultiplier: 2,\n};\n\n/**\n * Headers automatically added by gateway client for M2M calls\n */\nexport interface GatewayRequestHeaders {\n /**\n * Actor ID making the request\n */\n 'x-actor-id'?: string;\n\n /**\n * Actor type\n */\n 'x-actor-type'?: 'user' | 'app' | 'service' | 'super_admin';\n\n /**\n * Workspace ID for the request context\n */\n 'x-workspace-id'?: string;\n\n /**\n * Service identity for bypass validation\n */\n 'x-service-identity'?: string;\n\n /**\n * Call type indicator\n */\n 'x-call-type'?: 'internal' | 'cross-layer';\n\n /**\n * Permission bypass flag\n */\n 'x-bypass-permission'?: string;\n\n /**\n * RBAC bypass flag (set by gateway)\n */\n 'x-rbac-bypass'?: 'true' | 'false';\n\n /**\n * Bypass source (set by gateway)\n */\n 'x-bypass-source'?: string;\n\n /**\n * Bypass timestamp (set by gateway)\n */\n 'x-bypass-timestamp'?: string;\n\n /**\n * Cloudflare Access service-token client id, re-presented on cross-layer\n * outbound calls so the peer layer's CF-Access-gated public gateway admits\n * the request. Normally attached automatically from request context.\n */\n 'cf-access-client-id'?: string;\n\n /**\n * Cloudflare Access service-token client secret (paired with the client id).\n */\n 'cf-access-client-secret'?: string;\n\n /**\n * Delegated `app_as_user` bearer (`Bearer <jwt>`) for an internal-gateway\n * call made as an agent acting for a user. The internal gateway verifies it\n * and derives the actor; see `buildDelegatedGatewayHeaders`.\n */\n 'x-delegated-authorization'?: string;\n}\n"],"mappings":";;;;AAyJA,MAAa,0BAAsE;CACjF,QAAQ;EACN,OAAO;EACP,iBAAiB;GACf,MAAM;GACN,MAAM;GACN,aAAa;EACf;EACA,mBAAmB;GACjB,MAAM;GACN,MAAM;GACN,aAAa;EACf;CACF;CACA,QAAQ;EACN,OAAO;EACP,iBAAiB;GACf,MAAM;GACN,MAAM;GACN,aAAa;EACf;EACA,mBAAmB;GACjB,MAAM;GACN,MAAM;GACN,aAAa;EACf;CACF;AACF;;;;AAKA,MAAa,wBAGT;CACF,QAAQ,CACN;EACE,MAAM;EACN,UAAU,CAAC,UAAU;EACrB,aAAa;CACf,GACA;EACE,MAAM;EACN,UAAU,CAAC,SAAS;EACpB,aAAa;CACf,CACF;CACA,QAAQ,CACN;EACE,MAAM;EACN,UAAU,CAAC,UAAU;EACrB,aAAa;CACf,GACA;EACE,MAAM;EACN,UAAU,CAAC,SAAS;EACpB,aAAa;CACf,CACF;AACF;;;;;AAMA,SAAS,wBAAwB,OAA6B;CAE5D,MAAM,EAAE,MAAM,MAAM,gBADJ,wBAAwB,MACG,CAAC;CAG5C,OAAO,UAAiB,KAAK,GAAG,OAAO;AACzC;;;;;;;AAQA,MAAa,0BAAmE;CAK9E,QAAQ;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,gBAAgB,wBAAwB,QAAQ;CAClD;CACA,QAAQ;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,gBAAgB,wBAAwB,QAAQ;CAClD;AACF;;;;AA4BA,MAAa,iCAAuD;CAClE,kBAAkB;CAClB,cAAc;CACd,eAAe;AACjB;;;;AAkCA,MAAa,+BAAmD;CAC9D,aAAa;CACb,cAAc;CACd,UAAU;CACV,mBAAmB;AACrB"}
1
+ {"version":3,"file":"layer-Bcix-WCl.js","names":[],"sources":["../src/types/layer.ts"],"sourcesContent":["/**\n * Layer Type Definitions for Burdenoff Backend SDK\n *\n * This module defines types for the layer-aware architecture,\n * supporting wspace (workspace) and global (tenant) service layers.\n *\n * @module types/layer\n * @category Configuration\n */\n\n/**\n * Service layer types\n * - wspace: Workspace layer services (product-specific operations)\n * - global: Global/tenant layer services (cross-product services)\n */\nexport type ServiceLayer = 'wspace' | 'global';\n\n/**\n * Layer configuration for a service\n */\nexport interface LayerConfig {\n /**\n * Layer type this service belongs to\n * @example 'wspace' or 'global'\n */\n layer: ServiceLayer;\n\n /**\n * Service name (e.g., 'wspace-tags-svc', 'global-auth-svc')\n */\n serviceName: string;\n\n /**\n * Service identity for bypass headers\n * Used for M2M authentication\n * @default serviceName\n */\n serviceIdentity?: string;\n}\n\n/**\n * Gateway configuration per layer\n */\nexport interface LayerGatewayConfig {\n /**\n * Internal gateway URL (same layer int-gateway)\n * - wspace services use: wspace-int-gateway\n * - global services use: global-int-gateway\n */\n internalGatewayUrl: string;\n\n /**\n * Cross-layer gateway URL (cross layer public-gateway)\n * - wspace services use: global-public-gateway\n * - global services use: wspace-public-gateway\n */\n crossLayerGatewayUrl: string;\n}\n\n/**\n * Resource URLs per layer\n */\nexport interface LayerResourceUrls {\n /**\n * Event queue (Redis Streams) URL.\n *\n * Single fleet-shared Redis instance in every environment:\n * - ACA (prod/alpha): Azure Managed Redis — `REDIS_URL` injected from\n * KeyVault overrides this default.\n * - Local dev: self-hosted `shared-valkey` reachable via\n * docker-compose; the default below points at the same container\n * name used by `~/products/dev`'s compose graph.\n *\n * `LayerManager.resolveResourceConfig()` always prefers `REDIS_URL`\n * from the environment, so the layer-scoped default is only the\n * local-dev fallback.\n */\n eventQueueUrl: string;\n\n /**\n * Valkey/Redis URL for the layer\n */\n valkeyUrl: string;\n\n /**\n * Temporal server address for the layer\n */\n temporalAddress: string;\n\n /**\n * Temporal namespace for the layer\n */\n temporalNamespace: string;\n\n /**\n * RBAC gateway URL (for permission checks)\n */\n rbacGatewayUrl: string;\n}\n\n/**\n * Complete layer configuration including gateways and resources\n */\nexport interface LayerFullConfig extends LayerConfig {\n /**\n * Gateway configuration\n */\n gateways: LayerGatewayConfig;\n\n /**\n * Resource URLs\n */\n resources: LayerResourceUrls;\n}\n\n/**\n * Gateway routing rules by layer\n * Defines which gateway to use for same-layer vs cross-layer communication\n */\nexport interface GatewayRoutingConfig {\n /**\n * Layer this config applies to\n */\n layer: ServiceLayer;\n\n /**\n * Internal gateway for same-layer M2M calls\n */\n internalGateway: {\n /** Gateway host (without protocol) */\n host: string;\n /** Gateway port */\n port: number;\n /** GraphQL endpoint path */\n graphqlPath: string;\n };\n\n /**\n * Public gateway for cross-layer calls\n */\n crossLayerGateway: {\n /** Gateway host (without protocol) */\n host: string;\n /** Gateway port */\n port: number;\n /** GraphQL endpoint path */\n graphqlPath: string;\n };\n}\n\n/**\n * Default gateway routing configuration\n */\nexport const DEFAULT_GATEWAY_ROUTING: Record<ServiceLayer, GatewayRoutingConfig> = {\n wspace: {\n layer: 'wspace',\n internalGateway: {\n host: 'wspace-int-gateway',\n port: 4001,\n graphqlPath: '/workspaces/graphql',\n },\n crossLayerGateway: {\n host: 'global-public-gateway',\n port: 4000,\n graphqlPath: '/global/graphql',\n },\n },\n global: {\n layer: 'global',\n internalGateway: {\n host: 'global-int-gateway',\n port: 4002,\n graphqlPath: '/global/graphql',\n },\n crossLayerGateway: {\n host: 'wspace-public-gateway',\n port: 4003,\n graphqlPath: '/workspaces/graphql',\n },\n },\n};\n\n/**\n * Default stream configurations per layer\n */\nexport const DEFAULT_LAYER_STREAMS: Record<\n ServiceLayer,\n Array<{ name: string; subjects: string[]; description?: string }>\n> = {\n wspace: [\n {\n name: 'WSPACE_EVENTS',\n subjects: ['wspace.>'],\n description: 'Workspace layer events stream',\n },\n {\n name: 'WSPACE_GRAPH_EVENTS',\n subjects: ['graph.>'],\n description: 'Workspace layer graph events stream (captures all graph entity events)',\n },\n ],\n global: [\n {\n name: 'GLOBAL_EVENTS',\n subjects: ['global.>'],\n description: 'Global layer events stream',\n },\n {\n name: 'GLOBAL_GRAPH_EVENTS',\n subjects: ['graph.>'],\n description: 'Global layer graph events stream (captures all graph entity events)',\n },\n ],\n};\n\n/**\n * Build internal gateway URL for a layer\n * Uses HTTP for internal K8s communication (mTLS via Istio service mesh)\n */\nfunction buildInternalGatewayUrl(layer: ServiceLayer): string {\n const routing = DEFAULT_GATEWAY_ROUTING[layer];\n const { host, port, graphqlPath } = routing.internalGateway;\n // Internal K8s services use plain HTTP with mTLS handled by Istio\n const protocol = 'http';\n return `${protocol}://${host}:${port}${graphqlPath}`;\n}\n\n/**\n * Default resource URLs per layer\n *\n * Note: Internal K8s service communication uses plain HTTP with mTLS via Istio.\n * External traffic uses HTTPS via ingress gateway.\n */\nexport const DEFAULT_LAYER_RESOURCES: Record<ServiceLayer, LayerResourceUrls> = {\n // The event queue is a single fleet-shared Redis (Azure Managed Redis in\n // ACA, fed via REDIS_URL; self-hosted shared-valkey in local dev). The\n // layer-scoped default URL below is only the local-dev compose hostname —\n // production always overrides via REDIS_URL.\n wspace: {\n eventQueueUrl: 'redis://wspace-shared-valkey:6379',\n valkeyUrl: 'valkey://wspace-valkey:6379',\n temporalAddress: 'wspace-temporal:7233',\n temporalNamespace: 'wspace-default',\n rbacGatewayUrl: buildInternalGatewayUrl('wspace'),\n },\n global: {\n eventQueueUrl: 'redis://global-shared-valkey:6379',\n valkeyUrl: 'valkey://global-valkey:6379',\n temporalAddress: 'global-temporal:7233',\n temporalNamespace: 'global-default',\n rbacGatewayUrl: buildInternalGatewayUrl('global'),\n },\n};\n\n/**\n * Circuit breaker configuration for gateway client\n */\nexport interface CircuitBreakerConfig {\n /**\n * Number of failures before opening circuit\n * @default 5\n */\n failureThreshold: number;\n\n /**\n * Time in milliseconds to wait before attempting to close circuit\n * @default 30000 (30 seconds)\n */\n resetTimeout: number;\n\n /**\n * Time window in milliseconds for counting failures\n * @default 60000 (60 seconds)\n */\n failureWindow: number;\n}\n\n/**\n * Default circuit breaker configuration\n */\nexport const DEFAULT_CIRCUIT_BREAKER_CONFIG: CircuitBreakerConfig = {\n failureThreshold: 5,\n resetTimeout: 30000,\n failureWindow: 60000,\n};\n\n/**\n * Retry configuration for gateway client\n */\nexport interface GatewayRetryConfig {\n /**\n * Maximum number of retry attempts\n * @default 3\n */\n maxAttempts: number;\n\n /**\n * Initial delay in milliseconds before first retry\n * @default 1000 (1 second)\n */\n initialDelay: number;\n\n /**\n * Maximum delay in milliseconds between retries\n * @default 10000 (10 seconds)\n */\n maxDelay: number;\n\n /**\n * Backoff multiplier for exponential backoff\n * @default 2\n */\n backoffMultiplier: number;\n}\n\n/**\n * Default retry configuration\n */\nexport const DEFAULT_GATEWAY_RETRY_CONFIG: GatewayRetryConfig = {\n maxAttempts: 3,\n initialDelay: 1000,\n maxDelay: 10000,\n backoffMultiplier: 2,\n};\n\n/**\n * Headers automatically added by gateway client for M2M calls\n */\nexport interface GatewayRequestHeaders {\n /**\n * Actor ID making the request\n */\n 'x-actor-id'?: string;\n\n /**\n * Actor type\n */\n 'x-actor-type'?: 'user' | 'app' | 'service' | 'super_admin';\n\n /**\n * Workspace ID for the request context\n */\n 'x-workspace-id'?: string;\n\n /**\n * Service identity for bypass validation\n */\n 'x-service-identity'?: string;\n\n /**\n * Call type indicator\n */\n 'x-call-type'?: 'internal' | 'cross-layer';\n\n /**\n * Permission bypass flag\n */\n 'x-bypass-permission'?: string;\n\n /**\n * RBAC bypass flag (set by gateway)\n */\n 'x-rbac-bypass'?: 'true' | 'false';\n\n /**\n * Bypass source (set by gateway)\n */\n 'x-bypass-source'?: string;\n\n /**\n * Bypass timestamp (set by gateway)\n */\n 'x-bypass-timestamp'?: string;\n\n /**\n * Cloudflare Access service-token client id, re-presented on cross-layer\n * outbound calls so the peer layer's CF-Access-gated public gateway admits\n * the request. Normally attached automatically from request context.\n */\n 'cf-access-client-id'?: string;\n\n /**\n * Cloudflare Access service-token client secret (paired with the client id).\n */\n 'cf-access-client-secret'?: string;\n\n /**\n * Delegated `app_as_user` bearer (`Bearer <jwt>`) for an internal-gateway\n * call made as an agent acting for a user. The internal gateway verifies it\n * and derives the actor; see `buildDelegatedGatewayHeaders`.\n */\n 'x-delegated-authorization'?: string;\n\n /**\n * Name of the calling service. An internal gateway uses it as the actor id\n * of a service call that names no `x-actor-id`.\n */\n 'x-service-name'?: string;\n}\n"],"mappings":";;;;AAyJA,MAAa,0BAAsE;CACjF,QAAQ;EACN,OAAO;EACP,iBAAiB;GACf,MAAM;GACN,MAAM;GACN,aAAa;EACf;EACA,mBAAmB;GACjB,MAAM;GACN,MAAM;GACN,aAAa;EACf;CACF;CACA,QAAQ;EACN,OAAO;EACP,iBAAiB;GACf,MAAM;GACN,MAAM;GACN,aAAa;EACf;EACA,mBAAmB;GACjB,MAAM;GACN,MAAM;GACN,aAAa;EACf;CACF;AACF;;;;AAKA,MAAa,wBAGT;CACF,QAAQ,CACN;EACE,MAAM;EACN,UAAU,CAAC,UAAU;EACrB,aAAa;CACf,GACA;EACE,MAAM;EACN,UAAU,CAAC,SAAS;EACpB,aAAa;CACf,CACF;CACA,QAAQ,CACN;EACE,MAAM;EACN,UAAU,CAAC,UAAU;EACrB,aAAa;CACf,GACA;EACE,MAAM;EACN,UAAU,CAAC,SAAS;EACpB,aAAa;CACf,CACF;AACF;;;;;AAMA,SAAS,wBAAwB,OAA6B;CAE5D,MAAM,EAAE,MAAM,MAAM,gBADJ,wBAAwB,MACG,CAAC;CAG5C,OAAO,UAAiB,KAAK,GAAG,OAAO;AACzC;;;;;;;AAQA,MAAa,0BAAmE;CAK9E,QAAQ;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,gBAAgB,wBAAwB,QAAQ;CAClD;CACA,QAAQ;EACN,eAAe;EACf,WAAW;EACX,iBAAiB;EACjB,mBAAmB;EACnB,gBAAgB,wBAAwB,QAAQ;CAClD;AACF;;;;AA4BA,MAAa,iCAAuD;CAClE,kBAAkB;CAClB,cAAc;CACd,eAAe;AACjB;;;;AAkCA,MAAa,+BAAmD;CAC9D,aAAa;CACb,cAAc;CACd,UAAU;CACV,mBAAmB;AACrB"}
@@ -65,5 +65,6 @@ interface GatewayRequestHeaders {
65
65
  'cf-access-client-id'?: string;
66
66
  'cf-access-client-secret'?: string;
67
67
  'x-delegated-authorization'?: string;
68
+ 'x-service-name'?: string;
68
69
  }
69
70
  export { DEFAULT_LAYER_RESOURCES as a, GatewayRetryConfig as c, LayerFullConfig as d, LayerGatewayConfig as f, DEFAULT_GATEWAY_ROUTING as i, GatewayRoutingConfig as l, ServiceLayer as m, DEFAULT_CIRCUIT_BREAKER_CONFIG as n, DEFAULT_LAYER_STREAMS as o, LayerResourceUrls as p, DEFAULT_GATEWAY_RETRY_CONFIG as r, GatewayRequestHeaders as s, CircuitBreakerConfig as t, LayerConfig as u };
@@ -1,2 +1,2 @@
1
- import { a as LoggerTransport, d as redactSensitiveFields, f as redactSensitiveString, i as LoggerConfig, l as log, n as LogMeta, o as debug, p as warn, r as Logger, s as error, t as LogLevel, u as logger } from "../index-Cot73bdh.js";
1
+ import { a as LoggerTransport, d as redactSensitiveFields, f as redactSensitiveString, i as LoggerConfig, l as log, n as LogMeta, o as debug, p as warn, r as Logger, s as error, t as LogLevel, u as logger } from "../index-KlrnELrN.js";
2
2
  export { LogLevel, LogMeta, Logger, LoggerConfig, LoggerTransport, debug, error, log, logger, redactSensitiveFields, redactSensitiveString, warn };
@@ -1,2 +1,2 @@
1
- import { _ as TenantNotificationsModule, a as NotificationType, c as SendChannelNotificationOptions, d as BatchNotificationInput, f as NotificationChannel$1, g as SendWithTemplateInput, h as SendNotificationInput, i as NotificationResponse, l as SendNotificationOptions, m as NotificationType$1, n as Notification, o as NotificationsModule, p as NotificationPriority, r as NotificationChannel, s as RecipientInput, t as GetNotificationsOptions, u as SendTemplateNotificationOptions } from "../index-U_tu3zUl.js";
1
+ import { _ as TenantNotificationsModule, a as NotificationType, c as SendChannelNotificationOptions, d as BatchNotificationInput, f as NotificationChannel$1, g as SendWithTemplateInput, h as SendNotificationInput, i as NotificationResponse, l as SendNotificationOptions, m as NotificationType$1, n as Notification, o as NotificationsModule, p as NotificationPriority, r as NotificationChannel, s as RecipientInput, t as GetNotificationsOptions, u as SendTemplateNotificationOptions } from "../index-Dw_0wE4q.js";
2
2
  export { GetNotificationsOptions, Notification, NotificationChannel, NotificationPriority, NotificationResponse, NotificationType, NotificationsModule, RecipientInput, SendChannelNotificationOptions, SendNotificationOptions, SendTemplateNotificationOptions, type BatchNotificationInput as TenantBatchNotificationInput, NotificationChannel$1 as TenantNotificationChannel, NotificationType$1 as TenantNotificationType, TenantNotificationsModule, type SendNotificationInput as TenantSendNotificationInput, type SendWithTemplateInput as TenantSendWithTemplateInput };
@@ -1,5 +1,5 @@
1
- import { t as BurdenoffGraphQLClient } from "../graphql-CUDyhibV.js";
2
- import { p as SDKContext } from "../index-CTTwo9av.js";
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-C8jKLLel.js";
2
+ import { p as SDKContext } from "../index-BTaQMEgB.js";
3
3
  export declare enum PaymentStatus {
4
4
  PENDING = "pending",
5
5
  PROCESSING = "processing",
@@ -1,2 +1,2 @@
1
- import { a as Permission, c as RoleDefaultPermission, d as RBACClient, f as RBACDirectiveConfig, h as createRBACDirectiveFromEnv, i as PBACPermissionLevel, l as createRBACClientFromEnv, m as createRBACDirectiveForLayer, n as EffectivePermissionEntry, o as RBACModule, p as createRBACDirective, r as PBACActorType, s as Role, t as CheckPermissionOptions, u as LayerAwareRBACConfig } from "../index-C_GXXF32.js";
1
+ import { a as Permission, c as RoleDefaultPermission, d as RBACClient, f as RBACDirectiveConfig, h as createRBACDirectiveFromEnv, i as PBACPermissionLevel, l as createRBACClientFromEnv, m as createRBACDirectiveForLayer, n as EffectivePermissionEntry, o as RBACModule, p as createRBACDirective, r as PBACActorType, s as Role, t as CheckPermissionOptions, u as LayerAwareRBACConfig } from "../index-Bh6W5JO4.js";
2
2
  export { CheckPermissionOptions, EffectivePermissionEntry, type LayerAwareRBACConfig, PBACActorType, PBACPermissionLevel, Permission, RBACClient, type RBACDirectiveConfig, RBACModule, Role, RoleDefaultPermission, createRBACClientFromEnv, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv };
@@ -1,4 +1,4 @@
1
- import { t as BurdenoffGraphQLClient } from "../graphql-CUDyhibV.js";
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-C8jKLLel.js";
2
2
  import { GraphQLError } from "graphql";
3
3
  export type ResourceName = 'workspace' | 'workspaceMember' | 'sandbox' | 'vibe' | 'agent' | 'conversation' | 'message' | 'tag' | 'file' | 'group' | 'calendar' | 'scheduledTask' | 'form' | 'apiKey' | 'webhook';
4
4
  export type PlanTier = 'free' | 'paid';
@@ -1,4 +1,5 @@
1
1
  import { t as importOptionalPeer } from "./import-optional-peer-B82VYxeX.js";
2
+ import { n as isBunRuntime } from "./bun-runtime-metrics-CPy5D6NT.js";
2
3
 
3
4
  // src/telemetry/sdk.ts
4
5
  /**
@@ -9,6 +10,33 @@ import { t as importOptionalPeer } from "./import-optional-peer-B82VYxeX.js";
9
10
  * still compile and run. The function resolves `undefined` when the SDK
10
11
  * isn't available, letting `bootstrapTelemetry` fall back gracefully.
11
12
  */
13
+ /** The name `OTEL_NODE_{ENABLED,DISABLED}_INSTRUMENTATIONS` use for `@opentelemetry/instrumentation-runtime-node`. */
14
+ const RUNTIME_NODE_INSTRUMENTATION = "runtime-node";
15
+ /** True when a comma-separated `OTEL_NODE_*_INSTRUMENTATIONS` value names `name` (parsed as auto-instrumentations-node does). */
16
+ const listsInstrumentation = (value, name) => value !== void 0 && value.split(",").some((entry) => entry.trim() === name);
17
+ /**
18
+ * The config be-sdk hands to `getNodeAutoInstrumentations`.
19
+ *
20
+ * - `instrumentation-fs` is always off.
21
+ * - `instrumentation-runtime-node` is off under Bun unless
22
+ * `OTEL_NODE_ENABLED_INSTRUMENTATIONS` names `runtime-node` (BOFF-12287). On
23
+ * every 60 s OTLP metric export it reads `v8.getHeapSpaceStatistics()`,
24
+ * which Bun implements as a synchronous walk of the whole heap: a 0.1–1.4 s
25
+ * block once a minute on the prod gateways, during which no request is
26
+ * served. Event-loop lag stays visible through prom-client's
27
+ * `nodejs_eventloop_lag_*`. Dropped: the OTel `v8js_*`,
28
+ * `nodejs_eventloop_delay_*`, `nodejs_eventloop_utilization_*` and
29
+ * `nodejs_eventloop_time_*` series, which no dashboard or alert reads.
30
+ *
31
+ * auto-instrumentations-node lets a programmatic `enabled: false` win over
32
+ * both env vars, so the opt-in has to be checked here. Under Node nothing
33
+ * changes: the env vars keep their usual meaning.
34
+ */
35
+ function autoInstrumentationConfig(env = process.env, bun = isBunRuntime()) {
36
+ const config = { "@opentelemetry/instrumentation-fs": { enabled: false } };
37
+ if (bun && !listsInstrumentation(env["OTEL_NODE_ENABLED_INSTRUMENTATIONS"], RUNTIME_NODE_INSTRUMENTATION)) config["@opentelemetry/instrumentation-runtime-node"] = { enabled: false };
38
+ return config;
39
+ }
12
40
  const isThenable = (value) => {
13
41
  return typeof value === "object" && value !== null && typeof value.then === "function";
14
42
  };
@@ -66,8 +94,11 @@ async function createOtelSdk(cfg) {
66
94
  console.log("[sdk] importing @opentelemetry/auto-instrumentations-node...");
67
95
  let autoInstrumentations;
68
96
  try {
69
- autoInstrumentations = (await load("@opentelemetry/auto-instrumentations-node")).getNodeAutoInstrumentations({ "@opentelemetry/instrumentation-fs": { enabled: false } });
97
+ const auto = await load("@opentelemetry/auto-instrumentations-node");
98
+ const instrumentationConfig = autoInstrumentationConfig();
99
+ autoInstrumentations = auto.getNodeAutoInstrumentations(instrumentationConfig);
70
100
  console.log("[sdk] auto-instrumentations loaded");
101
+ if (instrumentationConfig["@opentelemetry/instrumentation-runtime-node"]?.enabled === false) console.log("[sdk] runtime-node instrumentation off under Bun (its heap statistics stall the event loop); list runtime-node in OTEL_NODE_ENABLED_INSTRUMENTATIONS to turn it on");
71
102
  } catch {
72
103
  autoInstrumentations = void 0;
73
104
  console.log("[sdk] auto-instrumentations not available (non-fatal)");
@@ -122,4 +153,4 @@ async function createOtelSdk(cfg) {
122
153
  }
123
154
 
124
155
  export { createOtelSdk };
125
- //# sourceMappingURL=sdk-B62itAH1.js.map
156
+ //# sourceMappingURL=sdk-DqIqX-Ue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-DqIqX-Ue.js","names":[],"sources":["../src/telemetry/sdk.ts"],"sourcesContent":["/**\n * Thin wrapper that initializes `@opentelemetry/sdk-node` with the\n * OTLPTrace + OTLPMetric exporters and standard auto-instrumentations.\n *\n * All imports are dynamic so services that haven't installed sdk-node\n * still compile and run. The function resolves `undefined` when the SDK\n * isn't available, letting `bootstrapTelemetry` fall back gracefully.\n */\nimport { importOptionalPeer } from '../utils/import-optional-peer.js';\nimport { isBunRuntime } from './bun-runtime-metrics.js';\nimport type { TelemetryIdGenerator } from './id-generator.js';\nimport type { Boundary, Env } from './index.js';\n\nexport interface OtelSdkConfig {\n serviceName: string;\n serviceVersion: string;\n boundary: Boundary;\n module?: string;\n env: Env;\n otlpEndpoint: string;\n sampleRatio: number;\n /**\n * Optional trace/span id generator handed to NodeSDK's tracer provider.\n * Omitted means the SDK's default random generator.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name. A package found\n * here is used as is; any other one is loaded at runtime from the consumer's\n * `node_modules` through `importOptionalPeer`. A service built with\n * `bun build --compile` has no `node_modules` at runtime, so it imports the\n * packages statically and hands them in here.\n */\n modules?: OtelModules;\n}\n\n/** The OpenTelemetry packages `createOtelSdk` can load. */\nexport type OtelPeerPackage =\n | '@opentelemetry/api'\n | '@opentelemetry/auto-instrumentations-node'\n | '@opentelemetry/exporter-metrics-otlp-http'\n | '@opentelemetry/exporter-trace-otlp-http'\n | '@opentelemetry/resources'\n | '@opentelemetry/sdk-metrics'\n | '@opentelemetry/sdk-node'\n | '@opentelemetry/sdk-trace-base'\n | '@opentelemetry/semantic-conventions';\n\n/** Module namespaces injected in place of runtime imports (see `OtelSdkConfig.modules`). */\nexport type OtelModules = Partial<Record<OtelPeerPackage, unknown>>;\n\nexport interface OtelSdkHandle {\n shutdown: () => Promise<void>;\n metricsEnabled: boolean;\n metricsDropReason?: string;\n}\n\n/** Per-instrumentation config handed to `getNodeAutoInstrumentations`, keyed by package name. */\nexport type AutoInstrumentationConfig = Record<string, { enabled: boolean }>;\n\n/** The name `OTEL_NODE_{ENABLED,DISABLED}_INSTRUMENTATIONS` use for `@opentelemetry/instrumentation-runtime-node`. */\nconst RUNTIME_NODE_INSTRUMENTATION = 'runtime-node';\n\n/** True when a comma-separated `OTEL_NODE_*_INSTRUMENTATIONS` value names `name` (parsed as auto-instrumentations-node does). */\nconst listsInstrumentation = (value: string | undefined, name: string): boolean =>\n value !== undefined && value.split(',').some((entry) => entry.trim() === name);\n\n/**\n * The config be-sdk hands to `getNodeAutoInstrumentations`.\n *\n * - `instrumentation-fs` is always off.\n * - `instrumentation-runtime-node` is off under Bun unless\n * `OTEL_NODE_ENABLED_INSTRUMENTATIONS` names `runtime-node` (BOFF-12287). On\n * every 60 s OTLP metric export it reads `v8.getHeapSpaceStatistics()`,\n * which Bun implements as a synchronous walk of the whole heap: a 0.1–1.4 s\n * block once a minute on the prod gateways, during which no request is\n * served. Event-loop lag stays visible through prom-client's\n * `nodejs_eventloop_lag_*`. Dropped: the OTel `v8js_*`,\n * `nodejs_eventloop_delay_*`, `nodejs_eventloop_utilization_*` and\n * `nodejs_eventloop_time_*` series, which no dashboard or alert reads.\n *\n * auto-instrumentations-node lets a programmatic `enabled: false` win over\n * both env vars, so the opt-in has to be checked here. Under Node nothing\n * changes: the env vars keep their usual meaning.\n */\nexport function autoInstrumentationConfig(\n env: Readonly<Record<string, string | undefined>> = process.env,\n bun: boolean = isBunRuntime()\n): AutoInstrumentationConfig {\n const config: AutoInstrumentationConfig = {\n '@opentelemetry/instrumentation-fs': { enabled: false },\n };\n if (bun && !listsInstrumentation(env['OTEL_NODE_ENABLED_INSTRUMENTATIONS'], RUNTIME_NODE_INSTRUMENTATION)) {\n config['@opentelemetry/instrumentation-runtime-node'] = { enabled: false };\n }\n return config;\n}\n\ntype Thenable = {\n then: (onfulfilled?: (value: void) => void, onrejected?: (reason: unknown) => void) => unknown;\n};\n\nconst isThenable = (value: unknown): value is Thenable => {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n};\n\nconst asyncDisposeMetricReader = async (metricReaderCandidate: unknown): Promise<void> => {\n const shutdown = (metricReaderCandidate as { shutdown?: () => void | Promise<void> }).shutdown;\n if (typeof shutdown === 'function') {\n const result = shutdown.call(metricReaderCandidate) as unknown;\n if (isThenable(result)) await result;\n }\n};\n\nexport async function createOtelSdk(cfg: OtelSdkConfig): Promise<OtelSdkHandle> {\n const load = (name: OtelPeerPackage): Promise<unknown> =>\n cfg.modules?.[name] !== undefined ? Promise.resolve(cfg.modules[name]) : importOptionalPeer(name);\n console.log('[sdk] importing @opentelemetry/sdk-node...');\n const sdkMod = (await load('@opentelemetry/sdk-node')) as {\n NodeSDK: new (init: Record<string, unknown>) => {\n start: () => void;\n shutdown: () => Promise<void>;\n };\n };\n\n console.log('[sdk] importing @opentelemetry/resources...');\n const resources = (await load('@opentelemetry/resources')) as {\n resourceFromAttributes: (attrs: Record<string, string | number>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/semantic-conventions...');\n const sem = (await load('@opentelemetry/semantic-conventions')) as Record<string, string>;\n\n console.log('[sdk] importing @opentelemetry/exporter-trace-otlp-http...');\n const traceExp = (await load('@opentelemetry/exporter-trace-otlp-http')) as {\n OTLPTraceExporter: new (init: Record<string, string>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/exporter-metrics-otlp-http...');\n let metricsExp: { OTLPMetricExporter?: new (init: Record<string, string>) => unknown } | undefined;\n try {\n metricsExp = (await load('@opentelemetry/exporter-metrics-otlp-http')) as typeof metricsExp;\n } catch {\n metricsExp = undefined;\n console.log('[sdk] metrics exporter not available (non-fatal)');\n }\n\n let metricReader: unknown;\n let metricsEnabled = false;\n let metricsDropReason: string | undefined;\n if (metricsExp?.OTLPMetricExporter) {\n try {\n const metricsSdk = (await load('@opentelemetry/sdk-metrics')) as {\n PeriodicExportingMetricReader: new (init: Record<string, unknown>) => unknown;\n };\n const candidate = new metricsSdk.PeriodicExportingMetricReader({\n exporter: new metricsExp.OTLPMetricExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/metrics`,\n }),\n });\n // Pre-flight API compatibility check. Some OTel package version\n // combinations construct `PeriodicExportingMetricReader` successfully\n // but lack `setMetricProducer` on the prototype chain (mixed\n // sdk-metrics versions, or runtime-specific class-inheritance\n // quirks — Bun has surfaced this in the past). Without the check,\n // `NodeSDK.start()` may register the global tracer provider BEFORE\n // it tries to call `setMetricProducer` and throws — leaving the\n // global tracer pointing at a half-initialized provider whose\n // span pipeline never drains. Skipping the metric reader when the\n // API isn't there avoids that whole failure mode in one pass.\n const setProducer = (candidate as { setMetricProducer?: unknown }).setMetricProducer;\n if (typeof setProducer === 'function') {\n metricReader = candidate;\n metricsEnabled = true;\n } else {\n metricsDropReason =\n 'setMetricProducer is not a function on PeriodicExportingMetricReader; skipping metrics path';\n await asyncDisposeMetricReader(candidate);\n metricReader = undefined;\n }\n } catch {\n if (metricsDropReason === undefined) {\n metricsDropReason = 'metric reader construction or compatibility check failed';\n }\n metricReader = undefined;\n }\n }\n\n console.log('[sdk] importing @opentelemetry/sdk-trace-base for sampler...');\n let sampler: unknown;\n try {\n const traceBase = (await load('@opentelemetry/sdk-trace-base')) as {\n ParentBasedSampler: new (init: Record<string, unknown>) => unknown;\n TraceIdRatioBasedSampler: new (ratio: number) => unknown;\n };\n sampler = new traceBase.ParentBasedSampler({\n root: new traceBase.TraceIdRatioBasedSampler(Math.min(1, Math.max(0, cfg.sampleRatio))),\n });\n } catch {\n sampler = undefined;\n console.log('[sdk] sampler not available (non-fatal)');\n }\n\n // Some services have auto-instrumentations installed; optional.\n console.log('[sdk] importing @opentelemetry/auto-instrumentations-node...');\n let autoInstrumentations: unknown[] | undefined;\n try {\n const auto = (await load('@opentelemetry/auto-instrumentations-node')) as {\n getNodeAutoInstrumentations: (cfg?: Record<string, unknown>) => unknown[];\n };\n const instrumentationConfig = autoInstrumentationConfig();\n autoInstrumentations = auto.getNodeAutoInstrumentations(instrumentationConfig);\n console.log('[sdk] auto-instrumentations loaded');\n if (instrumentationConfig['@opentelemetry/instrumentation-runtime-node']?.enabled === false) {\n console.log(\n '[sdk] runtime-node instrumentation off under Bun (its heap statistics stall the event loop); ' +\n 'list runtime-node in OTEL_NODE_ENABLED_INSTRUMENTATIONS to turn it on'\n );\n }\n } catch {\n autoInstrumentations = undefined;\n console.log('[sdk] auto-instrumentations not available (non-fatal)');\n }\n\n const serviceNamespaceByBoundary: Record<Boundary, string> = {\n wspace: 'workspaces',\n global: 'tenant',\n gateway: 'gateways',\n };\n const resourceAttributes: Record<string, string> = {\n [sem['SEMRESATTRS_SERVICE_NAME'] ?? 'service.name']: cfg.serviceName,\n [sem['SEMRESATTRS_SERVICE_VERSION'] ?? 'service.version']: cfg.serviceVersion,\n [sem['SEMRESATTRS_SERVICE_NAMESPACE'] ?? 'service.namespace']: serviceNamespaceByBoundary[cfg.boundary],\n [sem['SEMRESATTRS_DEPLOYMENT_ENVIRONMENT'] ?? 'deployment.environment']: cfg.env,\n 'burdenoff.boundary': cfg.boundary,\n };\n if (cfg.module) resourceAttributes['burdenoff.module'] = cfg.module;\n const serviceInstanceId = process.env['POD_NAME'] ?? process.env['HOSTNAME'];\n if (serviceInstanceId) resourceAttributes['service.instance.id'] = serviceInstanceId;\n const clusterName = process.env['CLUSTER_NAME'];\n if (clusterName) {\n resourceAttributes['cluster'] = clusterName;\n resourceAttributes['k8s.cluster.name'] = clusterName;\n }\n\n const resource = resources.resourceFromAttributes(resourceAttributes);\n\n const traceExporter = new traceExp.OTLPTraceExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/traces`,\n });\n\n // Single NodeSDK, single start. The pre-flight `setMetricProducer`\n // check above means we never pass an incompatible metric reader into\n // NodeSDK construction — so we no longer need the prior catch+rebuild\n // fallback dance, which had its own side-effect: the failed first\n // NodeSDK could leave the global tracer provider partially registered,\n // and the second NodeSDK's `setGlobalTracerProvider` becomes a no-op\n // — meaning spans flow into the FIRST (broken) provider and never\n // reach the exporter. Eliminating the fallback eliminates that hazard.\n console.log('[sdk] constructing NodeSDK...');\n const nodeSdk = new sdkMod.NodeSDK({\n resource,\n traceExporter,\n ...(metricReader ? { metricReader } : {}),\n ...(sampler ? { sampler } : {}),\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(autoInstrumentations ? { instrumentations: autoInstrumentations } : {}),\n });\n console.log('[sdk] NodeSDK constructed, calling start()...');\n // NodeSDK.start() returns void in modern versions and Promise<void> in older\n // ones. Cast to a permissive thenable shape so awaiting works either way\n // without tripping `@typescript-eslint/await-thenable`.\n const startResult = nodeSdk.start() as unknown;\n if (isThenable(startResult)) {\n await startResult;\n }\n console.log('[sdk] NodeSDK started');\n\n // Stash the @opentelemetry/api reference for pino-logger's mixin.\n try {\n (globalThis as unknown as { __otelApi?: unknown }).__otelApi = await load('@opentelemetry/api');\n console.log('[sdk] @opentelemetry/api stashed for pino mixin');\n } catch {\n console.log('[sdk] @opentelemetry/api stash failed (non-fatal)');\n }\n\n console.log('[sdk] OTel SDK initialization complete');\n return {\n shutdown: async (): Promise<void> => nodeSdk.shutdown(),\n metricsEnabled,\n metricsDropReason,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA6DA,MAAM,+BAA+B;;AAGrC,MAAM,wBAAwB,OAA2B,SACvD,UAAU,UAAa,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,UAAU,MAAM,KAAK,MAAM,IAAI;;;;;;;;;;;;;;;;;;;AAoB/E,SAAgB,0B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yBAAyB;CACnE,MAAM,cAAc,QAAQ,IAAI;CAChC,IAAI,aAAa;EACf,mBAAmB,aAAa;EAChC,mBAAmB,sBAAsB;CAC3C;CAEA,MAAM,WAAW,UAAU,uBAAuB,kBAAkB;CAEpE,MAAM,gBAAgB,IAAI,SAAS,kBAAkB,EACnD,KAAK,GAAG,IAAI,aAAa,QAAQ,OAAO,EAAE,EAAE,YAC9C,CAAC;CAUD,QAAQ,IAAI,+BAA+B;CAC3C,MAAM,UAAU,IAAI,OAAO,QAAQ;EACjC;EACA;EACA,GAAI,eAAe,EAAE,aAAa,IAAI,CAAC;EACvC,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;EAC7B,GAAI,IAAI,cAAc,EAAE,aAAa,IAAI,YAAY,IAAI,CAAC;EAC1D,GAAI,uBAAuB,EAAE,kBAAkB,qBAAqB,IAAI,CAAC;CAC3E,CAAC;CACD,QAAQ,IAAI,+CAA+C;CAI3D,MAAM,cAAc,QAAQ,MAAM;CAClC,IAAI,WAAW,WAAW,GACxB,MAAM;CAER,QAAQ,IAAI,uBAAuB;CAGnC,IAAI;EACF,AAAC,WAAkD,YAAY,MAAM,KAAK,oBAAoB;EAC9F,QAAQ,IAAI,iDAAiD;CAC/D,QAAQ;EACN,QAAQ,IAAI,mDAAmD;CACjE;CAEA,QAAQ,IAAI,wCAAwC;CACpD,OAAO;EACL,UAAU,YAA2B,QAAQ,SAAS;EACtD;EACA;CACF;AACF"}
@@ -1,5 +1,5 @@
1
- import { t as BurdenoffGraphQLClient } from "../graphql-CUDyhibV.js";
2
- import { p as SDKContext } from "../index-CTTwo9av.js";
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-C8jKLLel.js";
2
+ import { p as SDKContext } from "../index-BTaQMEgB.js";
3
3
  export interface SearchOptions {
4
4
  query: string;
5
5
  resourceTypes?: string[];
@@ -1,2 +1,2 @@
1
- import { t as index_d_exports } from "../index-cmR9k9ga.js";
1
+ import { t as index_d_exports } from "../index-DhFP_AIB.js";
2
2
  export { index_d_exports as RateLimit };
@@ -1,2 +1,2 @@
1
- import { a as resolveRateLimitModeFromEnv, c as RateLimitResult, i as enforceRateLimit, l as buildRateLimitKey, n as RateLimiterDeps, o as RateLimitConfig, r as checkRateLimit, s as RateLimitMode } from "../../index-cmR9k9ga.js";
1
+ import { a as resolveRateLimitModeFromEnv, c as RateLimitResult, i as enforceRateLimit, l as buildRateLimitKey, n as RateLimiterDeps, o as RateLimitConfig, r as checkRateLimit, s as RateLimitMode } from "../../index-DhFP_AIB.js";
2
2
  export { type RateLimitConfig, type RateLimitMode, type RateLimitResult, type RateLimiterDeps, buildRateLimitKey, checkRateLimit, enforceRateLimit, resolveRateLimitModeFromEnv };
@@ -6,6 +6,7 @@ import { ContextManager } from "../context/index.js";
6
6
  import { l as I18n } from "../i18n-BBMYFd0P.js";
7
7
  import { o as getMetricsRegistry } from "../metrics-collector-C2eShrlW.js";
8
8
  import { t as getWorkspaceQuotaRegistry } from "../metrics-BrLwNUrb.js";
9
+ import { t as collectPromDefaultMetrics } from "../bun-runtime-metrics-CPy5D6NT.js";
9
10
  import { i as suppressMutationAudit, r as runInExplicitActivityScope, t as createExplicitActivityScope } from "../explicit-activity-scope-DikJ7NAE.js";
10
11
  import { GraphQLError, Kind, OperationTypeNode } from "graphql";
11
12
  import crypto from "node:crypto";
@@ -1507,9 +1508,7 @@ async function createServer(definition) {
1507
1508
  }
1508
1509
  if (pathname === "/metrics" && request.method === "GET") try {
1509
1510
  const prom = await import("prom-client");
1510
- try {
1511
- prom.collectDefaultMetrics({ register: prom.register });
1512
- } catch {}
1511
+ collectPromDefaultMetrics(prom);
1513
1512
  const promBody = await prom.register.metrics();
1514
1513
  let sdkBody = "";
1515
1514
  await quotaGaugeRefresher.refresh();