@burdenoff/be-sdk 2026.1111.1 → 2026.1113.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/activity/index.d.ts +2 -2
  2. package/dist/ai-credits/index.d.ts +1 -1
  3. package/dist/auth/index.d.ts +1 -1
  4. package/dist/bootstrap/index.d.ts +1 -1
  5. package/dist/bun-runtime-metrics-CPy5D6NT.js +58 -0
  6. package/dist/bun-runtime-metrics-CPy5D6NT.js.map +1 -0
  7. package/dist/cache/index.d.ts +1 -1
  8. package/dist/context/index.d.ts +1 -1
  9. package/dist/event-queue/index.d.ts +1 -1
  10. package/dist/export/index.d.ts +1 -1
  11. package/dist/export/index.js +1 -1
  12. package/dist/{export-DJXE3Osa.js → export-lqKewsuF.js} +2 -2
  13. package/dist/{export-DJXE3Osa.js.map → export-lqKewsuF.js.map} +1 -1
  14. package/dist/files/index.d.ts +1 -1
  15. package/dist/gateway/index.d.ts +3 -3
  16. package/dist/gateway/index.js +2 -2
  17. package/dist/gateway-2en8Gx_a.js +274 -0
  18. package/dist/gateway-2en8Gx_a.js.map +1 -0
  19. package/dist/graph/index.d.ts +1 -1
  20. package/dist/{graphql-CUDyhibV.d.ts → graphql-C8jKLLel.d.ts} +1 -1
  21. package/dist/{index-B2LCaK0R.d.ts → index-479i3w77.d.ts} +1 -1
  22. package/dist/{index-BGzMYJsm.d.ts → index-8pUSoT85.d.ts} +1 -1
  23. package/dist/{index-ADmsX0BI.d.ts → index-9MJVKzWA.d.ts} +3 -3
  24. package/dist/{index-FbXPfen7.d.ts → index-BJwHEzpN.d.ts} +1 -1
  25. package/dist/{index-CTTwo9av.d.ts → index-BTaQMEgB.d.ts} +1 -1
  26. package/dist/{index-CDOqxSIi.d.ts → index-Base-sg5.d.ts} +1 -1
  27. package/dist/{index-C_GXXF32.d.ts → index-Bh6W5JO4.d.ts} +3 -3
  28. package/dist/{index-BeVtqGO-.d.ts → index-Bwn5Z1h-.d.ts} +1 -1
  29. package/dist/{index-FRRaa6h2.d.ts → index-CEtULfb_.d.ts} +3 -3
  30. package/dist/{index-DqbGqfAy.d.ts → index-Cwu5Mpji.d.ts} +1 -1
  31. package/dist/{index-CaM9JUcc.d.ts → index-DSynXDRD.d.ts} +1 -1
  32. package/dist/{index-CVCyKzhB.d.ts → index-DWER4-_x.d.ts} +3 -3
  33. package/dist/{index-cmR9k9ga.d.ts → index-DhFP_AIB.d.ts} +1 -1
  34. package/dist/{index-zd_NPGJo.d.ts → index-DqpCL9kD.d.ts} +4 -4
  35. package/dist/{index-U_tu3zUl.d.ts → index-Dw_0wE4q.d.ts} +2 -2
  36. package/dist/{index-3KOZ1zN9.d.ts → index-HeUeEsMU.d.ts} +1 -1
  37. package/dist/{index-Cot73bdh.d.ts → index-KlrnELrN.d.ts} +1 -1
  38. package/dist/{index-MArCb8Aq.d.ts → index-SvWwlTUC.d.ts} +1 -1
  39. package/dist/{index-CHwMhK6v.d.ts → index-YMGOJins.d.ts} +2 -2
  40. package/dist/index-oJMtR3nl.d.ts +88 -0
  41. package/dist/index.d.ts +21 -21
  42. package/dist/index.js +5 -5
  43. package/dist/init/index.d.ts +1 -1
  44. package/dist/init/index.js +1 -1
  45. package/dist/{init-CQPFmOOe.js → init-D814LeLF.js} +2 -2
  46. package/dist/{init-CQPFmOOe.js.map → init-D814LeLF.js.map} +1 -1
  47. package/dist/instrumentation/index.d.ts +2 -2
  48. package/dist/layer/index.d.ts +2 -2
  49. package/dist/layer-Bcix-WCl.js.map +1 -1
  50. package/dist/{layer-BZBZZWeV.d.ts → layer-C0zxAUgR.d.ts} +1 -0
  51. package/dist/logger/index.d.ts +1 -1
  52. package/dist/notifications/index.d.ts +1 -1
  53. package/dist/payments/index.d.ts +2 -2
  54. package/dist/rbac/index.d.ts +1 -1
  55. package/dist/resource-caps/index.d.ts +1 -1
  56. package/dist/{sdk-B62itAH1.js → sdk-DqIqX-Ue.js} +33 -2
  57. package/dist/sdk-DqIqX-Ue.js.map +1 -0
  58. package/dist/search/index.d.ts +2 -2
  59. package/dist/security/index.d.ts +1 -1
  60. package/dist/security/rate-limit/index.d.ts +1 -1
  61. package/dist/server/index.js +2 -3
  62. package/dist/server/index.js.map +1 -1
  63. package/dist/tags/index.d.ts +1 -1
  64. package/dist/telemetry/index.d.ts +2 -2
  65. package/dist/telemetry/index.js +8 -4
  66. package/dist/telemetry/index.js.map +1 -1
  67. package/dist/temporal/index.d.ts +1 -1
  68. package/dist/tracker/index.d.ts +2 -2
  69. package/dist/tracker/index.js +2 -2
  70. package/dist/{tracker-PQztSlhJ.js → tracker-Cl3cGKe-.js} +2 -2
  71. package/dist/{tracker-PQztSlhJ.js.map → tracker-Cl3cGKe-.js.map} +1 -1
  72. package/dist/translation/index.d.ts +2 -2
  73. package/dist/types/index.d.ts +2 -2
  74. package/dist/{types-C6EKaS3V.d.ts → types-gJ9Qqi9E.d.ts} +1 -1
  75. package/dist/usage/index.d.ts +1 -1
  76. package/dist/usage/index.js +1 -1
  77. package/dist/{usage-BRqVP3CJ.js → usage-ygkKsxdd.js} +2 -2
  78. package/dist/{usage-BRqVP3CJ.js.map → usage-ygkKsxdd.js.map} +1 -1
  79. package/package.json +1 -1
  80. package/dist/gateway-ByVo-n37.js +0 -50
  81. package/dist/gateway-ByVo-n37.js.map +0 -1
  82. package/dist/index-YOShAwkq.d.ts +0 -45
  83. package/dist/sdk-B62itAH1.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"usage-BRqVP3CJ.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,2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AgD;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"}
1
+ {"version":3,"file":"usage-ygkKsxdd.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 Qu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;;CAKA,MAAa,WAAW,UAAwD;EAC9E,MAAM,IAAI,+BACR,cACA,eAAe,4CAA4C,CAC7D;CACF;;;;CAKA,MAAa,aAAa,UAA4C;EACpE,MAAM,IAAI,+BACR,gBACA,eAAe,8CAA8C,CAC/D;CACF;;;;CAKA,MAAa,cAAc,UAGxB;EACD,MAAM,IAAI,+BACR,iBACA,eAAe,+CAA+C,CAChE;CACF;;;;;CAMA,MAAa,SAAS,UAGnB;EACD,MAAM,IAAI,+BAA+B,YAAY,eAAe,mCAAmC,CAAC;CAC1G;;;;;CAMA,MAAa,WACX,WACA,aACA,aACA,SACuB;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.1111.1",
3
+ "version": "2026.1113.1",
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,50 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
- import { a as isGatewayClientError, i as createGatewayClientFromEnv, r as createGatewayClient, t as GatewayClient } from "./client-sAJTrb4i.js";
3
- import { t as signServiceJwt } from "./service-jwt-Bu-WNA_-.js";
4
- import { n as GatewayError, r as GatewayErrorType, t as CircuitState } from "./types-BYMYND1L.js";
5
- import { t as security_exports } from "./security-DIG-95Ic.js";
6
-
7
- // src/gateway/delegated-transport.ts
8
- /** Header an internal gateway reads a delegated `app_as_user` bearer from. */
9
- const DELEGATED_AUTHORIZATION_HEADER = "x-delegated-authorization";
10
- const JWT_SEGMENT = /^[A-Za-z0-9_-]+$/;
11
- function isCompactJwt(token) {
12
- const segments = token.split(".");
13
- return segments.length === 3 && segments.every((segment) => JWT_SEGMENT.test(segment));
14
- }
15
- /**
16
- * Builds the request headers for a delegated internal-gateway call, for use as
17
- * `GatewayClient.internalQuery({ query, headers })`.
18
- *
19
- * @throws Error when the token is not a compact JWS (so a malformed value can
20
- * never be smuggled into a header) or the workspace id is blank.
21
- */
22
- function buildDelegatedGatewayHeaders(input) {
23
- const token = input.appAsUserToken;
24
- if (typeof token !== "string" || token.length === 0 || token.length > 8192 || !isCompactJwt(token)) throw new Error("Delegated gateway transport requires a compact app_as_user token");
25
- const headers = { [DELEGATED_AUTHORIZATION_HEADER]: `Bearer ${token}` };
26
- if (input.workspaceId !== void 0) {
27
- const workspaceId = input.workspaceId.trim();
28
- if (workspaceId.length === 0 || workspaceId !== input.workspaceId) throw new Error("Delegated gateway transport requires a non-blank workspace id");
29
- headers["x-workspace-id"] = workspaceId;
30
- }
31
- return headers;
32
- }
33
-
34
- // src/gateway/index.ts
35
- var gateway_exports = /* @__PURE__ */ __exportAll({
36
- CircuitState: () => CircuitState,
37
- DELEGATED_AUTHORIZATION_HEADER: () => DELEGATED_AUTHORIZATION_HEADER,
38
- GatewayClient: () => GatewayClient,
39
- GatewayError: () => GatewayError,
40
- GatewayErrorType: () => GatewayErrorType,
41
- Security: () => security_exports,
42
- buildDelegatedGatewayHeaders: () => buildDelegatedGatewayHeaders,
43
- createGatewayClient: () => createGatewayClient,
44
- createGatewayClientFromEnv: () => createGatewayClientFromEnv,
45
- isGatewayClientError: () => isGatewayClientError,
46
- signServiceJwt: () => signServiceJwt
47
- });
48
-
49
- export { DELEGATED_AUTHORIZATION_HEADER as n, buildDelegatedGatewayHeaders as r, gateway_exports as t };
50
- //# sourceMappingURL=gateway-ByVo-n37.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"gateway-ByVo-n37.js","names":[],"sources":["../src/gateway/delegated-transport.ts","../src/gateway/index.ts"],"sourcesContent":["/**\n * Delegated gateway transport (BOFF-9962).\n *\n * A service that must call the platform as \"agent X acting for user Y\" does\n * not set actor or consent headers itself: internal gateways strip those.\n * Instead it obtains a short-lived `app_as_user` token from global-auth\n * (`issueAppAsUserTokenInternal`) and presents it on the internal gateway's\n * `x-delegated-authorization` header. The gateway verifies the signature,\n * checks revocation and the grant's workspace bounds, and only then forwards\n * the represented user as the actor together with `x-verified-delegation`.\n *\n * @module gateway/delegated-transport\n */\n\nimport type { GatewayRequestHeaders } from '../types/layer.js';\n\n/** Header an internal gateway reads a delegated `app_as_user` bearer from. */\nexport const DELEGATED_AUTHORIZATION_HEADER = 'x-delegated-authorization';\n\nexport interface DelegatedGatewayTransportInput {\n /** Signed `app_as_user` access token issued by global-auth. */\n appAsUserToken: string;\n /** Workspace the call targets; must be inside the grant's workspace bounds. */\n workspaceId?: string;\n}\n\nconst JWT_SEGMENT = /^[A-Za-z0-9_-]+$/;\n\nfunction isCompactJwt(token: string): boolean {\n const segments = token.split('.');\n return segments.length === 3 && segments.every((segment) => JWT_SEGMENT.test(segment));\n}\n\n/**\n * Builds the request headers for a delegated internal-gateway call, for use as\n * `GatewayClient.internalQuery({ query, headers })`.\n *\n * @throws Error when the token is not a compact JWS (so a malformed value can\n * never be smuggled into a header) or the workspace id is blank.\n */\nexport function buildDelegatedGatewayHeaders(input: DelegatedGatewayTransportInput): GatewayRequestHeaders {\n const token = input.appAsUserToken;\n if (typeof token !== 'string' || token.length === 0 || token.length > 8192 || !isCompactJwt(token)) {\n throw new Error('Delegated gateway transport requires a compact app_as_user token');\n }\n const headers: GatewayRequestHeaders = {\n [DELEGATED_AUTHORIZATION_HEADER]: `Bearer ${token}`,\n };\n if (input.workspaceId !== undefined) {\n const workspaceId = input.workspaceId.trim();\n if (workspaceId.length === 0 || workspaceId !== input.workspaceId) {\n throw new Error('Delegated gateway transport requires a non-blank workspace id');\n }\n headers['x-workspace-id'] = workspaceId;\n }\n return headers;\n}\n","/**\n * Gateway Module\n *\n * Provides unified gateway client for layer-aware M2M communication\n * with circuit breaker and retry logic.\n *\n * @module gateway\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient, createGatewayClientFromEnv } from '@burdenoff/be-sdk/gateway';\n *\n * // Create from environment variables\n * const client = createGatewayClientFromEnv();\n *\n * // Or create manually\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer, uses int-gateway with bypass)\n * const internalResult = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call (via public gateway)\n * const crossLayerResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\n// Client exports\nexport { GatewayClient, createGatewayClient, createGatewayClientFromEnv, isGatewayClientError } from './client.js';\n\n// Service-JWT minting for cross-layer M2M auth. Exposed so non-GatewayClient\n// callers (e.g. bespoke graphql-request clients) can authenticate identically.\nexport { signServiceJwt } from './service-jwt.js';\n\n// Delegated internal-gateway transport (BOFF-9962): call as an agent acting\n// for a user by presenting a verified app_as_user token, never raw headers.\nexport {\n buildDelegatedGatewayHeaders,\n DELEGATED_AUTHORIZATION_HEADER,\n type DelegatedGatewayTransportInput,\n} from './delegated-transport.js';\n\n// Type exports\nexport {\n CircuitState,\n GatewayErrorType,\n GatewayError,\n type GatewayClientConfig,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type GraphQLError,\n type IGatewayClient,\n type ICircuitBreaker,\n type CircuitBreakerStats,\n type GatewayClientHealth,\n type RequestContext,\n} from './types.js';\n\n// Gateway-side security plugin stack (for public gateways).\n// Imported by consumers as `@burdenoff/be-sdk/gateway/security` — this\n// re-export lets `@burdenoff/be-sdk/gateway` also resolve the namespace.\nexport * as Security from './security/index.js';\n"],"mappings":";;;;;;;;AAiBA,MAAa,iCAAiC;AAS9C,MAAM,cAAc;AAEpB,SAAS,aAAa,OAAwB;CAC5C,MAAM,WAAW,MAAM,MAAM,GAAG;CAChC,OAAO,SAAS,WAAW,KAAK,SAAS,OAAO,YAAY,YAAY,KAAK,OAAO,CAAC;AACvF;;;;;;;;AASA,SAAgB,6BAA6B,OAA8D;CACzG,MAAM,QAAQ,MAAM;CACpB,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,QAAQ,CAAC,aAAa,KAAK,GAC/F,MAAM,IAAI,MAAM,kEAAkE;CAEpF,MAAM,UAAiC,GACpC,iCAAiC,UAAU,QAC9C;CACA,IAAI,MAAM,gBAAgB,QAAW;EACnC,MAAM,cAAc,MAAM,YAAY,KAAK;EAC3C,IAAI,YAAY,WAAW,KAAK,gBAAgB,MAAM,aACpD,MAAM,IAAI,MAAM,+DAA+D;EAEjF,QAAQ,oBAAoB;CAC9B;CACA,OAAO;AACT"}
@@ -1,45 +0,0 @@
1
- import { s as GatewayRequestHeaders } from "./layer-BZBZZWeV.js";
2
- import { a as GatewayError, c as GraphQLRequestOptions, d as IGatewayClient, f as RequestContext, i as GatewayClientHealth, l as GraphQLResponse, n as CircuitState, o as GatewayErrorType, r as GatewayClientConfig, s as GraphQLError, t as CircuitBreakerStats, u as ICircuitBreaker } from "./types-C6EKaS3V.js";
3
- import { t as index_d_exports$1 } from "./index-C0qLquY0.js";
4
- declare function isGatewayClientError(error: unknown): boolean;
5
- declare class GatewayClient implements IGatewayClient {
6
- private config;
7
- private layerManager;
8
- private internalCircuitBreaker;
9
- private crossLayerCircuitBreaker;
10
- private retryConfig;
11
- private defaultHeaders;
12
- constructor(config: GatewayClientConfig);
13
- private getInternalUrl;
14
- private getCrossLayerUrl;
15
- internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;
16
- crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;
17
- query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;
18
- getInternalCircuitBreaker(): ICircuitBreaker;
19
- getCrossLayerCircuitBreaker(): ICircuitBreaker;
20
- getHealthStatus(): GatewayClientHealth;
21
- updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void;
22
- private createRequestContext;
23
- private shouldRetryError;
24
- private calculateRetryDelay;
25
- private logRetryAttempt;
26
- private executeWithRetry;
27
- private buildRequestHeaders;
28
- private handleGraphQLErrors;
29
- private handleFetchError;
30
- private executeRequest;
31
- private sleep;
32
- }
33
- declare function createGatewayClient(config: GatewayClientConfig): GatewayClient;
34
- declare function createGatewayClientFromEnv(): GatewayClient;
35
- declare function signServiceJwt(actorId: string, ttlSeconds?: number): Promise<string | null>;
36
- declare const DELEGATED_AUTHORIZATION_HEADER = "x-delegated-authorization";
37
- interface DelegatedGatewayTransportInput {
38
- appAsUserToken: string;
39
- workspaceId?: string;
40
- }
41
- declare function buildDelegatedGatewayHeaders(input: DelegatedGatewayTransportInput): GatewayRequestHeaders;
42
- declare namespace index_d_exports {
43
- export { CircuitBreakerStats, CircuitState, DELEGATED_AUTHORIZATION_HEADER, DelegatedGatewayTransportInput, GatewayClient, GatewayClientConfig, GatewayClientHealth, GatewayError, GatewayErrorType, GraphQLError, GraphQLRequestOptions, GraphQLResponse, ICircuitBreaker, IGatewayClient, RequestContext, index_d_exports$1 as Security, buildDelegatedGatewayHeaders, createGatewayClient, createGatewayClientFromEnv, isGatewayClientError, signServiceJwt };
44
- }
45
- export { signServiceJwt as a, createGatewayClientFromEnv as c, buildDelegatedGatewayHeaders as i, isGatewayClientError as l, DELEGATED_AUTHORIZATION_HEADER as n, GatewayClient as o, DelegatedGatewayTransportInput as r, createGatewayClient as s, index_d_exports as t };
@@ -1 +0,0 @@
1
- {"version":3,"file":"sdk-B62itAH1.js","names":[],"sources":["../src/telemetry/sdk.ts"],"sourcesContent":["/**\n * Thin wrapper that initializes `@opentelemetry/sdk-node` with the\n * OTLPTrace + OTLPMetric exporters and standard auto-instrumentations.\n *\n * All imports are dynamic so services that haven't installed sdk-node\n * still compile and run. The function resolves `undefined` when the SDK\n * isn't available, letting `bootstrapTelemetry` fall back gracefully.\n */\nimport { importOptionalPeer } from '../utils/import-optional-peer.js';\nimport type { TelemetryIdGenerator } from './id-generator.js';\nimport type { Boundary, Env } from './index.js';\n\nexport interface OtelSdkConfig {\n serviceName: string;\n serviceVersion: string;\n boundary: Boundary;\n module?: string;\n env: Env;\n otlpEndpoint: string;\n sampleRatio: number;\n /**\n * Optional trace/span id generator handed to NodeSDK's tracer provider.\n * Omitted means the SDK's default random generator.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name. A package found\n * here is used as is; any other one is loaded at runtime from the consumer's\n * `node_modules` through `importOptionalPeer`. A service built with\n * `bun build --compile` has no `node_modules` at runtime, so it imports the\n * packages statically and hands them in here.\n */\n modules?: OtelModules;\n}\n\n/** The OpenTelemetry packages `createOtelSdk` can load. */\nexport type OtelPeerPackage =\n | '@opentelemetry/api'\n | '@opentelemetry/auto-instrumentations-node'\n | '@opentelemetry/exporter-metrics-otlp-http'\n | '@opentelemetry/exporter-trace-otlp-http'\n | '@opentelemetry/resources'\n | '@opentelemetry/sdk-metrics'\n | '@opentelemetry/sdk-node'\n | '@opentelemetry/sdk-trace-base'\n | '@opentelemetry/semantic-conventions';\n\n/** Module namespaces injected in place of runtime imports (see `OtelSdkConfig.modules`). */\nexport type OtelModules = Partial<Record<OtelPeerPackage, unknown>>;\n\nexport interface OtelSdkHandle {\n shutdown: () => Promise<void>;\n metricsEnabled: boolean;\n metricsDropReason?: string;\n}\n\ntype Thenable = {\n then: (onfulfilled?: (value: void) => void, onrejected?: (reason: unknown) => void) => unknown;\n};\n\nconst isThenable = (value: unknown): value is Thenable => {\n return typeof value === 'object' && value !== null && typeof (value as { then?: unknown }).then === 'function';\n};\n\nconst asyncDisposeMetricReader = async (metricReaderCandidate: unknown): Promise<void> => {\n const shutdown = (metricReaderCandidate as { shutdown?: () => void | Promise<void> }).shutdown;\n if (typeof shutdown === 'function') {\n const result = shutdown.call(metricReaderCandidate) as unknown;\n if (isThenable(result)) await result;\n }\n};\n\nexport async function createOtelSdk(cfg: OtelSdkConfig): Promise<OtelSdkHandle> {\n const load = (name: OtelPeerPackage): Promise<unknown> =>\n cfg.modules?.[name] !== undefined ? Promise.resolve(cfg.modules[name]) : importOptionalPeer(name);\n console.log('[sdk] importing @opentelemetry/sdk-node...');\n const sdkMod = (await load('@opentelemetry/sdk-node')) as {\n NodeSDK: new (init: Record<string, unknown>) => {\n start: () => void;\n shutdown: () => Promise<void>;\n };\n };\n\n console.log('[sdk] importing @opentelemetry/resources...');\n const resources = (await load('@opentelemetry/resources')) as {\n resourceFromAttributes: (attrs: Record<string, string | number>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/semantic-conventions...');\n const sem = (await load('@opentelemetry/semantic-conventions')) as Record<string, string>;\n\n console.log('[sdk] importing @opentelemetry/exporter-trace-otlp-http...');\n const traceExp = (await load('@opentelemetry/exporter-trace-otlp-http')) as {\n OTLPTraceExporter: new (init: Record<string, string>) => unknown;\n };\n\n console.log('[sdk] importing @opentelemetry/exporter-metrics-otlp-http...');\n let metricsExp: { OTLPMetricExporter?: new (init: Record<string, string>) => unknown } | undefined;\n try {\n metricsExp = (await load('@opentelemetry/exporter-metrics-otlp-http')) as typeof metricsExp;\n } catch {\n metricsExp = undefined;\n console.log('[sdk] metrics exporter not available (non-fatal)');\n }\n\n let metricReader: unknown;\n let metricsEnabled = false;\n let metricsDropReason: string | undefined;\n if (metricsExp?.OTLPMetricExporter) {\n try {\n const metricsSdk = (await load('@opentelemetry/sdk-metrics')) as {\n PeriodicExportingMetricReader: new (init: Record<string, unknown>) => unknown;\n };\n const candidate = new metricsSdk.PeriodicExportingMetricReader({\n exporter: new metricsExp.OTLPMetricExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/metrics`,\n }),\n });\n // Pre-flight API compatibility check. Some OTel package version\n // combinations construct `PeriodicExportingMetricReader` successfully\n // but lack `setMetricProducer` on the prototype chain (mixed\n // sdk-metrics versions, or runtime-specific class-inheritance\n // quirks — Bun has surfaced this in the past). Without the check,\n // `NodeSDK.start()` may register the global tracer provider BEFORE\n // it tries to call `setMetricProducer` and throws — leaving the\n // global tracer pointing at a half-initialized provider whose\n // span pipeline never drains. Skipping the metric reader when the\n // API isn't there avoids that whole failure mode in one pass.\n const setProducer = (candidate as { setMetricProducer?: unknown }).setMetricProducer;\n if (typeof setProducer === 'function') {\n metricReader = candidate;\n metricsEnabled = true;\n } else {\n metricsDropReason =\n 'setMetricProducer is not a function on PeriodicExportingMetricReader; skipping metrics path';\n await asyncDisposeMetricReader(candidate);\n metricReader = undefined;\n }\n } catch {\n if (metricsDropReason === undefined) {\n metricsDropReason = 'metric reader construction or compatibility check failed';\n }\n metricReader = undefined;\n }\n }\n\n console.log('[sdk] importing @opentelemetry/sdk-trace-base for sampler...');\n let sampler: unknown;\n try {\n const traceBase = (await load('@opentelemetry/sdk-trace-base')) as {\n ParentBasedSampler: new (init: Record<string, unknown>) => unknown;\n TraceIdRatioBasedSampler: new (ratio: number) => unknown;\n };\n sampler = new traceBase.ParentBasedSampler({\n root: new traceBase.TraceIdRatioBasedSampler(Math.min(1, Math.max(0, cfg.sampleRatio))),\n });\n } catch {\n sampler = undefined;\n console.log('[sdk] sampler not available (non-fatal)');\n }\n\n // Some services have auto-instrumentations installed; optional.\n console.log('[sdk] importing @opentelemetry/auto-instrumentations-node...');\n let autoInstrumentations: unknown[] | undefined;\n try {\n const auto = (await load('@opentelemetry/auto-instrumentations-node')) as {\n getNodeAutoInstrumentations: (cfg?: Record<string, unknown>) => unknown[];\n };\n autoInstrumentations = auto.getNodeAutoInstrumentations({\n '@opentelemetry/instrumentation-fs': { enabled: false },\n });\n console.log('[sdk] auto-instrumentations loaded');\n } catch {\n autoInstrumentations = undefined;\n console.log('[sdk] auto-instrumentations not available (non-fatal)');\n }\n\n const serviceNamespaceByBoundary: Record<Boundary, string> = {\n wspace: 'workspaces',\n global: 'tenant',\n gateway: 'gateways',\n };\n const resourceAttributes: Record<string, string> = {\n [sem['SEMRESATTRS_SERVICE_NAME'] ?? 'service.name']: cfg.serviceName,\n [sem['SEMRESATTRS_SERVICE_VERSION'] ?? 'service.version']: cfg.serviceVersion,\n [sem['SEMRESATTRS_SERVICE_NAMESPACE'] ?? 'service.namespace']: serviceNamespaceByBoundary[cfg.boundary],\n [sem['SEMRESATTRS_DEPLOYMENT_ENVIRONMENT'] ?? 'deployment.environment']: cfg.env,\n 'burdenoff.boundary': cfg.boundary,\n };\n if (cfg.module) resourceAttributes['burdenoff.module'] = cfg.module;\n const serviceInstanceId = process.env['POD_NAME'] ?? process.env['HOSTNAME'];\n if (serviceInstanceId) resourceAttributes['service.instance.id'] = serviceInstanceId;\n const clusterName = process.env['CLUSTER_NAME'];\n if (clusterName) {\n resourceAttributes['cluster'] = clusterName;\n resourceAttributes['k8s.cluster.name'] = clusterName;\n }\n\n const resource = resources.resourceFromAttributes(resourceAttributes);\n\n const traceExporter = new traceExp.OTLPTraceExporter({\n url: `${cfg.otlpEndpoint.replace(/\\/$/, '')}/v1/traces`,\n });\n\n // Single NodeSDK, single start. The pre-flight `setMetricProducer`\n // check above means we never pass an incompatible metric reader into\n // NodeSDK construction — so we no longer need the prior catch+rebuild\n // fallback dance, which had its own side-effect: the failed first\n // NodeSDK could leave the global tracer provider partially registered,\n // and the second NodeSDK's `setGlobalTracerProvider` becomes a no-op\n // — meaning spans flow into the FIRST (broken) provider and never\n // reach the exporter. Eliminating the fallback eliminates that hazard.\n console.log('[sdk] constructing NodeSDK...');\n const nodeSdk = new sdkMod.NodeSDK({\n resource,\n traceExporter,\n ...(metricReader ? { metricReader } : {}),\n ...(sampler ? { sampler } : {}),\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(autoInstrumentations ? { instrumentations: autoInstrumentations } : {}),\n });\n console.log('[sdk] NodeSDK constructed, calling start()...');\n // NodeSDK.start() returns void in modern versions and Promise<void> in older\n // ones. Cast to a permissive thenable shape so awaiting works either way\n // without tripping `@typescript-eslint/await-thenable`.\n const startResult = nodeSdk.start() as unknown;\n if (isThenable(startResult)) {\n await startResult;\n }\n console.log('[sdk] NodeSDK started');\n\n // Stash the @opentelemetry/api reference for pino-logger's mixin.\n try {\n (globalThis as unknown as { __otelApi?: unknown }).__otelApi = await load('@opentelemetry/api');\n console.log('[sdk] @opentelemetry/api stashed for pino mixin');\n } catch {\n console.log('[sdk] @opentelemetry/api stash failed (non-fatal)');\n }\n\n console.log('[sdk] OTel SDK initialization complete');\n return {\n shutdown: async (): Promise<void> => nodeSdk.shutdown(),\n metricsEnabled,\n metricsDropReason,\n };\n}\n"],"mappings":";;;;;;;;;;;AA4DA,MAAM,cAAc,UAAsC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAA6B,SAAS;AACtG;AAEA,MAAM,2BAA2B,OAAO,0BAAkD;CACxF,MAAM,WAAY,sBAAoE;CACtF,IAAI,OAAO,aAAa,YAAY;EAClC,MAAM,SAAS,SAAS,KAAK,qBAAqB;EAClD,IAAI,WAAW,MAAM,GAAG,MAAM;CAChC;AACF;AAEA,eAAsB,cAAc,KAA4C;CAC9E,MAAM,QAAQ,SACZ,IAAI,UAAU,UAAU,SAAY,QAAQ,QAAQ,IAAI,QAAQ,KAAK,IAAI,mBAAmB,IAAI;CAClG,QAAQ,IAAI,4CAA4C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