@burdenoff/be-sdk 2026.1110.3 → 2026.1110.4

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 (108) hide show
  1. package/dist/activity/index.d.ts +165 -0
  2. package/dist/activity/index.js +389 -0
  3. package/dist/activity/index.js.map +1 -0
  4. package/dist/ai-credits/index.js +1 -1
  5. package/dist/{ai-credits-Ca-NNcVx.js → ai-credits-xxfwGpHS.js} +2 -2
  6. package/dist/{ai-credits-Ca-NNcVx.js.map → ai-credits-xxfwGpHS.js.map} +1 -1
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/{auth-CEuBEBQN.js → auth-C5ctwSLp.js} +2 -2
  10. package/dist/{auth-CEuBEBQN.js.map → auth-C5ctwSLp.js.map} +1 -1
  11. package/dist/bootstrap/index.d.ts +74 -0
  12. package/dist/bootstrap/index.js +282 -0
  13. package/dist/bootstrap/index.js.map +1 -0
  14. package/dist/{client-DcZ3iGES.js → client-sAJTrb4i.js} +2 -2
  15. package/dist/{client-DcZ3iGES.js.map → client-sAJTrb4i.js.map} +1 -1
  16. package/dist/context/index.d.ts +35 -0
  17. package/dist/{context-CZnXf2yb.js → context/index.js} +38 -2
  18. package/dist/context/index.js.map +1 -0
  19. package/dist/database/index.js +1 -1
  20. package/dist/event-queue/index.d.ts +1 -1
  21. package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
  22. package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
  23. package/dist/export/index.js +1 -1
  24. package/dist/{export-B6fphx8a.js → export-DJXE3Osa.js} +3 -3
  25. package/dist/{export-B6fphx8a.js.map → export-DJXE3Osa.js.map} +1 -1
  26. package/dist/feature-flags/index.js +1 -1
  27. package/dist/{feature-flags-71oDkrUe.js → feature-flags-CP1KRgwD.js} +2 -2
  28. package/dist/{feature-flags-71oDkrUe.js.map → feature-flags-CP1KRgwD.js.map} +1 -1
  29. package/dist/files/index.js +1 -1
  30. package/dist/{files-DjH0099H.js → files-h5U-D2AF.js} +2 -2
  31. package/dist/{files-DjH0099H.js.map → files-h5U-D2AF.js.map} +1 -1
  32. package/dist/gateway/index.js +2 -2
  33. package/dist/{gateway-DBFmxWks.js → gateway-ByVo-n37.js} +2 -2
  34. package/dist/{gateway-DBFmxWks.js.map → gateway-ByVo-n37.js.map} +1 -1
  35. package/dist/graph/index.d.ts +1 -1
  36. package/dist/graph/index.js +1 -1
  37. package/dist/{graph-DDYgIryR.js → graph-CR7u4lpl.js} +2 -2
  38. package/dist/{graph-DDYgIryR.js.map → graph-CR7u4lpl.js.map} +1 -1
  39. package/dist/{graphql-DNkMkGBZ.d.ts → graphql-CUDyhibV.d.ts} +1 -1
  40. package/dist/{index-bZKZUvBu.d.ts → index-ADmsX0BI.d.ts} +3 -3
  41. package/dist/{index-BqYfCQSP.d.ts → index-B2LCaK0R.d.ts} +1 -1
  42. package/dist/{index-D6UeLAye.d.ts → index-CHwMhK6v.d.ts} +2 -2
  43. package/dist/{index-BQDsNAMR.d.ts → index-CTTwo9av.d.ts} +22 -1
  44. package/dist/{index-DZC-2o9R.d.ts → index-CVCyKzhB.d.ts} +2 -2
  45. package/dist/{index-CkT2aUr3.d.ts → index-C_GXXF32.d.ts} +2 -2
  46. package/dist/{index-BKwHQtHQ.d.ts → index-Cot73bdh.d.ts} +1 -1
  47. package/dist/{index-CnzbJZP7.d.ts → index-FRRaa6h2.d.ts} +2 -2
  48. package/dist/{index-N-huORcj.d.ts → index-U_tu3zUl.d.ts} +2 -2
  49. package/dist/index-cmR9k9ga.d.ts +26 -0
  50. package/dist/{index-CZTnQIRU.d.ts → index-zd_NPGJo.d.ts} +6 -141
  51. package/dist/index.d.ts +19 -479
  52. package/dist/index.js +22 -1492
  53. package/dist/index.js.map +1 -1
  54. package/dist/init/index.js +1 -1
  55. package/dist/{init-Dy3KhT6Y.js → init-CQPFmOOe.js} +3 -3
  56. package/dist/{init-Dy3KhT6Y.js.map → init-CQPFmOOe.js.map} +1 -1
  57. package/dist/instrumentation/index.d.ts +2 -2
  58. package/dist/logger/index.d.ts +1 -1
  59. package/dist/notifications/index.d.ts +1 -1
  60. package/dist/notifications/index.js +1 -1
  61. package/dist/{notifications-CdETrtFK.js → notifications-DY_i37WN.js} +2 -2
  62. package/dist/{notifications-CdETrtFK.js.map → notifications-DY_i37WN.js.map} +1 -1
  63. package/dist/payments/index.d.ts +144 -0
  64. package/dist/payments/index.js +404 -0
  65. package/dist/payments/index.js.map +1 -0
  66. package/dist/rate-limit-CBrK_U5H.js +142 -0
  67. package/dist/rate-limit-CBrK_U5H.js.map +1 -0
  68. package/dist/rbac/index.d.ts +1 -1
  69. package/dist/rbac/index.js +1 -1
  70. package/dist/{rbac-BB9l9Xph.js → rbac-Dvz0YzEt.js} +2 -2
  71. package/dist/{rbac-BB9l9Xph.js.map → rbac-Dvz0YzEt.js.map} +1 -1
  72. package/dist/resource-caps/index.d.ts +1 -1
  73. package/dist/search/index.d.ts +112 -0
  74. package/dist/search/index.js +266 -0
  75. package/dist/search/index.js.map +1 -0
  76. package/dist/security/index.d.ts +2 -0
  77. package/dist/security/index.js +4 -0
  78. package/dist/security/index.js.map +1 -0
  79. package/dist/security/rate-limit/index.d.ts +2 -0
  80. package/dist/security/rate-limit/index.js +4 -0
  81. package/dist/security/rate-limit/index.js.map +1 -0
  82. package/dist/server/index.js +3 -2
  83. package/dist/server/index.js.map +1 -1
  84. package/dist/{stub-BqwKn4eh.js → stub-BUnfMiAS.js} +3 -56
  85. package/dist/stub-BUnfMiAS.js.map +1 -0
  86. package/dist/tags/index.js +1 -1
  87. package/dist/{tags-B5xpbgsk.js → tags-CbijgoqR.js} +2 -2
  88. package/dist/{tags-B5xpbgsk.js.map → tags-CbijgoqR.js.map} +1 -1
  89. package/dist/telemetry/index.d.ts +2 -2
  90. package/dist/tracker/index.d.ts +2 -2
  91. package/dist/tracker/index.js +5 -3
  92. package/dist/{tracker-BQVoEFUo.js → tracker-PQztSlhJ.js} +9 -390
  93. package/dist/tracker-PQztSlhJ.js.map +1 -0
  94. package/dist/translation/index.d.ts +120 -0
  95. package/dist/translation/index.js +573 -0
  96. package/dist/translation/index.js.map +1 -0
  97. package/dist/types/index.d.ts +3 -0
  98. package/dist/{types-Cj2RWXbz.js → types/index.js} +3 -3
  99. package/dist/types/index.js.map +1 -0
  100. package/dist/usage/index.d.ts +1 -1
  101. package/dist/usage/index.js +1 -1
  102. package/dist/{usage-BKFZiWQn.js → usage-BRqVP3CJ.js} +4 -4
  103. package/dist/{usage-BKFZiWQn.js.map → usage-BRqVP3CJ.js.map} +1 -1
  104. package/package.json +1 -1
  105. package/dist/context-CZnXf2yb.js.map +0 -1
  106. package/dist/stub-BqwKn4eh.js.map +0 -1
  107. package/dist/tracker-BQVoEFUo.js.map +0 -1
  108. package/dist/types-Cj2RWXbz.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["/**\n * Core type definitions for Burdenoff Backend SDK\n */\n\nimport type { ServiceLayer } from './layer.js';\n\n/**\n * SDK Configuration\n */\nexport interface SDKConfig {\n /** Workspaces API GraphQL endpoint (should point to wspace-int-gateway for M2M calls) */\n workspacesApiUrl: string;\n /**\n * Tenant API GraphQL endpoint for cross-layer (wspace → global) M2M calls.\n * Cross-layer traffic must go through the **public** global gateway\n * (`GLOBAL_PUBLIC_GATEWAY_URL`). In alpha and production this is the private\n * Route53 address of that gateway; the internal gateway is for same-layer calls.\n */\n tenantApiUrl?: string;\n /**\n * Calling service's layer (`wspace` | `global`). Used to construct the\n * cross-layer GatewayClient. Defaults to the `SERVICE_LAYER` env var, then\n * `wspace`.\n */\n serviceLayer?: ServiceLayer;\n /**\n * Calling service name. Used as the cross-layer GatewayClient service identity\n * and the `sub` of the minted service JWT. Defaults to the `SERVICE_NAME` env\n * var, then `burdenoff-be-sdk`.\n */\n serviceName?: string;\n /** Default timeout for API requests in milliseconds */\n timeout?: number;\n /** Retry configuration */\n retry?: RetryConfig;\n /** Logger configuration */\n logger?: LoggerConfig;\n /** Event queue configuration (Redis Streams). Reads `REDIS_URL` when present. */\n eventQueue?: EventQueueSDKConfig;\n /** Temporal module type (workspace or tenant) */\n temporalModuleType?: 'workspace' | 'tenant';\n /** Temporal server address */\n temporalAddress?: string;\n /** Temporal namespace */\n temporalNamespace?: string;\n /** Temporal task queue */\n temporalTaskQueue?: string;\n /** Auto-connect to Temporal (default: true) */\n temporalAutoConnect?: boolean;\n}\n\n/**\n * Retry configuration for API requests\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts */\n maxAttempts: number;\n /** Initial retry delay in milliseconds */\n initialDelay: number;\n /** Maximum retry delay in milliseconds */\n maxDelay: number;\n /** Backoff multiplier */\n backoffMultiplier: number;\n}\n\n/**\n * Logger configuration\n */\nexport interface LoggerConfig {\n /** Log level */\n level: 'debug' | 'info' | 'warn' | 'error';\n /** Enable console output */\n console: boolean;\n /** Custom logger transport */\n transport?: LoggerTransport;\n}\n\n/**\n * Custom logger transport interface\n */\nexport interface LoggerTransport {\n log(level: string, message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Actor type for RBAC authorization\n * - user: Direct user request (via frontend)\n * - app: OAuth app acting on behalf of user\n * - service: M2M service-to-service communication\n * - super_admin: Platform administration (bypasses all checks)\n */\nexport type ActorType = 'user' | 'app' | 'service' | 'super_admin';\n\n/**\n * Request context passed with every SDK operation\n */\nexport interface SDKContext {\n /** Actor ID - identifies the entity making the request */\n actorId?: string;\n /** Actor type - determines authorization behavior */\n actorType?: ActorType;\n /** Workspace ID */\n workspaceId?: string;\n /** Organization routing context for gateway calls. */\n organizationId?: string;\n /** Tenant ID */\n tenantId?: string;\n /** Project ID */\n projectId?: string;\n /** App ID */\n appId?: string;\n /** JWT token for authentication */\n token?: string;\n /** Product ID */\n productId?: string;\n /**\n * Cloudflare Access service-token client id, captured from the inbound\n * `cf-access-client-id` header. Re-presented on cross-layer outbound calls so\n * the peer layer's CF-Access-gated public gateway admits the request.\n */\n cfAccessClientId?: string;\n /**\n * Cloudflare Access service-token client secret, from `cf-access-client-secret`.\n * Sensitive — redacted by the SDK logger's secret pattern; never log directly.\n */\n cfAccessClientSecret?: string;\n /**\n * Cloudflare Access USER-SSO credential — the `CF_Authorization` cookie value,\n * forwarded by the public gateway as `x-cf-authorization`. On alpha a real user\n * request carries this (not the service-token pair); re-presented as the\n * `CF_Authorization` cookie on cross-layer outbound calls so the peer layer's\n * CF-Access-gated public gateway (same CF-Access app / shared AUD) admits it.\n * Sensitive — never log directly. See BOFF-2929.\n */\n cfAuthorization?: string;\n /** Additional custom context */\n [key: string]: unknown;\n}\n\n/**\n * SDK Error base class\n */\nexport class SDKError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: Record<string, unknown>\n ) {\n super(message);\n this.name = 'SDKError';\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n\n/**\n * Permission denied error\n */\nexport class PermissionDeniedError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'PERMISSION_DENIED', details);\n this.name = 'PermissionDeniedError';\n Object.setPrototypeOf(this, PermissionDeniedError.prototype);\n }\n}\n\n/**\n * Authentication error\n */\nexport class AuthenticationError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'AUTHENTICATION_ERROR', details);\n this.name = 'AuthenticationError';\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * API error from backend\n */\nexport class APIError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'API_ERROR', details);\n this.name = 'APIError';\n Object.setPrototypeOf(this, APIError.prototype);\n }\n}\n\n/**\n * Validation error\n */\nexport class ValidationError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'VALIDATION_ERROR', details);\n this.name = 'ValidationError';\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\n/**\n * Quota exceeded error\n */\nexport class QuotaExceededError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'QUOTA_EXCEEDED', details);\n this.name = 'QuotaExceededError';\n Object.setPrototypeOf(this, QuotaExceededError.prototype);\n }\n}\n\n/**\n * Network error\n */\nexport class NetworkError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'NETWORK_ERROR', details);\n this.name = 'NetworkError';\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n\n/**\n * Timeout error\n */\nexport class TimeoutError extends SDKError {\n constructor(message: string, details?: Record<string, unknown>) {\n super(message, 'TIMEOUT_ERROR', details);\n this.name = 'TimeoutError';\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Event queue SDK configuration (Redis Streams backend).\n *\n * The publisher is created via `createPublisher()` from\n * `@burdenoff/be-sdk/event-queue` and reads `REDIS_URL` from the env.\n * The fields here are for client-name + reconnect tuning only.\n */\nexport interface EventQueueSDKConfig {\n /** Redis Streams server URL. Overrides `REDIS_URL` env if set. */\n url?: string;\n /** Optional password for TLS/auth */\n password?: string;\n /** Maximum reconnect attempts (default: -1 = infinite) */\n maxReconnectAttempts?: number;\n /** Reconnect time wait in milliseconds (default: 2000) */\n reconnectTimeWait?: number;\n /** Client name for logging (default: service name) */\n name?: string;\n /** Auto-connect on SDK initialization (default: true) */\n autoConnect?: boolean;\n}\n\n/**\n * Event queue health status\n */\nexport interface EventQueueHealthStatus {\n status: 'healthy' | 'unhealthy' | 'not_configured';\n connected: boolean;\n url?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Temporal health status\n */\nexport interface TemporalHealthStatus {\n status: 'healthy' | 'unhealthy' | 'not_configured';\n connected: boolean;\n address?: string;\n namespace?: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Overall SDK health status\n */\nexport interface SDKHealthStatus {\n eventQueue: EventQueueHealthStatus;\n temporal: TemporalHealthStatus;\n}\n\n/**\n * SDK shutdown options\n */\nexport interface SDKShutdownOptions {\n /** Shutdown timeout in milliseconds (default: 5000) */\n timeout?: number;\n /** Force shutdown even if timeout is exceeded (default: true) */\n force?: boolean;\n}\n\n// ============================================================================\n// Layer Types Export\n// ============================================================================\n\n/**\n * Re-export all layer-related types for convenience\n */\nexport type {\n ServiceLayer,\n LayerConfig,\n LayerGatewayConfig,\n LayerResourceUrls,\n LayerFullConfig,\n GatewayRoutingConfig,\n CircuitBreakerConfig,\n GatewayRetryConfig,\n GatewayRequestHeaders,\n} from './layer.js';\n\nexport {\n DEFAULT_GATEWAY_ROUTING,\n DEFAULT_LAYER_RESOURCES,\n DEFAULT_LAYER_STREAMS,\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n} from './layer.js';\n"],"mappings":";;;;;;AA8IA,IAAa,WAAb,MAAa,iBAAiB,MAAM;CAGzB;CACA;CAHT,YACE,SACA,AAAO,MACP,AAAO,SACP;EACA,MAAM,OAAO;EAHN;EACA;EAGP,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,SAAS,SAAS;CAChD;AACF;;;;AAKA,IAAa,wBAAb,MAAa,8BAA8B,SAAS;CAClD,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,qBAAqB,OAAO;EAC3C,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,sBAAsB,SAAS;CAC7D;AACF;;;;AAKA,IAAa,sBAAb,MAAa,4BAA4B,SAAS;CAChD,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,wBAAwB,OAAO;EAC9C,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,oBAAoB,SAAS;CAC3D;AACF;;;;AAKA,IAAa,WAAb,MAAa,iBAAiB,SAAS;CACrC,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,aAAa,OAAO;EACnC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,SAAS,SAAS;CAChD;AACF;;;;AAKA,IAAa,kBAAb,MAAa,wBAAwB,SAAS;CAC5C,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,oBAAoB,OAAO;EAC1C,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,gBAAgB,SAAS;CACvD;AACF;;;;AAKA,IAAa,qBAAb,MAAa,2BAA2B,SAAS;CAC/C,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,kBAAkB,OAAO;EACxC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,mBAAmB,SAAS;CAC1D;AACF;;;;AAKA,IAAa,eAAb,MAAa,qBAAqB,SAAS;CACzC,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,iBAAiB,OAAO;EACvC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,aAAa,SAAS;CACpD;AACF;;;;AAKA,IAAa,eAAb,MAAa,qBAAqB,SAAS;CACzC,YAAY,SAAiB,SAAmC;EAC9D,MAAM,SAAS,iBAAiB,OAAO;EACvC,KAAK,OAAO;EACZ,OAAO,eAAe,MAAM,aAAa,SAAS;CACpD;AACF"}
@@ -1,2 +1,2 @@
1
- import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index-DZC-2o9R.js";
1
+ import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index-CVCyKzhB.js";
2
2
  export { BillingUsageClient, type BillingUsageClientConfig, type BillingUsageOperationInput, CHECK_WORKSPACE_QUOTA_QUERY, CheckQuotaOptions, CheckWorkspaceQuotaOptions, GetUsageOptions, type OrgBillingUsageOperationInput, Quota, QuotaCheckResult, type QuotaLimit, QuotaPeriod, SetQuotaOptions, TRACK_USAGE_MUTATION, TrackUsageOptions, TrackWorkspaceUsageOptions, UsageEntityType, UsageMetricType, UsageModule, UsageOperationUnsupportedError, UsageRecord, UsageSummary, type WorkspaceBillingUsageOperationInput, WorkspaceQuotaCheckResult, buildTrackUsageInput };
@@ -1,4 +1,4 @@
1
- import { a as UsageModule, c as BillingUsageClient, i as UsageMetricType, n as QuotaPeriod, o as UsageOperationUnsupportedError, r as TRACK_USAGE_MUTATION, s as buildTrackUsageInput, t as CHECK_WORKSPACE_QUOTA_QUERY } from "../usage-BKFZiWQn.js";
1
+ import { a as UsageModule, c as BillingUsageClient, i as UsageMetricType, n as QuotaPeriod, o as UsageOperationUnsupportedError, r as TRACK_USAGE_MUTATION, s as buildTrackUsageInput, t as CHECK_WORKSPACE_QUOTA_QUERY } from "../usage-BRqVP3CJ.js";
2
2
 
3
3
  export { BillingUsageClient, CHECK_WORKSPACE_QUOTA_QUERY, QuotaPeriod, TRACK_USAGE_MUTATION, UsageMetricType, UsageModule, UsageOperationUnsupportedError, buildTrackUsageInput };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
- import { a as QuotaExceededError, c as ValidationError, o as SDKError } from "./types-Cj2RWXbz.js";
2
- import { t as GatewayClient } from "./client-DcZ3iGES.js";
1
+ import { QuotaExceededError, SDKError, ValidationError } from "./types/index.js";
2
+ import { t as GatewayClient } from "./client-sAJTrb4i.js";
3
3
  import { a as logger } from "./logger-B6rCpb7D.js";
4
- import "./gateway-DBFmxWks.js";
4
+ import "./gateway-ByVo-n37.js";
5
5
  import { randomUUID } from "node:crypto";
6
6
 
7
7
  // src/usage/billing.ts
@@ -679,4 +679,4 @@ var UsageModule = class {
679
679
  };
680
680
 
681
681
  export { UsageModule as a, BillingUsageClient as c, UsageMetricType as i, QuotaPeriod as n, UsageOperationUnsupportedError as o, TRACK_USAGE_MUTATION as r, buildTrackUsageInput as s, CHECK_WORKSPACE_QUOTA_QUERY as t };
682
- //# sourceMappingURL=usage-BKFZiWQn.js.map
682
+ //# sourceMappingURL=usage-BRqVP3CJ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"usage-BKFZiWQn.js","names":[],"sources":["../src/usage/billing.ts","../src/usage/index.ts"],"sourcesContent":["/**\n * Billing Usage Client\n *\n * Canonical cross-layer quota/usage surface for wspace services talking to\n * `global-billing-svc`. All transport (URL resolution, actor/service header\n * assembly, service-JWT minting, retries, circuit breaker, timeouts,\n * telemetry) comes from the {@link GatewayClient}:\n *\n * - **wspace -> wspace** (resolving a workspace's org) uses `internalQuery`\n * (same-layer internal gateway, `WSPACE_INT_GATEWAY_URL`).\n * - **wspace -> global** (billing account + quota + usage) uses\n * `crossLayerQuery`, which routes via the global PUBLIC gateway\n * (`GLOBAL_PUBLIC_GATEWAY_URL`) and mints a signed `service` JWT the\n * gateway trusts. Only `x-actor-type: service` is presented — never\n * `x-actor-id` (auth-middleware reads that as an on-behalf-of override and\n * downgrades the caller to `user`, yielding a 403). Actor identity for the\n * usage record is carried in the GraphQL variables (`userId`), not in\n * headers.\n *\n * Every read/write fails open (returns `null`/`false`, or `true` for the\n * workspace quota gate) so transient billing unavailability never blocks a\n * product operation; callers that need hard enforcement must layer it on top.\n *\n * @module usage/billing\n * @category Usage\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Bound each gateway attempt so a slow billing gateway never stalls the\n * (blocking) quota-limit read.\n */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\n/** Default TTL for the in-process plan-limit cache. */\nconst DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** Lazy prune threshold — keeps the plan-limit cache bounded without timers. */\nconst QUOTA_LIMIT_CACHE_MAX_ENTRIES = 1_000;\n\nconst GET_WORKSPACE_ORG_QUERY = `\n query GetWorkspaceOrg($workspaceId: ID!) {\n workspace(id: $workspaceId) {\n orgId\n }\n }\n`;\n\nconst GET_DEFAULT_BILLING_ACCOUNT_QUERY = `\n query GetDefaultBillingAccount($orgId: ID!) {\n getDefaultBillingAccountByOrgId(orgId: $orgId) {\n id\n }\n }\n`;\n\nconst CHECK_QUOTA_QUERY = `\n query CheckQuotaExhausted($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n checkQuotaExhausted(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limitLeft\n noLimit\n quotaAssignmentId\n }\n }\n`;\n\nconst ADD_USAGE_MUTATION = `\n mutation AddUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String!\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n addUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\nconst GET_QUOTA_LIMIT_QUERY = `\n query GetQuotaLimit($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n getQuotaUsageAndLimit(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limit\n noLimit\n }\n }\n`;\n\nconst FREE_UP_USAGE_MUTATION = `\n mutation FreeUpUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n freeUpUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\ninterface WorkspaceOrgQueryData {\n workspace?: {\n orgId?: string | null;\n } | null;\n}\n\ninterface BillingAccountQueryData {\n getDefaultBillingAccountByOrgId?: {\n id?: string | null;\n } | null;\n}\n\ninterface QuotaCheckQueryData {\n checkQuotaExhausted?: {\n limitLeft: number;\n noLimit: boolean;\n quotaAssignmentId: string;\n } | null;\n}\n\ninterface QuotaLimitQueryData {\n getQuotaUsageAndLimit?: {\n limit: number;\n noLimit: boolean;\n } | null;\n}\n\ninterface UsageMutationData {\n addUsage?: boolean;\n freeUpUsage?: boolean;\n}\n\n/** Common input for a quota/usage operation against a billing account. */\nexport interface BillingUsageOperationInput {\n quotaName: string;\n value?: number;\n description: string;\n /**\n * Product scope for the quota/usage record. Required — every caller must be\n * explicit about which product's meter it is touching (there is no implicit\n * default, which historically shipped as a copy-paste `'vibecontrols'`).\n */\n productId: string;\n userId?: string;\n hash?: string;\n tags?: Record<string, unknown>;\n}\n\n/** Quota/usage operation addressed by organization. */\nexport interface OrgBillingUsageOperationInput extends BillingUsageOperationInput {\n orgId: string;\n}\n\n/** Quota/usage operation addressed by workspace (org resolved internally). */\nexport interface WorkspaceBillingUsageOperationInput extends BillingUsageOperationInput {\n workspaceId: string;\n}\n\n/** Plan limit for a quota, as stored by billing-svc. */\nexport interface QuotaLimit {\n limit: number;\n noLimit: boolean;\n}\n\n/** Configuration for {@link BillingUsageClient}. */\nexport interface BillingUsageClientConfig {\n /**\n * Owning service identity (e.g. `wspace-tags-svc`). Sent as the service\n * identity header and used for log attribution.\n */\n serviceName: string;\n /** Per-request timeout in milliseconds. Defaults to 5s. */\n timeout?: number;\n /**\n * Pre-built {@link GatewayClient}. When omitted, one is created for the\n * `wspace` layer (deriving internal/cross-layer gateway URLs from env).\n * Primarily a test seam.\n */\n gatewayClient?: GatewayClient;\n /** TTL for the in-process plan-limit cache. Defaults to 5 minutes. */\n quotaLimitCacheTtlMs?: number;\n}\n\ninterface CachedQuotaLimit extends QuotaLimit {\n expiresAt: number;\n}\n\nfunction unwrap<TData>(data: TData | undefined): TData {\n if (!data) {\n throw new Error('GraphQL response did not include data');\n }\n return data;\n}\n\n/**\n * Canonical quota/usage client for wspace -> global-billing-svc traffic.\n *\n * See the module docstring for the transport contract. All methods fail open;\n * see individual method docs for the exact fallback value.\n */\nexport class BillingUsageClient {\n private readonly gatewayClient: GatewayClient;\n private readonly quotaLimitCacheTtlMs: number;\n private readonly logPrefix: string;\n\n // In-process cache for plan limits (changes at most when a workspace\n // upgrades their plan). Lazily pruned on access — no timers in a library.\n private readonly quotaLimitCache = new Map<string, CachedQuotaLimit>();\n\n constructor(config: BillingUsageClientConfig) {\n if (!config.serviceName) {\n throw new TypeError('BillingUsageClient requires a serviceName');\n }\n this.gatewayClient =\n config.gatewayClient ??\n new GatewayClient({\n layer: 'wspace',\n serviceName: config.serviceName,\n timeout: config.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS,\n });\n this.quotaLimitCacheTtlMs = config.quotaLimitCacheTtlMs ?? DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS;\n this.logPrefix = `[billing-usage:${config.serviceName}]`;\n }\n\n /**\n * Same-layer (wspace -> wspace) internal-gateway call.\n */\n private async queryWorkspaceLayer<TData>(\n query: string,\n variables: Record<string, unknown>,\n workspaceId: string\n ): Promise<TData> {\n const response = await this.gatewayClient.internalQuery<TData>({\n query,\n variables,\n headers: { 'x-workspace-id': workspaceId },\n // Blocking on the create path — keep it single-shot & snappy; consumers fail open.\n skipRetry: true,\n });\n return unwrap(response.data);\n }\n\n /**\n * Cross-layer (wspace -> global) public-gateway call. No actor headers — the\n * signed service JWT carries identity; adding `x-actor-id` would 403.\n */\n private async queryGlobalLayer<TData>(query: string, variables: Record<string, unknown>): Promise<TData> {\n const response = await this.gatewayClient.crossLayerQuery<TData>({ query, variables });\n return unwrap(response.data);\n }\n\n /**\n * Resolve the organization that owns a workspace. Fails open (`null`).\n */\n async getOrgIdFromWorkspace(workspaceId: string): Promise<string | null> {\n try {\n const data = await this.queryWorkspaceLayer<WorkspaceOrgQueryData>(\n GET_WORKSPACE_ORG_QUERY,\n { workspaceId },\n workspaceId\n );\n return data.workspace?.orgId ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve workspace org`, {\n workspaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Resolve the default billing account for an organization via the global\n * layer. Fails open (`null`).\n */\n async getDefaultBillingAccountId(orgId: string): Promise<string | null> {\n try {\n const data = await this.queryGlobalLayer<BillingAccountQueryData>(GET_DEFAULT_BILLING_ACCOUNT_QUERY, {\n orgId,\n });\n return data.getDefaultBillingAccountByOrgId?.id ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve default billing account`, {\n orgId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Check that an organization still has quota headroom for `value` units of\n * `quotaName`. Returns `false` when no billing account exists or the quota\n * is exhausted; rethrows nothing — transport errors propagate to the caller\n * of this low-level variant (the workspace variant fails open instead).\n */\n async ensureQuotaAvailableForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for org quota check`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const amount = input.value ?? 1;\n const data = await this.queryGlobalLayer<QuotaCheckQueryData>(CHECK_QUOTA_QUERY, {\n billingAccountId,\n quotaName: input.quotaName,\n productId: input.productId,\n });\n\n const result = data.checkQuotaExhausted;\n if (!result) {\n return false;\n }\n\n if (result.noLimit) {\n return true;\n }\n\n return result.limitLeft >= amount;\n }\n\n /**\n * Workspace-addressed quota gate: resolves the org, then applies\n * {@link ensureQuotaAvailableForOrg}. Fails OPEN (`true`) when org\n * resolution fails (unbilled / dev / internal workspaces) so local-stack\n * test workspaces and workspaces with a transiently broken tenant lookup\n * are never locked out; real limits only kick in when the workspace has a\n * billable org.\n */\n async ensureQuotaAvailableForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available; allowing quota op (fail-open)`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return true;\n }\n\n return this.ensureQuotaAvailableForOrg({ ...input, orgId });\n }\n\n /**\n * Record usage against an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async addUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for addUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(ADD_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.addUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link addUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async addUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace addUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.addUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Credit usage back to an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async freeUpUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for freeUpUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(FREE_UP_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.freeUpUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link freeUpUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async freeUpUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace freeUpUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.freeUpUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Fetch the plan limit for a quota from billing-svc, bypassing billing's\n * internal usage counter (the caller's own DB is the source of truth for\n * current usage; billing only stores the plan maximum). Results are cached\n * in-process per workspace/quota/product. Fails open (`null`) when billing\n * is unreachable so dev/test workspaces without billing accounts are never\n * blocked.\n */\n async getQuotaLimitForWorkspace(\n workspaceId: string,\n quotaName: string,\n productId: string\n ): Promise<QuotaLimit | null> {\n const cacheKey = `${workspaceId}:${quotaName}:${productId}`;\n const cached = this.quotaLimitCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) {\n return { limit: cached.limit, noLimit: cached.noLimit };\n }\n\n const orgId = await this.getOrgIdFromWorkspace(workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No org found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n const billingAccountId = await this.getDefaultBillingAccountId(orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n try {\n const data = await this.queryGlobalLayer<QuotaLimitQueryData>(GET_QUOTA_LIMIT_QUERY, {\n billingAccountId,\n quotaName,\n productId,\n });\n\n const result = data.getQuotaUsageAndLimit;\n if (!result) {\n return null;\n }\n\n this.rememberQuotaLimit(cacheKey, { limit: result.limit, noLimit: result.noLimit });\n return { limit: result.limit, noLimit: result.noLimit };\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to fetch quota limit; failing open`, {\n workspaceId,\n quotaName,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n private rememberQuotaLimit(cacheKey: string, value: QuotaLimit): void {\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const now = Date.now();\n for (const [key, entry] of this.quotaLimitCache) {\n if (entry.expiresAt <= now) this.quotaLimitCache.delete(key);\n }\n // Still full after pruning (all entries fresh): drop the oldest-inserted\n // entries rather than refusing to cache. Plan limits are re-fetchable.\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const overflow = this.quotaLimitCache.size - QUOTA_LIMIT_CACHE_MAX_ENTRIES + 1;\n let removed = 0;\n for (const key of this.quotaLimitCache.keys()) {\n this.quotaLimitCache.delete(key);\n removed += 1;\n if (removed >= overflow) break;\n }\n }\n }\n this.quotaLimitCache.set(cacheKey, { ...value, expiresAt: Date.now() + this.quotaLimitCacheTtlMs });\n }\n}\n","/**\n * Usage & Quota Module\n *\n * Checks and records workspace quota usage against the workspace usage owner\n * (wspace-activity-svc). The owner's published contract is:\n *\n * - `checkWorkspaceQuota(workspaceId, quotaName, amount): WorkspaceQuotaCheckResult!`\n * - `trackUsage(input: TrackUsageInput!): Boolean!`\n *\n * Quotas are keyed by `quotaName` (for example `platform.projects.created`), not by the\n * `entityId`/`entityType`/`metricType` triple this module used to send. That triple was\n * never part of the owner's schema, so every legacy call failed GraphQL validation\n * (BOFF-10955). The legacy methods remain for source compatibility and fail with\n * {@link UsageOperationUnsupportedError} before any network call.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { SDKError, ValidationError, QuotaExceededError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Legacy usage metric names. The workspace usage owner has no metric types; quotas are\n * addressed by `quotaName`. Kept so existing `sdk.tracker.track({ usage: { metricType } })`\n * call sites keep compiling; the tracker does not meter a metric type on its own.\n */\nexport enum UsageMetricType {\n API_CALLS = 'api_calls',\n STORAGE = 'storage',\n BANDWIDTH = 'bandwidth',\n USERS = 'users',\n PROJECTS = 'projects',\n WORKSPACES = 'workspaces',\n RECORDS = 'records',\n COMPUTE_TIME = 'compute_time',\n TRANSACTIONS = 'transactions',\n CUSTOM = 'custom',\n}\n\nexport enum QuotaPeriod {\n DAILY = 'daily',\n WEEKLY = 'weekly',\n MONTHLY = 'monthly',\n YEARLY = 'yearly',\n LIFETIME = 'lifetime',\n}\n\n/**\n * Entity type for usage tracking\n */\nexport type UsageEntityType = 'user' | 'workspace' | 'organization';\n\nexport interface TrackUsageOptions {\n /** User or workspace consuming the resource */\n entityId: string;\n /** Type of entity (user or workspace) */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to increment */\n amount: number;\n /** Optional resource identifier */\n resourceId?: string;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface CheckQuotaOptions {\n /** Entity to check quota for */\n entityId: string;\n /** Type of entity */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to check availability for */\n requestedAmount: number;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface QuotaCheckResult {\n allowed: boolean;\n currentUsage: number;\n quotaLimit: number;\n remainingQuota: number;\n resetAt?: string;\n period: QuotaPeriod;\n reason?: string;\n}\n\nexport interface UsageRecord {\n id: string;\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n amount: number;\n resourceId?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n recordedAt: string;\n}\n\nexport interface UsageSummary {\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n totalUsage: number;\n period: QuotaPeriod;\n periodStart: string;\n periodEnd: string;\n quotaLimit?: number;\n utilizationPercentage?: number;\n}\n\nexport interface SetQuotaOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n workspaceId?: string;\n organizationId?: string;\n}\n\nexport interface Quota {\n id: string;\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n currentUsage: number;\n resetAt: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GetUsageOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType?: UsageMetricType;\n startDate?: string;\n endDate?: string;\n workspaceId?: string;\n organizationId?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Thrown by SDK usage operations the workspace usage owner does not expose. */\nexport class UsageOperationUnsupportedError extends SDKError {\n constructor(operation: string, guidance: string) {\n super(\n `UsageModule.${operation} is not supported by the workspace usage owner: ${guidance}`,\n 'USAGE_OPERATION_UNSUPPORTED',\n { operation }\n );\n this.name = 'UsageOperationUnsupportedError';\n Object.setPrototypeOf(this, UsageOperationUnsupportedError.prototype);\n }\n}\n\n/**\n * Query sent to the owner's `checkWorkspaceQuota`. Every argument and selected field must\n * exist on the published wspace schema (see tests/usage-module.test.ts).\n */\nexport const CHECK_WORKSPACE_QUOTA_QUERY = `\n query CheckWorkspaceQuota($workspaceId: ID!, $quotaName: String!, $amount: Float) {\n checkWorkspaceQuota(workspaceId: $workspaceId, quotaName: $quotaName, amount: $amount) {\n allowed\n assignmentId\n limitLeft\n noLimit\n }\n }\n`;\n\n/** Mutation sent to the owner's `trackUsage`, which returns `Boolean!`. */\nexport const TRACK_USAGE_MUTATION = `\n mutation TrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n }\n`;\n\nexport interface CheckWorkspaceQuotaOptions {\n /** Quota to check, for example `platform.projects.created`. */\n quotaName: string;\n /** Amount the caller is about to consume. Must be positive; defaults to 1. */\n amount?: number;\n /** Workspace that owns the quota. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the check is made for. Defaults to the SDK context's actor. */\n userId?: string;\n}\n\n/** The owner's `WorkspaceQuotaCheckResult`. */\nexport interface WorkspaceQuotaCheckResult {\n /** True when the quota has enough remaining capacity for the requested amount. */\n allowed: boolean;\n /** Active assignment to charge, or null when the workspace's plan does not include the quota. */\n assignmentId: string | null;\n /** Remaining capacity after the requested amount; null when unlimited or not provisioned. */\n limitLeft: number | null;\n /** True when the quota is unlimited. */\n noLimit: boolean;\n}\n\nexport interface TrackWorkspaceUsageOptions {\n /** Quota to charge, for example `platform.projects.created`. */\n quotaName: string;\n /** Product the quota belongs to, for example `platform`. Defaults to the SDK context's product. */\n productId?: string;\n /**\n * Amount to record. A positive amount consumes quota; a negative amount releases it (for\n * example on delete). The owner only accepts negative amounts from services and super\n * admins, which is how this module relays the call. Zero is rejected.\n */\n amount: number;\n /** Human-readable reason stored on the usage record. */\n description: string;\n /** Workspace to charge. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the usage is recorded for. Defaults to the SDK context's actor. */\n userId?: string;\n /** Assignment returned by {@link UsageModule.checkWorkspaceQuota}; saves the owner a lookup. */\n quotaAssignmentId?: string;\n /** Billing account reference stored on the record. Omit for workspace quotas. */\n billingAccountId?: string;\n /**\n * Idempotency key. The owner records one charge per hash and workspace, so a retried\n * request cannot charge twice. A random key is generated per call when omitted.\n */\n hash?: string;\n /** Additional metadata stored on the usage record. */\n metadata?: Record<string, unknown>;\n}\n\nfunction legacyGuidance(replacement: string): string {\n return `quotas are addressed by quotaName on the workspace usage owner; use ${replacement}`;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Builds the owner's `TrackUsageInput` from SDK options, filling defaults from the context.\n * Throws {@link ValidationError} for input the owner would refuse.\n */\nexport function buildTrackUsageInput(\n options: TrackWorkspaceUsageOptions,\n context: SDKContext = {}\n): Record<string, unknown> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const productId = nonEmpty(options.productId) ?? nonEmpty(context.productId);\n if (!productId) {\n throw new ValidationError('Product ID is required');\n }\n const description = nonEmpty(options.description);\n if (!description) {\n throw new ValidationError('Description is required');\n }\n if (typeof options.amount !== 'number' || !Number.isFinite(options.amount) || options.amount === 0) {\n throw new ValidationError('Amount must be a finite, non-zero number');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n const input: Record<string, unknown> = {\n quotaName,\n productId,\n amount: options.amount,\n description,\n workspaceId,\n hash: nonEmpty(options.hash) ?? `sdk-usage:${randomUUID()}`,\n };\n const userId = nonEmpty(options.userId) ?? nonEmpty(context.actorId);\n if (userId) input['userId'] = userId;\n if (options.quotaAssignmentId) input['quotaAssignmentId'] = options.quotaAssignmentId;\n if (options.billingAccountId) input['billingAccountId'] = options.billingAccountId;\n if (options.metadata) input['metadata'] = options.metadata;\n return input;\n}\n\n/**\n * Usage & Quota Module\n */\nexport class UsageModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Context for one owner call: relayed as a platform service acting for `userId`, with the\n * quota's workspace in scope. The owner takes the workspace from this context, never from\n * the input, and only lets services release (decrement) usage.\n */\n private requestContext(workspaceId: string, userId: string | undefined): SDKContext {\n const actorId = userId ?? this.context.actorId;\n return {\n ...this.context,\n ...(actorId ? { actorId } : {}),\n actorType: 'service',\n workspaceId,\n };\n }\n\n /**\n * Check whether a workspace quota has capacity for `amount` (default 1).\n */\n public async checkWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const amount = options.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {\n throw new ValidationError('Quota checks need a positive amount');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(this.context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n logger.debug('[Usage] Checking workspace quota', { workspaceId, quotaName, amount });\n\n const response = await this.client.query<{ checkWorkspaceQuota: WorkspaceQuotaCheckResult }>(\n CHECK_WORKSPACE_QUOTA_QUERY,\n { workspaceId, quotaName, amount },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n const result = response.checkWorkspaceQuota;\n logger.debug('[Usage] Workspace quota check result', { workspaceId, quotaName, allowed: result.allowed });\n return result;\n }\n\n /**\n * Check a workspace quota and throw {@link QuotaExceededError} when it has no capacity.\n * Returns the check result so the caller can pass `assignmentId` to {@link trackUsage}.\n */\n public async requireWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const result = await this.checkWorkspaceQuota(options);\n if (!result.allowed) {\n const notProvisioned = result.assignmentId === null;\n throw new QuotaExceededError(\n notProvisioned ? `Quota ${options.quotaName} is not included in this workspace's plan` : 'Quota exceeded',\n {\n quotaName: options.quotaName,\n requestedAmount: options.amount ?? 1,\n limitLeft: result.limitLeft,\n notProvisioned,\n }\n );\n }\n return result;\n }\n\n /**\n * Record workspace quota usage. A negative amount releases previously recorded usage.\n * Resolves to `true` once the owner has stored (or deduplicated) the record.\n */\n public async trackUsage(options: TrackWorkspaceUsageOptions): Promise<boolean> {\n const input = buildTrackUsageInput(options, this.context);\n const workspaceId = input['workspaceId'] as string;\n\n logger.debug('[Usage] Tracking workspace usage', {\n workspaceId,\n quotaName: input['quotaName'],\n amount: input['amount'],\n });\n\n const response = await this.client.query<{ trackUsage: boolean }>(\n TRACK_USAGE_MUTATION,\n { input },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n logger.info('[Usage] Workspace usage tracked', { workspaceId, quotaName: input['quotaName'] });\n return response.trackUsage;\n }\n\n /**\n * @deprecated The workspace usage owner has no `trackUsage` record shape keyed by\n * `entityId`/`metricType`. Use {@link trackUsage} with a `quotaName`.\n */\n public async track(_options: TrackUsageOptions): Promise<UsageRecord> {\n throw new UsageOperationUnsupportedError('track', legacyGuidance('trackUsage({ quotaName, productId, amount })'));\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link checkWorkspaceQuota}.\n */\n public async checkQuota(_options: CheckQuotaOptions): Promise<QuotaCheckResult> {\n throw new UsageOperationUnsupportedError(\n 'checkQuota',\n legacyGuidance('checkWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link requireWorkspaceQuota}.\n */\n public async requireQuota(_options: CheckQuotaOptions): Promise<void> {\n throw new UsageOperationUnsupportedError(\n 'requireQuota',\n legacyGuidance('requireWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated Use {@link requireWorkspaceQuota} followed by {@link trackUsage}.\n */\n public async trackAndCheck(_options: TrackUsageOptions): Promise<{\n usage: UsageRecord;\n quotaCheck: QuotaCheckResult;\n }> {\n throw new UsageOperationUnsupportedError(\n 'trackAndCheck',\n legacyGuidance('requireWorkspaceQuota() and then trackUsage()')\n );\n }\n\n /**\n * @deprecated The owner has no `getUsage` operation; read records with the owner's\n * `getUsageRecords(filters, pagination)`.\n */\n public async getUsage(_options: GetUsageOptions): Promise<{\n records: UsageRecord[];\n total: number;\n }> {\n throw new UsageOperationUnsupportedError('getUsage', legacyGuidance(\"the owner's getUsageRecords query\"));\n }\n\n /**\n * @deprecated The owner's `getUsageSummary` takes `UsageFilters` and returns a list; this\n * signature does not map onto it.\n */\n public async getSummary(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType,\n _period: QuotaPeriod\n ): Promise<UsageSummary> {\n throw new UsageOperationUnsupportedError(\n 'getSummary',\n legacyGuidance(\"the owner's getUsageSummary(filters) query\")\n );\n }\n\n /**\n * @deprecated Quota limits are assigned by global-billing-svc through the owner's\n * `assignWorkspaceQuota`, which only billing's service identity may call.\n */\n public async setQuota(_options: SetQuotaOptions): Promise<Quota> {\n throw new UsageOperationUnsupportedError('setQuota', 'quota limits are assigned by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `getQuota` operation; read `workspaceQuotaStatuses(workspaceId)`.\n */\n public async getQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<Quota | null> {\n throw new UsageOperationUnsupportedError('getQuota', legacyGuidance(\"the owner's workspaceQuotaStatuses query\"));\n }\n\n /**\n * @deprecated The owner has no `getQuotas` operation; read `workspaceQuotaAssignments(workspaceId)`.\n */\n public async getQuotas(_entityId: string, _entityType: UsageEntityType): Promise<Quota[]> {\n throw new UsageOperationUnsupportedError(\n 'getQuotas',\n legacyGuidance(\"the owner's workspaceQuotaAssignments query\")\n );\n }\n\n /**\n * @deprecated The owner has no `resetQuota` operation; quotas reset on their `resetPeriod`.\n */\n public async resetQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('resetQuota', \"quotas reset on the assignment's resetPeriod\");\n }\n\n /**\n * @deprecated The owner has no `deleteQuota` operation; billing deactivates assignments.\n */\n public async deleteQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('deleteQuota', 'quota assignments are deactivated by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `trackUsageBulk` operation. Call {@link trackUsage} per record.\n */\n public async trackBulk(_records: TrackUsageOptions[]): Promise<UsageRecord[]> {\n throw new UsageOperationUnsupportedError('trackBulk', legacyGuidance('trackUsage() per record'));\n }\n}\n\nexport {\n BillingUsageClient,\n type BillingUsageClientConfig,\n type BillingUsageOperationInput,\n type OrgBillingUsageOperationInput,\n type WorkspaceBillingUsageOperationInput,\n type QuotaLimit,\n} from './billing.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,6BAA6B;;AAGnC,MAAM,mCAAmC;;AAGzC,MAAM,gCAAgC;AAEtC,MAAM,0BAA0B;;;;;;;AAQhC,MAAM,oCAAoC;;;;;;;AAQ1C,MAAM,oBAAoB;;;;;;;;;;;;;AAc1B,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;AAwB3B,MAAM,wBAAwB;;;;;;;;;;;;AAa9B,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;AA+G/B,SAAS,OAAc,MAAgC;CACrD,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,uCAAuC;CAEzD,OAAO;AACT;;;;;;;AAQA,IAAa,qBAAb,MAAgC;CAC9B,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAIjB,AAAiB,kCAAkB,IAAI,IAA8B;CAErE,YAAY,QAAkC;EAC5C,IAAI,CAAC,OAAO,aACV,MAAM,IAAI,UAAU,2CAA2C;EAEjE,KAAK,gBACH,OAAO,iBACP,IAAI,cAAc;GAChB,OAAO;GACP,aAAa,OAAO;GACpB,SAAS,OAAO,WAAW;EAC7B,CAAC;EACH,KAAK,uBAAuB,OAAO,wBAAwB;EAC3D,KAAK,YAAY,kBAAkB,OAAO,YAAY;CACxD;;;;CAKA,MAAc,oBACZ,OACA,WACA,aACgB;EAQhB,OAAO,QAAO,MAPS,KAAK,cAAc,cAAqB;GAC7D;GACA;GACA,SAAS,EAAE,kBAAkB,YAAY;GAEzC,WAAW;EACb,CAAC,EACqB,CAAC,IAAI;CAC7B;;;;;CAMA,M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src/usage/index.ts"],"sourcesContent":["/**\n * Billing Usage Client\n *\n * Canonical cross-layer quota/usage surface for wspace services talking to\n * `global-billing-svc`. All transport (URL resolution, actor/service header\n * assembly, service-JWT minting, retries, circuit breaker, timeouts,\n * telemetry) comes from the {@link GatewayClient}:\n *\n * - **wspace -> wspace** (resolving a workspace's org) uses `internalQuery`\n * (same-layer internal gateway, `WSPACE_INT_GATEWAY_URL`).\n * - **wspace -> global** (billing account + quota + usage) uses\n * `crossLayerQuery`, which routes via the global PUBLIC gateway\n * (`GLOBAL_PUBLIC_GATEWAY_URL`) and mints a signed `service` JWT the\n * gateway trusts. Only `x-actor-type: service` is presented — never\n * `x-actor-id` (auth-middleware reads that as an on-behalf-of override and\n * downgrades the caller to `user`, yielding a 403). Actor identity for the\n * usage record is carried in the GraphQL variables (`userId`), not in\n * headers.\n *\n * Every read/write fails open (returns `null`/`false`, or `true` for the\n * workspace quota gate) so transient billing unavailability never blocks a\n * product operation; callers that need hard enforcement must layer it on top.\n *\n * @module usage/billing\n * @category Usage\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Bound each gateway attempt so a slow billing gateway never stalls the\n * (blocking) quota-limit read.\n */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\n/** Default TTL for the in-process plan-limit cache. */\nconst DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** Lazy prune threshold — keeps the plan-limit cache bounded without timers. */\nconst QUOTA_LIMIT_CACHE_MAX_ENTRIES = 1_000;\n\nconst GET_WORKSPACE_ORG_QUERY = `\n query GetWorkspaceOrg($workspaceId: ID!) {\n workspace(id: $workspaceId) {\n orgId\n }\n }\n`;\n\nconst GET_DEFAULT_BILLING_ACCOUNT_QUERY = `\n query GetDefaultBillingAccount($orgId: ID!) {\n getDefaultBillingAccountByOrgId(orgId: $orgId) {\n id\n }\n }\n`;\n\nconst CHECK_QUOTA_QUERY = `\n query CheckQuotaExhausted($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n checkQuotaExhausted(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limitLeft\n noLimit\n quotaAssignmentId\n }\n }\n`;\n\nconst ADD_USAGE_MUTATION = `\n mutation AddUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String!\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n addUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\nconst GET_QUOTA_LIMIT_QUERY = `\n query GetQuotaLimit($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n getQuotaUsageAndLimit(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limit\n noLimit\n }\n }\n`;\n\nconst FREE_UP_USAGE_MUTATION = `\n mutation FreeUpUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n freeUpUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\ninterface WorkspaceOrgQueryData {\n workspace?: {\n orgId?: string | null;\n } | null;\n}\n\ninterface BillingAccountQueryData {\n getDefaultBillingAccountByOrgId?: {\n id?: string | null;\n } | null;\n}\n\ninterface QuotaCheckQueryData {\n checkQuotaExhausted?: {\n limitLeft: number;\n noLimit: boolean;\n quotaAssignmentId: string;\n } | null;\n}\n\ninterface QuotaLimitQueryData {\n getQuotaUsageAndLimit?: {\n limit: number;\n noLimit: boolean;\n } | null;\n}\n\ninterface UsageMutationData {\n addUsage?: boolean;\n freeUpUsage?: boolean;\n}\n\n/** Common input for a quota/usage operation against a billing account. */\nexport interface BillingUsageOperationInput {\n quotaName: string;\n value?: number;\n description: string;\n /**\n * Product scope for the quota/usage record. Required — every caller must be\n * explicit about which product's meter it is touching (there is no implicit\n * default, which historically shipped as a copy-paste `'vibecontrols'`).\n */\n productId: string;\n userId?: string;\n hash?: string;\n tags?: Record<string, unknown>;\n}\n\n/** Quota/usage operation addressed by organization. */\nexport interface OrgBillingUsageOperationInput extends BillingUsageOperationInput {\n orgId: string;\n}\n\n/** Quota/usage operation addressed by workspace (org resolved internally). */\nexport interface WorkspaceBillingUsageOperationInput extends BillingUsageOperationInput {\n workspaceId: string;\n}\n\n/** Plan limit for a quota, as stored by billing-svc. */\nexport interface QuotaLimit {\n limit: number;\n noLimit: boolean;\n}\n\n/** Configuration for {@link BillingUsageClient}. */\nexport interface BillingUsageClientConfig {\n /**\n * Owning service identity (e.g. `wspace-tags-svc`). Sent as the service\n * identity header and used for log attribution.\n */\n serviceName: string;\n /** Per-request timeout in milliseconds. Defaults to 5s. */\n timeout?: number;\n /**\n * Pre-built {@link GatewayClient}. When omitted, one is created for the\n * `wspace` layer (deriving internal/cross-layer gateway URLs from env).\n * Primarily a test seam.\n */\n gatewayClient?: GatewayClient;\n /** TTL for the in-process plan-limit cache. Defaults to 5 minutes. */\n quotaLimitCacheTtlMs?: number;\n}\n\ninterface CachedQuotaLimit extends QuotaLimit {\n expiresAt: number;\n}\n\nfunction unwrap<TData>(data: TData | undefined): TData {\n if (!data) {\n throw new Error('GraphQL response did not include data');\n }\n return data;\n}\n\n/**\n * Canonical quota/usage client for wspace -> global-billing-svc traffic.\n *\n * See the module docstring for the transport contract. All methods fail open;\n * see individual method docs for the exact fallback value.\n */\nexport class BillingUsageClient {\n private readonly gatewayClient: GatewayClient;\n private readonly quotaLimitCacheTtlMs: number;\n private readonly logPrefix: string;\n\n // In-process cache for plan limits (changes at most when a workspace\n // upgrades their plan). Lazily pruned on access — no timers in a library.\n private readonly quotaLimitCache = new Map<string, CachedQuotaLimit>();\n\n constructor(config: BillingUsageClientConfig) {\n if (!config.serviceName) {\n throw new TypeError('BillingUsageClient requires a serviceName');\n }\n this.gatewayClient =\n config.gatewayClient ??\n new GatewayClient({\n layer: 'wspace',\n serviceName: config.serviceName,\n timeout: config.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS,\n });\n this.quotaLimitCacheTtlMs = config.quotaLimitCacheTtlMs ?? DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS;\n this.logPrefix = `[billing-usage:${config.serviceName}]`;\n }\n\n /**\n * Same-layer (wspace -> wspace) internal-gateway call.\n */\n private async queryWorkspaceLayer<TData>(\n query: string,\n variables: Record<string, unknown>,\n workspaceId: string\n ): Promise<TData> {\n const response = await this.gatewayClient.internalQuery<TData>({\n query,\n variables,\n headers: { 'x-workspace-id': workspaceId },\n // Blocking on the create path — keep it single-shot & snappy; consumers fail open.\n skipRetry: true,\n });\n return unwrap(response.data);\n }\n\n /**\n * Cross-layer (wspace -> global) public-gateway call. No actor headers — the\n * signed service JWT carries identity; adding `x-actor-id` would 403.\n */\n private async queryGlobalLayer<TData>(query: string, variables: Record<string, unknown>): Promise<TData> {\n const response = await this.gatewayClient.crossLayerQuery<TData>({ query, variables });\n return unwrap(response.data);\n }\n\n /**\n * Resolve the organization that owns a workspace. Fails open (`null`).\n */\n async getOrgIdFromWorkspace(workspaceId: string): Promise<string | null> {\n try {\n const data = await this.queryWorkspaceLayer<WorkspaceOrgQueryData>(\n GET_WORKSPACE_ORG_QUERY,\n { workspaceId },\n workspaceId\n );\n return data.workspace?.orgId ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve workspace org`, {\n workspaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Resolve the default billing account for an organization via the global\n * layer. Fails open (`null`).\n */\n async getDefaultBillingAccountId(orgId: string): Promise<string | null> {\n try {\n const data = await this.queryGlobalLayer<BillingAccountQueryData>(GET_DEFAULT_BILLING_ACCOUNT_QUERY, {\n orgId,\n });\n return data.getDefaultBillingAccountByOrgId?.id ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve default billing account`, {\n orgId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Check that an organization still has quota headroom for `value` units of\n * `quotaName`. Returns `false` when no billing account exists or the quota\n * is exhausted; rethrows nothing — transport errors propagate to the caller\n * of this low-level variant (the workspace variant fails open instead).\n */\n async ensureQuotaAvailableForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for org quota check`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const amount = input.value ?? 1;\n const data = await this.queryGlobalLayer<QuotaCheckQueryData>(CHECK_QUOTA_QUERY, {\n billingAccountId,\n quotaName: input.quotaName,\n productId: input.productId,\n });\n\n const result = data.checkQuotaExhausted;\n if (!result) {\n return false;\n }\n\n if (result.noLimit) {\n return true;\n }\n\n return result.limitLeft >= amount;\n }\n\n /**\n * Workspace-addressed quota gate: resolves the org, then applies\n * {@link ensureQuotaAvailableForOrg}. Fails OPEN (`true`) when org\n * resolution fails (unbilled / dev / internal workspaces) so local-stack\n * test workspaces and workspaces with a transiently broken tenant lookup\n * are never locked out; real limits only kick in when the workspace has a\n * billable org.\n */\n async ensureQuotaAvailableForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available; allowing quota op (fail-open)`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return true;\n }\n\n return this.ensureQuotaAvailableForOrg({ ...input, orgId });\n }\n\n /**\n * Record usage against an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async addUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for addUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(ADD_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.addUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link addUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async addUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace addUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.addUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Credit usage back to an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async freeUpUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for freeUpUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(FREE_UP_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.freeUpUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link freeUpUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async freeUpUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace freeUpUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.freeUpUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Fetch the plan limit for a quota from billing-svc, bypassing billing's\n * internal usage counter (the caller's own DB is the source of truth for\n * current usage; billing only stores the plan maximum). Results are cached\n * in-process per workspace/quota/product. Fails open (`null`) when billing\n * is unreachable so dev/test workspaces without billing accounts are never\n * blocked.\n */\n async getQuotaLimitForWorkspace(\n workspaceId: string,\n quotaName: string,\n productId: string\n ): Promise<QuotaLimit | null> {\n const cacheKey = `${workspaceId}:${quotaName}:${productId}`;\n const cached = this.quotaLimitCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) {\n return { limit: cached.limit, noLimit: cached.noLimit };\n }\n\n const orgId = await this.getOrgIdFromWorkspace(workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No org found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n const billingAccountId = await this.getDefaultBillingAccountId(orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n try {\n const data = await this.queryGlobalLayer<QuotaLimitQueryData>(GET_QUOTA_LIMIT_QUERY, {\n billingAccountId,\n quotaName,\n productId,\n });\n\n const result = data.getQuotaUsageAndLimit;\n if (!result) {\n return null;\n }\n\n this.rememberQuotaLimit(cacheKey, { limit: result.limit, noLimit: result.noLimit });\n return { limit: result.limit, noLimit: result.noLimit };\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to fetch quota limit; failing open`, {\n workspaceId,\n quotaName,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n private rememberQuotaLimit(cacheKey: string, value: QuotaLimit): void {\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const now = Date.now();\n for (const [key, entry] of this.quotaLimitCache) {\n if (entry.expiresAt <= now) this.quotaLimitCache.delete(key);\n }\n // Still full after pruning (all entries fresh): drop the oldest-inserted\n // entries rather than refusing to cache. Plan limits are re-fetchable.\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const overflow = this.quotaLimitCache.size - QUOTA_LIMIT_CACHE_MAX_ENTRIES + 1;\n let removed = 0;\n for (const key of this.quotaLimitCache.keys()) {\n this.quotaLimitCache.delete(key);\n removed += 1;\n if (removed >= overflow) break;\n }\n }\n }\n this.quotaLimitCache.set(cacheKey, { ...value, expiresAt: Date.now() + this.quotaLimitCacheTtlMs });\n }\n}\n","/**\n * Usage & Quota Module\n *\n * Checks and records workspace quota usage against the workspace usage owner\n * (wspace-activity-svc). The owner's published contract is:\n *\n * - `checkWorkspaceQuota(workspaceId, quotaName, amount): WorkspaceQuotaCheckResult!`\n * - `trackUsage(input: TrackUsageInput!): Boolean!`\n *\n * Quotas are keyed by `quotaName` (for example `platform.projects.created`), not by the\n * `entityId`/`entityType`/`metricType` triple this module used to send. That triple was\n * never part of the owner's schema, so every legacy call failed GraphQL validation\n * (BOFF-10955). The legacy methods remain for source compatibility and fail with\n * {@link UsageOperationUnsupportedError} before any network call.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { SDKError, ValidationError, QuotaExceededError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Legacy usage metric names. The workspace usage owner has no metric types; quotas are\n * addressed by `quotaName`. Kept so existing `sdk.tracker.track({ usage: { metricType } })`\n * call sites keep compiling; the tracker does not meter a metric type on its own.\n */\nexport enum UsageMetricType {\n API_CALLS = 'api_calls',\n STORAGE = 'storage',\n BANDWIDTH = 'bandwidth',\n USERS = 'users',\n PROJECTS = 'projects',\n WORKSPACES = 'workspaces',\n RECORDS = 'records',\n COMPUTE_TIME = 'compute_time',\n TRANSACTIONS = 'transactions',\n CUSTOM = 'custom',\n}\n\nexport enum QuotaPeriod {\n DAILY = 'daily',\n WEEKLY = 'weekly',\n MONTHLY = 'monthly',\n YEARLY = 'yearly',\n LIFETIME = 'lifetime',\n}\n\n/**\n * Entity type for usage tracking\n */\nexport type UsageEntityType = 'user' | 'workspace' | 'organization';\n\nexport interface TrackUsageOptions {\n /** User or workspace consuming the resource */\n entityId: string;\n /** Type of entity (user or workspace) */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to increment */\n amount: number;\n /** Optional resource identifier */\n resourceId?: string;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface CheckQuotaOptions {\n /** Entity to check quota for */\n entityId: string;\n /** Type of entity */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to check availability for */\n requestedAmount: number;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface QuotaCheckResult {\n allowed: boolean;\n currentUsage: number;\n quotaLimit: number;\n remainingQuota: number;\n resetAt?: string;\n period: QuotaPeriod;\n reason?: string;\n}\n\nexport interface UsageRecord {\n id: string;\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n amount: number;\n resourceId?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n recordedAt: string;\n}\n\nexport interface UsageSummary {\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n totalUsage: number;\n period: QuotaPeriod;\n periodStart: string;\n periodEnd: string;\n quotaLimit?: number;\n utilizationPercentage?: number;\n}\n\nexport interface SetQuotaOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n workspaceId?: string;\n organizationId?: string;\n}\n\nexport interface Quota {\n id: string;\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n currentUsage: number;\n resetAt: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GetUsageOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType?: UsageMetricType;\n startDate?: string;\n endDate?: string;\n workspaceId?: string;\n organizationId?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Thrown by SDK usage operations the workspace usage owner does not expose. */\nexport class UsageOperationUnsupportedError extends SDKError {\n constructor(operation: string, guidance: string) {\n super(\n `UsageModule.${operation} is not supported by the workspace usage owner: ${guidance}`,\n 'USAGE_OPERATION_UNSUPPORTED',\n { operation }\n );\n this.name = 'UsageOperationUnsupportedError';\n Object.setPrototypeOf(this, UsageOperationUnsupportedError.prototype);\n }\n}\n\n/**\n * Query sent to the owner's `checkWorkspaceQuota`. Every argument and selected field must\n * exist on the published wspace schema (see tests/usage-module.test.ts).\n */\nexport const CHECK_WORKSPACE_QUOTA_QUERY = `\n query CheckWorkspaceQuota($workspaceId: ID!, $quotaName: String!, $amount: Float) {\n checkWorkspaceQuota(workspaceId: $workspaceId, quotaName: $quotaName, amount: $amount) {\n allowed\n assignmentId\n limitLeft\n noLimit\n }\n }\n`;\n\n/** Mutation sent to the owner's `trackUsage`, which returns `Boolean!`. */\nexport const TRACK_USAGE_MUTATION = `\n mutation TrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n }\n`;\n\nexport interface CheckWorkspaceQuotaOptions {\n /** Quota to check, for example `platform.projects.created`. */\n quotaName: string;\n /** Amount the caller is about to consume. Must be positive; defaults to 1. */\n amount?: number;\n /** Workspace that owns the quota. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the check is made for. Defaults to the SDK context's actor. */\n userId?: string;\n}\n\n/** The owner's `WorkspaceQuotaCheckResult`. */\nexport interface WorkspaceQuotaCheckResult {\n /** True when the quota has enough remaining capacity for the requested amount. */\n allowed: boolean;\n /** Active assignment to charge, or null when the workspace's plan does not include the quota. */\n assignmentId: string | null;\n /** Remaining capacity after the requested amount; null when unlimited or not provisioned. */\n limitLeft: number | null;\n /** True when the quota is unlimited. */\n noLimit: boolean;\n}\n\nexport interface TrackWorkspaceUsageOptions {\n /** Quota to charge, for example `platform.projects.created`. */\n quotaName: string;\n /** Product the quota belongs to, for example `platform`. Defaults to the SDK context's product. */\n productId?: string;\n /**\n * Amount to record. A positive amount consumes quota; a negative amount releases it (for\n * example on delete). The owner only accepts negative amounts from services and super\n * admins, which is how this module relays the call. Zero is rejected.\n */\n amount: number;\n /** Human-readable reason stored on the usage record. */\n description: string;\n /** Workspace to charge. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the usage is recorded for. Defaults to the SDK context's actor. */\n userId?: string;\n /** Assignment returned by {@link UsageModule.checkWorkspaceQuota}; saves the owner a lookup. */\n quotaAssignmentId?: string;\n /** Billing account reference stored on the record. Omit for workspace quotas. */\n billingAccountId?: string;\n /**\n * Idempotency key. The owner records one charge per hash and workspace, so a retried\n * request cannot charge twice. A random key is generated per call when omitted.\n */\n hash?: string;\n /** Additional metadata stored on the usage record. */\n metadata?: Record<string, unknown>;\n}\n\nfunction legacyGuidance(replacement: string): string {\n return `quotas are addressed by quotaName on the workspace usage owner; use ${replacement}`;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Builds the owner's `TrackUsageInput` from SDK options, filling defaults from the context.\n * Throws {@link ValidationError} for input the owner would refuse.\n */\nexport function buildTrackUsageInput(\n options: TrackWorkspaceUsageOptions,\n context: SDKContext = {}\n): Record<string, unknown> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const productId = nonEmpty(options.productId) ?? nonEmpty(context.productId);\n if (!productId) {\n throw new ValidationError('Product ID is required');\n }\n const description = nonEmpty(options.description);\n if (!description) {\n throw new ValidationError('Description is required');\n }\n if (typeof options.amount !== 'number' || !Number.isFinite(options.amount) || options.amount === 0) {\n throw new ValidationError('Amount must be a finite, non-zero number');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n const input: Record<string, unknown> = {\n quotaName,\n productId,\n amount: options.amount,\n description,\n workspaceId,\n hash: nonEmpty(options.hash) ?? `sdk-usage:${randomUUID()}`,\n };\n const userId = nonEmpty(options.userId) ?? nonEmpty(context.actorId);\n if (userId) input['userId'] = userId;\n if (options.quotaAssignmentId) input['quotaAssignmentId'] = options.quotaAssignmentId;\n if (options.billingAccountId) input['billingAccountId'] = options.billingAccountId;\n if (options.metadata) input['metadata'] = options.metadata;\n return input;\n}\n\n/**\n * Usage & Quota Module\n */\nexport class UsageModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Context for one owner call: relayed as a platform service acting for `userId`, with the\n * quota's workspace in scope. The owner takes the workspace from this context, never from\n * the input, and only lets services release (decrement) usage.\n */\n private requestContext(workspaceId: string, userId: string | undefined): SDKContext {\n const actorId = userId ?? this.context.actorId;\n return {\n ...this.context,\n ...(actorId ? { actorId } : {}),\n actorType: 'service',\n workspaceId,\n };\n }\n\n /**\n * Check whether a workspace quota has capacity for `amount` (default 1).\n */\n public async checkWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const amount = options.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {\n throw new ValidationError('Quota checks need a positive amount');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(this.context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n logger.debug('[Usage] Checking workspace quota', { workspaceId, quotaName, amount });\n\n const response = await this.client.query<{ checkWorkspaceQuota: WorkspaceQuotaCheckResult }>(\n CHECK_WORKSPACE_QUOTA_QUERY,\n { workspaceId, quotaName, amount },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n const result = response.checkWorkspaceQuota;\n logger.debug('[Usage] Workspace quota check result', { workspaceId, quotaName, allowed: result.allowed });\n return result;\n }\n\n /**\n * Check a workspace quota and throw {@link QuotaExceededError} when it has no capacity.\n * Returns the check result so the caller can pass `assignmentId` to {@link trackUsage}.\n */\n public async requireWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const result = await this.checkWorkspaceQuota(options);\n if (!result.allowed) {\n const notProvisioned = result.assignmentId === null;\n throw new QuotaExceededError(\n notProvisioned ? `Quota ${options.quotaName} is not included in this workspace's plan` : 'Quota exceeded',\n {\n quotaName: options.quotaName,\n requestedAmount: options.amount ?? 1,\n limitLeft: result.limitLeft,\n notProvisioned,\n }\n );\n }\n return result;\n }\n\n /**\n * Record workspace quota usage. A negative amount releases previously recorded usage.\n * Resolves to `true` once the owner has stored (or deduplicated) the record.\n */\n public async trackUsage(options: TrackWorkspaceUsageOptions): Promise<boolean> {\n const input = buildTrackUsageInput(options, this.context);\n const workspaceId = input['workspaceId'] as string;\n\n logger.debug('[Usage] Tracking workspace usage', {\n workspaceId,\n quotaName: input['quotaName'],\n amount: input['amount'],\n });\n\n const response = await this.client.query<{ trackUsage: boolean }>(\n TRACK_USAGE_MUTATION,\n { input },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n logger.info('[Usage] Workspace usage tracked', { workspaceId, quotaName: input['quotaName'] });\n return response.trackUsage;\n }\n\n /**\n * @deprecated The workspace usage owner has no `trackUsage` record shape keyed by\n * `entityId`/`metricType`. Use {@link trackUsage} with a `quotaName`.\n */\n public async track(_options: TrackUsageOptions): Promise<UsageRecord> {\n throw new UsageOperationUnsupportedError('track', legacyGuidance('trackUsage({ quotaName, productId, amount })'));\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link checkWorkspaceQuota}.\n */\n public async checkQuota(_options: CheckQuotaOptions): Promise<QuotaCheckResult> {\n throw new UsageOperationUnsupportedError(\n 'checkQuota',\n legacyGuidance('checkWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link requireWorkspaceQuota}.\n */\n public async requireQuota(_options: CheckQuotaOptions): Promise<void> {\n throw new UsageOperationUnsupportedError(\n 'requireQuota',\n legacyGuidance('requireWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated Use {@link requireWorkspaceQuota} followed by {@link trackUsage}.\n */\n public async trackAndCheck(_options: TrackUsageOptions): Promise<{\n usage: UsageRecord;\n quotaCheck: QuotaCheckResult;\n }> {\n throw new UsageOperationUnsupportedError(\n 'trackAndCheck',\n legacyGuidance('requireWorkspaceQuota() and then trackUsage()')\n );\n }\n\n /**\n * @deprecated The owner has no `getUsage` operation; read records with the owner's\n * `getUsageRecords(filters, pagination)`.\n */\n public async getUsage(_options: GetUsageOptions): Promise<{\n records: UsageRecord[];\n total: number;\n }> {\n throw new UsageOperationUnsupportedError('getUsage', legacyGuidance(\"the owner's getUsageRecords query\"));\n }\n\n /**\n * @deprecated The owner's `getUsageSummary` takes `UsageFilters` and returns a list; this\n * signature does not map onto it.\n */\n public async getSummary(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType,\n _period: QuotaPeriod\n ): Promise<UsageSummary> {\n throw new UsageOperationUnsupportedError(\n 'getSummary',\n legacyGuidance(\"the owner's getUsageSummary(filters) query\")\n );\n }\n\n /**\n * @deprecated Quota limits are assigned by global-billing-svc through the owner's\n * `assignWorkspaceQuota`, which only billing's service identity may call.\n */\n public async setQuota(_options: SetQuotaOptions): Promise<Quota> {\n throw new UsageOperationUnsupportedError('setQuota', 'quota limits are assigned by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `getQuota` operation; read `workspaceQuotaStatuses(workspaceId)`.\n */\n public async getQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<Quota | null> {\n throw new UsageOperationUnsupportedError('getQuota', legacyGuidance(\"the owner's workspaceQuotaStatuses query\"));\n }\n\n /**\n * @deprecated The owner has no `getQuotas` operation; read `workspaceQuotaAssignments(workspaceId)`.\n */\n public async getQuotas(_entityId: string, _entityType: UsageEntityType): Promise<Quota[]> {\n throw new UsageOperationUnsupportedError(\n 'getQuotas',\n legacyGuidance(\"the owner's workspaceQuotaAssignments query\")\n );\n }\n\n /**\n * @deprecated The owner has no `resetQuota` operation; quotas reset on their `resetPeriod`.\n */\n public async resetQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('resetQuota', \"quotas reset on the assignment's resetPeriod\");\n }\n\n /**\n * @deprecated The owner has no `deleteQuota` operation; billing deactivates assignments.\n */\n public async deleteQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('deleteQuota', 'quota assignments are deactivated by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `trackUsageBulk` operation. Call {@link trackUsage} per record.\n */\n public async trackBulk(_records: TrackUsageOptions[]): Promise<UsageRecord[]> {\n throw new UsageOperationUnsupportedError('trackBulk', legacyGuidance('trackUsage() per record'));\n }\n}\n\nexport {\n BillingUsageClient,\n type BillingUsageClientConfig,\n type BillingUsageOperationInput,\n type OrgBillingUsageOperationInput,\n type WorkspaceBillingUsageOperationInput,\n type QuotaLimit,\n} from './billing.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,6BAA6B;;AAGnC,MAAM,mCAAmC;;AAGzC,MAAM,gCAAgC;AAEtC,MAAM,0BAA0B;;;;;;;AAQhC,MAAM,oCAAoC;;;;;;;AAQ1C,MAAM,oBAAoB;;;;;;;;;;;;;AAc1B,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;AAwB3B,MAAM,wBAAwB;;;;;;;;;;;;AAa9B,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;AA+G/B,SAAS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;EACvB,MAAM,IAAI,+BACR,cACA,eAAe,4CAA4C,CAC7D;CACF;;;;;CAMA,MAAa,SAAS,UAA2C;EAC/D,MAAM,IAAI,+BAA+B,YAAY,iDAAiD;CACxG;;;;CAKA,MAAa,SACX,WACA,aACA,aACuB;EACvB,MAAM,IAAI,+BAA+B,YAAY,eAAe,0CAA0C,CAAC;CACjH;;;;CAKA,MAAa,UAAU,WAAmB,aAAgD;EACxF,MAAM,IAAI,+BACR,aACA,eAAe,6CAA6C,CAC9D;CACF;;;;CAKA,MAAa,WACX,WACA,aACA,aACkB;EAClB,MAAM,IAAI,+BAA+B,cAAc,8CAA8C;CACvG;;;;CAKA,MAAa,YACX,WACA,aACA,aACkB;EAClB,MAAM,IAAI,+BAA+B,eAAe,yDAAyD;CACnH;;;;CAKA,MAAa,UAAU,UAAuD;EAC5E,MAAM,IAAI,+BAA+B,aAAa,eAAe,yBAAyB,CAAC;CACjG;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/be-sdk",
3
- "version": "2026.1110.3",
3
+ "version": "2026.1110.4",
4
4
  "description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"context-CZnXf2yb.js","names":[],"sources":["../src/context/index.ts"],"sourcesContent":["/**\n * Context Module\n * Manages request-scoped context using AsyncLocalStorage\n * Thread-safe context propagation for async operations\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { SDKContext } from '../types/index.js';\n\nconst asyncLocalStorage = new AsyncLocalStorage<SDKContext>();\n\n/**\n * Module-level fallback for the Cloudflare Access service token.\n *\n * WHY THIS EXISTS — read before \"simplifying\" it away:\n * `asyncLocalStorage.enterWith()` (used by `setContext`) does NOT reliably\n * propagate across every async boundary under Bun + GraphQL Yoga — the same\n * limitation documented for the Prisma workspace context store\n * (see `src/prisma/workspace-extension.ts`). On top of that, the `createServer`\n * request path (`src/server/context.ts` `buildContext`) populates the *Prisma*\n * workspace store, not this `ContextManager` ALS at all. So a resolver-initiated\n * cross-layer call would otherwise read an empty context and attach no CF creds,\n * making the propagation a silent no-op on alpha.\n *\n * Unlike workspaceId/actorId (which differ per request and would race in a\n * module-level singleton), the CF Access service token is effectively\n * CONSTANT per environment — it's a single service-token pair fronting the\n * gateway. So caching it module-side is race-safe: concurrent requests all\n * carry the same value. It is only ever set when a request actually presents\n * the headers (gated upstream on `cf-ray`), and stays unset in dev/prod where\n * no CF Access sits in front of the gateways.\n */\nlet cfAccessFallback: { clientId: string; clientSecret: string } | undefined;\n\n/**\n * Module-level fallback for the CF Access USER-SSO cookie (`CF_Authorization`),\n * mirroring `cfAccessFallback` for the same Bun+Yoga ALS-unreliability reason.\n * Unlike the service-token pair this is per-USER and ~1h TTL — but for passing\n * the CF edge any valid member cookie suffices (app-layer identity travels in\n * `x-actor-*`). Refreshed by every inbound CF request, so an active fleet keeps\n * a live value. See BOFF-2929.\n */\nlet cfAuthorizationFallback: string | undefined;\n\n/**\n * Context Manager for handling request-scoped context\n */\nexport class ContextManager {\n /**\n * Get current context from async local storage\n */\n public static getContext(): SDKContext | undefined {\n return asyncLocalStorage.getStore();\n }\n\n /**\n * Set context for current async scope\n * Merges with existing context if present\n */\n public static setContext(context: SDKContext): void {\n const currentContext = this.getContext() || {};\n asyncLocalStorage.enterWith({ ...currentContext, ...context });\n // Mirror CF creds to the module-level fallback so cross-layer calls can\n // recover them even when enterWith() doesn't reach the resolver chain.\n if ((context.cfAccessClientId && context.cfAccessClientSecret) || context.cfAuthorization) {\n this.setCfAccessContext(context.cfAccessClientId, context.cfAccessClientSecret, context.cfAuthorization);\n }\n }\n\n /**\n * Record the Cloudflare Access service token for the current process.\n *\n * Call this from every request-context builder that may receive CF headers\n * (the SDK `createServer` `buildContext` and the bootstrap HTTP middleware\n * both do). Stored in a module-level fallback because `enterWith()` is not a\n * reliable carrier under Bun + Yoga — see the `cfAccessFallback` note above.\n *\n * Deliberately a NO-OP when either cred is absent: `buildContext` runs on\n * every request, so clearing here on a tokenless request could wipe the value\n * a concurrent CF request just stored. The token is constant per environment,\n * so \"remember, never clear on absence\" is both safe and correct. Use\n * `clearContext()` to reset (shutdown / tests).\n */\n public static setCfAccessContext(clientId?: string, clientSecret?: string, cfAuthorization?: string): void {\n if (clientId && clientSecret) {\n cfAccessFallback = { clientId, clientSecret };\n }\n // CF Access user-SSO cookie — remember, never clear on absence (same policy\n // as the service token). Present on real alpha user requests; kept live by\n // ongoing traffic. See BOFF-2929.\n if (cfAuthorization) {\n cfAuthorizationFallback = cfAuthorization;\n }\n }\n\n /**\n * Run function with specific context\n * Context is isolated to this execution and its children\n */\n public static async withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T> {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Run synchronous function with specific context\n */\n public static withContextSync<T>(context: SDKContext, fn: () => T): T {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Clear current context (including the module-level CF Access fallback).\n */\n public static clearContext(): void {\n asyncLocalStorage.disable();\n cfAccessFallback = undefined;\n cfAuthorizationFallback = undefined;\n }\n\n /**\n * Get actor ID from context\n */\n public static getActorId(): string | undefined {\n return this.getContext()?.actorId;\n }\n\n /**\n * Get legacy user ID from context.\n */\n public static getUser(): string | undefined {\n const context = this.getContext();\n const userId = context?.['userId'];\n return typeof userId === 'string' ? userId : context?.actorId;\n }\n\n /**\n * Get workspace ID from context\n */\n public static getWorkspace(): string | undefined {\n return this.getContext()?.workspaceId;\n }\n\n /**\n * Get tenant ID from context\n */\n public static getTenant(): string | undefined {\n return this.getContext()?.tenantId;\n }\n\n /**\n * Get legacy organization ID from context.\n */\n public static getOrganization(): string | undefined {\n const organizationId = this.getContext()?.['organizationId'];\n return typeof organizationId === 'string' ? organizationId : undefined;\n }\n\n /**\n * Get project ID from context\n */\n public static getProject(): string | undefined {\n return this.getContext()?.projectId;\n }\n\n /**\n * Get app ID from context\n */\n public static getApp(): string | undefined {\n return this.getContext()?.appId;\n }\n\n /**\n * Get JWT token from context\n */\n public static getToken(): string | undefined {\n return this.getContext()?.token;\n }\n\n /**\n * Get product ID from context\n */\n public static getProduct(): string | undefined {\n return this.getContext()?.productId;\n }\n\n /**\n * Get the Cloudflare Access service-token client id (ALS first, then the\n * module-level fallback — see `cfAccessFallback`).\n */\n public static getCfAccessClientId(): string | undefined {\n return this.getContext()?.cfAccessClientId ?? cfAccessFallback?.clientId;\n }\n\n /**\n * Get the Cloudflare Access service-token client secret (ALS first, then the\n * module-level fallback — see `cfAccessFallback`).\n */\n public static getCfAccessClientSecret(): string | undefined {\n return this.getContext()?.cfAccessClientSecret ?? cfAccessFallback?.clientSecret;\n }\n\n /**\n * Get the Cloudflare Access user-SSO cookie value (`CF_Authorization`) — ALS\n * first, then the module-level fallback (see `cfAuthorizationFallback`).\n */\n public static getCfAuthorization(): string | undefined {\n return this.getContext()?.cfAuthorization ?? cfAuthorizationFallback;\n }\n\n /**\n * Build the Cloudflare Access credentials to re-present on a\n * cross-layer outbound call.\n *\n * Cross-layer calls (wspace ↔ global) traverse the peer layer's PUBLIC\n * gateway, which on alpha sits behind Cloudflare Access. Without the CF\n * service token the request is rejected at the CF edge before reaching the\n * gateway. We reuse the *inbound* request's CF creds (propagated by the\n * public gateway into request-scoped context) so the cross-layer leg passes.\n *\n * Inbound-only: sourced from the request context (AsyncLocalStorage first,\n * module-level fallback second — see `cfAccessFallback`). Returns `{}` unless\n * BOTH creds are present — so it is a no-op in environments without CF in\n * front of the gateways (local dev, and production, which is not\n * CF-Access-gated and has no CF service token).\n */\n public static getCfAccessHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n\n // Service-token pair (machine callers). Present only when a service token\n // fronted the inbound call — not on browser user requests.\n const clientId = this.getCfAccessClientId();\n const clientSecret = this.getCfAccessClientSecret();\n if (clientId && clientSecret) {\n headers['cf-access-client-id'] = clientId;\n headers['cf-access-client-secret'] = clientSecret;\n }\n\n // User-SSO cookie. On alpha a real user request carries the CF_Authorization\n // cookie rather than the service-token pair; re-present it as the cookie so\n // the peer layer's CF Access (same app / shared AUD) admits the cross-layer\n // call. See BOFF-2929.\n const cfAuthorization = this.getCfAuthorization();\n if (cfAuthorization) {\n headers['cookie'] = `CF_Authorization=${cfAuthorization}`;\n }\n\n return headers;\n }\n\n /**\n * Update specific context fields\n */\n public static updateContext(updates: Partial<SDKContext>): void {\n const current = this.getContext();\n if (current) {\n this.setContext({ ...current, ...updates });\n } else {\n this.setContext(updates);\n }\n }\n\n /**\n * Check if context exists\n */\n public static hasContext(): boolean {\n return this.getContext() !== undefined;\n }\n\n /**\n * Get custom field from context\n */\n public static getCustomField(key: string): unknown {\n return this.getContext()?.[key];\n }\n\n /**\n * Set custom field in context\n */\n public static setCustomField(key: string, value: unknown): void {\n const current = this.getContext() || {};\n this.setContext({ ...current, [key]: value });\n }\n}\n\n/**\n * Default export for convenience\n */\nexport const contextManager = ContextManager;\n\n/**\n * Helper function to extract context from HTTP request\n */\nexport function extractContextFromRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n user?: { user_id?: string; workspace_id?: string; tenant_endpoint?: string };\n}): SDKContext {\n const context: SDKContext = {};\n\n // Extract from user object (if JWT already verified)\n if (req.user) {\n context.actorId = req.user.user_id;\n context.workspaceId = req.user.workspace_id;\n context.tenantId = req.user.tenant_endpoint;\n }\n\n // Extract from headers\n const getHeader = (key: string): string | undefined => {\n const value = req.headers[key.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n };\n\n const authHeader = getHeader('authorization');\n if (authHeader) {\n context.token = authHeader.replace('Bearer ', '');\n }\n\n const workspaceId = getHeader('x-workspace-id');\n if (workspaceId && !context.workspaceId) {\n context.workspaceId = workspaceId;\n }\n\n const productId = getHeader('x-product-id');\n if (productId) {\n context.productId = productId;\n }\n\n const projectId = getHeader('x-project-id');\n if (projectId) {\n context.projectId = projectId;\n }\n\n const appId = getHeader('x-app-id');\n if (appId) {\n context.appId = appId;\n }\n\n // Cloudflare Access service token. Forwarded to subgraphs by the public\n // gateways only when the request actually transited CF (cf-ray present), so\n // we can capture whatever arrives here. Re-presented on cross-layer outbound\n // calls — see ContextManager.getCfAccessHeaders.\n const cfAccessClientId = getHeader('cf-access-client-id');\n if (cfAccessClientId) {\n context.cfAccessClientId = cfAccessClientId;\n }\n\n const cfAccessClientSecret = getHeader('cf-access-client-secret');\n if (cfAccessClientSecret) {\n context.cfAccessClientSecret = cfAccessClientSecret;\n }\n\n // CF Access user-SSO cookie, forwarded by the public gateway as\n // x-cf-authorization. Re-presented as the CF_Authorization cookie on\n // cross-layer calls (see getCfAccessHeaders). See BOFF-2929.\n const cfAuthorization = getHeader('x-cf-authorization');\n if (cfAuthorization) {\n context.cfAuthorization = cfAuthorization;\n }\n\n return context;\n}\n"],"mappings":";;;;;;;;AASA,MAAM,oBAAoB,IAAI,kBAA8B;;;;;;;;;;;;;;;;;;;;;;AAuB5D,IAAI;;;;;;;;;AAUJ,IAAI;;;;AAKJ,IAAa,iBAAb,MAA4B;;;;CAI1B,OAAc,aAAqC;EACjD,OAAO,kBAAkB,SAAS;CACpC;;;;;CAMA,OAAc,WAAW,SAA2B;EAClD,MAAM,iBAAiB,KAAK,WAAW,KAAK,CAAC;EAC7C,kBAAkB,UAAU;GAAE,GAAG;GAAgB,GAAG;EAAQ,CAAC;EAG7D,IAAK,QAAQ,oBAAoB,QAAQ,wBAAyB,QAAQ,iBACxE,KAAK,mBAAmB,QAAQ,kBAAkB,QAAQ,sBAAsB,QAAQ,eAAe;CAE3G;;;;;;;;;;;;;;;CAgBA,OAAc,mBAAmB,UAAmB,cAAuB,iBAAgC;EACzG,IAAI,YAAY,cACd,mBAAmB;GAAE;GAAU;EAAa;EAK9C,IAAI,iBACF,0BAA0B;CAE9B;;;;;CAMA,aAAoB,YAAe,SAAqB,IAAkC;EACxF,OAAO,kBAAkB,IAAI,SAAS,EAAE;CAC1C;;;;CAK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,eAAe,KAAK,wBAAwB;EAClD,IAAI,YAAY,cAAc;GAC5B,QAAQ,yBAAyB;GACjC,QAAQ,6BAA6B;EACvC;EAMA,MAAM,kBAAkB,KAAK,mBAAmB;EAChD,IAAI,iBACF,QAAQ,YAAY,oBAAoB;EAG1C,OAAO;CACT;;;;CAKA,OAAc,cAAc,SAAoC;EAC9D,MAAM,UAAU,KAAK,WAAW;EAChC,IAAI,SACF,KAAK,WAAW;GAAE,GAAG;GAAS,GAAG;EAAQ,CAAC;OAE1C,KAAK,WAAW,OAAO;CAE3B;;;;CAKA,OAAc,aAAsB;EAClC,OAAO,KAAK,WAAW,MAAM;CAC/B;;;;CAKA,OAAc,eAAe,KAAsB;EACjD,OAAO,KAAK,WAAW,CAAC,GAAG;CAC7B;;;;CAKA,OAAc,eAAe,KAAa,OAAsB;EAC9D,MAAM,UAAU,KAAK,WAAW,KAAK,CAAC;EACtC,KAAK,WAAW;GAAE,GAAG;IAAU,MAAM;EAAM,CAAC;CAC9C;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"stub-BqwKn4eh.js","names":[],"sources":["../src/activity/explicit-activity-scope.ts","../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"sourcesContent":["/**\n * Explicit-activity scope\n *\n * Lets the mutation-audit backstop (`createMutationAuditPlugin` in\n * `@burdenoff/be-sdk/server`) know whether a GraphQL operation already wrote an\n * activity row through an explicit call (`trackOperation`, `trackerStub.track`,\n * `ActivityModule.log`, or a service's own `logAudit` wrapper over them). When it\n * did, the backstop skips its generic `graphql.mutation` row so the activity feed\n * never carries two rows for one mutation.\n *\n * The scope is entered with `AsyncLocalStorage.run()` around the operation's\n * execute function. `run()` (unlike `enterWith()`) propagates through every\n * promise continuation started inside it, including fire-and-forget calls made\n * by resolvers, so concurrent requests never see each other's marks.\n *\n * Outside a scope (background jobs, event consumers, REST handlers) every\n * function here is a no-op.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/** Per-operation record of explicit activity writes. */\nexport interface ExplicitActivityScope {\n /** Number of explicit activity writes made while the operation executed. */\n explicitCount: number;\n /** True once `suppressMutationAudit()` was called for this operation. */\n suppressed: boolean;\n}\n\nconst scopeStorage = new AsyncLocalStorage<ExplicitActivityScope>();\n\n/** Create a fresh, unmarked scope. */\nexport function createExplicitActivityScope(): ExplicitActivityScope {\n return { explicitCount: 0, suppressed: false };\n}\n\n/** Run `fn` with `scope` as the active explicit-activity scope. */\nexport function runInExplicitActivityScope<T>(scope: ExplicitActivityScope, fn: () => T): T {\n return scopeStorage.run(scope, fn);\n}\n\n/** The active scope, or undefined outside a GraphQL operation that mounts the backstop. */\nexport function getExplicitActivityScope(): ExplicitActivityScope | undefined {\n return scopeStorage.getStore();\n}\n\n/**\n * Record that an explicit activity write happened in the current operation.\n * Called by the SDK's own activity writers; services never need to call it.\n */\nexport function markExplicitActivity(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.explicitCount += 1;\n}\n\n/**\n * Tell the mutation-audit backstop not to write its generic row for the current\n * operation.\n *\n * Use it in a resolver whose audit trail goes through a path the SDK cannot see\n * (for example a direct call to the activity subgraph), or for a mutation that\n * must deliberately leave no activity row. Has no effect outside an operation\n * that mounts the backstop.\n */\nexport function suppressMutationAudit(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.suppressed = true;\n}\n","/**\n * Assistant-session attribution (BOFF-9649)\n *\n * When an AI assistant session runs a GraphQL mutation for its owner, the\n * assistant session relay (wspace-sandbox-svc) forwards it to a public gateway\n * as the owner, with a signed assistant-session marker. The gateway verifies\n * that marker against the owner's verified token, strips any copy a client\n * sent, and passes the result to subgraphs as three headers:\n *\n * x-actor-origin: ai_assistant\n * x-assistant-session-id: <the relay session id (the assistant sandbox id)>\n * x-assistant-correlation-id: <the proposal / idempotency key, when there is one>\n *\n * A service never verifies these itself. `buildContext` reads them only when it\n * already trusts the gateway's actor headers, exposes them as\n * `context.assistantSession`, and binds them to the operation's workspace\n * context so `trackOperation` can stamp every activity row written while the\n * operation runs, without each service re-implementing audit.\n *\n * Values outside the vocabulary or the id pattern are dropped, never coerced:\n * a wrong attribution is worse than none.\n */\n\n/** The only actor origin the platform records today. */\nexport const AI_ASSISTANT_ACTOR_ORIGIN = 'ai_assistant';\n\nexport type ActorOrigin = typeof AI_ASSISTANT_ACTOR_ORIGIN;\n\n/** Gateway-to-subgraph headers. Clients cannot set them: the public gateways strip them. */\nexport const ACTOR_ORIGIN_HEADER = 'x-actor-origin';\nexport const ASSISTANT_SESSION_ID_HEADER = 'x-assistant-session-id';\nexport const ASSISTANT_CORRELATION_ID_HEADER = 'x-assistant-correlation-id';\n\n/** Session ids (UUIDs, cuid-style ids) and proposal / idempotency keys. */\nconst ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The assistant session an operation ran under. */\nexport interface AssistantSessionAttribution {\n actorOrigin: ActorOrigin;\n /** The relay session id: the assistant sandbox that ran the mutation. */\n assistantSessionId: string;\n /** The proposal / idempotency key the mutation ran under, when it had one. */\n assistantCorrelationId?: string;\n}\n\nfunction attributionId(value: unknown): string | undefined {\n return typeof value === 'string' && ATTRIBUTION_ID_PATTERN.test(value) ? value : undefined;\n}\n\n/**\n * Build an attribution from raw values. Undefined unless the origin is\n * `ai_assistant` and the session id is well formed; a malformed correlation id\n * is dropped on its own.\n */\nexport function toAssistantSessionAttribution(\n actorOrigin: unknown,\n assistantSessionId: unknown,\n assistantCorrelationId?: unknown\n): AssistantSessionAttribution | undefined {\n if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return undefined;\n const sessionId = attributionId(assistantSessionId);\n if (!sessionId) return undefined;\n const correlationId = attributionId(assistantCorrelationId);\n return {\n actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,\n assistantSessionId: sessionId,\n ...(correlationId ? { assistantCorrelationId: correlationId } : {}),\n };\n}\n\n/**\n * Read the gateway's assistant-session headers. The caller decides whether the\n * request's gateway headers are trusted at all; this only parses them.\n */\nexport function parseAssistantSessionHeaders(\n getHeader: (name: string) => string | null | undefined\n): AssistantSessionAttribution | undefined {\n return toAssistantSessionAttribution(\n getHeader(ACTOR_ORIGIN_HEADER),\n getHeader(ASSISTANT_SESSION_ID_HEADER),\n getHeader(ASSISTANT_CORRELATION_ID_HEADER)\n );\n}\n\n/** Re-validate an attribution-shaped value (from a request context or caller options). */\nexport function readAssistantSessionAttribution(value: unknown): AssistantSessionAttribution | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n return toAssistantSessionAttribution(\n record['actorOrigin'],\n record['assistantSessionId'],\n record['assistantCorrelationId']\n );\n}\n","/**\n * Unified Tracking — Auto-Promoting Implementation\n *\n * Automatically promotes from stub to real tracking when gateway URLs are configured.\n * When WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL is set, this module will:\n * - Log activity events via GraphQL to the activity service\n * - Track usage via GraphQL to the usage service (if usage options provided)\n * - RBAC checks are NOT performed here (handled by gateway @rbac directives)\n *\n * When no gateway URL is configured, falls back to debug-level logging (stub mode).\n *\n * This is a backward-compatible drop-in replacement for the original stub. All 1,100+\n * existing call sites continue to work without modification.\n *\n * @module tracker/stub\n * @category Tracking\n */\nimport { randomUUID } from 'node:crypto';\n\nimport { logger } from '../logger/index.js';\nimport { markExplicitActivity } from '../activity/explicit-activity-scope.js';\nimport { readAssistantSessionAttribution, type AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { getScopedWorkspaceContext, getWorkspaceContext } from '../prisma/workspace-extension.js';\n\n/**\n * Tracking event interface\n */\nexport interface TrackingEvent {\n eventType: string;\n entityType: string;\n entityId: string;\n userId?: string;\n workspaceId?: string;\n metadata?: Record<string, unknown>;\n timestamp?: Date;\n}\n\n/**\n * RBAC check options\n */\nexport interface RbacCheckOptions {\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n skipRbacCheck?: boolean;\n options?: {\n allowOwnerAccess?: boolean;\n allowWorkspaceAdmin?: boolean;\n scope?: string;\n };\n}\n\n/**\n * Usage tracking options\n */\nexport interface UsageTrackingOptions {\n billingAccountId?: string;\n addUsage?: boolean;\n description?: string;\n tags?: Record<string, unknown>;\n quotaName?: string;\n value?: number;\n}\n\n/**\n * Activity tracking options\n */\nexport interface ActivityTrackingOptions {\n activityType?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n teamId?: string;\n groupId?: string;\n projectId?: string;\n targetUserId?: string;\n resourceType?: string;\n resourceId?: string;\n enabled?: boolean;\n /**\n * Idempotency key forwarded to the activity owner's `RecordActivityInput.dedupeKey`.\n * When omitted, a unique key is generated per tracked operation so that delivery retries of the\n * SAME operation converge to exactly one activity row. Supply a stable key only when the caller\n * itself may replay the same logical event (backfill/import).\n */\n dedupeKey?: string;\n}\n\n/**\n * Kind of actor behind a tracked operation — the gateway `x-actor-type` vocabulary.\n *\n * An AI agent acting through a product service is an `app` actor; recording it lets the\n * activity owner tell agent actions apart from human ones (BOFF-9684).\n */\nexport type TrackedActorType = 'user' | 'app' | 'service' | 'super_admin';\n\nconst TRACKED_ACTOR_TYPES: ReadonlySet<string> = new Set<TrackedActorType>(['user', 'app', 'service', 'super_admin']);\n\nexport function isTrackedActorType(value: unknown): value is TrackedActorType {\n return typeof value === 'string' && TRACKED_ACTOR_TYPES.has(value);\n}\n\n/**\n * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\n /**\n * Kind of actor `userId` identifies. When omitted it is taken from `context` (`actor.type` or\n * `actorType`) or, with no `context`, from the ambient be-sdk workspace context; a value outside\n * the vocabulary is dropped rather than sent. The activity owner honours it because the tracker\n * calls it as a relaying `service`.\n */\n actorType?: TrackedActorType;\n /**\n * The user on whose behalf `userId` acted — for an AI-agent action, the human who started the\n * run. When omitted it is taken from `context.onBehalfOf`; the activity owner otherwise records\n * the actor itself.\n */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation ran under (BOFF-9649). When omitted it is taken from\n * `context.assistantSession` or, failing that, from the operation's own async scope (never from\n * another request's). Sent to global-activity-svc as `actorOrigin` / `assistantSessionId` /\n * `assistantCorrelationId`.\n */\n assistantSession?: AssistantSessionAttribution;\n context?: unknown;\n rbacCheck?: RbacCheckOptions;\n activityOptions?: ActivityTrackingOptions;\n usageOptions?: UsageTrackingOptions & { enabled?: boolean };\n success?: boolean;\n errorMessage?: string;\n productId?: string;\n // Legacy properties for backward compatibility (can be at top level or in nested objects)\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n tenantId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway URL resolution — cached at module level for performance\n// ---------------------------------------------------------------------------\n\nlet _gatewayUrl: string | undefined;\nlet _gatewayLayer: ActivityLayer | undefined;\nlet _gatewayUrlResolved = false;\n\n/**\n * Which activity subgraph the resolved gateway fronts.\n *\n * The two canonical activity owners accept DIFFERENT `RecordActivityInput` shapes, so the\n * payload must be built per layer:\n * - `wspace` → wspace-activity-svc: requires `action`; carries workspace-scoped fields\n * (workspaceId/teamId/targetUserId/productId/success).\n * - `global` → global-activity-svc: requires `action` AND `resource`; carries tenant-scoped\n * fields (tenantId/actorId/ipAddress/userAgent).\n * Sending one layer's shape to the other fails GraphQL validation.\n */\nexport type ActivityLayer = 'wspace' | 'global';\n\n/**\n * The layer the running service belongs to, when its environment says so: `SERVICE_LAYER`, then a\n * `global-` / `wspace-` `SERVICE_NAME` prefix (the same rule the RBAC directive and the Temporal\n * client use). Undefined when neither says.\n */\nfunction declaredServiceLayer(): ActivityLayer | undefined {\n const layer = process.env['SERVICE_LAYER'];\n if (layer === 'global' || layer === 'wspace') return layer;\n const name = process.env['SERVICE_NAME'] ?? '';\n if (name.startsWith('global-')) return 'global';\n if (name.startsWith('wspace-')) return 'wspace';\n return undefined;\n}\n\n/**\n * Resolve the internal gateway URL from environment.\n *\n * Activity belongs to the service's OWN layer: workspace services record in wspace-activity-svc\n * through WSPACE_INT_GATEWAY_URL, global services in global-activity-svc through\n * GLOBAL_INT_GATEWAY_URL. Global services also hold WSPACE_INT_GATEWAY_URL for cross-layer\n * calls, so the URL that happens to be set is not a layer signal: the declared layer\n * (`SERVICE_LAYER` / `SERVICE_NAME`) decides, and only an undeclared service falls back to\n * \"workspace URL first\" (BOFF-9649 — every global service was sending its audit rows to the\n * workspace activity owner, which rejected them). Undefined (stub mode) when no URL is set.\n */\nfunction getGatewayUrl(): string | undefined {\n if (!_gatewayUrlResolved) {\n const wspaceUrl = process.env['WSPACE_INT_GATEWAY_URL'];\n const globalUrl = process.env['GLOBAL_INT_GATEWAY_URL'];\n const declared = declaredServiceLayer();\n\n // A declared global service uses its own owner; anything else keeps \"workspace URL first\".\n const useGlobal = Boolean(globalUrl) && (declared === 'global' || !wspaceUrl);\n if (useGlobal) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n }\n if (declared && _gatewayLayer && declared !== _gatewayLayer) {\n logger.warn(\n `[trackOperation] ${declared} service has no ${declared === 'global' ? 'GLOBAL' : 'WSPACE'}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`\n );\n }\n _gatewayUrlResolved = true;\n\n if (_gatewayUrl) {\n logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);\n } else {\n logger.debug('[trackOperation] No gateway URL configured — running in stub mode');\n }\n }\n return _gatewayUrl;\n}\n\n/**\n * Resolve which activity layer the configured gateway fronts.\n * Always call `getGatewayUrl()` first — it performs the resolution.\n */\nfunction getGatewayLayer(): ActivityLayer {\n // Default to 'wspace': the overwhelming majority of services are workspace-layer, and a wspace\n // payload omits only optional global fields, so a mis-detection degrades rather than fails.\n return _gatewayLayer ?? 'wspace';\n}\n\n/**\n * Reset the cached gateway resolution. Test-only seam — module-level caching would otherwise make\n * per-layer behaviour untestable within a single process.\n */\nexport function __resetGatewayCacheForTests(): void {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n _gatewayUrlResolved = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fire-and-forget GraphQL helper\n// ---------------------------------------------------------------------------\n\nconst LOG_ACTIVITY_MUTATION = /* GraphQL */ `\n mutation RecordActivity($input: RecordActivityInput!) {\n recordActivity(input: $input) {\n id\n }\n }\n`;\n\n/**\n * Derive the `resource` value required by global-activity-svc.\n *\n * Prefers an explicit resourceType; otherwise falls back to the leading dotted segment of the\n * operation name (`auth.session.revoke` → `auth`), which matches the platform's\n * `<domain>.<resource>.<verb>` activity taxonomy. Never returns empty — `resource` is non-nullable\n * on global-activity-svc and an empty string would be silently useless in the audit trail.\n */\nfunction deriveResource(options: UnifiedTrackingOptions): string {\n const explicit = options.activityOptions?.resourceType ?? options.resourceType;\n if (explicit && explicit.trim().length > 0) return explicit;\n\n const op = options.operationName;\n if (op && op.trim().length > 0) {\n const [head] = op.split('.');\n if (head && head.trim().length > 0) return head;\n }\n return 'unknown';\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/**\n * Resolve the kind of actor behind a tracked operation. Exported for unit tests.\n *\n * Precedence: the explicit `actorType` option, then the request `context` the caller passed\n * (`actor.type`, then the flat `actorType`), then the ambient be-sdk workspace context. A request\n * context is authoritative once given: an unknown kind there yields undefined rather than falling\n * through to the ambient context, which could belong to a different request in the same async\n * chain. A wrong attribution is worse than none.\n */\nexport function resolveTrackedActorType(options: UnifiedTrackingOptions): TrackedActorType | undefined {\n if (options.actorType !== undefined) {\n return isTrackedActorType(options.actorType) ? options.actorType : undefined;\n }\n const context = readRecord(options.context);\n if (context) {\n const actor = readRecord(context['actor']);\n const fromContext = actor?.['type'] ?? context['actorType'];\n return isTrackedActorType(fromContext) ? fromContext : undefined;\n }\n const ambient = getWorkspaceContext()?.actorType;\n return isTrackedActorType(ambient) ? ambient : undefined;\n}\n\nfunction resolveOnBehalfOf(options: UnifiedTrackingOptions): string | undefined {\n if (options.onBehalfOf) return options.onBehalfOf;\n const fromContext = readRecord(options.context)?.['onBehalfOf'];\n return typeof fromContext === 'string' && fromContext.length > 0 ? fromContext : undefined;\n}\n\n/**\n * Resolve the assistant session behind a tracked operation (BOFF-9649). Exported for unit tests.\n *\n * Precedence: the explicit `assistantSession` option, then `context.assistantSession`, then the\n * workspace context bound to the operation's own async scope. The module-level fallback context is\n * never read: it belongs to whichever request built its context last, and tagging a human's row\n * as AI-originated (or the reverse) is worse than leaving it untagged.\n */\nexport function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined {\n if (options.assistantSession !== undefined) return readAssistantSessionAttribution(options.assistantSession);\n const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.['assistantSession']);\n if (fromContext) return fromContext;\n return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);\n}\n\n/**\n * Input fields an older activity owner may not define yet: wspace-activity-svc before BOFF-9684\n * (`actorType`, `onBehalfOf`), global-activity-svc before BOFF-9649 (assistant-session fields).\n */\nconst ATTRIBUTION_FIELDS = [\n 'actorType',\n 'onBehalfOf',\n 'actorOrigin',\n 'assistantSessionId',\n 'assistantCorrelationId',\n] as const;\n\n/**\n * True when the activity owner rejected the write only because it predates the attribution\n * fields (`Field \"actorType\" is not defined by type \"RecordActivityInput\"`).\n */\nfunction isUnknownAttributionFieldRejection(detail: string): boolean {\n return ATTRIBUTION_FIELDS.some(\n (field) => detail.includes(`\"${field}\"`) && /not defined|unknown field|is not defined by type/i.test(detail)\n );\n}\n\n/**\n * Build the layer-appropriate `RecordActivityInput`.\n *\n * Exported for unit testing: the whole class of defect this guards against is a payload that is\n * structurally plausible but rejected by the owning subgraph, which — because delivery is\n * fire-and-forget — is invisible at runtime.\n */\nexport function buildActivityInput(options: UnifiedTrackingOptions, layer: ActivityLayer): Record<string, unknown> {\n const actOpts = options.activityOptions;\n\n // `action` is REQUIRED by both layers. It is the field that was previously sent as the\n // (non-existent) `activityType`, which made every audit write fail validation.\n const action = actOpts?.activityType ?? options.action ?? options.operationName ?? 'unknown';\n\n const description = actOpts?.description ?? `${options.operationName ?? 'operation'} executed`;\n const resourceType = actOpts?.resourceType ?? options.resourceType;\n const resourceId = actOpts?.resourceId ?? options.resourceId;\n const workspaceId = actOpts?.workspaceId ?? options.workspaceId;\n\n const metadata: Record<string, unknown> = {\n ...actOpts?.metadata,\n success: options.success ?? true,\n ...(options.operationName ? { operationName: options.operationName } : {}),\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n };\n\n const assistantSession = layer === 'global' ? resolveAssistantSession(options) : undefined;\n\n const input: Record<string, unknown> =\n layer === 'global'\n ? {\n action,\n // Required (non-nullable) on global-activity-svc.\n resource: deriveResource(options),\n description,\n resourceType,\n resourceId,\n userId: options.userId,\n actorId: options.userId,\n tenantId: options.tenantId,\n workspaceId,\n metadata,\n // AI-originated change (BOFF-9649): which assistant session made it.\n actorOrigin: assistantSession?.actorOrigin,\n assistantSessionId: assistantSession?.assistantSessionId,\n assistantCorrelationId: assistantSession?.assistantCorrelationId,\n }\n : {\n action,\n description,\n resourceType,\n resourceId,\n workspaceId,\n targetUserId: actOpts?.targetUserId,\n teamId: actOpts?.teamId,\n productId: options.productId,\n success: options.success ?? true,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n metadata: { ...metadata, userId: options.userId },\n // Who acted (BOFF-9684). wspace-activity-svc only; global-activity-svc has no such fields.\n actorType: resolveTrackedActorType(options),\n onBehalfOf: resolveOnBehalfOf(options),\n };\n\n // Both activity owners accept `dedupeKey` and return the existing row when it is replayed, which\n // is what makes delivery retries safe (a timed-out attempt may still have committed).\n input['dedupeKey'] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;\n\n return input;\n}\n\n/**\n * Delivery policy for activity writes.\n *\n * A single attempt silently lost audit records whenever the internal gateway or the activity\n * subgraph was briefly unavailable (e.g. during a single-replica rolling deploy): the write timed\n * out, was logged at warn level, and the attributed activity never existed. Writes now retry\n * transient failures with backoff. Retrying is idempotent because every input carries a\n * `dedupeKey` (see {@link buildActivityInput}).\n */\nconst ACTIVITY_ATTEMPT_TIMEOUT_MS = 5000;\nconst DEFAULT_ACTIVITY_RETRY_DELAYS_MS: readonly number[] = [1000, 3000, 8000];\nlet activityRetryDelaysMs: readonly number[] = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n\n/** HTTP statuses that mean \"the request may not have been processed — try again\". */\nconst RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);\n\n/**\n * GraphQL error codes that describe an unavailable dependency rather than a rejected payload.\n * The internal gateways mask an unreachable subgraph as INTERNAL_SERVER_ERROR, and surface request\n * validation failures as BAD_USER_INPUT (or with no code at all from graphql-js), so a payload the\n * owner rejects is never retried.\n */\nconst RETRYABLE_GRAPHQL_CODES = new Set([\n 'INTERNAL_SERVER_ERROR',\n 'SERVICE_UNAVAILABLE',\n 'AUTH_SERVICE_UNAVAILABLE',\n 'DOWNSTREAM_SERVICE_ERROR',\n 'GATEWAY_TIMEOUT',\n]);\n\n/**\n * Override the retry backoff schedule. Test-only seam so retry behaviour can be exercised without\n * real sleeps; pass `undefined` to restore the default schedule.\n */\nexport function __setActivityRetryDelaysForTests(delaysMs: readonly number[] | undefined): void {\n activityRetryDelaysMs = delaysMs ?? DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n}\n\ntype GraphQLErrorBody = { errors?: Array<{ message?: string; extensions?: { code?: unknown } }> };\n\ntype AttemptOutcome =\n { kind: 'delivered' } | { kind: 'rejected'; detail: string } | { kind: 'transient'; detail: string };\n\nfunction classifyGraphQLErrors(errors: NonNullable<GraphQLErrorBody['errors']>): AttemptOutcome {\n const detail = errors\n .map((e) => e?.message ?? 'unknown error')\n .join('; ')\n .slice(0, 500);\n const transient = errors.every((e) => {\n const code = e?.extensions?.code;\n return typeof code === 'string' && RETRYABLE_GRAPHQL_CODES.has(code);\n });\n return transient ? { kind: 'transient', detail } : { kind: 'rejected', detail };\n}\n\nasync function attemptActivityDelivery(\n gatewayUrl: string,\n headers: Record<string, string>,\n body: string\n): Promise<AttemptOutcome> {\n try {\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS), // never block the caller for long\n });\n\n if (!response.ok) {\n const detail = `HTTP ${response.status}`;\n return RETRYABLE_HTTP_STATUSES.has(response.status)\n ? { kind: 'transient', detail }\n : { kind: 'rejected', detail };\n }\n\n // A GraphQL validation/execution failure is returned as HTTP 200 with an `errors` array.\n // Without this check a malformed payload is indistinguishable from a successful write, which\n // is exactly how a fleet-wide audit outage stayed invisible: every call \"succeeded\" at the\n // HTTP layer while the subgraph rejected the input.\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const errors = parsed?.errors;\n if (errors && errors.length > 0) {\n return classifyGraphQLErrors(errors);\n }\n return { kind: 'delivered' };\n } catch (err) {\n // Network failure or per-attempt timeout: the write may or may not have landed; the dedupeKey\n // makes a retry safe either way.\n return { kind: 'transient', detail: (err as Error).message };\n }\n}\n\n/**\n * Fire-and-forget activity log via GraphQL, retrying transient failures.\n * Never throws — logs errors and continues.\n */\nasync function fireActivityLog(\n gatewayUrl: string,\n options: UnifiedTrackingOptions,\n layer: ActivityLayer\n): Promise<void> {\n try {\n const actOpts = options.activityOptions;\n const input = buildActivityInput(options, layer);\n\n // Strip undefined values\n for (const key of Object.keys(input)) {\n if (input[key] === undefined) delete input[key];\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Forward actor context if available\n if (options.userId) {\n headers['x-actor-id'] = options.userId;\n headers['x-actor-type'] = 'service';\n }\n if (options.workspaceId ?? actOpts?.workspaceId) {\n headers['x-workspace-id'] = (options.workspaceId ?? actOpts?.workspaceId) as string;\n }\n\n const operation = options.operationName ?? 'operation';\n // Serialize once, outside the retry loop: a payload JSON cannot encode (bigint, cycles) is a\n // deterministic failure and must not be retried as if it were a network error.\n let body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\n let attributionStripped = false;\n const maxAttempts = activityRetryDelaysMs.length + 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await attemptActivityDelivery(gatewayUrl, headers, body);\n if (outcome.kind === 'delivered') {\n if (attempt > 1) {\n logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);\n }\n return;\n }\n if (\n outcome.kind === 'rejected' &&\n !attributionStripped &&\n ATTRIBUTION_FIELDS.some((field) => field in input) &&\n isUnknownAttributionFieldRejection(outcome.detail)\n ) {\n // The owner predates the attribution fields (rollout skew). Losing the audit row would\n // be worse than losing who-acted on it, so resend once without them.\n attributionStripped = true;\n const stripped = { ...input };\n for (const field of ATTRIBUTION_FIELDS) delete stripped[field];\n body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input: stripped } });\n logger.warn(\n `[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending \"${operation}\" without them`\n );\n attempt -= 1;\n continue;\n }\n if (outcome.kind === 'rejected') {\n logger.error(\n `[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n const delay = activityRetryDelaysMs[attempt - 1];\n if (delay === undefined) {\n // An audit record is about to be lost: this must be visible at error level.\n logger.error(\n `[trackOperation] Activity log failed after ${attempt} attempts for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n logger.warn(\n `[trackOperation] Activity log attempt ${attempt} failed for \"${operation}\" (${outcome.detail}); retrying in ${delay}ms`\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (err) {\n // Fire-and-forget: log but never throw\n logger.warn(`[trackOperation] Activity log failed: ${(err as Error).message}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main trackOperation function\n// ---------------------------------------------------------------------------\n\n/**\n * Simple tracker class with auto-promoting behavior\n */\nexport class UnifiedTrackerStub {\n private static instance: UnifiedTrackerStub;\n\n static getInstance(): UnifiedTrackerStub {\n if (!UnifiedTrackerStub.instance) {\n UnifiedTrackerStub.instance = new UnifiedTrackerStub();\n }\n return UnifiedTrackerStub.instance;\n }\n\n async track(event: TrackingEvent): Promise<void> {\n markExplicitActivity();\n const gatewayUrl = getGatewayUrl();\n if (gatewayUrl) {\n await fireActivityLog(\n gatewayUrl,\n {\n operationName: event.eventType,\n userId: event.userId,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n activityOptions: {\n activityType: event.eventType,\n metadata: event.metadata,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n enabled: true,\n },\n },\n getGatewayLayer()\n );\n } else {\n logger.debug('[UnifiedTracker:Stub]', event.eventType, event.entityType, event.entityId);\n }\n }\n\n async trackBatch(events: TrackingEvent[]): Promise<void> {\n for (const event of events) {\n await this.track(event);\n }\n }\n}\n\nexport const trackerStub = UnifiedTrackerStub.getInstance();\n\n/**\n * Unified tracking function — auto-promoting\n *\n * When a gateway URL is configured (WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL),\n * this function makes real fire-and-forget GraphQL calls for activity logging.\n * When no gateway URL is configured, it falls back to debug-level logging (stub mode).\n *\n * RBAC checks are NOT performed here — they are handled by gateway @rbac directives.\n * The rbacCheck option is accepted for interface compatibility but not enforced.\n *\n * @param options - Tracking options\n * @returns Always returns true (never blocks the calling operation)\n */\nexport async function trackOperation(options: UnifiedTrackingOptions): Promise<boolean> {\n const { operationName, userId, success = true } = options;\n const gatewayUrl = getGatewayUrl();\n const activityEnabled = options.activityOptions?.enabled !== false;\n\n // An explicit activity write: the mutation-audit backstop must not add a second row for this\n // operation. Marked in stub mode too, so dedupe behaves the same locally as when deployed.\n if (activityEnabled) markExplicitActivity();\n\n if (!gatewayUrl) {\n // Stub mode — debug log only\n logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);\n return true;\n }\n\n // Real mode — fire-and-forget activity logging\n if (activityEnabled) {\n // Do NOT await — fire and forget so we never block the caller\n void fireActivityLog(gatewayUrl, options, getGatewayLayer());\n } else {\n logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);\n }\n\n return true;\n}\n\n/**\n * Product tracker type definition\n */\nexport type ProductTracker = {\n track: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n freeUp: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackActivityOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackUsageOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackCustom: (operationName: string, additionalOptions: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n productId: string;\n userId: string;\n billingAccountId: string | undefined;\n defaultContext: Partial<UnifiedTrackingOptions> | undefined;\n};\n\n/**\n * Create a product-scoped tracker (auto-promoting implementation)\n *\n * @param productId - Product identifier\n * @param userId - User identifier\n * @param billingAccountId - Optional billing account ID\n * @param defaultContext - Optional default tracking context\n * @returns Product tracker instance\n */\nexport function createProductTracker(\n productId: string,\n userId: string,\n billingAccountId?: string,\n defaultContext?: Partial<UnifiedTrackingOptions>\n): ProductTracker {\n return {\n async track(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n async freeUp(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: {\n ...defaultContext?.activityOptions,\n ...additionalOptions?.activityOptions,\n activityType: 'free_up',\n },\n });\n },\n async trackActivityOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { ...defaultContext?.activityOptions, ...additionalOptions?.activityOptions, enabled: true },\n usageOptions: { enabled: false },\n });\n },\n async trackUsageOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { enabled: false },\n usageOptions: { ...defaultContext?.usageOptions, ...additionalOptions?.usageOptions, enabled: true },\n });\n },\n async trackCustom(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n productId,\n userId,\n billingAccountId,\n defaultContext,\n };\n}\n\n/**\n * Constants for tracking\n */\nexport const UNIFIED_TRACKER_CONSTANTS = {\n DEFAULT_PRODUCT_ID: 'module',\n OPERATIONS: {} as const,\n PRODUCTS: {} as const,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAAe,IAAI,kBAAyC;;AAGlE,SAAgB,8BAAqD;CACnE,OAAO;EAAE,eAAe;EAAG,YAAY;CAAM;AAC/C;;AAGA,SAAgB,2BAA8B,OAA8B,IAAgB;CAC1F,OAAO,aAAa,IAAI,OAAO,EAAE;AACnC;;;;;AAWA,SAAgB,uBAA6B;CAC3C,MAAM,QAAQ,aAAa,SAAS;CACpC,IAAI,OAAO,MAAM,iBAAiB;AACpC;;;;;;;;;;AAWA,SAAgB,wBAA8B;CAC5C,MAAM,QAAQ,aAAa,SAAS;CACpC,IAAI,OAAO,MAAM,aAAa;AAChC;;;;;;;;;;;;;;;;;;;;;;;;;;AC3CA,MAAa,4BAA4B;;AAKzC,MAAa,sBAAsB;AACnC,MAAa,8BAA8B;AAC3C,MAAa,kCAAkC;;AAG/C,MAAM,yBAAyB;AAW/B,SAAS,cAAc,OAAoC;CACzD,OAAO,OAAO,UAAU,YAAY,uBAAuB,KAAK,KAAK,IAAI,QAAQ;AACnF;;;;;;AAOA,SAAgB,8BACd,aACA,oBACA,wBACyC;CACzC,IAAI,gCAA2C,OAAO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