@burdenoff/be-sdk 2026.1107.5 → 2026.1108.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.
- package/dist/EventQueueFactory-PP534MBQ.js +8 -0
- package/dist/{EventQueueFactory-T7T6GRWZ.js.map → EventQueueFactory-PP534MBQ.js.map} +1 -1
- package/dist/{chunk-LRFUXS73.js → chunk-2T3N5SNW.js} +88 -73
- package/dist/chunk-2T3N5SNW.js.map +1 -0
- package/dist/{chunk-FVWXQ26J.js → chunk-7EISSMFP.js} +3 -3
- package/dist/{chunk-FVWXQ26J.js.map → chunk-7EISSMFP.js.map} +1 -1
- package/dist/{chunk-OQGA4RU6.js → chunk-DJNHR37J.js} +3 -3
- package/dist/{chunk-OQGA4RU6.js.map → chunk-DJNHR37J.js.map} +1 -1
- package/dist/{chunk-MIK45HQD.js → chunk-E6OAFS7A.js} +4 -4
- package/dist/{chunk-MIK45HQD.js.map → chunk-E6OAFS7A.js.map} +1 -1
- package/dist/{chunk-QFS5VXM2.js → chunk-FHVBMQDW.js} +5 -5
- package/dist/{chunk-QFS5VXM2.js.map → chunk-FHVBMQDW.js.map} +1 -1
- package/dist/{chunk-XGNOYVSW.js → chunk-K56L7NUR.js} +3 -3
- package/dist/{chunk-XGNOYVSW.js.map → chunk-K56L7NUR.js.map} +1 -1
- package/dist/{chunk-IA6AUVAG.js → chunk-O2JMZHNH.js} +4 -4
- package/dist/{chunk-IA6AUVAG.js.map → chunk-O2JMZHNH.js.map} +1 -1
- package/dist/{chunk-FG37SJML.js → chunk-OBZQ4AJC.js} +3 -3
- package/dist/{chunk-FG37SJML.js.map → chunk-OBZQ4AJC.js.map} +1 -1
- package/dist/{chunk-TRYGWO7H.js → chunk-QVPIACWD.js} +198 -402
- package/dist/chunk-QVPIACWD.js.map +1 -0
- package/dist/event-queue/index.js +4 -4
- package/dist/graph/index.js +6 -6
- package/dist/{index-C1IPam0T.d.ts → index-DnjJ9CwI.d.ts} +7 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +22 -22
- package/dist/index.js.map +1 -1
- package/dist/init/index.js +1 -1
- package/dist/prisma/index.js +6 -6
- package/dist/tracker/index.d.ts +1 -1
- package/dist/tracker/index.js +4 -4
- package/dist/usage/index.d.ts +48 -14
- package/dist/usage/index.js +1 -1
- package/package.json +1 -1
- package/dist/EventQueueFactory-T7T6GRWZ.js +0 -8
- package/dist/chunk-LRFUXS73.js.map +0 -1
- package/dist/chunk-TRYGWO7H.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/usage/billing.ts","../src/usage/index.ts"],"names":["DEFAULT_REQUEST_TIMEOUT_MS","DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS","QUOTA_LIMIT_CACHE_MAX_ENTRIES","GET_WORKSPACE_ORG_QUERY","GET_DEFAULT_BILLING_ACCOUNT_QUERY","CHECK_QUOTA_QUERY","ADD_USAGE_MUTATION","GET_QUOTA_LIMIT_QUERY","FREE_UP_USAGE_MUTATION","unwrap","data","Error","BillingUsageClient","gatewayClient","quotaLimitCacheTtlMs","logPrefix","quotaLimitCache","Map","config","serviceName","TypeError","GatewayClient","layer","timeout","queryWorkspaceLayer","query","variables","workspaceId","response","internalQuery","headers","skipRetry","queryGlobalLayer","crossLayerQuery","getOrgIdFromWorkspace","workspace","orgId","error","logger","warn","message","String","getDefaultBillingAccountId","getDefaultBillingAccountByOrgId","id","ensureQuotaAvailableForOrg","input","billingAccountId","quotaName","amount","value","productId","result","checkQuotaExhausted","noLimit","limitLeft","ensureQuotaAvailableForWorkspace","addUsageForOrg","description","tags","hash","userId","addUsage","addUsageForWorkspace","freeUpUsageForOrg","freeUpUsage","freeUpUsageForWorkspace","getQuotaLimitForWorkspace","cacheKey","cached","get","expiresAt","Date","now","limit","getQuotaUsageAndLimit","rememberQuotaLimit","size","key","entry","delete","overflow","removed","keys","set","UsageMetricType","QuotaPeriod","UsageOperationUnsupportedError","SDKError","operation","guidance","name","Object","setPrototypeOf","prototype","CHECK_WORKSPACE_QUOTA_QUERY","TRACK_USAGE_MUTATION","legacyGuidance","replacement","nonEmpty","trimmed","trim","undefined","buildTrackUsageInput","options","context","ValidationError","Number","isFinite","randomUUID","actorId","quotaAssignmentId","metadata","UsageModule","client","requestContext","actorType","checkWorkspaceQuota","debug","allowed","requireWorkspaceQuota","notProvisioned","assignmentId","QuotaExceededError","requestedAmount","trackUsage","info","track","_options","checkQuota","requireQuota","trackAndCheck","getUsage","getSummary","_entityId","_entityType","_metricType","_period","setQuota","getQuota","getQuotas","resetQuota","deleteQuota","trackBulk","_records"],"mappings":";;;;;;;AAkCA,IAAMA,0BAAAA,GAA6B,GAAA;AAGnC,IAAMC,gCAAAA,GAAmC,IAAI,EAAA,GAAK,GAAA;AAGlD,IAAMC,6BAAAA,GAAgC,GAAA;AAEtC,IAAMC,uBAAAA,GAA0B;;;;;;;AAQhC,IAAMC,iCAAAA,GAAoC;;;;;;;AAQ1C,IAAMC,iBAAAA,GAAoB;;;;;;;;;;;;;AAc1B,IAAMC,kBAAAA,GAAqB;;;;;;;;;;;;;;;;;;;;;;;AAwB3B,IAAMC,qBAAAA,GAAwB;;;;;;;;;;;;AAa9B,IAAMC,sBAAAA,GAAyB;;;;;;;;;;;;;;;;;;;;;;;AA+G/B,SAASC,OAAcC,IAAAA,EAAuB;AAC5C,EAAA,IAAI,CAACA,IAAAA,EAAM;AACT,IAAA,MAAM,IAAIC,MAAM,uCAAA,CAAA;AAClB,EAAA;AACA,EAAA,OAAOD,IAAAA;AACT;AALSD,MAAAA,CAAAA,MAAAA,EAAAA,QAAAA,CAAAA;AAaF,IAAMG,qBAAN,MAAMA;EAzOb;;;AA0OmBC,EAAAA,aAAAA;AACAC,EAAAA,oBAAAA;AACAC,EAAAA,SAAAA;;;AAIAC,EAAAA,eAAAA,uBAAsBC,GAAAA,EAAAA;AAEvC,EAAA,WAAA,CAAYC,MAAAA,EAAkC;AAC5C,IAAA,IAAI,CAACA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,SAAAA,EACAC,WAAAA,EACAC,WAAAA,EACkB;AAClB,IAAA,MAAM,IAAIjD,8BAAAA,CAA+B,YAAA,EAAc,8CAAA,CAAA;AACzD,EAAA;;;;EAKA,MAAauD,WAAAA,CACXR,SAAAA,EACAC,WAAAA,EACAC,WAAAA,EACkB;AAClB,IAAA,MAAM,IAAIjD,8BAAAA,CAA+B,aAAA,EAAe,yDAAA,CAAA;AAC1D,EAAA;;;;AAKA,EAAA,MAAawD,UAAUC,QAAAA,EAAuD;AAC5E,IAAA,MAAM,IAAIzD,8BAAAA,CAA+B,WAAA,EAAaU,cAAAA,CAAe,yBAAA,CAAA,CAAA;AACvE,EAAA;AACF","file":"chunk-QVPIACWD.js","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"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
export { EVENT_TAXONOMY_BRAND, EventPriority, EventsManager, EventsModule, LIFECYCLE_SUBJECTS, ModuleEventsService, PLATFORM_EVENT_TAXONOMY, REFERENCE_PRODUCT_EVENT_TAXONOMY, WSPACE_GRAPH_EVENTS_STREAM, buildConsumerGroupName, createConsumer, createEventsManagerSingleton, createLifecycleConsumer, createModuleEventsService, createPublisher, defineEventTaxonomy, eventSpec, isDefinedEventTaxonomy, mergeEventTaxonomies, parseOrganizationDeleted, parseWorkspaceDeletedGraph, parseWorkspaceDeletedStream, parseWorkspaceMemberRemoved, publishTaxonomyEvent, taxonomyEventNames, taxonomyNameViolation } from '../chunk-
|
|
2
|
-
export { GraphEventEmitterImpl, MemoryEventBus, MemoryEventConsumer, MemoryEventPublisher, MemoryEventQueue, createGraphEventEmitter2 as createGraphEventEmitter, createMemoryConsumer, createGraphEventEmitter as createMemoryGraphEventEmitter, createMemoryPublisher, getGraphEventEmitter, resetGraphEventEmitter } from '../chunk-
|
|
3
|
-
export { EventQueueFactory, QueueType, RedisStreamsEventConsumer, RedisStreamsEventPublisher } from '../chunk-
|
|
1
|
+
export { EVENT_TAXONOMY_BRAND, EventPriority, EventsManager, EventsModule, LIFECYCLE_SUBJECTS, ModuleEventsService, PLATFORM_EVENT_TAXONOMY, REFERENCE_PRODUCT_EVENT_TAXONOMY, WSPACE_GRAPH_EVENTS_STREAM, buildConsumerGroupName, createConsumer, createEventsManagerSingleton, createLifecycleConsumer, createModuleEventsService, createPublisher, defineEventTaxonomy, eventSpec, isDefinedEventTaxonomy, mergeEventTaxonomies, parseOrganizationDeleted, parseWorkspaceDeletedGraph, parseWorkspaceDeletedStream, parseWorkspaceMemberRemoved, publishTaxonomyEvent, taxonomyEventNames, taxonomyNameViolation } from '../chunk-E6OAFS7A.js';
|
|
2
|
+
export { GraphEventEmitterImpl, MemoryEventBus, MemoryEventConsumer, MemoryEventPublisher, MemoryEventQueue, createGraphEventEmitter2 as createGraphEventEmitter, createMemoryConsumer, createGraphEventEmitter as createMemoryGraphEventEmitter, createMemoryPublisher, getGraphEventEmitter, resetGraphEventEmitter } from '../chunk-7EISSMFP.js';
|
|
3
|
+
export { EventQueueFactory, QueueType, RedisStreamsEventConsumer, RedisStreamsEventPublisher } from '../chunk-K56L7NUR.js';
|
|
4
4
|
export { EVENT_STREAMS_URL_ENV_KEYS, GRAPH_EVENTS_URL_ENV_KEYS, eventKeyScopeForUrl, resolveEventStreamsUrl, resolveEventStreamsUrlSource, resolveGraphEventsUrl, resolveGraphEventsUrlSource } from '../chunk-KS2HQCJR.js';
|
|
5
|
-
import '../chunk-KO2ZXZ7W.js';
|
|
6
5
|
export { RedisStreamsConnection, dlqKey as redisDlqKey, streamKey as redisStreamKey } from '../chunk-6XEXJATV.js';
|
|
6
|
+
import '../chunk-KO2ZXZ7W.js';
|
|
7
7
|
import '../chunk-RU266375.js';
|
|
8
8
|
import '../chunk-XE4OXN2W.js';
|
|
9
9
|
//# sourceMappingURL=index.js.map
|
package/dist/graph/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
export { AUDIT_FIELDS, GraphEventsPublisher, GraphExportService, GraphModule, SOFT_DELETE_FIELDS, STANDARD_FIELDS, TENANT_FIELDS, createGraphEventsHelper, createGraphExportService, createPrismaGraphIntegration, createRelationshipFromEntity, defineEntity, defineGraphConfig, defineModuleGraph, defineRelationship, getGraphEventsPublisher, getGraphStats, initializeGraph, isGraphInitialized } from '../chunk-
|
|
2
|
-
export { GraphRegistry, addGraphExtension, createEntityEvent, createRelationshipEvent, extractEntityTitle, extractMinimalFields, getCollectionForEntity, parseRelationship, shouldSyncEntity, shouldSyncRelationship, withDeferredGraphEvents } from '../chunk-
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
5
|
-
import '../chunk-
|
|
1
|
+
export { AUDIT_FIELDS, GraphEventsPublisher, GraphExportService, GraphModule, SOFT_DELETE_FIELDS, STANDARD_FIELDS, TENANT_FIELDS, createGraphEventsHelper, createGraphExportService, createPrismaGraphIntegration, createRelationshipFromEntity, defineEntity, defineGraphConfig, defineModuleGraph, defineRelationship, getGraphEventsPublisher, getGraphStats, initializeGraph, isGraphInitialized } from '../chunk-O2JMZHNH.js';
|
|
2
|
+
export { GraphRegistry, addGraphExtension, createEntityEvent, createRelationshipEvent, extractEntityTitle, extractMinimalFields, getCollectionForEntity, parseRelationship, shouldSyncEntity, shouldSyncRelationship, withDeferredGraphEvents } from '../chunk-DJNHR37J.js';
|
|
3
|
+
import '../chunk-E6OAFS7A.js';
|
|
4
|
+
import '../chunk-7EISSMFP.js';
|
|
5
|
+
import '../chunk-K56L7NUR.js';
|
|
6
6
|
import '../chunk-KS2HQCJR.js';
|
|
7
|
-
import '../chunk-KO2ZXZ7W.js';
|
|
8
7
|
import '../chunk-6XEXJATV.js';
|
|
8
|
+
import '../chunk-KO2ZXZ7W.js';
|
|
9
9
|
import '../chunk-I3KOWRT3.js';
|
|
10
10
|
import '../chunk-5CAFHK2Z.js';
|
|
11
11
|
import '../chunk-RU266375.js';
|
|
@@ -282,9 +282,12 @@ interface TrackOptions {
|
|
|
282
282
|
};
|
|
283
283
|
usage?: {
|
|
284
284
|
enabled?: boolean;
|
|
285
|
-
|
|
285
|
+
quotaName?: string;
|
|
286
|
+
productId?: string;
|
|
287
|
+
description?: string;
|
|
286
288
|
amount?: number;
|
|
287
289
|
checkQuota?: boolean;
|
|
290
|
+
metricType?: UsageMetricType;
|
|
288
291
|
entityType?: 'user' | 'workspace' | 'organization';
|
|
289
292
|
};
|
|
290
293
|
notification?: {
|
|
@@ -308,6 +311,7 @@ interface TrackResult {
|
|
|
308
311
|
quotaAvailable?: boolean;
|
|
309
312
|
quotaRemaining?: number;
|
|
310
313
|
activityId?: string;
|
|
314
|
+
usageTracked?: boolean;
|
|
311
315
|
usageRecordId?: string;
|
|
312
316
|
notificationIds?: string[];
|
|
313
317
|
error?: {
|
|
@@ -326,9 +330,10 @@ declare class TrackerModule {
|
|
|
326
330
|
constructor(client: BurdenoffGraphQLClient, context?: SDKContext);
|
|
327
331
|
track(options: TrackOptions): Promise<TrackResult>;
|
|
328
332
|
trackOrThrow(options: TrackOptions): Promise<TrackResult>;
|
|
329
|
-
trackSimple(userId: string, action: string, resourceType: string, resourceId?: string,
|
|
333
|
+
trackSimple(userId: string, action: string, resourceType: string, resourceId?: string, _metricType?: UsageMetricType): Promise<boolean>;
|
|
330
334
|
private validateOptions;
|
|
331
335
|
private checkPermission;
|
|
336
|
+
private resolveUsage;
|
|
332
337
|
private checkQuota;
|
|
333
338
|
private trackUsage;
|
|
334
339
|
private logSuccessActivity;
|
package/dist/index.d.ts
CHANGED
|
@@ -7,8 +7,8 @@ import { T as TenantNotificationsModule, a as NotificationsModule } from './inde
|
|
|
7
7
|
export { t as Notifications } from './index-DwMJZ8PP.js';
|
|
8
8
|
import { RBACModule } from './rbac/index.js';
|
|
9
9
|
export { LayerAwareRBACConfig, RBACDirectiveConfig, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './rbac/index.js';
|
|
10
|
-
import { A as ActivityModule, T as TrackerModule } from './index-
|
|
11
|
-
export { a as Activity, b as ActivityActorType, c as ActivityOperationUnsupportedError, G as GetActivitiesOptions, L as LogActivityOptions } from './index-
|
|
10
|
+
import { A as ActivityModule, T as TrackerModule } from './index-DnjJ9CwI.js';
|
|
11
|
+
export { a as Activity, b as ActivityActorType, c as ActivityOperationUnsupportedError, G as GetActivitiesOptions, L as LogActivityOptions } from './index-DnjJ9CwI.js';
|
|
12
12
|
import { UsageModule } from './usage/index.js';
|
|
13
13
|
export { BillingUsageClient, BillingUsageClientConfig, BillingUsageOperationInput, OrgBillingUsageOperationInput, QuotaLimit, WorkspaceBillingUsageOperationInput } from './usage/index.js';
|
|
14
14
|
import { DatabaseConfig, DatabaseModule } from './database/index.js';
|
package/dist/index.js
CHANGED
|
@@ -1,31 +1,30 @@
|
|
|
1
1
|
export { NAME_MAX_LENGTH, NAME_MIN_LENGTH, RbacCoverageError, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, validation_exports as Validation, analyzeRbacCoverage, assertRbacCoverage, lengthInCodePoints, validateName, validateUserFields, validateUsername } from './chunk-PYD44IHJ.js';
|
|
2
|
+
export { init_exports as Init } from './chunk-OBZQ4AJC.js';
|
|
2
3
|
export { sharing_exports as Sharing } from './chunk-554Z4C2K.js';
|
|
3
4
|
export { tags_exports as Tags } from './chunk-PBZFAAOM.js';
|
|
4
5
|
export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager } from './chunk-VXVLKRU6.js';
|
|
5
|
-
import { ActivityModule, TrackerModule } from './chunk-
|
|
6
|
-
export { ActivityModule, ActivityOperationUnsupportedError, TrackerModule } from './chunk-
|
|
7
|
-
import './chunk-
|
|
8
|
-
|
|
9
|
-
export { BillingUsageClient, UsageModule } from './chunk-TRYGWO7H.js';
|
|
10
|
-
export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
|
|
6
|
+
import { ActivityModule, TrackerModule } from './chunk-2T3N5SNW.js';
|
|
7
|
+
export { ActivityModule, ActivityOperationUnsupportedError, TrackerModule } from './chunk-2T3N5SNW.js';
|
|
8
|
+
import { UsageModule } from './chunk-QVPIACWD.js';
|
|
9
|
+
export { BillingUsageClient, UsageModule } from './chunk-QVPIACWD.js';
|
|
11
10
|
import { TenantNotificationsModule, NotificationsModule } from './chunk-KH4TRQCO.js';
|
|
12
11
|
export { tenant_notifications_exports as Notifications, NotificationsModule } from './chunk-KH4TRQCO.js';
|
|
13
12
|
export { observability_exports as Observability } from './chunk-VAT66FJA.js';
|
|
14
13
|
export { platform_exports as Platform } from './chunk-HC6MPUIH.js';
|
|
15
|
-
export { prisma_exports as Prisma } from './chunk-
|
|
16
|
-
import './chunk-E4QNLVY4.js';
|
|
14
|
+
export { prisma_exports as Prisma } from './chunk-FHVBMQDW.js';
|
|
17
15
|
export { PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, product_alias_exports as ProductAlias, RENAME_CONCERNS, billingIdVariants, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, templateKeyVariants, toCurrentName, toLegacyName } from './chunk-OBBCR6WY.js';
|
|
18
16
|
import { RBACModule } from './chunk-A6DE32ZS.js';
|
|
19
17
|
export { RBACModule, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './chunk-A6DE32ZS.js';
|
|
20
|
-
export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
|
|
21
|
-
export { init_exports as Init } from './chunk-FG37SJML.js';
|
|
22
18
|
export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-63ZXJ42X.js';
|
|
19
|
+
import './chunk-JVMAQOA3.js';
|
|
20
|
+
import './chunk-E4QNLVY4.js';
|
|
21
|
+
export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
|
|
23
22
|
export { instrumentation_exports as Instrumentation } from './chunk-RYTSVGGA.js';
|
|
24
23
|
import './chunk-GCIB76AJ.js';
|
|
24
|
+
export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
|
|
25
25
|
export { export_exports as Export } from './chunk-VTJTAAXC.js';
|
|
26
26
|
export { feature_flags_exports as FeatureFlags } from './chunk-UNASM5VJ.js';
|
|
27
27
|
export { files_exports as Files } from './chunk-OXNCBE7P.js';
|
|
28
|
-
export { cache_exports as Cache } from './chunk-XOJORS75.js';
|
|
29
28
|
export { gateway_exports as Gateway } from './chunk-CFXWH2IS.js';
|
|
30
29
|
import './chunk-726AR6Q7.js';
|
|
31
30
|
import { GatewayClient } from './chunk-SPRG6G6G.js';
|
|
@@ -35,25 +34,26 @@ import './chunk-VFCMR5GX.js';
|
|
|
35
34
|
import { ContextManager } from './chunk-RZOFS2BQ.js';
|
|
36
35
|
export { ContextManager } from './chunk-RZOFS2BQ.js';
|
|
37
36
|
import { GatewayError, GatewayErrorType } from './chunk-QWNNFE4P.js';
|
|
38
|
-
import './chunk-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
import './chunk-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
import './chunk-
|
|
45
|
-
import { QueueType, EventQueueFactory } from './chunk-XGNOYVSW.js';
|
|
37
|
+
import { GraphModule } from './chunk-O2JMZHNH.js';
|
|
38
|
+
export { graph_exports as Graph, GraphModule } from './chunk-O2JMZHNH.js';
|
|
39
|
+
import './chunk-DJNHR37J.js';
|
|
40
|
+
import { EventsModule } from './chunk-E6OAFS7A.js';
|
|
41
|
+
export { event_queue_exports as EventQueue, EventsModule } from './chunk-E6OAFS7A.js';
|
|
42
|
+
import './chunk-7EISSMFP.js';
|
|
43
|
+
import { QueueType, EventQueueFactory } from './chunk-K56L7NUR.js';
|
|
46
44
|
import { resolveEventStreamsUrl } from './chunk-KS2HQCJR.js';
|
|
47
|
-
import { disposeAll } from './chunk-KO2ZXZ7W.js';
|
|
48
|
-
export { lifecycle_exports as Lifecycle, disposeAll, getRegisteredDisposableCount, registerDisposable, unregisterDisposable } from './chunk-KO2ZXZ7W.js';
|
|
49
45
|
export { graphql_exports as GraphQL } from './chunk-ZZK3WEDI.js';
|
|
50
46
|
import './chunk-MWPYA2HD.js';
|
|
51
47
|
import './chunk-6XEXJATV.js';
|
|
48
|
+
export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
|
|
52
49
|
export { ai_credits_exports as AiCredits } from './chunk-MESLAC5W.js';
|
|
53
50
|
import { AuthModule } from './chunk-4XIBXZ6J.js';
|
|
54
51
|
export { AuthModule } from './chunk-4XIBXZ6J.js';
|
|
55
52
|
export { utils_exports as Utils } from './chunk-LA5KPWZ2.js';
|
|
56
|
-
export {
|
|
53
|
+
export { cache_exports as Cache } from './chunk-XOJORS75.js';
|
|
54
|
+
import './chunk-A5F6Z5UE.js';
|
|
55
|
+
import { disposeAll } from './chunk-KO2ZXZ7W.js';
|
|
56
|
+
export { lifecycle_exports as Lifecycle, disposeAll, getRegisteredDisposableCount, registerDisposable, unregisterDisposable } from './chunk-KO2ZXZ7W.js';
|
|
57
57
|
export { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from './chunk-KJOSPVB2.js';
|
|
58
58
|
export { crypto_exports as Crypto } from './chunk-SBS4S2PJ.js';
|
|
59
59
|
import { DatabaseModule } from './chunk-ID3WR4JS.js';
|