@camunda/ccma-api 5.17.0 → 5.18.0
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/index.d.ts +2 -2
- package/dist/index.js.map +2 -2
- package/dist/services/audit-logger/audit-logger.system.service.js +3 -0
- package/dist/services/audit-logger/audit-logger.system.service.js.map +2 -2
- package/dist/services/audit-logger/audit-logger.system.service.spec.d.ts +1 -0
- package/dist/services/console/console.approvals.m2m.service.d.ts +36 -1
- package/dist/services/console/console.approvals.m2m.service.js +41 -0
- package/dist/services/console/console.approvals.m2m.service.js.map +2 -2
- package/dist/services/control/control.approvals.service.d.ts +38 -3
- package/dist/services/control/control.approvals.service.js +18 -0
- package/dist/services/control/control.approvals.service.js.map +2 -2
- package/dist/utils/api.d.ts +6 -0
- package/dist/utils/api.js +7 -3
- package/dist/utils/api.js.map +2 -2
- package/dist/utils/api.redact-body.spec.d.ts +1 -0
- package/package.json +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/services/control/control.approvals.service.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type {\n ApprovalEntityType,\n ApprovalJobDto,\n ApprovalJobStatus,\n ApprovalSortField,\n ApprovalSortOrder,\n ApprovalStatusCountsDto,\n ApprovalUseCaseDto,\n ClusterBulkOperationPayloadDto,\n ClusterBulkOperationType,\n ClusterCorpseKind,\n ClusterPlanModificationConfig,\n ClusterTtlDeletionPayload,\n EnterpriseIncludingValueMetrics,\n GenerationImageVersionsDto,\n LicensingModelType,\n ReleaseTrainPublishPayload,\n ReleaseTrainRollbackPayload,\n} from '@camunda/ccma-shared-types'\nimport { CLUSTER_BULK_OPERATION_RULES } from '@camunda/ccma-shared-types'\nimport type {\n RequestBaseParams,\n RequestBaseServiceContext,\n} from '../../types/general.types.js'\nimport { request } from '../../utils/api.js'\nimport { HttpError } from '../../utils/errors.js'\n\n/**\n * The four-eyes approval surface of control-backend.\n *\n * One service for the whole mechanism, and not one for each use case. The\n * generic routes (list, read, approve, reject, withdraw, run) carry no\n * knowledge of a use case, which is what lets one view in control-frontend\n * show every privileged action. Only the create calls are per use case,\n * because a payload can be validated only for the use case it belongs to.\n *\n * A use case that walks its own rollout behind a flag answers 404 on its\n * create route while that flag is off.\n */\n\nconst BASE = { id: 'control' } as const\n\nexport interface ApprovalPageDto {\n approvals: ApprovalJobDto[]\n page: {\n limit: number\n offset: number\n /** True when the next page holds more. Never read the length instead. */\n hasMore: boolean\n }\n}\n\n/**\n * What narrows the queue. The list and the counts read the same fields.\n *\n * `entityType` and `entityId` are ONE filter, not two. control-backend answers\n * 400 for one without the other, so the type carries both or neither.\n */\nexport type ApprovalFacetParams = {\n /** One use case type, or more. A request matches when its type is any of them. */\n type?: string | readonly string[]\n /**\n * One organization, matched whole against `orgId` of the payload.\n *\n * It reads only the payload, so `entityType`/`entityId` is wider. That filter\n * reads the entity link, so it finds a request that touches the organization\n * through another field. The organization page of control-frontend asks the\n * entity-link filter, not this one. `orgId` is also not `q`: the free text\n * reads the whole payload as text.\n */\n orgId?: string\n /**\n * Free text. control-backend matches it in the reason, the person who\n * opened the request, the action and its label, and the payload that the\n * summary shows.\n */\n q?: string\n /**\n * The queue of one person: what they opened, or what waits for them.\n *\n * `actionable` is the rule of the Approve button asked in SQL \u2014 pending,\n * opened by somebody else, not approved by this person yet, and guarded by\n * permissions that they hold.\n */\n mine?: 'created' | 'actionable'\n} & (\n | {\n /**\n * The kind of entity a request must touch. Read with `entityId`.\n *\n * It reads the entity link of control-backend, so it is wider and truer\n * than `orgId`: a cluster-move request answers for its source\n * organization, its target organization AND the cluster. The organization\n * and cluster detail pages of control-frontend ask this.\n */\n entityType: ApprovalEntityType\n /** The id of the entity a request must touch. Read with `entityType`. */\n entityId: string\n }\n | { entityType?: never; entityId?: never }\n)\n\nexport interface ListApprovalsRequest extends RequestBaseParams {\n params?: ApprovalFacetParams & {\n status?: ApprovalJobStatus\n /**\n * An ISO 8601 instant. Only the requests that changed at or after it: the\n * last write of the request, or the run of its action. A control-backend\n * from before this parameter ignores it and answers every request.\n */\n updatedSince?: string\n sort?: ApprovalSortField\n order?: ApprovalSortOrder\n limit?: number\n offset?: number\n }\n}\n\nexport interface CountApprovalsRequest extends RequestBaseParams {\n params?: ApprovalFacetParams\n}\n\nexport interface ApprovalIdRequest extends RequestBaseParams {\n params: { id: string }\n}\n\nexport interface RejectApprovalRequest extends RequestBaseParams {\n params: { id: string; reason: string }\n}\n\n/** A withdrawal says why, or says nothing. The reason is not demanded. */\nexport interface WithdrawApprovalRequest extends RequestBaseParams {\n params: { id: string; reason?: string }\n}\n\n/** The envelope that every create route of every use case shares. */\nexport interface CreateApprovalRequest<TPayload> extends RequestBaseParams {\n params: {\n payload: TPayload\n reason?: string\n /** More approvals than the floor of the use case. Never fewer. */\n requiredAcks?: number\n }\n}\n\nexport interface SendToExpiredTrialPayloadDto {\n orgId: string\n orgName?: string\n}\n\nexport interface CreatePersonalOrganisationPayloadDto {\n /** 3 to 100 characters, after the spaces at both ends are cut. */\n name: string\n}\n\n/**\n * The create call of `create-personal-organisation`.\n *\n * It has no `requiredAcks`: the request needs no approval, and the route\n * answers 400 to a body that names the field.\n */\nexport interface CreatePersonalOrganisationRequest extends RequestBaseParams {\n params: {\n payload: CreatePersonalOrganisationPayloadDto\n reason?: string\n }\n}\n\n/** The create call of `extend-trial`. It has no `requiredAcks`. */\nexport interface CreateExtendTrialRequest extends RequestBaseParams {\n params: {\n payload: ExtendTrialPayloadDto\n reason?: string\n }\n}\n\n/** The create call of `cluster-ttl-deletion`. It has no `requiredAcks`. */\nexport interface CreateClusterTtlDeletionRequest extends RequestBaseParams {\n params: {\n payload: ClusterTtlDeletionPayload\n reason?: string\n }\n}\n\nexport interface CreateCustomHardwareSizingPayloadDto {\n /** The organization that gets the plan. The requester must own it. */\n orgId: string\n /** 3 to 100 characters, after the spaces at both ends are cut. */\n name: string\n /** The cluster plan, in the same format as the plan route of the admin tool. */\n plan: Record<string, unknown>\n clusterPlanId?: never\n}\n\n/** An existing cluster plan. Nothing is created: it is added to the list of the organization. */\nexport interface LinkCustomHardwareSizingPayloadDto {\n /** The organization that gets the plan. The requester must own it. */\n orgId: string\n clusterPlanId: string\n name?: never\n plan?: never\n}\n\n/**\n * `unlink` removes the plan from one organization that the requester owns.\n * `delete` removes it from every organization of the requester, and deletes it.\n */\nexport type RemoveCustomHardwareSizingPayloadDto =\n | { mode: 'unlink'; clusterPlanId: string; orgId: string }\n | { mode: 'delete'; clusterPlanId: string }\n\nexport interface CreateCustomGenerationPayloadDto {\n /** The organization that gets the generation. The requester must own it. */\n orgId: string\n /** 3 to 100 characters, after the spaces at both ends are cut. */\n name: string\n /** The images and env vars, in the format of the generation route of the admin tool. */\n versions: Record<string, string>\n /** Generations whose clusters can upgrade to this one. */\n upgradeableFrom?: string[]\n generationId?: never\n}\n\n/** An existing generation. Nothing is created: it is added to the list of the organization. */\nexport interface LinkCustomGenerationPayloadDto {\n /** The organization that gets the generation. The requester must own it. */\n orgId: string\n generationId: string\n name?: never\n versions?: never\n upgradeableFrom?: never\n}\n\n/**\n * `unlink` removes the generation from one organization that the requester\n * owns. `delete` removes it from every organization of the requester, and\n * deletes it.\n */\nexport type RemoveCustomGenerationPayloadDto =\n | { mode: 'unlink'; generationId: string; orgId: string }\n | { mode: 'delete'; generationId: string }\n\n/**\n * `apply` applies a new config to a cluster of an organization that the\n * requester owns, and the new config replaces the active config. `deactivate`\n * deactivates the active config `configId`.\n */\nexport type SelfServiceClusterModificationPayloadDto =\n | {\n mode: 'apply'\n orgId: string\n clusterUuid: string\n /** 1 to 500 characters. */\n description: string\n /** At least one entry. */\n planModifications: ClusterPlanModificationConfig[]\n /** An ISO datetime with an offset, for example `toISOString()`. */\n expiresAt?: string\n }\n | { mode: 'deactivate'; orgId: string; clusterUuid: string; configId: string }\n\n/**\n * The call of a self-service use case: custom hardware sizing and custom\n * generations. Like `CreatePersonalOrganisationRequest`, it has no\n * `requiredAcks`.\n */\nexport interface SelfServiceApprovalRequest<TPayload>\n extends RequestBaseParams {\n params: {\n payload: TPayload\n reason?: string\n }\n}\n\n/** @deprecated Use `SelfServiceApprovalRequest`. */\nexport type CustomHardwareSizingRequest<TPayload> =\n SelfServiceApprovalRequest<TPayload>\n\nexport interface ExtendTrialPayloadDto {\n orgId: string\n orgName?: string\n /**\n * Days of trial counted from the moment the action RUNS.\n *\n * Never a date. Accounts holds the new expiry inside a window that it\n * measures when the call arrives, and under approvals that is days after the\n * person chose the value. See `use-cases/extend-trial.ts` in\n * control-backend.\n */\n days: number\n}\n\nexport interface MoveClusterOrgPayloadDto {\n clusterId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n clusterName?: string\n targetOrgId: string\n /** A copy, for the same reason as `clusterName`. */\n targetOrgName?: string\n // The SOURCE organization is not here on purpose. control-backend resolves it\n // server-side from the cluster's current owner, so a caller cannot attach the\n // request to an organization the cluster never belonged to.\n}\n\nexport interface ChangePlatformRolesPayloadDto {\n userId: string\n /** A copy, so a list shows a person and not an Auth0 id. Nothing reads it. */\n userEmail?: string\n /**\n * A CHANGE, and never the whole set. Accounts applies it over the roles that\n * the user holds when the action RUNS, so a role change that somebody else\n * made while the request waited stays.\n */\n rolesToAdd: string[]\n rolesToRemove: string[]\n}\n\nexport interface ChangeOrgLimitsPayloadDto {\n orgId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n orgName?: string\n /** One key of `allSalesPlanLimits()`. One limit for each request. */\n limitKey: string\n /**\n * The override that the person who asked READ. Absent for \"not set\".\n *\n * Accounts compares it with the override that it holds when the action\n * runs, and writes nothing when the two differ. See `staleApprovalKeys`.\n */\n expected?: string | number | boolean\n /** The new override. `null` clears it, and the default of the plan applies. */\n value: string | number | boolean | null\n}\n\n/** One generation of a change-generation-versions request. */\nexport interface ChangeGenerationVersionsTargetDto {\n id: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n name?: string\n /**\n * A copy of the cluster count when the request was opened, for the\n * approver. Absent when the browser could not read it.\n */\n clusterCount?: number\n /**\n * The values that the person who asked READ, one for each key of\n * `versions`. Console changes nothing on this generation when one differs\n * at the run.\n */\n expectedVersions: GenerationImageVersionsDto\n}\n\n/**\n * The payload of a delete-cluster-corpses request, as a browser sends it.\n * control-backend reads the corpses of the kind from console and stores them\n * with the request, as the set that the approvers read.\n */\nexport interface DeleteClusterCorpsesPayloadDto {\n kind: ClusterCorpseKind\n}\n\nexport interface ChangeGenerationVersionsPayloadDto {\n generations: ChangeGenerationVersionsTargetDto[]\n /**\n * The image versions to write on every generation. Only the keys that\n * change are here. An empty string clears an optional one. The env var\n * fields never go through a request: see `GENERATION_IMAGE_VERSION_KEYS`.\n */\n versions: GenerationImageVersionsDto\n}\n\n/**\n * The payload of a force-delete-cluster-plan-type request, as a browser\n * sends it. control-backend reads the clusters of the type from console and\n * stores them with the request, as the set that the approvers read.\n */\nexport interface ForceDeleteClusterPlanTypePayloadDto {\n planTypeId: string\n}\n\n/**\n * The payload of an automated-enterprise-onboarding request: the fields of\n * the accounts wizard \"New Enterprise Onboarding\".\n */\nexport interface AutomatedEnterpriseOnboardingPayloadDto {\n /** The prefix of the two organization names. */\n orgName: string\n sfdcId: string\n awsOnly: boolean\n renewalTermInMonths: number\n licensingModel: 'legacy' | '2025'\n /** The start of the subscription, `YYYY-MM-DD`. */\n startDate: string\n valueMetrics: {\n processInstances: number\n decisionInstances: number\n taskUsers: number\n tenants: number\n }\n reservations: {\n basic: number\n standard: number\n advanced: number\n }\n /** The person who becomes the owner of both organizations. */\n ownerEmail: string\n}\n\n/** One cluster of the organization and the plan type it moves to. */\nexport interface OnboardToEnterpriseClusterDto {\n clusterId: string\n /** A copy, so the approver reads a name. Nothing reads it. */\n clusterName?: string\n planTypeId: string\n /** A copy of the name of the plan type, for the approver to read. */\n planTypeName?: string\n numberOfAllocatedHwPackages?: number\n keepModification: boolean\n}\n\nexport interface OnboardToEnterprisePayloadDto {\n orgId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n orgName?: string\n salesPlanId: string\n /** A copy of the name of the new plan, for the approver to read. */\n salesPlanName?: string\n /**\n * The plan that the person who asked READ. Accounts compares it with the\n * plan that it holds when the action runs, and switches nothing when the\n * two differ. An organization with no plan cannot be onboarded this way.\n */\n expectedSalesPlanId: string\n expectedSalesPlanName?: string\n contract: {\n /** The renewal term, in months. */\n duration: number\n includedValueMetrics: EnterpriseIncludingValueMetrics\n /** `YYYY-MM-DD`. */\n enterPriseStartDate: string\n enterpriseDevOnly: boolean\n awsOnly: boolean\n licensingModel: LicensingModelType\n salesForceId?: string\n }\n /** One entry for each cluster of the organization. Empty for none. */\n clusters: OnboardToEnterpriseClusterDto[]\n /** The reservations after the switch, by plan type uuid. */\n reservations: Record<string, number>\n /** The names of the plan types of `reservations`, for the approver. */\n reservationNames?: Record<string, string>\n}\n\nexport interface ChangeClusterPlanTypePayloadDto {\n clusterId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n clusterName?: string\n /** The organization that owns the cluster. Console refuses another one. */\n orgId: string\n /** A copy, for the same reason as `clusterName`. */\n orgName?: string\n toPlanTypeUuid: string\n /** A copy of the name of the new plan type, for the approver to read. */\n toPlanTypeName?: string\n /**\n * The hardware packages of the cluster after the change, 1 at least.\n *\n * Always sent, also for a plan type with no availability class, where it is\n * 1. Console checks the reservations of the organization only when the\n * packages are in the call, and the check is the point of this use case.\n */\n numberOfAllocatedHwPackages: number\n /**\n * The plan type that the person who asked READ.\n *\n * Console compares it with the plan type of the cluster when the action\n * runs, and changes nothing when the two differ.\n */\n expectedPlanTypeUuid: string\n /** A copy of the name of the current plan type, for the approver to read. */\n expectedPlanTypeName?: string\n /**\n * The hardware packages that the person who asked READ, 1 for a cluster\n * that holds none. The same stale guard as `expectedPlanTypeUuid`.\n */\n expectedNumberOfAllocatedHwPackages: number\n /**\n * The cluster plan that the person who asked READ. Console decides the\n * plan move from it, so it is part of the stale guard too, and Console\n * refuses a cluster that runs none, so a request needs one.\n */\n expectedClusterPlanUuid: string\n /** A copy of the name of that plan, for the approver to read. */\n expectedClusterPlanName?: string\n /**\n * The active modification config that the person who asked READ, absent\n * when the cluster has none. The change removes it, and an approver must\n * read which one goes.\n */\n expectedActiveModificationConfigUuid?: string\n /**\n * The active plan of the NEW plan type that the person who asked READ. The\n * cluster moves to it, so a plan that a Camundi changed on the type while\n * the request waited fails the guard, and Console refuses a type that has\n * none, so a request needs one.\n */\n expectedTargetPlanUuid: string\n /** A copy of the name of that plan, for the approver to read. */\n expectedTargetPlanName?: string\n /**\n * Whether the cluster plan moves to the active plan of the new type, as\n * the dialog read it. The list of migratable plans can change while the\n * request waits, and a verdict that moved changes whether the cluster\n * restarts, so Console refuses a request whose verdict moved.\n */\n expectedClusterPlanUpdate: boolean\n /**\n * Whether the active modification config of the cluster stays after the\n * change. Absent reads as false: the change removes it, and the approver\n * reads which one goes. The dialog shows what the config changes, so the\n * person who asks can choose.\n */\n keepModification?: boolean\n}\n\nexport interface ChangeSalesPlanPayloadDto {\n orgId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n orgName?: string\n salesPlanId: string\n /** A copy of the name of the new plan, for the approver to read. */\n salesPlanName?: string\n /**\n * The plan that the person who asked READ. Absent for \"no plan\".\n *\n * Accounts compares it with the plan that it holds when the action runs,\n * and switches nothing when the two differ.\n */\n expectedSalesPlanId?: string\n /** A copy of the name of the current plan, for the approver to read. */\n expectedSalesPlanName?: string\n /** Skips the validation of the switch. The approver sees it. */\n force: boolean\n}\n\n/** Every value of a flag row that a person can change. */\nexport interface FeatureFlagValuesDto {\n description: string\n enabled: boolean\n orgIds: string[]\n emailDomains: string[]\n /** The team that owns the flag. A create needs it. An older row has none. */\n owner?: string\n /** `YYYY-MM-DD`, the day after which the flag is late. */\n expiresAt?: string\n /**\n * The issue that tracks the flag. A create and an edit need it. An older\n * row has none.\n */\n issueUrl?: string\n}\n\n/**\n * One change of the feature flag table: the action, and the whole row that it\n * asks for.\n *\n * An edit and a delete carry the row that the person who asked READ, as\n * `expected`. The action writes nothing when the row changed in the meantime.\n * `key` of an edit and a delete is a copy for the approver, and the action\n * compares it too.\n */\nexport type ChangeFeatureFlagPayloadDto =\n | {\n action: 'create'\n key: string\n value: FeatureFlagValuesDto & { owner: string; issueUrl: string }\n }\n | {\n action: 'update'\n id: string\n key: string\n expected: FeatureFlagValuesDto\n value: FeatureFlagValuesDto & { issueUrl: string }\n }\n | {\n action: 'delete'\n id: string\n key: string\n expected: FeatureFlagValuesDto\n }\n\nexport interface DeleteSsoConnectionPayloadDto {\n strategy: 'waad' | 'samlp'\n connectionId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n connectionName?: string\n /**\n * The organizations that the connection serves, as copies for the approver.\n * The request is findable on the page of each one.\n */\n orgIds?: string[]\n}\n\nexport interface DeleteOrganizationPayloadDto {\n orgId: string\n /**\n * The name that the approvers read. Accounts refuses the deletion when the\n * organization has another name when the action runs.\n */\n orgName: string\n}\n\nexport interface DeleteUserPayloadDto {\n userId: string\n /**\n * The address that the approvers read. Accounts refuses the deletion when\n * the user has another address when the action runs.\n */\n userEmail: string\n}\n\nexport interface ChangeUserEmailPayloadDto {\n userId: string\n /**\n * The address that the person who asked READ. Accounts compares it with\n * the address that the user has when the action runs, and changes nothing\n * when the two differ.\n */\n expectedEmail: string\n newEmail: string\n}\n\nexport interface PurgeUsersPayloadDto {\n /**\n * The users to delete, at most `PURGE_USERS_MAX_USERS`. The address is a\n * copy for the approver, and accounts refuses a user whose address is not\n * that copy. A list that came from a file of ids carries none.\n */\n users: { userId: string; email?: string }[]\n}\n\nexport interface UpdateUserMetadataPayloadDto {\n userId: string\n /** A copy, so a list shows a person and not an Auth0 id. Nothing reads it. */\n userEmail?: string\n /** `app` writes `app_metadata`, `user` writes `user_metadata`. */\n kind: 'app' | 'user'\n /**\n * The metadata that the person who asked READ. Absent for \"not set\".\n * Accounts writes nothing when it holds another value when the action runs.\n */\n expected?: Record<string, unknown>\n metadata: Record<string, unknown>\n}\n\nexport interface DeleteInternalBackupPayloadDto {\n clusterId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n clusterName?: string\n backupName: string\n /** A copy of the Slack link of the incident, for the approver to read. */\n incidentLink?: string\n}\n\n/**\n * The query string of a read, with the fields that carry no value dropped.\n *\n * An empty value is not the same as an absent one: `q=` would reach the schema\n * of control-backend, which holds the text at one character and answers 400.\n * A list goes as one comma list, which is the form control-backend reads for\n * `type`. An empty list is dropped like an empty text.\n */\nfunction querySuffix(params: object = {}): string {\n const query = new URLSearchParams()\n for (const [key, raw] of Object.entries(params)) {\n const value = Array.isArray(raw) ? raw.join(',') : raw\n if (value !== undefined && value !== '') {\n query.set(key, String(value))\n }\n }\n return query.size > 0 ? `?${query.toString()}` : ''\n}\n\nfunction contextFor(\n name: string,\n url: string,\n normalizedUrl: string,\n type: 'get' | 'post',\n source: string,\n): RequestBaseServiceContext {\n return {\n method: {\n name: `ControlApprovalsService.${name}`,\n url,\n normalizedUrl,\n type,\n },\n source,\n target: { name: 'control', type: 'internal' },\n }\n}\n\nexport class ControlApprovalsService {\n /**\n * The registered privileged actions, with the rules that guard each one.\n *\n * A frontend reads this to run the same policy as the service, so it never\n * holds a copy of the registry. A new use case then needs no frontend\n * deploy.\n */\n public static async listUseCases(\n params: RequestBaseParams,\n ): Promise<ApprovalUseCaseDto[]> {\n const serviceContext = contextFor(\n 'listUseCases',\n 'api/approvals/use-cases',\n 'api/approvals/use-cases',\n 'get',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ useCases: ApprovalUseCaseDto[] }>({\n config: params.config,\n base: BASE,\n url: serviceContext.method.url,\n method: 'get',\n metricsDetails: serviceContext,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!.useCases\n }\n\n /**\n * One page of the requests that the caller can read.\n *\n * It is not the whole table: control-backend hides a request whose use case\n * the caller cannot act on, unless the caller opened it.\n */\n public static async list(\n params: ListApprovalsRequest,\n ): Promise<ApprovalPageDto> {\n const suffix = querySuffix(params.params)\n const serviceContext = contextFor(\n 'list',\n `api/approvals${suffix}`,\n 'api/approvals',\n 'get',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<ApprovalPageDto>({\n config: params.config,\n base: BASE,\n url: serviceContext.method.url,\n method: 'get',\n metricsDetails: serviceContext,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!\n }\n\n /**\n * How many requests each status holds, for the status filters of a queue.\n *\n * It is the same question as `list` without the status, so a filter that\n * shows a number never opens an empty page.\n */\n public static async counts(\n params: CountApprovalsRequest,\n ): Promise<ApprovalStatusCountsDto> {\n const suffix = querySuffix(params.params)\n const serviceContext = contextFor(\n 'counts',\n `api/approvals/counts${suffix}`,\n 'api/approvals/counts',\n 'get',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ counts: ApprovalStatusCountsDto }>({\n config: params.config,\n base: BASE,\n url: serviceContext.method.url,\n method: 'get',\n metricsDetails: serviceContext,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!.counts\n }\n\n public static async get(params: ApprovalIdRequest): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'get',\n `api/approvals/${params.params.id}`,\n 'api/approvals/:id',\n 'get',\n )\n }\n\n /**\n * What a create route answers, plus whether it opened a NEW request.\n *\n * The route answers 201 for a fresh request and 200 for the one already\n * open for the same target \u2014 `create` deduplicates. A caller that must\n * tell the two apart (a floor-of-one use case, where 200 is the ordinary\n * path and not a failure) reads `created`.\n */\n public static async createMoveClusterOrg(\n params: CreateApprovalRequest<MoveClusterOrgPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createMoveClusterOrg',\n 'api/approvals/move-cluster-org',\n )\n }\n\n /**\n * Opens a cluster bulk operation of one type.\n *\n * Each type is its own use case with its own route, because each one has\n * its own permission. The floor of approvals is the same for every type,\n * and it depends on the stage: 2 on prod, 1 on dev, int and local. The\n * route is `api/approvals/<use case>`, as for every other use case. A 200\n * means that the same operation over the same clusters is already open.\n */\n public static async createClusterBulkOperation<\n T extends ClusterBulkOperationType,\n >(\n type: T,\n params: CreateApprovalRequest<ClusterBulkOperationPayloadDto<T>>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n const useCase = CLUSTER_BULK_OPERATION_RULES[type].useCase\n return ControlApprovalsService.create(\n params,\n 'createClusterBulkOperation',\n `api/approvals/${useCase}`,\n )\n }\n\n /**\n * Opens a change-platform-roles request.\n *\n * Opening one needs `accounts:admin:changeRole`, the same permission that\n * approving needs, and the reason is necessary. A 200 means that a request\n * for the same user is already open.\n */\n public static async createChangePlatformRoles(\n params: CreateApprovalRequest<ChangePlatformRolesPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangePlatformRoles',\n 'api/approvals/change-platform-roles',\n )\n }\n\n /**\n * Opens a delete-internal-backup request.\n *\n * Opening one needs `console:clusters:canCreateInternalBackup`, the same\n * permission that approving needs. A 200 means that a request for the same\n * backup is already open.\n */\n public static async createDeleteInternalBackup(\n params: CreateApprovalRequest<DeleteInternalBackupPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteInternalBackup',\n 'api/approvals/delete-internal-backup',\n )\n }\n\n /**\n * Opens a change-org-limits request.\n *\n * Opening one needs `accounts:admin:mayChangeOrgLimits`, the same\n * permission that approving needs. A 200 means that a request for the same\n * limit of the same organization is already open.\n */\n public static async createChangeOrgLimits(\n params: CreateApprovalRequest<ChangeOrgLimitsPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeOrgLimits',\n 'api/approvals/change-org-limits',\n )\n }\n\n /**\n * Opens a delete-sso-connection request.\n *\n * Opening one needs `AccountsPermissions.ADMIN_AUTH0_CONNECTIONS_DELETE`, the same\n * permission that approving needs. A 200 means that a request for the same\n * connection is already open.\n */\n public static async createDeleteSsoConnection(\n params: CreateApprovalRequest<DeleteSsoConnectionPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteSsoConnection',\n 'api/approvals/delete-sso-connection',\n )\n }\n\n /**\n * Opens an onboard-to-enterprise request.\n *\n * Opening one needs `AccountsPermissions.ENTERPRISE_ORG_CONVERT`, the same\n * permission that approving needs. A 200 means that a request for the same\n * organization is already open. The route answers 404 while\n * `control.onboardToEnterpriseApproval` is off.\n */\n public static async createOnboardToEnterprise(\n params: CreateApprovalRequest<OnboardToEnterprisePayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createOnboardToEnterprise',\n 'api/approvals/onboard-to-enterprise',\n )\n }\n\n /**\n * Opens a change-sales-plan request.\n *\n * Opening one needs `AccountsPermissions.SALES_PLAN_SWITCH`, the same\n * permission that approving needs. A 200 means that a request for the same\n * organization is already open.\n */\n public static async createChangeSalesPlan(\n params: CreateApprovalRequest<ChangeSalesPlanPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeSalesPlan',\n 'api/approvals/change-sales-plan',\n )\n }\n\n /**\n * Opens a change-generation-versions request.\n *\n * Opening one needs `ConsolePermissions.CHANNELS_AND_GENERATIONS_ADMIN`,\n * the same permission that approving needs. A 200 means that a request\n * over the same generations is already open. The route answers 404 while\n * `control.changeGenerationVersions` is off.\n */\n public static async createChangeGenerationVersions(\n params: CreateApprovalRequest<ChangeGenerationVersionsPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeGenerationVersions',\n 'api/approvals/change-generation-versions',\n )\n }\n\n /**\n * Opens a delete-cluster-corpses request.\n *\n * Opening one needs `ConsolePermissions.CLUSTERS_DELETE_CLUSTER`, the same\n * permission that approving needs. A 200 means that a request for the same\n * kind is already open. The route answers 404 while\n * `control.deleteClusterCorpses` is off, 409 when console has no corpse\n * that a request can take, and 412 when console does not answer its\n * corpses.\n */\n public static async createDeleteClusterCorpses(\n params: CreateApprovalRequest<DeleteClusterCorpsesPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteClusterCorpses',\n 'api/approvals/delete-cluster-corpses',\n )\n }\n\n /**\n * Opens a force-delete-cluster-plan-type request.\n *\n * Opening one needs `ConsolePermissions.CLUSTER_PLAN_TYPE_FORCE_DELETE`,\n * the same permission that approving needs. A 200 means that a request for\n * the same plan type is already open. The route answers 404 while\n * `control.forceDeleteClusterPlanType` is off or when console does not know\n * the plan type, 409 when no cluster uses the type or more than the cap do,\n * and 412 when console does not answer its clusters.\n */\n public static async createForceDeleteClusterPlanType(\n params: CreateApprovalRequest<ForceDeleteClusterPlanTypePayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createForceDeleteClusterPlanType',\n 'api/approvals/force-delete-cluster-plan-type',\n )\n }\n\n /**\n * Opens an automated-enterprise-onboarding request.\n *\n * Opening one needs `AccountsPermissions.ENTERPRISE_ORG_CONVERT`, the same\n * permission that approving needs. A 200 means that a request with the\n * same organization name is already open. The route answers 404 while\n * `control.automatedEnterpriseOnboarding` is off.\n */\n public static async createAutomatedEnterpriseOnboarding(\n params: CreateApprovalRequest<AutomatedEnterpriseOnboardingPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createAutomatedEnterpriseOnboarding',\n 'api/approvals/automated-enterprise-onboarding',\n )\n }\n\n /**\n * Opens a change-cluster-plan-type request.\n *\n * Opening one needs `ConsolePermissions.CLUSTERS_CAN_UPDATE_CLUSTERPLANTYPE`,\n * the same permission that approving needs. A 200 means that a request for\n * the same cluster is already open. The route answers 404 while\n * `control.changeClusterPlanType` is off.\n */\n public static async createChangeClusterPlanType(\n params: CreateApprovalRequest<ChangeClusterPlanTypePayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeClusterPlanType',\n 'api/approvals/change-cluster-plan-type',\n )\n }\n\n /**\n * Opens a delete-organization request.\n *\n * Opening one needs `AccountsPermissions.DELETE_ORG`, the same permission\n * that approving needs. A 200 means that a request for the same\n * organization is already open.\n */\n public static async createDeleteOrganization(\n params: CreateApprovalRequest<DeleteOrganizationPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteOrganization',\n 'api/approvals/delete-organization',\n )\n }\n\n /**\n * Opens a delete-user request.\n *\n * Opening one needs `AccountsPermissions.DELETE_USER`, the same permission\n * that approving needs. A 200 means that a request for the same user is\n * already open.\n */\n public static async createDeleteUser(\n params: CreateApprovalRequest<DeleteUserPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteUser',\n 'api/approvals/delete-user',\n )\n }\n\n /**\n * Opens a change-user-email request.\n *\n * Opening one needs `AccountsPermissions.ADMIN_CHANGE_EMAIL`, the same\n * permission that approving needs. A 200 means that a request for the same\n * user is already open.\n */\n public static async createChangeUserEmail(\n params: CreateApprovalRequest<ChangeUserEmailPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeUserEmail',\n 'api/approvals/change-user-email',\n )\n }\n\n /**\n * Opens a purge-users request.\n *\n * Opening one needs `AccountsPermissions.GOD_PURGE_USERS` and\n * `AccountsPermissions.DELETE_USER`, the same permissions that approving\n * needs. A 200 means that a request for the same set of users is already\n * open.\n */\n public static async createPurgeUsers(\n params: CreateApprovalRequest<PurgeUsersPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createPurgeUsers',\n 'api/approvals/purge-users',\n )\n }\n\n /**\n * Opens an update-user-metadata request.\n *\n * Opening one needs `AccountsPermissions.GOD_UPDATE_USER_METADATA`, the\n * same permission that approving needs. A 200 means that a request for the\n * same user and the same kind of metadata is already open.\n */\n public static async createUpdateUserMetadata(\n params: CreateApprovalRequest<UpdateUserMetadataPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createUpdateUserMetadata',\n 'api/approvals/update-user-metadata',\n )\n }\n\n /**\n * Opens a change-feature-flag request.\n *\n * Opening one needs `aafw`, the same permission that approving needs. A 200\n * means that a request for the same flag is already open. On int this is\n * the only way to change a flag.\n */\n public static async createChangeFeatureFlag(\n params: CreateApprovalRequest<ChangeFeatureFlagPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeFeatureFlag',\n 'api/approvals/change-feature-flag',\n )\n }\n\n /**\n * Opens a release-train publish request. The caller sends no `preview`:\n * control-backend reads it from console when the request opens.\n */\n public static async createReleaseTrainPublish(\n params: CreateApprovalRequest<Omit<ReleaseTrainPublishPayload, 'preview'>>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createReleaseTrainPublish',\n 'api/approvals/release-train-publish',\n )\n }\n\n /** Opens a release-train rollback request. The caller sends no `preview`. */\n public static async createReleaseTrainRollback(\n params: CreateApprovalRequest<Omit<ReleaseTrainRollbackPayload, 'preview'>>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createReleaseTrainRollback',\n 'api/approvals/release-train-rollback',\n )\n }\n\n /** Adds the approval of the caller. The last one can run the action. */\n public static async acknowledge(\n params: ApprovalIdRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'acknowledge',\n `api/approvals/${params.params.id}/ack`,\n 'api/approvals/:id/ack',\n 'post',\n )\n }\n\n /** Closes a request without running the action. The reason is necessary. */\n public static async reject(\n params: RejectApprovalRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'reject',\n `api/approvals/${params.params.id}/reject`,\n 'api/approvals/:id/reject',\n 'post',\n { reason: params.params.reason },\n )\n }\n\n /**\n * Takes back a request. Only the person who opened it can.\n *\n * The reason is optional, and it lands in the same field that a rejection\n * writes. The creator cannot reject their own request, so this is where they\n * say why they closed it.\n */\n public static async withdraw(\n params: WithdrawApprovalRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'withdraw',\n `api/approvals/${params.params.id}/withdraw`,\n 'api/approvals/:id/withdraw',\n 'post',\n params.params.reason ? { reason: params.params.reason } : undefined,\n )\n }\n\n /**\n * Runs a request that holds its approvals.\n *\n * Only a use case in the explicit mode needs this. An action that throws\n * leaves the request `failed`, and this call still answers 200 with it, so\n * read `status` and `executionError` of the answer.\n */\n public static async execute(\n params: ApprovalIdRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'execute',\n `api/approvals/${params.params.id}/execute`,\n 'api/approvals/:id/execute',\n 'post',\n )\n }\n\n /** Opens a send-to-expired-trial request. Any signed-in Camundi can. */\n public static async createSendToExpiredTrial(\n params: CreateApprovalRequest<SendToExpiredTrialPayloadDto>,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createSendToExpiredTrial',\n 'api/approvals/send-to-expired-trial',\n )\n return approval\n }\n\n /**\n * Opens an extend-trial request.\n *\n * Opening one needs `accounts:admin:extendTrial`, and the reason is\n * necessary. The request needs no approval, so the answer already holds the\n * outcome.\n */\n public static async createExtendTrial(\n params: CreateExtendTrialRequest,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createExtendTrial',\n 'api/approvals/extend-trial',\n )\n return approval\n }\n\n /**\n * Opens a create-personal-organisation request. Any signed-in Camundi can.\n *\n * The request needs no approval, so the answer already holds the outcome,\n * and the route answers 404 while `control.personalOrganisation` is off.\n */\n public static async createPersonalOrganisation(\n params: CreatePersonalOrganisationRequest,\n ): Promise<ApprovalJobDto> {\n // The route answers 429 for the cap, and the cap does not go away. `request`\n // tries a 429 up to 8 times with growing waits, so a person at the cap\n // would wait minutes for the message. A rate limit of the service is a\n // retry that the person can press.\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createPersonalOrganisation',\n 'api/approvals/create-personal-organisation',\n { retryRateLimit: false },\n )\n return approval\n }\n\n /**\n * Opens a cluster-ttl-deletion request. Only the delete cron of\n * console-backend can, with an m2m token that holds `cmctd`.\n *\n * The request needs no approval, so the answer already holds the outcome.\n * For a cluster with a live request, the answer is that request.\n */\n public static async createClusterTtlDeletion(\n params: CreateClusterTtlDeletionRequest,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createClusterTtlDeletion',\n 'api/approvals/cluster-ttl-deletion',\n )\n return approval\n }\n\n /**\n * Opens a create-custom-hardware-sizing request. Any signed-in Camundi\n * can. It runs on dev only, needs no approval, and the route answers 403\n * on every other stage.\n */\n public static async createCustomHardwareSizing(\n params: SelfServiceApprovalRequest<\n CreateCustomHardwareSizingPayloadDto | LinkCustomHardwareSizingPayloadDto\n >,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createCustomHardwareSizing',\n 'api/approvals/create-custom-hardware-sizing',\n )\n return approval\n }\n\n /** Opens a remove-custom-hardware-sizing request. See the one above. */\n public static async removeCustomHardwareSizing(\n params: SelfServiceApprovalRequest<RemoveCustomHardwareSizingPayloadDto>,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'removeCustomHardwareSizing',\n 'api/approvals/remove-custom-hardware-sizing',\n )\n return approval\n }\n\n /** Opens a create-custom-generation request. Dev only, no approval. */\n public static async createCustomGeneration(\n params: SelfServiceApprovalRequest<\n CreateCustomGenerationPayloadDto | LinkCustomGenerationPayloadDto\n >,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createCustomGeneration',\n 'api/approvals/create-custom-generation',\n )\n return approval\n }\n\n /** Opens a remove-custom-generation request. See the one above. */\n public static async removeCustomGeneration(\n params: SelfServiceApprovalRequest<RemoveCustomGenerationPayloadDto>,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'removeCustomGeneration',\n 'api/approvals/remove-custom-generation',\n )\n return approval\n }\n\n /**\n * Opens a self-service-cluster-modification request. Any signed-in Camundi\n * can, and accounts then checks that the Camundi owns the organization. It\n * runs on dev only and needs no approval, so the answer holds the outcome.\n * A 200 means that the same request of this person still runs.\n */\n public static async createSelfServiceClusterModification(\n params: SelfServiceApprovalRequest<SelfServiceClusterModificationPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createSelfServiceClusterModification',\n 'api/approvals/self-service-cluster-modification',\n )\n }\n\n /**\n * The shared half of every call that answers one request.\n *\n * Six routes answer `{ approval }` and differ only in the verb and the path.\n * One private helper keeps the metrics context, the status check and the\n * unwrapping in one place.\n */\n private static async readOne(\n params: RequestBaseParams,\n name: string,\n url: string,\n normalizedUrl: string,\n method: 'get' | 'post',\n body?: Record<string, unknown>,\n ): Promise<ApprovalJobDto> {\n const serviceContext = contextFor(\n name,\n url,\n normalizedUrl,\n method,\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ approval: ApprovalJobDto }>({\n config: params.config,\n base: BASE,\n url,\n method,\n metricsDetails: serviceContext,\n body,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!.approval\n }\n\n /**\n * The shared half of every create route. See `approvalRequestBody`.\n *\n * The route answers 201 for a fresh request and 200 for the one already\n * open for the same target (`create` deduplicates). `created` carries that\n * difference. `createSendToExpiredTrial` and `createExtendTrial` do not\n * need it, so they read `approval` alone off this result.\n */\n private static async create<TPayload>(\n params: CreateApprovalRequest<TPayload>,\n name: string,\n url: string,\n options: {\n /** False sends the call once, also when the answer is a 429. */\n retryRateLimit?: boolean\n } = {},\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n const serviceContext = contextFor(\n name,\n url,\n url,\n 'post',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ approval: ApprovalJobDto }>({\n config: params.config,\n base: BASE,\n url,\n method: 'post',\n metricsDetails: serviceContext,\n ...(options.retryRateLimit === false\n ? { retry: { attempts: 1, remaining: 0 } }\n : {}),\n body: {\n payload: params.params.payload,\n reason: params.params.reason,\n requiredAcks: params.params.requiredAcks,\n },\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return {\n approval: response.body!.approval,\n created: response.status === 201,\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type {\n ApprovalEntityType,\n ApprovalJobDto,\n ApprovalJobStatus,\n ApprovalSortField,\n ApprovalSortOrder,\n ApprovalStatusCountsDto,\n ApprovalUseCaseDto,\n ClusterBulkOperationPayloadDto,\n ClusterBulkOperationType,\n ClusterCorpseKind,\n ClusterPlanModificationConfig,\n ClusterTtlDeletionPayload,\n EnterpriseIncludingValueMetrics,\n GenerationEnvVarsDto,\n GenerationImageVersionsDto,\n LicensingModelType,\n ReleaseTrainPublishPayload,\n ReleaseTrainRollbackPayload,\n} from '@camunda/ccma-shared-types'\nimport { CLUSTER_BULK_OPERATION_RULES } from '@camunda/ccma-shared-types'\nimport type {\n RequestBaseParams,\n RequestBaseServiceContext,\n} from '../../types/general.types.js'\nimport { request } from '../../utils/api.js'\nimport { HttpError } from '../../utils/errors.js'\n\n/**\n * The four-eyes approval surface of control-backend.\n *\n * One service for the whole mechanism, and not one for each use case. The\n * generic routes (list, read, approve, reject, withdraw, run) carry no\n * knowledge of a use case, which is what lets one view in control-frontend\n * show every privileged action. Only the create calls are per use case,\n * because a payload can be validated only for the use case it belongs to.\n *\n * A use case that walks its own rollout behind a flag answers 404 on its\n * create route while that flag is off.\n */\n\nconst BASE = { id: 'control' } as const\n\nexport interface ApprovalPageDto {\n approvals: ApprovalJobDto[]\n page: {\n limit: number\n offset: number\n /** True when the next page holds more. Never read the length instead. */\n hasMore: boolean\n }\n}\n\n/**\n * What narrows the queue. The list and the counts read the same fields.\n *\n * `entityType` and `entityId` are ONE filter, not two. control-backend answers\n * 400 for one without the other, so the type carries both or neither.\n */\nexport type ApprovalFacetParams = {\n /** One use case type, or more. A request matches when its type is any of them. */\n type?: string | readonly string[]\n /**\n * One organization, matched whole against `orgId` of the payload.\n *\n * It reads only the payload, so `entityType`/`entityId` is wider. That filter\n * reads the entity link, so it finds a request that touches the organization\n * through another field. The organization page of control-frontend asks the\n * entity-link filter, not this one. `orgId` is also not `q`: the free text\n * reads the whole payload as text.\n */\n orgId?: string\n /**\n * Free text. control-backend matches it in the reason, the person who\n * opened the request, the action and its label, and the payload that the\n * summary shows.\n */\n q?: string\n /**\n * The queue of one person: what they opened, or what waits for them.\n *\n * `actionable` is the rule of the Approve button asked in SQL \u2014 pending,\n * opened by somebody else, not approved by this person yet, and guarded by\n * permissions that they hold.\n */\n mine?: 'created' | 'actionable'\n} & (\n | {\n /**\n * The kind of entity a request must touch. Read with `entityId`.\n *\n * It reads the entity link of control-backend, so it is wider and truer\n * than `orgId`: a cluster-move request answers for its source\n * organization, its target organization AND the cluster. The organization\n * and cluster detail pages of control-frontend ask this.\n */\n entityType: ApprovalEntityType\n /** The id of the entity a request must touch. Read with `entityType`. */\n entityId: string\n }\n | { entityType?: never; entityId?: never }\n)\n\nexport interface ListApprovalsRequest extends RequestBaseParams {\n params?: ApprovalFacetParams & {\n status?: ApprovalJobStatus\n /**\n * An ISO 8601 instant. Only the requests that changed at or after it: the\n * last write of the request, or the run of its action. A control-backend\n * from before this parameter ignores it and answers every request.\n */\n updatedSince?: string\n sort?: ApprovalSortField\n order?: ApprovalSortOrder\n limit?: number\n offset?: number\n }\n}\n\nexport interface CountApprovalsRequest extends RequestBaseParams {\n params?: ApprovalFacetParams\n}\n\nexport interface ApprovalIdRequest extends RequestBaseParams {\n params: { id: string }\n}\n\nexport interface RejectApprovalRequest extends RequestBaseParams {\n params: { id: string; reason: string }\n}\n\n/** A withdrawal says why, or says nothing. The reason is not demanded. */\nexport interface WithdrawApprovalRequest extends RequestBaseParams {\n params: { id: string; reason?: string }\n}\n\n/** The envelope that every create route of every use case shares. */\nexport interface CreateApprovalRequest<TPayload> extends RequestBaseParams {\n params: {\n payload: TPayload\n reason?: string\n /** More approvals than the floor of the use case. Never fewer. */\n requiredAcks?: number\n }\n}\n\nexport interface SendToExpiredTrialPayloadDto {\n orgId: string\n orgName?: string\n}\n\nexport interface CreatePersonalOrganisationPayloadDto {\n /** 3 to 100 characters, after the spaces at both ends are cut. */\n name: string\n}\n\n/**\n * The create call of `create-personal-organisation`.\n *\n * It has no `requiredAcks`: the request needs no approval, and the route\n * answers 400 to a body that names the field.\n */\nexport interface CreatePersonalOrganisationRequest extends RequestBaseParams {\n params: {\n payload: CreatePersonalOrganisationPayloadDto\n reason?: string\n }\n}\n\n/** The create call of `extend-trial`. It has no `requiredAcks`. */\nexport interface CreateExtendTrialRequest extends RequestBaseParams {\n params: {\n payload: ExtendTrialPayloadDto\n reason?: string\n }\n}\n\n/** The create call of `cluster-ttl-deletion`. It has no `requiredAcks`. */\nexport interface CreateClusterTtlDeletionRequest extends RequestBaseParams {\n params: {\n payload: ClusterTtlDeletionPayload\n reason?: string\n }\n}\n\nexport interface CreateCustomHardwareSizingPayloadDto {\n /** The organization that gets the plan. The requester must own it. */\n orgId: string\n /** 3 to 100 characters, after the spaces at both ends are cut. */\n name: string\n /** The cluster plan, in the same format as the plan route of the admin tool. */\n plan: Record<string, unknown>\n clusterPlanId?: never\n}\n\n/** An existing cluster plan. Nothing is created: it is added to the list of the organization. */\nexport interface LinkCustomHardwareSizingPayloadDto {\n /** The organization that gets the plan. The requester must own it. */\n orgId: string\n clusterPlanId: string\n name?: never\n plan?: never\n}\n\n/**\n * `unlink` removes the plan from one organization that the requester owns.\n * `delete` removes it from every organization of the requester, and deletes it.\n */\nexport type RemoveCustomHardwareSizingPayloadDto =\n | { mode: 'unlink'; clusterPlanId: string; orgId: string }\n | { mode: 'delete'; clusterPlanId: string }\n\nexport interface CreateCustomGenerationPayloadDto {\n /** The organization that gets the generation. The requester must own it. */\n orgId: string\n /** 3 to 100 characters, after the spaces at both ends are cut. */\n name: string\n /** The images and env vars, in the format of the generation route of the admin tool. */\n versions: Record<string, string>\n /** Generations whose clusters can upgrade to this one. */\n upgradeableFrom?: string[]\n generationId?: never\n}\n\n/** An existing generation. Nothing is created: it is added to the list of the organization. */\nexport interface LinkCustomGenerationPayloadDto {\n /** The organization that gets the generation. The requester must own it. */\n orgId: string\n generationId: string\n name?: never\n versions?: never\n upgradeableFrom?: never\n}\n\n/**\n * `unlink` removes the generation from one organization that the requester\n * owns. `delete` removes it from every organization of the requester, and\n * deletes it.\n */\nexport type RemoveCustomGenerationPayloadDto =\n | { mode: 'unlink'; generationId: string; orgId: string }\n | { mode: 'delete'; generationId: string }\n\n/**\n * `apply` applies a new config to a cluster of an organization that the\n * requester owns, and the new config replaces the active config. `deactivate`\n * deactivates the active config `configId`.\n */\nexport type SelfServiceClusterModificationPayloadDto =\n | {\n mode: 'apply'\n orgId: string\n clusterUuid: string\n /** 1 to 500 characters. */\n description: string\n /** At least one entry. */\n planModifications: ClusterPlanModificationConfig[]\n /** An ISO datetime with an offset, for example `toISOString()`. */\n expiresAt?: string\n }\n | { mode: 'deactivate'; orgId: string; clusterUuid: string; configId: string }\n\n/**\n * The call of a self-service use case: custom hardware sizing and custom\n * generations. Like `CreatePersonalOrganisationRequest`, it has no\n * `requiredAcks`.\n */\nexport interface SelfServiceApprovalRequest<TPayload>\n extends RequestBaseParams {\n params: {\n payload: TPayload\n reason?: string\n }\n}\n\n/** @deprecated Use `SelfServiceApprovalRequest`. */\nexport type CustomHardwareSizingRequest<TPayload> =\n SelfServiceApprovalRequest<TPayload>\n\nexport interface ExtendTrialPayloadDto {\n orgId: string\n orgName?: string\n /**\n * Days of trial counted from the moment the action RUNS.\n *\n * Never a date. Accounts holds the new expiry inside a window that it\n * measures when the call arrives, and under approvals that is days after the\n * person chose the value. See `use-cases/extend-trial.ts` in\n * control-backend.\n */\n days: number\n}\n\nexport interface MoveClusterOrgPayloadDto {\n clusterId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n clusterName?: string\n targetOrgId: string\n /** A copy, for the same reason as `clusterName`. */\n targetOrgName?: string\n // The SOURCE organization is not here on purpose. control-backend resolves it\n // server-side from the cluster's current owner, so a caller cannot attach the\n // request to an organization the cluster never belonged to.\n}\n\nexport interface ChangePlatformRolesPayloadDto {\n userId: string\n /** A copy, so a list shows a person and not an Auth0 id. Nothing reads it. */\n userEmail?: string\n /**\n * A CHANGE, and never the whole set. Accounts applies it over the roles that\n * the user holds when the action RUNS, so a role change that somebody else\n * made while the request waited stays.\n */\n rolesToAdd: string[]\n rolesToRemove: string[]\n}\n\nexport interface ChangeOrgLimitsPayloadDto {\n orgId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n orgName?: string\n /** One key of `allSalesPlanLimits()`. One limit for each request. */\n limitKey: string\n /**\n * The override that the person who asked READ. Absent for \"not set\".\n *\n * Accounts compares it with the override that it holds when the action\n * runs, and writes nothing when the two differ. See `staleApprovalKeys`.\n */\n expected?: string | number | boolean\n /** The new override. `null` clears it, and the default of the plan applies. */\n value: string | number | boolean | null\n}\n\n/** One generation of a change-generation-versions request. */\nexport interface ChangeGenerationVersionsTargetDto {\n id: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n name?: string\n /**\n * A copy of the cluster count when the request was opened, for the\n * approver. Absent when the browser could not read it.\n */\n clusterCount?: number\n /**\n * The values that the person who asked READ, one for each key of\n * `versions`. Console changes nothing on this generation when one differs\n * at the run.\n */\n expectedVersions: GenerationImageVersionsDto\n}\n\n/**\n * The payload of a delete-cluster-corpses request, as a browser sends it.\n * control-backend reads the corpses of the kind from console and stores them\n * with the request, as the set that the approvers read.\n */\nexport interface DeleteClusterCorpsesPayloadDto {\n kind: ClusterCorpseKind\n}\n\nexport interface ChangeGenerationVersionsPayloadDto {\n generations: ChangeGenerationVersionsTargetDto[]\n /**\n * The image versions to write on every generation. Only the keys that\n * change are here. An empty string clears an optional one. No env var\n * field is here (see `GENERATION_ENV_VARS_KEYS`).\n */\n versions: GenerationImageVersionsDto\n}\n\n/**\n * The payload of an edit-generation request: the new name and env vars of\n * ONE generation, and the values that the person who asked READ.\n */\nexport interface EditGenerationPayloadDto {\n generationId: string\n /** The name that the person who asked READ. The stale guard of `name`. */\n expectedName: string\n /** The new name. Absent keeps the name. */\n name?: string\n /**\n * The env var text to write. Only the keys that change are here. An empty\n * string clears a field.\n */\n envVars: GenerationEnvVarsDto\n /** The text that the person who asked READ, one for each key of `envVars`. */\n expectedEnvVars: GenerationEnvVarsDto\n /**\n * A copy of the cluster count when the request was opened, for the\n * approver. Absent when the browser could not read it.\n */\n clusterCount?: number\n}\n\n/**\n * The payload of a force-delete-cluster-plan-type request, as a browser\n * sends it. control-backend reads the clusters of the type from console and\n * stores them with the request, as the set that the approvers read.\n */\nexport interface ForceDeleteClusterPlanTypePayloadDto {\n planTypeId: string\n}\n\n/**\n * The payload of an automated-enterprise-onboarding request: the fields of\n * the accounts wizard \"New Enterprise Onboarding\".\n */\nexport interface AutomatedEnterpriseOnboardingPayloadDto {\n /** The prefix of the two organization names. */\n orgName: string\n sfdcId: string\n awsOnly: boolean\n renewalTermInMonths: number\n licensingModel: 'legacy' | '2025'\n /** The start of the subscription, `YYYY-MM-DD`. */\n startDate: string\n valueMetrics: {\n processInstances: number\n decisionInstances: number\n taskUsers: number\n tenants: number\n }\n reservations: {\n basic: number\n standard: number\n advanced: number\n }\n /** The person who becomes the owner of both organizations. */\n ownerEmail: string\n}\n\n/** One cluster of the organization and the plan type it moves to. */\nexport interface OnboardToEnterpriseClusterDto {\n clusterId: string\n /** A copy, so the approver reads a name. Nothing reads it. */\n clusterName?: string\n planTypeId: string\n /** A copy of the name of the plan type, for the approver to read. */\n planTypeName?: string\n numberOfAllocatedHwPackages?: number\n keepModification: boolean\n}\n\nexport interface OnboardToEnterprisePayloadDto {\n orgId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n orgName?: string\n salesPlanId: string\n /** A copy of the name of the new plan, for the approver to read. */\n salesPlanName?: string\n /**\n * The plan that the person who asked READ. Accounts compares it with the\n * plan that it holds when the action runs, and switches nothing when the\n * two differ. An organization with no plan cannot be onboarded this way.\n */\n expectedSalesPlanId: string\n expectedSalesPlanName?: string\n contract: {\n /** The renewal term, in months. */\n duration: number\n includedValueMetrics: EnterpriseIncludingValueMetrics\n /** `YYYY-MM-DD`. */\n enterPriseStartDate: string\n enterpriseDevOnly: boolean\n awsOnly: boolean\n licensingModel: LicensingModelType\n salesForceId?: string\n }\n /** One entry for each cluster of the organization. Empty for none. */\n clusters: OnboardToEnterpriseClusterDto[]\n /** The reservations after the switch, by plan type uuid. */\n reservations: Record<string, number>\n /** The names of the plan types of `reservations`, for the approver. */\n reservationNames?: Record<string, string>\n}\n\nexport interface ChangeClusterPlanTypePayloadDto {\n clusterId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n clusterName?: string\n /** The organization that owns the cluster. Console refuses another one. */\n orgId: string\n /** A copy, for the same reason as `clusterName`. */\n orgName?: string\n toPlanTypeUuid: string\n /** A copy of the name of the new plan type, for the approver to read. */\n toPlanTypeName?: string\n /**\n * The hardware packages of the cluster after the change, 1 at least.\n *\n * Always sent, also for a plan type with no availability class, where it is\n * 1. Console checks the reservations of the organization only when the\n * packages are in the call, and the check is the point of this use case.\n */\n numberOfAllocatedHwPackages: number\n /**\n * The plan type that the person who asked READ.\n *\n * Console compares it with the plan type of the cluster when the action\n * runs, and changes nothing when the two differ.\n */\n expectedPlanTypeUuid: string\n /** A copy of the name of the current plan type, for the approver to read. */\n expectedPlanTypeName?: string\n /**\n * The hardware packages that the person who asked READ, 1 for a cluster\n * that holds none. The same stale guard as `expectedPlanTypeUuid`.\n */\n expectedNumberOfAllocatedHwPackages: number\n /**\n * The cluster plan that the person who asked READ. Console decides the\n * plan move from it, so it is part of the stale guard too, and Console\n * refuses a cluster that runs none, so a request needs one.\n */\n expectedClusterPlanUuid: string\n /** A copy of the name of that plan, for the approver to read. */\n expectedClusterPlanName?: string\n /**\n * The active modification config that the person who asked READ, absent\n * when the cluster has none. The change removes it, and an approver must\n * read which one goes.\n */\n expectedActiveModificationConfigUuid?: string\n /**\n * The active plan of the NEW plan type that the person who asked READ. The\n * cluster moves to it, so a plan that a Camundi changed on the type while\n * the request waited fails the guard, and Console refuses a type that has\n * none, so a request needs one.\n */\n expectedTargetPlanUuid: string\n /** A copy of the name of that plan, for the approver to read. */\n expectedTargetPlanName?: string\n /**\n * Whether the cluster plan moves to the active plan of the new type, as\n * the dialog read it. The list of migratable plans can change while the\n * request waits, and a verdict that moved changes whether the cluster\n * restarts, so Console refuses a request whose verdict moved.\n */\n expectedClusterPlanUpdate: boolean\n /**\n * Whether the active modification config of the cluster stays after the\n * change. Absent reads as false: the change removes it, and the approver\n * reads which one goes. The dialog shows what the config changes, so the\n * person who asks can choose.\n */\n keepModification?: boolean\n}\n\nexport interface ChangeSalesPlanPayloadDto {\n orgId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n orgName?: string\n salesPlanId: string\n /** A copy of the name of the new plan, for the approver to read. */\n salesPlanName?: string\n /**\n * The plan that the person who asked READ. Absent for \"no plan\".\n *\n * Accounts compares it with the plan that it holds when the action runs,\n * and switches nothing when the two differ.\n */\n expectedSalesPlanId?: string\n /** A copy of the name of the current plan, for the approver to read. */\n expectedSalesPlanName?: string\n /** Skips the validation of the switch. The approver sees it. */\n force: boolean\n}\n\n/** Every value of a flag row that a person can change. */\nexport interface FeatureFlagValuesDto {\n description: string\n enabled: boolean\n orgIds: string[]\n emailDomains: string[]\n /** The team that owns the flag. A create needs it. An older row has none. */\n owner?: string\n /** `YYYY-MM-DD`, the day after which the flag is late. */\n expiresAt?: string\n /**\n * The issue that tracks the flag. A create and an edit need it. An older\n * row has none.\n */\n issueUrl?: string\n}\n\n/**\n * One change of the feature flag table: the action, and the whole row that it\n * asks for.\n *\n * An edit and a delete carry the row that the person who asked READ, as\n * `expected`. The action writes nothing when the row changed in the meantime.\n * `key` of an edit and a delete is a copy for the approver, and the action\n * compares it too.\n */\nexport type ChangeFeatureFlagPayloadDto =\n | {\n action: 'create'\n key: string\n value: FeatureFlagValuesDto & { owner: string; issueUrl: string }\n }\n | {\n action: 'update'\n id: string\n key: string\n expected: FeatureFlagValuesDto\n value: FeatureFlagValuesDto & { issueUrl: string }\n }\n | {\n action: 'delete'\n id: string\n key: string\n expected: FeatureFlagValuesDto\n }\n\nexport interface DeleteSsoConnectionPayloadDto {\n strategy: 'waad' | 'samlp'\n connectionId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n connectionName?: string\n /**\n * The organizations that the connection serves, as copies for the approver.\n * The request is findable on the page of each one.\n */\n orgIds?: string[]\n}\n\nexport interface DeleteOrganizationPayloadDto {\n orgId: string\n /**\n * The name that the approvers read. Accounts refuses the deletion when the\n * organization has another name when the action runs.\n */\n orgName: string\n}\n\nexport interface DeleteUserPayloadDto {\n userId: string\n /**\n * The address that the approvers read. Accounts refuses the deletion when\n * the user has another address when the action runs.\n */\n userEmail: string\n}\n\nexport interface ChangeUserEmailPayloadDto {\n userId: string\n /**\n * The address that the person who asked READ. Accounts compares it with\n * the address that the user has when the action runs, and changes nothing\n * when the two differ.\n */\n expectedEmail: string\n newEmail: string\n}\n\nexport interface PurgeUsersPayloadDto {\n /**\n * The users to delete, at most `PURGE_USERS_MAX_USERS`. The address is a\n * copy for the approver, and accounts refuses a user whose address is not\n * that copy. A list that came from a file of ids carries none.\n */\n users: { userId: string; email?: string }[]\n}\n\nexport interface UpdateUserMetadataPayloadDto {\n userId: string\n /** A copy, so a list shows a person and not an Auth0 id. Nothing reads it. */\n userEmail?: string\n /** `app` writes `app_metadata`, `user` writes `user_metadata`. */\n kind: 'app' | 'user'\n /**\n * The metadata that the person who asked READ. Absent for \"not set\".\n * Accounts writes nothing when it holds another value when the action runs.\n */\n expected?: Record<string, unknown>\n metadata: Record<string, unknown>\n}\n\nexport interface DeleteInternalBackupPayloadDto {\n clusterId: string\n /** A copy, so a list shows a name that a person knows. Nothing reads it. */\n clusterName?: string\n backupName: string\n /** A copy of the Slack link of the incident, for the approver to read. */\n incidentLink?: string\n}\n\n/**\n * The query string of a read, with the fields that carry no value dropped.\n *\n * An empty value is not the same as an absent one: `q=` would reach the schema\n * of control-backend, which holds the text at one character and answers 400.\n * A list goes as one comma list, which is the form control-backend reads for\n * `type`. An empty list is dropped like an empty text.\n */\nfunction querySuffix(params: object = {}): string {\n const query = new URLSearchParams()\n for (const [key, raw] of Object.entries(params)) {\n const value = Array.isArray(raw) ? raw.join(',') : raw\n if (value !== undefined && value !== '') {\n query.set(key, String(value))\n }\n }\n return query.size > 0 ? `?${query.toString()}` : ''\n}\n\nfunction contextFor(\n name: string,\n url: string,\n normalizedUrl: string,\n type: 'get' | 'post',\n source: string,\n): RequestBaseServiceContext {\n return {\n method: {\n name: `ControlApprovalsService.${name}`,\n url,\n normalizedUrl,\n type,\n },\n source,\n target: { name: 'control', type: 'internal' },\n }\n}\n\nexport class ControlApprovalsService {\n /**\n * The registered privileged actions, with the rules that guard each one.\n *\n * A frontend reads this to run the same policy as the service, so it never\n * holds a copy of the registry. A new use case then needs no frontend\n * deploy.\n */\n public static async listUseCases(\n params: RequestBaseParams,\n ): Promise<ApprovalUseCaseDto[]> {\n const serviceContext = contextFor(\n 'listUseCases',\n 'api/approvals/use-cases',\n 'api/approvals/use-cases',\n 'get',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ useCases: ApprovalUseCaseDto[] }>({\n config: params.config,\n base: BASE,\n url: serviceContext.method.url,\n method: 'get',\n metricsDetails: serviceContext,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!.useCases\n }\n\n /**\n * One page of the requests that the caller can read.\n *\n * It is not the whole table: control-backend hides a request whose use case\n * the caller cannot act on, unless the caller opened it.\n */\n public static async list(\n params: ListApprovalsRequest,\n ): Promise<ApprovalPageDto> {\n const suffix = querySuffix(params.params)\n const serviceContext = contextFor(\n 'list',\n `api/approvals${suffix}`,\n 'api/approvals',\n 'get',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<ApprovalPageDto>({\n config: params.config,\n base: BASE,\n url: serviceContext.method.url,\n method: 'get',\n metricsDetails: serviceContext,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!\n }\n\n /**\n * How many requests each status holds, for the status filters of a queue.\n *\n * It is the same question as `list` without the status, so a filter that\n * shows a number never opens an empty page.\n */\n public static async counts(\n params: CountApprovalsRequest,\n ): Promise<ApprovalStatusCountsDto> {\n const suffix = querySuffix(params.params)\n const serviceContext = contextFor(\n 'counts',\n `api/approvals/counts${suffix}`,\n 'api/approvals/counts',\n 'get',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ counts: ApprovalStatusCountsDto }>({\n config: params.config,\n base: BASE,\n url: serviceContext.method.url,\n method: 'get',\n metricsDetails: serviceContext,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!.counts\n }\n\n public static async get(params: ApprovalIdRequest): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'get',\n `api/approvals/${params.params.id}`,\n 'api/approvals/:id',\n 'get',\n )\n }\n\n /**\n * What a create route answers, plus whether it opened a NEW request.\n *\n * The route answers 201 for a fresh request and 200 for the one already\n * open for the same target \u2014 `create` deduplicates. A caller that must\n * tell the two apart (a floor-of-one use case, where 200 is the ordinary\n * path and not a failure) reads `created`.\n */\n public static async createMoveClusterOrg(\n params: CreateApprovalRequest<MoveClusterOrgPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createMoveClusterOrg',\n 'api/approvals/move-cluster-org',\n )\n }\n\n /**\n * Opens a cluster bulk operation of one type.\n *\n * Each type is its own use case with its own route, because each one has\n * its own permission. The floor of approvals is the same for every type,\n * and it depends on the stage: 2 on prod, 1 on dev, int and local. The\n * route is `api/approvals/<use case>`, as for every other use case. A 200\n * means that the same operation over the same clusters is already open.\n */\n public static async createClusterBulkOperation<\n T extends ClusterBulkOperationType,\n >(\n type: T,\n params: CreateApprovalRequest<ClusterBulkOperationPayloadDto<T>>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n const useCase = CLUSTER_BULK_OPERATION_RULES[type].useCase\n return ControlApprovalsService.create(\n params,\n 'createClusterBulkOperation',\n `api/approvals/${useCase}`,\n )\n }\n\n /**\n * Opens a change-platform-roles request.\n *\n * Opening one needs `accounts:admin:changeRole`, the same permission that\n * approving needs, and the reason is necessary. A 200 means that a request\n * for the same user is already open.\n */\n public static async createChangePlatformRoles(\n params: CreateApprovalRequest<ChangePlatformRolesPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangePlatformRoles',\n 'api/approvals/change-platform-roles',\n )\n }\n\n /**\n * Opens a delete-internal-backup request.\n *\n * Opening one needs `console:clusters:canCreateInternalBackup`, the same\n * permission that approving needs. A 200 means that a request for the same\n * backup is already open.\n */\n public static async createDeleteInternalBackup(\n params: CreateApprovalRequest<DeleteInternalBackupPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteInternalBackup',\n 'api/approvals/delete-internal-backup',\n )\n }\n\n /**\n * Opens a change-org-limits request.\n *\n * Opening one needs `accounts:admin:mayChangeOrgLimits`, the same\n * permission that approving needs. A 200 means that a request for the same\n * limit of the same organization is already open.\n */\n public static async createChangeOrgLimits(\n params: CreateApprovalRequest<ChangeOrgLimitsPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeOrgLimits',\n 'api/approvals/change-org-limits',\n )\n }\n\n /**\n * Opens a delete-sso-connection request.\n *\n * Opening one needs `AccountsPermissions.ADMIN_AUTH0_CONNECTIONS_DELETE`, the same\n * permission that approving needs. A 200 means that a request for the same\n * connection is already open.\n */\n public static async createDeleteSsoConnection(\n params: CreateApprovalRequest<DeleteSsoConnectionPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteSsoConnection',\n 'api/approvals/delete-sso-connection',\n )\n }\n\n /**\n * Opens an onboard-to-enterprise request.\n *\n * Opening one needs `AccountsPermissions.ENTERPRISE_ORG_CONVERT`, the same\n * permission that approving needs. A 200 means that a request for the same\n * organization is already open. The route answers 404 while\n * `control.onboardToEnterpriseApproval` is off.\n */\n public static async createOnboardToEnterprise(\n params: CreateApprovalRequest<OnboardToEnterprisePayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createOnboardToEnterprise',\n 'api/approvals/onboard-to-enterprise',\n )\n }\n\n /**\n * Opens a change-sales-plan request.\n *\n * Opening one needs `AccountsPermissions.SALES_PLAN_SWITCH`, the same\n * permission that approving needs. A 200 means that a request for the same\n * organization is already open.\n */\n public static async createChangeSalesPlan(\n params: CreateApprovalRequest<ChangeSalesPlanPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeSalesPlan',\n 'api/approvals/change-sales-plan',\n )\n }\n\n /**\n * Opens a change-generation-versions request.\n *\n * Opening one needs `ConsolePermissions.CHANNELS_AND_GENERATIONS_ADMIN`,\n * the same permission that approving needs. A 200 means that a request\n * over the same generations is already open. The route answers 404 while\n * `control.changeGenerationVersions` is off.\n */\n public static async createChangeGenerationVersions(\n params: CreateApprovalRequest<ChangeGenerationVersionsPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeGenerationVersions',\n 'api/approvals/change-generation-versions',\n )\n }\n\n /**\n * Opens an edit-generation request.\n *\n * Opening one needs `ConsolePermissions.CHANNELS_AND_GENERATIONS_ADMIN`,\n * the same permission that approving needs. A 200 means that a request\n * over the same generation is already open. The route answers 404 while\n * `control.editGeneration` is off.\n */\n public static async createEditGeneration(\n params: CreateApprovalRequest<EditGenerationPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createEditGeneration',\n 'api/approvals/edit-generation',\n // The payload holds env var text.\n { redactBody: true },\n )\n }\n\n /**\n * Opens a delete-cluster-corpses request.\n *\n * Opening one needs `ConsolePermissions.CLUSTERS_DELETE_CLUSTER`, the same\n * permission that approving needs. A 200 means that a request for the same\n * kind is already open. The route answers 404 while\n * `control.deleteClusterCorpses` is off, 409 when console has no corpse\n * that a request can take, and 412 when console does not answer its\n * corpses.\n */\n public static async createDeleteClusterCorpses(\n params: CreateApprovalRequest<DeleteClusterCorpsesPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteClusterCorpses',\n 'api/approvals/delete-cluster-corpses',\n )\n }\n\n /**\n * Opens a force-delete-cluster-plan-type request.\n *\n * Opening one needs `ConsolePermissions.CLUSTER_PLAN_TYPE_FORCE_DELETE`,\n * the same permission that approving needs. A 200 means that a request for\n * the same plan type is already open. The route answers 404 while\n * `control.forceDeleteClusterPlanType` is off or when console does not know\n * the plan type, 409 when no cluster uses the type or more than the cap do,\n * and 412 when console does not answer its clusters.\n */\n public static async createForceDeleteClusterPlanType(\n params: CreateApprovalRequest<ForceDeleteClusterPlanTypePayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createForceDeleteClusterPlanType',\n 'api/approvals/force-delete-cluster-plan-type',\n )\n }\n\n /**\n * Opens an automated-enterprise-onboarding request.\n *\n * Opening one needs `AccountsPermissions.ENTERPRISE_ORG_CONVERT`, the same\n * permission that approving needs. A 200 means that a request with the\n * same organization name is already open. The route answers 404 while\n * `control.automatedEnterpriseOnboarding` is off.\n */\n public static async createAutomatedEnterpriseOnboarding(\n params: CreateApprovalRequest<AutomatedEnterpriseOnboardingPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createAutomatedEnterpriseOnboarding',\n 'api/approvals/automated-enterprise-onboarding',\n )\n }\n\n /**\n * Opens a change-cluster-plan-type request.\n *\n * Opening one needs `ConsolePermissions.CLUSTERS_CAN_UPDATE_CLUSTERPLANTYPE`,\n * the same permission that approving needs. A 200 means that a request for\n * the same cluster is already open. The route answers 404 while\n * `control.changeClusterPlanType` is off.\n */\n public static async createChangeClusterPlanType(\n params: CreateApprovalRequest<ChangeClusterPlanTypePayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeClusterPlanType',\n 'api/approvals/change-cluster-plan-type',\n )\n }\n\n /**\n * Opens a delete-organization request.\n *\n * Opening one needs `AccountsPermissions.DELETE_ORG`, the same permission\n * that approving needs. A 200 means that a request for the same\n * organization is already open.\n */\n public static async createDeleteOrganization(\n params: CreateApprovalRequest<DeleteOrganizationPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteOrganization',\n 'api/approvals/delete-organization',\n )\n }\n\n /**\n * Opens a delete-user request.\n *\n * Opening one needs `AccountsPermissions.DELETE_USER`, the same permission\n * that approving needs. A 200 means that a request for the same user is\n * already open.\n */\n public static async createDeleteUser(\n params: CreateApprovalRequest<DeleteUserPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createDeleteUser',\n 'api/approvals/delete-user',\n )\n }\n\n /**\n * Opens a change-user-email request.\n *\n * Opening one needs `AccountsPermissions.ADMIN_CHANGE_EMAIL`, the same\n * permission that approving needs. A 200 means that a request for the same\n * user is already open.\n */\n public static async createChangeUserEmail(\n params: CreateApprovalRequest<ChangeUserEmailPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeUserEmail',\n 'api/approvals/change-user-email',\n )\n }\n\n /**\n * Opens a purge-users request.\n *\n * Opening one needs `AccountsPermissions.GOD_PURGE_USERS` and\n * `AccountsPermissions.DELETE_USER`, the same permissions that approving\n * needs. A 200 means that a request for the same set of users is already\n * open.\n */\n public static async createPurgeUsers(\n params: CreateApprovalRequest<PurgeUsersPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createPurgeUsers',\n 'api/approvals/purge-users',\n )\n }\n\n /**\n * Opens an update-user-metadata request.\n *\n * Opening one needs `AccountsPermissions.GOD_UPDATE_USER_METADATA`, the\n * same permission that approving needs. A 200 means that a request for the\n * same user and the same kind of metadata is already open.\n */\n public static async createUpdateUserMetadata(\n params: CreateApprovalRequest<UpdateUserMetadataPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createUpdateUserMetadata',\n 'api/approvals/update-user-metadata',\n )\n }\n\n /**\n * Opens a change-feature-flag request.\n *\n * Opening one needs `aafw`, the same permission that approving needs. A 200\n * means that a request for the same flag is already open. On int this is\n * the only way to change a flag.\n */\n public static async createChangeFeatureFlag(\n params: CreateApprovalRequest<ChangeFeatureFlagPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createChangeFeatureFlag',\n 'api/approvals/change-feature-flag',\n )\n }\n\n /**\n * Opens a release-train publish request. The caller sends no `preview`:\n * control-backend reads it from console when the request opens.\n */\n public static async createReleaseTrainPublish(\n params: CreateApprovalRequest<Omit<ReleaseTrainPublishPayload, 'preview'>>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createReleaseTrainPublish',\n 'api/approvals/release-train-publish',\n )\n }\n\n /** Opens a release-train rollback request. The caller sends no `preview`. */\n public static async createReleaseTrainRollback(\n params: CreateApprovalRequest<Omit<ReleaseTrainRollbackPayload, 'preview'>>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createReleaseTrainRollback',\n 'api/approvals/release-train-rollback',\n )\n }\n\n /** Adds the approval of the caller. The last one can run the action. */\n public static async acknowledge(\n params: ApprovalIdRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'acknowledge',\n `api/approvals/${params.params.id}/ack`,\n 'api/approvals/:id/ack',\n 'post',\n )\n }\n\n /** Closes a request without running the action. The reason is necessary. */\n public static async reject(\n params: RejectApprovalRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'reject',\n `api/approvals/${params.params.id}/reject`,\n 'api/approvals/:id/reject',\n 'post',\n { reason: params.params.reason },\n )\n }\n\n /**\n * Takes back a request. Only the person who opened it can.\n *\n * The reason is optional, and it lands in the same field that a rejection\n * writes. The creator cannot reject their own request, so this is where they\n * say why they closed it.\n */\n public static async withdraw(\n params: WithdrawApprovalRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'withdraw',\n `api/approvals/${params.params.id}/withdraw`,\n 'api/approvals/:id/withdraw',\n 'post',\n params.params.reason ? { reason: params.params.reason } : undefined,\n )\n }\n\n /**\n * Runs a request that holds its approvals.\n *\n * Only a use case in the explicit mode needs this. An action that throws\n * leaves the request `failed`, and this call still answers 200 with it, so\n * read `status` and `executionError` of the answer.\n */\n public static async execute(\n params: ApprovalIdRequest,\n ): Promise<ApprovalJobDto> {\n return ControlApprovalsService.readOne(\n params,\n 'execute',\n `api/approvals/${params.params.id}/execute`,\n 'api/approvals/:id/execute',\n 'post',\n )\n }\n\n /** Opens a send-to-expired-trial request. Any signed-in Camundi can. */\n public static async createSendToExpiredTrial(\n params: CreateApprovalRequest<SendToExpiredTrialPayloadDto>,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createSendToExpiredTrial',\n 'api/approvals/send-to-expired-trial',\n )\n return approval\n }\n\n /**\n * Opens an extend-trial request.\n *\n * Opening one needs `accounts:admin:extendTrial`, and the reason is\n * necessary. The request needs no approval, so the answer already holds the\n * outcome.\n */\n public static async createExtendTrial(\n params: CreateExtendTrialRequest,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createExtendTrial',\n 'api/approvals/extend-trial',\n )\n return approval\n }\n\n /**\n * Opens a create-personal-organisation request. Any signed-in Camundi can.\n *\n * The request needs no approval, so the answer already holds the outcome,\n * and the route answers 404 while `control.personalOrganisation` is off.\n */\n public static async createPersonalOrganisation(\n params: CreatePersonalOrganisationRequest,\n ): Promise<ApprovalJobDto> {\n // The route answers 429 for the cap, and the cap does not go away. `request`\n // tries a 429 up to 8 times with growing waits, so a person at the cap\n // would wait minutes for the message. A rate limit of the service is a\n // retry that the person can press.\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createPersonalOrganisation',\n 'api/approvals/create-personal-organisation',\n { retryRateLimit: false },\n )\n return approval\n }\n\n /**\n * Opens a cluster-ttl-deletion request. Only the delete cron of\n * console-backend can, with an m2m token that holds `cmctd`.\n *\n * The request needs no approval, so the answer already holds the outcome.\n * For a cluster with a live request, the answer is that request.\n */\n public static async createClusterTtlDeletion(\n params: CreateClusterTtlDeletionRequest,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createClusterTtlDeletion',\n 'api/approvals/cluster-ttl-deletion',\n )\n return approval\n }\n\n /**\n * Opens a create-custom-hardware-sizing request. Any signed-in Camundi\n * can. It runs on dev only, needs no approval, and the route answers 403\n * on every other stage.\n */\n public static async createCustomHardwareSizing(\n params: SelfServiceApprovalRequest<\n CreateCustomHardwareSizingPayloadDto | LinkCustomHardwareSizingPayloadDto\n >,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createCustomHardwareSizing',\n 'api/approvals/create-custom-hardware-sizing',\n )\n return approval\n }\n\n /** Opens a remove-custom-hardware-sizing request. See the one above. */\n public static async removeCustomHardwareSizing(\n params: SelfServiceApprovalRequest<RemoveCustomHardwareSizingPayloadDto>,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'removeCustomHardwareSizing',\n 'api/approvals/remove-custom-hardware-sizing',\n )\n return approval\n }\n\n /** Opens a create-custom-generation request. Dev only, no approval. */\n public static async createCustomGeneration(\n params: SelfServiceApprovalRequest<\n CreateCustomGenerationPayloadDto | LinkCustomGenerationPayloadDto\n >,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'createCustomGeneration',\n 'api/approvals/create-custom-generation',\n )\n return approval\n }\n\n /** Opens a remove-custom-generation request. See the one above. */\n public static async removeCustomGeneration(\n params: SelfServiceApprovalRequest<RemoveCustomGenerationPayloadDto>,\n ): Promise<ApprovalJobDto> {\n const { approval } = await ControlApprovalsService.create(\n params,\n 'removeCustomGeneration',\n 'api/approvals/remove-custom-generation',\n )\n return approval\n }\n\n /**\n * Opens a self-service-cluster-modification request. Any signed-in Camundi\n * can, and accounts then checks that the Camundi owns the organization. It\n * runs on dev only and needs no approval, so the answer holds the outcome.\n * A 200 means that the same request of this person still runs.\n */\n public static async createSelfServiceClusterModification(\n params: SelfServiceApprovalRequest<SelfServiceClusterModificationPayloadDto>,\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n return ControlApprovalsService.create(\n params,\n 'createSelfServiceClusterModification',\n 'api/approvals/self-service-cluster-modification',\n )\n }\n\n /**\n * The shared half of every call that answers one request.\n *\n * Six routes answer `{ approval }` and differ only in the verb and the path.\n * One private helper keeps the metrics context, the status check and the\n * unwrapping in one place.\n */\n private static async readOne(\n params: RequestBaseParams,\n name: string,\n url: string,\n normalizedUrl: string,\n method: 'get' | 'post',\n body?: Record<string, unknown>,\n ): Promise<ApprovalJobDto> {\n const serviceContext = contextFor(\n name,\n url,\n normalizedUrl,\n method,\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ approval: ApprovalJobDto }>({\n config: params.config,\n base: BASE,\n url,\n method,\n metricsDetails: serviceContext,\n body,\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return response.body!.approval\n }\n\n /**\n * The shared half of every create route. See `approvalRequestBody`.\n *\n * The route answers 201 for a fresh request and 200 for the one already\n * open for the same target (`create` deduplicates). `created` carries that\n * difference. `createSendToExpiredTrial` and `createExtendTrial` do not\n * need it, so they read `approval` alone off this result.\n */\n private static async create<TPayload>(\n params: CreateApprovalRequest<TPayload>,\n name: string,\n url: string,\n options: {\n /** False sends the call once, also when the answer is a 429. */\n retryRateLimit?: boolean\n /** True masks every value of the body in the log lines. */\n redactBody?: boolean\n } = {},\n ): Promise<{ approval: ApprovalJobDto; created: boolean }> {\n const serviceContext = contextFor(\n name,\n url,\n url,\n 'post',\n params.config.metrics?.source || 'unset',\n )\n const response = await request<{ approval: ApprovalJobDto }>({\n config: params.config,\n base: BASE,\n url,\n method: 'post',\n metricsDetails: serviceContext,\n ...(options.retryRateLimit === false\n ? { retry: { attempts: 1, remaining: 0 } }\n : {}),\n redactBody: options.redactBody,\n body: {\n payload: params.params.payload,\n reason: params.params.reason,\n requiredAcks: params.params.requiredAcks,\n },\n })\n if (!response.ok) {\n throw new HttpError(\n `${serviceContext.method.name}: ${response.status} ${response.statusText}`,\n response.status,\n response.statusText,\n )\n }\n return {\n approval: response.body!.approval,\n created: response.status === 201,\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AA0BA,SAAS,oCAAoC;AAK7C,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAe1B,MAAM,OAAO,EAAE,IAAI,UAAU;AAgpB7B,SAAS,YAAY,SAAiB,CAAC,GAAW;AAChD,QAAM,QAAQ,IAAI,gBAAgB;AAClC,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,MAAM,GAAG;AAC/C,UAAM,QAAQ,MAAM,QAAQ,GAAG,IAAI,IAAI,KAAK,GAAG,IAAI;AACnD,QAAI,UAAU,UAAa,UAAU,IAAI;AACvC,YAAM,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,IAC9B;AAAA,EACF;AACA,SAAO,MAAM,OAAO,IAAI,IAAI,MAAM,SAAS,CAAC,KAAK;AACnD;AAEA,SAAS,WACP,MACA,KACA,eACA,MACA,QAC2B;AAC3B,SAAO;AAAA,I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AAAA,MACA,OAAO,OAAO,SAAS,UAAU;AAAA,IACnC;AACA,UAAM,WAAW,MAAM,QAAsC;AAAA,MAC3D,QAAQ,OAAO;AAAA,MACf,MAAM;AAAA,MACN;AAAA,MACA,QAAQ;AAAA,MACR,gBAAgB;AAAA,MAChB,GAAI,QAAQ,mBAAmB,QAC3B,EAAE,OAAO,EAAE,UAAU,GAAG,WAAW,EAAE,EAAE,IACvC,CAAC;AAAA,MACL,YAAY,QAAQ;AAAA,MACpB,MAAM;AAAA,QACJ,SAAS,OAAO,OAAO;AAAA,QACvB,QAAQ,OAAO,OAAO;AAAA,QACtB,cAAc,OAAO,OAAO;AAAA,MAC9B;AAAA,IACF,CAAC;AACD,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,IAAI;AAAA,QACR,GAAG,eAAe,OAAO,IAAI,KAAK,SAAS,MAAM,IAAI,SAAS,UAAU;AAAA,QACxE,SAAS;AAAA,QACT,SAAS;AAAA,MACX;AAAA,IACF;AACA,WAAO;AAAA,MACL,UAAU,SAAS,KAAM;AAAA,MACzB,SAAS,SAAS,WAAW;AAAA,IAC/B;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/utils/api.d.ts
CHANGED
|
@@ -34,6 +34,12 @@ export interface RequestPayload extends RequestBaseParams {
|
|
|
34
34
|
* fix. The `error` metric and the response stay the same.
|
|
35
35
|
*/
|
|
36
36
|
warnOnNoStatus?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Opt-in: a log line of this request names the top-level keys of the body
|
|
39
|
+
* and masks every value. Use it for a body that holds text with no fixed
|
|
40
|
+
* key to mask, such as the env vars of a generation.
|
|
41
|
+
*/
|
|
42
|
+
redactBody?: boolean;
|
|
37
43
|
body?: any;
|
|
38
44
|
metricsDetails: RequestBaseServiceContext;
|
|
39
45
|
}
|
package/dist/utils/api.js
CHANGED
|
@@ -86,9 +86,13 @@ function log(payload, type, message, additionalData) {
|
|
|
86
86
|
let body;
|
|
87
87
|
if (payload.body) {
|
|
88
88
|
body = JSON.parse(JSON.stringify(payload.body));
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
89
|
+
if (payload.redactBody && typeof body !== "object") {
|
|
90
|
+
body = "********";
|
|
91
|
+
} else {
|
|
92
|
+
for (const key of Object.keys(body)) {
|
|
93
|
+
if (payload.redactBody || key.toLowerCase().includes("password") || key.toLowerCase().includes("secret") || key.toLowerCase().includes("token")) {
|
|
94
|
+
body[key] = "********";
|
|
95
|
+
}
|
|
92
96
|
}
|
|
93
97
|
}
|
|
94
98
|
}
|
package/dist/utils/api.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/api.ts"],
|
|
4
|
-
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type {\n RequestBaseCustomMetricsDetailsType,\n RequestBaseMethodType,\n RequestBaseParams,\n RequestBaseServiceContext,\n} from '../types/general.types.js'\nimport { getEnvParam, type ServiceName } from './environments.js'\nimport { frontendCache } from './frontendCache.js'\n\nexport interface RequestPayload extends RequestBaseParams {\n base?: {\n id: ServiceName\n }\n url: string\n method: RequestBaseMethodType\n headers?: { [key: string]: string }\n type?: 'json' | 'text' | 'form' | 'none'\n responseType?: 'json' | 'text' | 'blob' | 'none'\n retry?: {\n attempts: number\n remaining: number\n }\n /**\n * Opt-in: retry transient gateway failures (502/503/504 and network/fetch\n * errors) with backoff, mirroring the 429 retry. Retried attempts emit a\n * `transient-retry` metric instead of `error`, so a healed blip (e.g. an\n * envoy connection reset during a pod restart) doesn't count toward the\n * internal error-rate alert. Only enable for idempotent-safe calls \u2014 a\n * retried POST may execute twice.\n */\n retryTransientErrors?: boolean\n transientRetry?: {\n attempts: number\n remaining: number\n }\n /**\n * Opt-in: log a failure with no HTTP status (timeout, connection reset) at\n * `warn` instead of `error`. Use it for third-party sites that we cannot\n * fix. The `error` metric and the response stay the same.\n */\n warnOnNoStatus?: boolean\n body?: any\n metricsDetails: RequestBaseServiceContext\n}\n\nconst TRANSIENT_RETRY_STATUS = [502, 503, 504]\n/**\n * Cap on the error body kept as `statusText`. It ends up in the thrown error's\n * message, the log line, and the `ccma.errors` payload, and some upstreams\n * (LiteLLM, GCP load balancers) answer failures with a full HTML page \u2014 one\n * such response is kilobytes of markup standing in for a reason phrase. The\n * head is what carries the actual reason.\n */\nconst MAX_ERROR_BODY_LENGTH = 500\n/** Appended in place of what was cut, and counted against the cap above. */\nconst ERROR_BODY_TRUNCATION_MARKER = '\u2026 [truncated]'\nconst MAX_TRANSIENT_RETRIES = 3\n\nlet sendToAccountsNg: () => boolean = () => false\n\n/**\n * Sends the requests to accounts with the header `x-ccma-backend: next` while\n * `isOn` answers true. The gateway then routes them to accounts-ng (spec\n * `docs/specs/accounts-ng.md`, section 9). A frontend sets it to read the flag\n * `accounts.ngBackend`. A backend never sets it: the gateway weights move the\n * calls of the backends.\n */\nexport const setAccountsNgBackend = (isOn: () => boolean): void => {\n sendToAccountsNg = isOn\n}\n\n/**\n * The header that sends a request to accounts-ng, or none. A frontend helper\n * that calls `fetch` for accounts itself adds it too.\n */\nexport const accountsNgHeaders = (): Record<string, string> => {\n try {\n return sendToAccountsNg() ? { 'x-ccma-backend': 'next' } : {}\n } catch (_error) {\n // never let a flag read break a request\n return {}\n }\n}\n\n/**\n * True for an absolute URL on the accounts host of the stage. Many callers\n * send such a URL with no `base`.\n */\nfunction isAccountsUrl(payload: RequestPayload): boolean {\n if (payload.base) {\n return false\n }\n try {\n const accounts = getEnvParam('accounts', payload.config)\n return payload.url === accounts || payload.url.startsWith(`${accounts}/`)\n } catch (_error) {\n return false\n }\n}\n\nexport interface Response<T> {\n body?: T\n status: number\n statusText?: string\n ok: boolean\n meta: {\n duration: number\n }\n}\n\nfunction sendMetrics(\n payload: RequestPayload,\n type: RequestBaseCustomMetricsDetailsType,\n options?: {\n duration?: number\n statusCode?: string\n error?: string\n },\n) {\n if (payload.config.metrics) {\n if (payload.config.metrics.types.includes(type)) {\n let durationBucket: string | undefined\n if (options?.duration) {\n if (options.duration < 100) {\n durationBucket = '0 | <100ms'\n } else if (options.duration < 200) {\n durationBucket = '1 | <200ms'\n } else if (options.duration < 500) {\n durationBucket = '2 | <500ms'\n } else if (options.duration < 1000) {\n durationBucket = '3 | <1s'\n } else {\n durationBucket = '4 | >=1s'\n }\n }\n\n // only add normalized errors as labels\n let error = 'other'\n if (options?.error) {\n try {\n const errorMessage = options.error\n if (errorMessage.startsWith('<!DOCTYPE html>')) {\n error = 'html-response'\n } else if (errorMessage.includes('UND_ERR_CONNECT_TIMEOUT')) {\n error = 'connect-timeout'\n }\n } catch (_error) {\n // ignore it\n }\n } else {\n error = 'unset'\n }\n\n const metrics: RequestBaseServiceContext = {\n ...payload.metricsDetails,\n eventType: type,\n durationBucket,\n statusCode: options?.statusCode,\n error,\n }\n try {\n payload.config.metrics.callback(metrics)\n } catch (metricsCallbackError) {\n log(payload, 'debug', `Failed to send metrics`, {\n error: metricsCallbackError,\n metrics,\n })\n }\n }\n }\n}\n\nexport function log(\n payload: RequestPayload,\n type: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n additionalData?: any,\n) {\n if (payload.config.logger) {\n const messageParts: string[] = []\n messageParts.push(payload.metricsDetails?.method?.name)\n messageParts.push(\n `${payload.metricsDetails?.target?.name} (${payload.metricsDetails?.target?.type})`,\n )\n messageParts.push(message)\n let body: any\n if (payload.body) {\n body = JSON.parse(JSON.stringify(payload.body))\n for (const key of Object.keys(body)) {\n if (\n key.toLowerCase().includes('password') ||\n key.toLowerCase().includes('secret') ||\n key.toLowerCase().includes('token')\n ) {\n body[key] = '********'\n }\n }\n }\n\n let fullUrl = 'unset'\n\n if (payload.base) {\n try {\n const base = getEnvParam(payload.base.id, payload.config)\n fullUrl = base ? `${base}/${payload.url}` : payload.url\n } catch (_error) {\n fullUrl = `failed to get base url for ${payload.base.id}`\n }\n }\n\n let url = `${payload.url}`.toLowerCase()\n if (url.includes('secret') || url.includes('password')) {\n url = url.split('?')[0]\n }\n\n const data = {\n base: payload.base,\n method: payload.method,\n url,\n fullUrl,\n retry: payload.retry,\n body,\n context: payload.metricsDetails,\n ...additionalData,\n }\n // `warn` is optional on the logger, so fall back to `error` and lose no log\n const { logger } = payload.config\n const fullMessage = messageParts.join(' > ')\n if (type === 'warn') {\n if (logger.warn) {\n logger.warn(fullMessage, { data })\n } else {\n logger.error(fullMessage, { data })\n }\n } else {\n logger[type](fullMessage, { data })\n }\n }\n}\n\nfunction rateLimitWaitingTime(attempt: number): number {\n const noise = Math.random() * 100\n const waitingTime = 2 ** attempt * 1000 + noise\n return Math.floor(waitingTime)\n}\n\nfunction transientRetryWaitingTime(attempt: number): number {\n const noise = Math.random() * 100\n // 500ms, 1s, 2s (+jitter) \u2014 bounded so a fire-and-forget call heals fast.\n return Math.floor(2 ** attempt * 250 + noise)\n}\n\nfunction canRetryTransient(payload: RequestPayload): boolean {\n if (!payload.retryTransientErrors) {\n return false\n }\n const remaining = payload.transientRetry?.remaining ?? MAX_TRANSIENT_RETRIES\n return remaining > 0\n}\n\nasync function scheduleTransientRetry(payload: RequestPayload): Promise<void> {\n const attempts = payload.transientRetry?.attempts ?? 1\n const remaining = payload.transientRetry?.remaining ?? MAX_TRANSIENT_RETRIES\n const waitingTime = transientRetryWaitingTime(attempts)\n log(\n payload,\n 'debug',\n `transient error, attempt ${attempts}, remaining ${remaining}, waiting ${waitingTime}ms`,\n )\n await new Promise((resolve) => {\n setTimeout(resolve, waitingTime)\n })\n // eslint-disable-next-line require-atomic-updates\n payload.transientRetry = {\n attempts: attempts + 1,\n remaining: remaining - 1,\n }\n}\n\nexport async function request<T>(\n payload: RequestPayload,\n): Promise<Response<T>> {\n log(payload, 'debug', 'starting request')\n sendMetrics(payload, 'request')\n // configure frontend cache if enabled (browser only)\n try {\n if (payload.config.frontendCaching?.enabled) {\n frontendCache.configure(payload.config.frontendCaching)\n }\n } catch (_cacheConfigError) {\n // ignore configuration errors silently\n }\n let token\n if (payload.config.auth) {\n token = await payload.config.auth.getToken()\n }\n // Dynamic (e.g. correlation) headers first, then explicit per-request headers\n // override them, then auth/content-type below take final precedence.\n //\n // Correlation headers (traceparent, x-cc-session-id) identify our internal\n // request/session, so they must only ever reach Camunda-owned systems. Every\n // third-party target is marked `type: 'external'`, so we gate on that here:\n // external targets never receive dynamic headers even if the caller's config\n // sets getDynamicHeaders. This makes propagation safe-by-default and removes\n // the footgun of a shared config that is used for both internal and\n // third-party calls (e.g. BASIC_API_CONFIG \u2192 token-issuer vs Slack).\n let dynamicHeaders: Record<string, string> = {}\n if (payload.metricsDetails?.target?.type !== 'external') {\n try {\n dynamicHeaders = payload.config.getDynamicHeaders?.() ?? {}\n } catch (_error) {\n // never let header evaluation break a request\n }\n }\n const headers: { [key: string]: string } = {\n ...dynamicHeaders,\n ...(payload.headers ?? {}),\n }\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n if (payload.base?.id === 'accounts' || isAccountsUrl(payload)) {\n Object.assign(headers, accountsNgHeaders())\n }\n const type = payload.type ?? 'json'\n let body\n if (type) {\n switch (type) {\n case 'json':\n headers['Content-Type'] = 'application/json'\n body = payload.body ? JSON.stringify(payload.body) : undefined\n break\n case 'text':\n headers['Content-Type'] = 'text/plain'\n body = payload.body ? JSON.stringify(payload.body) : undefined\n break\n case 'form':\n if (payload.body) {\n const formData = new URLSearchParams()\n Object.keys(payload.body).forEach((key) => {\n formData.append(key, payload.body[key])\n })\n body = formData\n }\n break\n }\n }\n let base\n if (payload.base) {\n try {\n base = getEnvParam(payload.base.id, payload.config)\n } catch (error) {\n log(payload, 'error', `Failed to get base url for ${payload.base.id}`, {\n error,\n })\n throw error\n }\n }\n const url = base ? `${base}/${payload.url}` : payload.url\n\n // Attempt cache read for GET requests (stale-while-revalidate when callback supplied)\n let serveCachedAndReturnAfterNetwork = false\n if (payload.method === 'get' && payload.config.frontendCaching?.enabled) {\n try {\n const cached = await frontendCache.get<T>('get', url)\n if (cached) {\n const fresh = frontendCache.isFresh(cached)\n if (payload.onCachedResponse) {\n payload.onCachedResponse(cached.payload, { fresh, source: 'cache' })\n if (!fresh) {\n log(payload, 'debug', 'cache stale, refreshing in background')\n serveCachedAndReturnAfterNetwork = true\n } else {\n log(payload, 'debug', 'cache fresh, returning early')\n sendMetrics(payload, 'success', { duration: 0, statusCode: '200' })\n return {\n // eslint-disable-next-line id-length\n ok: true,\n status: 200,\n statusText: 'cached',\n body: cached.payload,\n meta: { duration: 0 },\n }\n }\n } else if (fresh) {\n // no callback but fresh -> return directly\n log(payload, 'debug', 'cache hit, returning cached response')\n sendMetrics(payload, 'success', { duration: 0, statusCode: '200' })\n return {\n // eslint-disable-next-line id-length\n ok: true,\n status: 200,\n statusText: 'cached',\n body: cached.payload,\n meta: { duration: 0 },\n }\n } else {\n log(payload, 'debug', 'cache stale, proceeding with network request')\n }\n }\n } catch (_cacheGetError) {\n // ignore cache errors\n }\n }\n const start = performance.now()\n const proxyAgent = payload.config.proxyAgent ?? {}\n try {\n const fetchResponse = await fetch(url, {\n signal: payload.config.timeout\n ? AbortSignal.timeout(payload.config.timeout)\n : undefined,\n method: payload.method.toUpperCase(),\n headers,\n body,\n ...proxyAgent,\n })\n const end = performance.now()\n const duration = end - start\n\n if ([429].includes(fetchResponse.status)) {\n // rate limiting, retry\n log(payload, 'info', 'rate limited', { durationMs: Math.floor(duration) })\n sendMetrics(payload, 'rate-limit-retry', {\n duration,\n statusCode: String(fetchResponse.status),\n })\n const remaining = payload.retry?.remaining ?? 8\n const attempts = payload.retry?.attempts ?? 1\n if (remaining > 0) {\n let waitingTime = rateLimitWaitingTime(attempts)\n if (fetchResponse.headers.has('x-ratelimit-reset')) {\n const rateLimitHeader = fetchResponse.headers.get('x-ratelimit-reset')\n log(\n payload,\n 'debug',\n `rate limited, found x-ratelimit-reset header: ${rateLimitHeader}`,\n )\n const rateLimitHeaderNumber = Number(rateLimitHeader)\n if (Number.isNaN(rateLimitHeaderNumber)) {\n waitingTime = Date.parse(rateLimitHeader ?? '0') - Date.now()\n } else {\n waitingTime = rateLimitHeaderNumber - Date.now()\n }\n }\n if (waitingTime < 0 || waitingTime > 180000) {\n waitingTime = rateLimitWaitingTime(attempts)\n }\n log(\n payload,\n 'debug',\n `rate limited, attempt ${attempts}, remaining ${remaining}, waiting ${waitingTime}ms`,\n )\n await new Promise((resolve) => {\n setTimeout(resolve, waitingTime)\n })\n // eslint-disable-next-line require-atomic-updates\n payload.retry = {\n attempts: attempts + 1,\n remaining: remaining - 1,\n }\n return request(payload)\n }\n log(payload, 'debug', `rate limited, no more retries`, {\n durationMs: Math.floor(duration),\n })\n }\n\n const response: Response<T> = {\n // eslint-disable-next-line id-length\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n meta: {\n duration,\n },\n }\n\n const responseType = payload.responseType ?? type\n\n if (response.ok) {\n log(payload, 'debug', `request successful in ${Math.floor(duration)}ms`, {\n baseUrl: base,\n durationMs: Math.floor(duration),\n })\n sendMetrics(payload, 'success', {\n duration,\n statusCode: String(fetchResponse.status),\n })\n switch (responseType) {\n case 'json':\n try {\n response.body = await fetchResponse.json()\n } catch (_error) {\n log(\n payload,\n 'debug',\n `Failed to parse json body. Returning empty object.`,\n {\n baseUrl: base,\n },\n )\n response.body = {} as T\n try {\n const responseBodyText = await fetchResponse.text()\n log(payload, 'debug', `Response body text`, {\n baseUrl: base,\n responseBodyText,\n status: fetchResponse.status,\n })\n } catch (textError) {\n // this is fine\n log(payload, 'debug', `Failed to parse response body text.`, {\n baseUrl: base,\n status: fetchResponse.status,\n error: textError,\n })\n }\n }\n break\n case 'text':\n response.body = (await fetchResponse.text()) as T\n break\n case 'blob':\n // Binary payloads (file downloads, e.g. database dumps). Not cached.\n response.body = (await fetchResponse.blob()) as T\n break\n default:\n response.body = (await fetchResponse.text()) as T\n }\n // store in cache after parsing\n if (\n payload.method === 'get' &&\n payload.config.frontendCaching?.enabled &&\n response.body !== undefined &&\n responseType !== 'blob'\n ) {\n try {\n await frontendCache.set('get', url, response.body as any)\n log(payload, 'debug', 'cache store successful')\n } catch (_cacheSetError) {\n // ignore cache set error\n }\n }\n } else {\n let statusText = fetchResponse.statusText\n try {\n statusText = await fetchResponse.text()\n } catch (_error) {\n // this is fine\n }\n if (statusText.length > MAX_ERROR_BODY_LENGTH) {\n // The marker is part of the budget, so the stored value never exceeds\n // MAX_ERROR_BODY_LENGTH \u2014 appending it after slicing to the full cap\n // would put the result over the bound the constant advertises.\n statusText = `${statusText.slice(\n 0,\n MAX_ERROR_BODY_LENGTH - ERROR_BODY_TRUNCATION_MARKER.length,\n )}${ERROR_BODY_TRUNCATION_MARKER}`\n }\n response.statusText = statusText\n log(\n payload,\n 'debug',\n `request failed with status ${response.status}: ${statusText}`,\n {\n baseUrl: base,\n durationMs: Math.floor(duration),\n },\n )\n\n // Transient gateway failure (e.g. envoy \"connection termination\" 503\n // during a pod restart). When opted in, retry with backoff and record it\n // as `transient-retry` rather than `error`, so a healed blip stays off\n // the internal error-rate alert.\n if (\n TRANSIENT_RETRY_STATUS.includes(response.status) &&\n canRetryTransient(payload)\n ) {\n sendMetrics(payload, 'transient-retry', {\n duration,\n statusCode: String(fetchResponse.status),\n error: statusText,\n })\n await scheduleTransientRetry(payload)\n return request(payload)\n }\n\n // Special Handling for dedicated target systems to not count special status codes as errors\n // eslint-disable-next-line no-shadow\n let type: RequestBaseCustomMetricsDetailsType = 'error'\n const noErrorStatusCodes: number[] = []\n switch (payload.metricsDetails.target.name) {\n case 'auth0':\n noErrorStatusCodes.push(...[400, 404, 409])\n break\n case 'accounts':\n case 'console':\n noErrorStatusCodes.push(...[404, 409])\n if (payload.metricsDetails.method.name === 'createTemporaryCluster') {\n // case: cannot create temporary cluster\n noErrorStatusCodes.push(...[400, 403, 412])\n }\n if (\n [\n 'ConsoleM2MService.verifyZeebeClient',\n 'ConsoleM2MService.verifyApiClient',\n ].includes(payload.metricsDetails.method.name)\n ) {\n // case: api/zeebe client credentials are invalid\n noErrorStatusCodes.push(...[401])\n }\n if (\n payload.metricsDetails.method.name ===\n 'OrgsService.createAndReturnSocialLoginUser'\n ) {\n noErrorStatusCodes.push(\n ...[\n // onboard user, user already has an org\n 400,\n // existing extSSO-connection\n 412,\n ],\n )\n }\n break\n case 'control':\n if (\n payload.metricsDetails.method.name ===\n 'ControlAgentClientsInternalService.verify'\n ) {\n // case: the credentials of an agent client are invalid\n noErrorStatusCodes.push(401)\n }\n break\n }\n\n if (noErrorStatusCodes.includes(response.status)) {\n type = 'success'\n }\n\n sendMetrics(payload, type, {\n duration,\n statusCode: String(fetchResponse.status),\n error: statusText,\n })\n }\n if (serveCachedAndReturnAfterNetwork && response.ok) {\n // when we served stale via callback earlier, we now also return the fresh response\n log(payload, 'debug', 'stale cache updated, returning new data')\n }\n return response\n } catch (error: any) {\n const duration = performance.now() - start\n let errorMessage: string | undefined\n if (error?.cause?.code) {\n errorMessage = error?.cause?.code\n } else if (error?.message) {\n errorMessage = error?.message\n }\n // Network/fetch error with no HTTP status (e.g. connection reset, timeout).\n // Retry-on-opt-in before treating it as an error (see else branch above).\n if (canRetryTransient(payload)) {\n log(payload, 'debug', `request failed with no status, retrying`, {\n baseUrl: base,\n error,\n durationMs: Math.floor(duration),\n })\n sendMetrics(payload, 'transient-retry', {\n statusCode: 'fetch-error',\n duration,\n error: errorMessage,\n })\n await scheduleTransientRetry(payload)\n return request(payload)\n }\n log(\n payload,\n payload.warnOnNoStatus ? 'warn' : 'error',\n `request failed with no status`,\n {\n baseUrl: base,\n error,\n durationMs: Math.floor(duration),\n },\n )\n sendMetrics(payload, 'error', {\n statusCode: 'fetch-error',\n duration,\n error: errorMessage,\n })\n const response: Response<T> = {\n // eslint-disable-next-line id-length\n ok: false,\n status: 500,\n statusText: 'fetch error',\n meta: {\n duration,\n },\n }\n return response\n }\n}\n"],
|
|
5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AAEA,kBAAY,SAASA,OAAM;AAAA,QACzB;AAAA,QACA,YAAY,OAAO,cAAc,MAAM;AAAA,QACvC,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AACA,QAAI,oCAAoC,SAAS,IAAI;AAEnD,UAAI,SAAS,SAAS,yCAAyC;AAAA,IACjE;AACA,WAAO;AAAA,EACT,SAAS,OAAY;AACnB,UAAM,WAAW,YAAY,IAAI,IAAI;AACrC,QAAI;AACJ,QAAI,OAAO,OAAO,MAAM;AACtB,qBAAe,OAAO,OAAO;AAAA,IAC/B,WAAW,OAAO,SAAS;AACzB,qBAAe,OAAO;AAAA,IACxB;AAGA,QAAI,kBAAkB,OAAO,GAAG;AAC9B,UAAI,SAAS,SAAS,2CAA2C;AAAA,QAC/D,SAAS;AAAA,QACT;AAAA,QACA,YAAY,KAAK,MAAM,QAAQ;AAAA,MACjC,CAAC;AACD,kBAAY,SAAS,mBAAmB;AAAA,QACtC,YAAY;AAAA,QACZ;AAAA,QACA,OAAO;AAAA,MACT,CAAC;AACD,YAAM,uBAAuB,OAAO;AACpC,aAAO,QAAQ,OAAO;AAAA,IACxB;AACA;AAAA,MACE;AAAA,MACA,QAAQ,iBAAiB,SAAS;AAAA,MAClC;AAAA,MACA;AAAA,QACE,SAAS;AAAA,QACT;AAAA,QACA,YAAY,KAAK,MAAM,QAAQ;AAAA,MACjC;AAAA,IACF;AACA,gBAAY,SAAS,SAAS;AAAA,MAC5B,YAAY;AAAA,MACZ;AAAA,MACA,OAAO;AAAA,IACT,CAAC;AACD,UAAM,WAAwB;AAAA;AAAA,MAE5B,IAAI;AAAA,MACJ,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,MAAM;AAAA,QACJ;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;",
|
|
4
|
+
"sourcesContent": ["/*\n * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH\n * under one or more contributor license agreements. Licensed under a commercial license.\n * You may not use this file except in compliance with the commercial license.\n */\n\nimport type {\n RequestBaseCustomMetricsDetailsType,\n RequestBaseMethodType,\n RequestBaseParams,\n RequestBaseServiceContext,\n} from '../types/general.types.js'\nimport { getEnvParam, type ServiceName } from './environments.js'\nimport { frontendCache } from './frontendCache.js'\n\nexport interface RequestPayload extends RequestBaseParams {\n base?: {\n id: ServiceName\n }\n url: string\n method: RequestBaseMethodType\n headers?: { [key: string]: string }\n type?: 'json' | 'text' | 'form' | 'none'\n responseType?: 'json' | 'text' | 'blob' | 'none'\n retry?: {\n attempts: number\n remaining: number\n }\n /**\n * Opt-in: retry transient gateway failures (502/503/504 and network/fetch\n * errors) with backoff, mirroring the 429 retry. Retried attempts emit a\n * `transient-retry` metric instead of `error`, so a healed blip (e.g. an\n * envoy connection reset during a pod restart) doesn't count toward the\n * internal error-rate alert. Only enable for idempotent-safe calls \u2014 a\n * retried POST may execute twice.\n */\n retryTransientErrors?: boolean\n transientRetry?: {\n attempts: number\n remaining: number\n }\n /**\n * Opt-in: log a failure with no HTTP status (timeout, connection reset) at\n * `warn` instead of `error`. Use it for third-party sites that we cannot\n * fix. The `error` metric and the response stay the same.\n */\n warnOnNoStatus?: boolean\n /**\n * Opt-in: a log line of this request names the top-level keys of the body\n * and masks every value. Use it for a body that holds text with no fixed\n * key to mask, such as the env vars of a generation.\n */\n redactBody?: boolean\n body?: any\n metricsDetails: RequestBaseServiceContext\n}\n\nconst TRANSIENT_RETRY_STATUS = [502, 503, 504]\n/**\n * Cap on the error body kept as `statusText`. It ends up in the thrown error's\n * message, the log line, and the `ccma.errors` payload, and some upstreams\n * (LiteLLM, GCP load balancers) answer failures with a full HTML page \u2014 one\n * such response is kilobytes of markup standing in for a reason phrase. The\n * head is what carries the actual reason.\n */\nconst MAX_ERROR_BODY_LENGTH = 500\n/** Appended in place of what was cut, and counted against the cap above. */\nconst ERROR_BODY_TRUNCATION_MARKER = '\u2026 [truncated]'\nconst MAX_TRANSIENT_RETRIES = 3\n\nlet sendToAccountsNg: () => boolean = () => false\n\n/**\n * Sends the requests to accounts with the header `x-ccma-backend: next` while\n * `isOn` answers true. The gateway then routes them to accounts-ng (spec\n * `docs/specs/accounts-ng.md`, section 9). A frontend sets it to read the flag\n * `accounts.ngBackend`. A backend never sets it: the gateway weights move the\n * calls of the backends.\n */\nexport const setAccountsNgBackend = (isOn: () => boolean): void => {\n sendToAccountsNg = isOn\n}\n\n/**\n * The header that sends a request to accounts-ng, or none. A frontend helper\n * that calls `fetch` for accounts itself adds it too.\n */\nexport const accountsNgHeaders = (): Record<string, string> => {\n try {\n return sendToAccountsNg() ? { 'x-ccma-backend': 'next' } : {}\n } catch (_error) {\n // never let a flag read break a request\n return {}\n }\n}\n\n/**\n * True for an absolute URL on the accounts host of the stage. Many callers\n * send such a URL with no `base`.\n */\nfunction isAccountsUrl(payload: RequestPayload): boolean {\n if (payload.base) {\n return false\n }\n try {\n const accounts = getEnvParam('accounts', payload.config)\n return payload.url === accounts || payload.url.startsWith(`${accounts}/`)\n } catch (_error) {\n return false\n }\n}\n\nexport interface Response<T> {\n body?: T\n status: number\n statusText?: string\n ok: boolean\n meta: {\n duration: number\n }\n}\n\nfunction sendMetrics(\n payload: RequestPayload,\n type: RequestBaseCustomMetricsDetailsType,\n options?: {\n duration?: number\n statusCode?: string\n error?: string\n },\n) {\n if (payload.config.metrics) {\n if (payload.config.metrics.types.includes(type)) {\n let durationBucket: string | undefined\n if (options?.duration) {\n if (options.duration < 100) {\n durationBucket = '0 | <100ms'\n } else if (options.duration < 200) {\n durationBucket = '1 | <200ms'\n } else if (options.duration < 500) {\n durationBucket = '2 | <500ms'\n } else if (options.duration < 1000) {\n durationBucket = '3 | <1s'\n } else {\n durationBucket = '4 | >=1s'\n }\n }\n\n // only add normalized errors as labels\n let error = 'other'\n if (options?.error) {\n try {\n const errorMessage = options.error\n if (errorMessage.startsWith('<!DOCTYPE html>')) {\n error = 'html-response'\n } else if (errorMessage.includes('UND_ERR_CONNECT_TIMEOUT')) {\n error = 'connect-timeout'\n }\n } catch (_error) {\n // ignore it\n }\n } else {\n error = 'unset'\n }\n\n const metrics: RequestBaseServiceContext = {\n ...payload.metricsDetails,\n eventType: type,\n durationBucket,\n statusCode: options?.statusCode,\n error,\n }\n try {\n payload.config.metrics.callback(metrics)\n } catch (metricsCallbackError) {\n log(payload, 'debug', `Failed to send metrics`, {\n error: metricsCallbackError,\n metrics,\n })\n }\n }\n }\n}\n\nexport function log(\n payload: RequestPayload,\n type: 'debug' | 'info' | 'warn' | 'error',\n message: string,\n additionalData?: any,\n) {\n if (payload.config.logger) {\n const messageParts: string[] = []\n messageParts.push(payload.metricsDetails?.method?.name)\n messageParts.push(\n `${payload.metricsDetails?.target?.name} (${payload.metricsDetails?.target?.type})`,\n )\n messageParts.push(message)\n let body: any\n if (payload.body) {\n body = JSON.parse(JSON.stringify(payload.body))\n // A string has no keys to mask, and writing to its index throws.\n if (payload.redactBody && typeof body !== 'object') {\n body = '********'\n } else {\n for (const key of Object.keys(body)) {\n if (\n payload.redactBody ||\n key.toLowerCase().includes('password') ||\n key.toLowerCase().includes('secret') ||\n key.toLowerCase().includes('token')\n ) {\n body[key] = '********'\n }\n }\n }\n }\n\n let fullUrl = 'unset'\n\n if (payload.base) {\n try {\n const base = getEnvParam(payload.base.id, payload.config)\n fullUrl = base ? `${base}/${payload.url}` : payload.url\n } catch (_error) {\n fullUrl = `failed to get base url for ${payload.base.id}`\n }\n }\n\n let url = `${payload.url}`.toLowerCase()\n if (url.includes('secret') || url.includes('password')) {\n url = url.split('?')[0]\n }\n\n const data = {\n base: payload.base,\n method: payload.method,\n url,\n fullUrl,\n retry: payload.retry,\n body,\n context: payload.metricsDetails,\n ...additionalData,\n }\n // `warn` is optional on the logger, so fall back to `error` and lose no log\n const { logger } = payload.config\n const fullMessage = messageParts.join(' > ')\n if (type === 'warn') {\n if (logger.warn) {\n logger.warn(fullMessage, { data })\n } else {\n logger.error(fullMessage, { data })\n }\n } else {\n logger[type](fullMessage, { data })\n }\n }\n}\n\nfunction rateLimitWaitingTime(attempt: number): number {\n const noise = Math.random() * 100\n const waitingTime = 2 ** attempt * 1000 + noise\n return Math.floor(waitingTime)\n}\n\nfunction transientRetryWaitingTime(attempt: number): number {\n const noise = Math.random() * 100\n // 500ms, 1s, 2s (+jitter) \u2014 bounded so a fire-and-forget call heals fast.\n return Math.floor(2 ** attempt * 250 + noise)\n}\n\nfunction canRetryTransient(payload: RequestPayload): boolean {\n if (!payload.retryTransientErrors) {\n return false\n }\n const remaining = payload.transientRetry?.remaining ?? MAX_TRANSIENT_RETRIES\n return remaining > 0\n}\n\nasync function scheduleTransientRetry(payload: RequestPayload): Promise<void> {\n const attempts = payload.transientRetry?.attempts ?? 1\n const remaining = payload.transientRetry?.remaining ?? MAX_TRANSIENT_RETRIES\n const waitingTime = transientRetryWaitingTime(attempts)\n log(\n payload,\n 'debug',\n `transient error, attempt ${attempts}, remaining ${remaining}, waiting ${waitingTime}ms`,\n )\n await new Promise((resolve) => {\n setTimeout(resolve, waitingTime)\n })\n // eslint-disable-next-line require-atomic-updates\n payload.transientRetry = {\n attempts: attempts + 1,\n remaining: remaining - 1,\n }\n}\n\nexport async function request<T>(\n payload: RequestPayload,\n): Promise<Response<T>> {\n log(payload, 'debug', 'starting request')\n sendMetrics(payload, 'request')\n // configure frontend cache if enabled (browser only)\n try {\n if (payload.config.frontendCaching?.enabled) {\n frontendCache.configure(payload.config.frontendCaching)\n }\n } catch (_cacheConfigError) {\n // ignore configuration errors silently\n }\n let token\n if (payload.config.auth) {\n token = await payload.config.auth.getToken()\n }\n // Dynamic (e.g. correlation) headers first, then explicit per-request headers\n // override them, then auth/content-type below take final precedence.\n //\n // Correlation headers (traceparent, x-cc-session-id) identify our internal\n // request/session, so they must only ever reach Camunda-owned systems. Every\n // third-party target is marked `type: 'external'`, so we gate on that here:\n // external targets never receive dynamic headers even if the caller's config\n // sets getDynamicHeaders. This makes propagation safe-by-default and removes\n // the footgun of a shared config that is used for both internal and\n // third-party calls (e.g. BASIC_API_CONFIG \u2192 token-issuer vs Slack).\n let dynamicHeaders: Record<string, string> = {}\n if (payload.metricsDetails?.target?.type !== 'external') {\n try {\n dynamicHeaders = payload.config.getDynamicHeaders?.() ?? {}\n } catch (_error) {\n // never let header evaluation break a request\n }\n }\n const headers: { [key: string]: string } = {\n ...dynamicHeaders,\n ...(payload.headers ?? {}),\n }\n if (token) {\n headers.Authorization = `Bearer ${token}`\n }\n if (payload.base?.id === 'accounts' || isAccountsUrl(payload)) {\n Object.assign(headers, accountsNgHeaders())\n }\n const type = payload.type ?? 'json'\n let body\n if (type) {\n switch (type) {\n case 'json':\n headers['Content-Type'] = 'application/json'\n body = payload.body ? JSON.stringify(payload.body) : undefined\n break\n case 'text':\n headers['Content-Type'] = 'text/plain'\n body = payload.body ? JSON.stringify(payload.body) : undefined\n break\n case 'form':\n if (payload.body) {\n const formData = new URLSearchParams()\n Object.keys(payload.body).forEach((key) => {\n formData.append(key, payload.body[key])\n })\n body = formData\n }\n break\n }\n }\n let base\n if (payload.base) {\n try {\n base = getEnvParam(payload.base.id, payload.config)\n } catch (error) {\n log(payload, 'error', `Failed to get base url for ${payload.base.id}`, {\n error,\n })\n throw error\n }\n }\n const url = base ? `${base}/${payload.url}` : payload.url\n\n // Attempt cache read for GET requests (stale-while-revalidate when callback supplied)\n let serveCachedAndReturnAfterNetwork = false\n if (payload.method === 'get' && payload.config.frontendCaching?.enabled) {\n try {\n const cached = await frontendCache.get<T>('get', url)\n if (cached) {\n const fresh = frontendCache.isFresh(cached)\n if (payload.onCachedResponse) {\n payload.onCachedResponse(cached.payload, { fresh, source: 'cache' })\n if (!fresh) {\n log(payload, 'debug', 'cache stale, refreshing in background')\n serveCachedAndReturnAfterNetwork = true\n } else {\n log(payload, 'debug', 'cache fresh, returning early')\n sendMetrics(payload, 'success', { duration: 0, statusCode: '200' })\n return {\n // eslint-disable-next-line id-length\n ok: true,\n status: 200,\n statusText: 'cached',\n body: cached.payload,\n meta: { duration: 0 },\n }\n }\n } else if (fresh) {\n // no callback but fresh -> return directly\n log(payload, 'debug', 'cache hit, returning cached response')\n sendMetrics(payload, 'success', { duration: 0, statusCode: '200' })\n return {\n // eslint-disable-next-line id-length\n ok: true,\n status: 200,\n statusText: 'cached',\n body: cached.payload,\n meta: { duration: 0 },\n }\n } else {\n log(payload, 'debug', 'cache stale, proceeding with network request')\n }\n }\n } catch (_cacheGetError) {\n // ignore cache errors\n }\n }\n const start = performance.now()\n const proxyAgent = payload.config.proxyAgent ?? {}\n try {\n const fetchResponse = await fetch(url, {\n signal: payload.config.timeout\n ? AbortSignal.timeout(payload.config.timeout)\n : undefined,\n method: payload.method.toUpperCase(),\n headers,\n body,\n ...proxyAgent,\n })\n const end = performance.now()\n const duration = end - start\n\n if ([429].includes(fetchResponse.status)) {\n // rate limiting, retry\n log(payload, 'info', 'rate limited', { durationMs: Math.floor(duration) })\n sendMetrics(payload, 'rate-limit-retry', {\n duration,\n statusCode: String(fetchResponse.status),\n })\n const remaining = payload.retry?.remaining ?? 8\n const attempts = payload.retry?.attempts ?? 1\n if (remaining > 0) {\n let waitingTime = rateLimitWaitingTime(attempts)\n if (fetchResponse.headers.has('x-ratelimit-reset')) {\n const rateLimitHeader = fetchResponse.headers.get('x-ratelimit-reset')\n log(\n payload,\n 'debug',\n `rate limited, found x-ratelimit-reset header: ${rateLimitHeader}`,\n )\n const rateLimitHeaderNumber = Number(rateLimitHeader)\n if (Number.isNaN(rateLimitHeaderNumber)) {\n waitingTime = Date.parse(rateLimitHeader ?? '0') - Date.now()\n } else {\n waitingTime = rateLimitHeaderNumber - Date.now()\n }\n }\n if (waitingTime < 0 || waitingTime > 180000) {\n waitingTime = rateLimitWaitingTime(attempts)\n }\n log(\n payload,\n 'debug',\n `rate limited, attempt ${attempts}, remaining ${remaining}, waiting ${waitingTime}ms`,\n )\n await new Promise((resolve) => {\n setTimeout(resolve, waitingTime)\n })\n // eslint-disable-next-line require-atomic-updates\n payload.retry = {\n attempts: attempts + 1,\n remaining: remaining - 1,\n }\n return request(payload)\n }\n log(payload, 'debug', `rate limited, no more retries`, {\n durationMs: Math.floor(duration),\n })\n }\n\n const response: Response<T> = {\n // eslint-disable-next-line id-length\n ok: fetchResponse.ok,\n status: fetchResponse.status,\n statusText: fetchResponse.statusText,\n meta: {\n duration,\n },\n }\n\n const responseType = payload.responseType ?? type\n\n if (response.ok) {\n log(payload, 'debug', `request successful in ${Math.floor(duration)}ms`, {\n baseUrl: base,\n durationMs: Math.floor(duration),\n })\n sendMetrics(payload, 'success', {\n duration,\n statusCode: String(fetchResponse.status),\n })\n switch (responseType) {\n case 'json':\n try {\n response.body = await fetchResponse.json()\n } catch (_error) {\n log(\n payload,\n 'debug',\n `Failed to parse json body. Returning empty object.`,\n {\n baseUrl: base,\n },\n )\n response.body = {} as T\n try {\n const responseBodyText = await fetchResponse.text()\n log(payload, 'debug', `Response body text`, {\n baseUrl: base,\n responseBodyText,\n status: fetchResponse.status,\n })\n } catch (textError) {\n // this is fine\n log(payload, 'debug', `Failed to parse response body text.`, {\n baseUrl: base,\n status: fetchResponse.status,\n error: textError,\n })\n }\n }\n break\n case 'text':\n response.body = (await fetchResponse.text()) as T\n break\n case 'blob':\n // Binary payloads (file downloads, e.g. database dumps). Not cached.\n response.body = (await fetchResponse.blob()) as T\n break\n default:\n response.body = (await fetchResponse.text()) as T\n }\n // store in cache after parsing\n if (\n payload.method === 'get' &&\n payload.config.frontendCaching?.enabled &&\n response.body !== undefined &&\n responseType !== 'blob'\n ) {\n try {\n await frontendCache.set('get', url, response.body as any)\n log(payload, 'debug', 'cache store successful')\n } catch (_cacheSetError) {\n // ignore cache set error\n }\n }\n } else {\n let statusText = fetchResponse.statusText\n try {\n statusText = await fetchResponse.text()\n } catch (_error) {\n // this is fine\n }\n if (statusText.length > MAX_ERROR_BODY_LENGTH) {\n // The marker is part of the budget, so the stored value never exceeds\n // MAX_ERROR_BODY_LENGTH \u2014 appending it after slicing to the full cap\n // would put the result over the bound the constant advertises.\n statusText = `${statusText.slice(\n 0,\n MAX_ERROR_BODY_LENGTH - ERROR_BODY_TRUNCATION_MARKER.length,\n )}${ERROR_BODY_TRUNCATION_MARKER}`\n }\n response.statusText = statusText\n log(\n payload,\n 'debug',\n `request failed with status ${response.status}: ${statusText}`,\n {\n baseUrl: base,\n durationMs: Math.floor(duration),\n },\n )\n\n // Transient gateway failure (e.g. envoy \"connection termination\" 503\n // during a pod restart). When opted in, retry with backoff and record it\n // as `transient-retry` rather than `error`, so a healed blip stays off\n // the internal error-rate alert.\n if (\n TRANSIENT_RETRY_STATUS.includes(response.status) &&\n canRetryTransient(payload)\n ) {\n sendMetrics(payload, 'transient-retry', {\n duration,\n statusCode: String(fetchResponse.status),\n error: statusText,\n })\n await scheduleTransientRetry(payload)\n return request(payload)\n }\n\n // Special Handling for dedicated target systems to not count special status codes as errors\n // eslint-disable-next-line no-shadow\n let type: RequestBaseCustomMetricsDetailsType = 'error'\n const noErrorStatusCodes: number[] = []\n switch (payload.metricsDetails.target.name) {\n case 'auth0':\n noErrorStatusCodes.push(...[400, 404, 409])\n break\n case 'accounts':\n case 'console':\n noErrorStatusCodes.push(...[404, 409])\n if (payload.metricsDetails.method.name === 'createTemporaryCluster') {\n // case: cannot create temporary cluster\n noErrorStatusCodes.push(...[400, 403, 412])\n }\n if (\n [\n 'ConsoleM2MService.verifyZeebeClient',\n 'ConsoleM2MService.verifyApiClient',\n ].includes(payload.metricsDetails.method.name)\n ) {\n // case: api/zeebe client credentials are invalid\n noErrorStatusCodes.push(...[401])\n }\n if (\n payload.metricsDetails.method.name ===\n 'OrgsService.createAndReturnSocialLoginUser'\n ) {\n noErrorStatusCodes.push(\n ...[\n // onboard user, user already has an org\n 400,\n // existing extSSO-connection\n 412,\n ],\n )\n }\n break\n case 'control':\n if (\n payload.metricsDetails.method.name ===\n 'ControlAgentClientsInternalService.verify'\n ) {\n // case: the credentials of an agent client are invalid\n noErrorStatusCodes.push(401)\n }\n break\n }\n\n if (noErrorStatusCodes.includes(response.status)) {\n type = 'success'\n }\n\n sendMetrics(payload, type, {\n duration,\n statusCode: String(fetchResponse.status),\n error: statusText,\n })\n }\n if (serveCachedAndReturnAfterNetwork && response.ok) {\n // when we served stale via callback earlier, we now also return the fresh response\n log(payload, 'debug', 'stale cache updated, returning new data')\n }\n return response\n } catch (error: any) {\n const duration = performance.now() - start\n let errorMessage: string | undefined\n if (error?.cause?.code) {\n errorMessage = error?.cause?.code\n } else if (error?.message) {\n errorMessage = error?.message\n }\n // Network/fetch error with no HTTP status (e.g. connection reset, timeout).\n // Retry-on-opt-in before treating it as an error (see else branch above).\n if (canRetryTransient(payload)) {\n log(payload, 'debug', `request failed with no status, retrying`, {\n baseUrl: base,\n error,\n durationMs: Math.floor(duration),\n })\n sendMetrics(payload, 'transient-retry', {\n statusCode: 'fetch-error',\n duration,\n error: errorMessage,\n })\n await scheduleTransientRetry(payload)\n return request(payload)\n }\n log(\n payload,\n payload.warnOnNoStatus ? 'warn' : 'error',\n `request failed with no status`,\n {\n baseUrl: base,\n error,\n durationMs: Math.floor(duration),\n },\n )\n sendMetrics(payload, 'error', {\n statusCode: 'fetch-error',\n duration,\n error: errorMessage,\n })\n const response: Response<T> = {\n // eslint-disable-next-line id-length\n ok: false,\n status: 500,\n statusText: 'fetch error',\n meta: {\n duration,\n },\n }\n return response\n }\n}\n"],
|
|
5
|
+
"mappings": "AAYA,SAAS,mBAAqC;AAC9C,SAAS,qBAAqB;AA4C9B,MAAM,yBAAyB,CAAC,KAAK,KAAK,GAAG;AAQ7C,MAAM,wBAAwB;AAE9B,MAAM,+BAA+B;AACrC,MAAM,wBAAwB;AAE9B,IAAI,mBAAkC,MAAM;AASrC,MAAM,uBAAuB,CAAC,SAA8B;AACjE,qBAAmB;AACrB;AAMO,MAAM,oBAAoB,MAA8B;AAC7D,MAAI;AACF,WAAO,iBAAiB,IAAI,EAAE,kBAAkB,OAAO,IAAI,CAAC;AAAA,EAC9D,SAAS,QAAQ;AAEf,WAAO,CAAC;AAAA,EACV;AACF;AAMA,SAAS,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,OAAO;AAAA,IAC/B,WAAW,OAAO,SAAS;AACzB,qBAAe,OAAO;AAAA,IACxB;AAGA,QAAI,kBAAkB,OAAO,GAAG;AAC9B,UAAI,SAAS,SAAS,2CAA2C;AAAA,QAC/D,SAAS;AAAA,QACT;AAAA,QACA,YAAY,KAAK,MAAM,QAAQ;AAAA,MACjC,CAAC;AACD,kBAAY,SAAS,mBAAmB;AAAA,QACtC,YAAY;AAAA,QACZ;AAAA,QACA,OAAO;AAAA,MACT,CAAC;AACD,YAAM,uBAAuB,OAAO;AACpC,aAAO,QAAQ,OAAO;AAAA,IACxB;AACA;AAAA,MACE;AAAA,MACA,QAAQ,iBAAiB,SAAS;AAAA,MAClC;AAAA,MACA;AAAA,QACE,SAAS;AAAA,QACT;AAAA,QACA,YAAY,KAAK,MAAM,QAAQ;AAAA,MACjC;AAAA,IACF;AACA,gBAAY,SAAS,SAAS;AAAA,MAC5B,YAAY;AAAA,MACZ;AAAA,MACA,OAAO;AAAA,IACT,CAAC;AACD,UAAM,WAAwB;AAAA;AAAA,MAE5B,IAAI;AAAA,MACJ,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,MAAM;AAAA,QACJ;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": ["type"]
|
|
7
7
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@camunda/ccma-api",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.18.0",
|
|
4
4
|
"description": "Centralized API service layer for Camunda Cloud Management Apps",
|
|
5
5
|
"bugs": {
|
|
6
6
|
"url": "https://github.com/camunda/camunda-cloud-management-apps/issues"
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@camunda/ccma-shared-types": "10.
|
|
44
|
+
"@camunda/ccma-shared-types": "10.5.0"
|
|
45
45
|
},
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "node esbuild.mjs && tsc --emitDeclarationOnly --outDir dist",
|