diff --git a/.husky/post-checkout b/.husky/post-checkout deleted file mode 100755 index 59ef5f6f..00000000 --- a/.husky/post-checkout +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env sh -. "$(dirname -- "$0")/_/husky.sh" - -./.husky/scripts/sync-node-modules diff --git a/.husky/post-merge b/.husky/post-merge deleted file mode 100755 index 59ef5f6f..00000000 --- a/.husky/post-merge +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env sh -. "$(dirname -- "$0")/_/husky.sh" - -./.husky/scripts/sync-node-modules diff --git a/.husky/post-rewrite b/.husky/post-rewrite deleted file mode 100755 index 59ef5f6f..00000000 --- a/.husky/post-rewrite +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env sh -. "$(dirname -- "$0")/_/husky.sh" - -./.husky/scripts/sync-node-modules diff --git a/.husky/pre-commit b/.husky/pre-commit deleted file mode 100755 index 7e154687..00000000 --- a/.husky/pre-commit +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env sh -. "$(dirname -- "$0")/_/husky.sh" - -npm run lint-staged diff --git a/.husky/scripts/sync-node-modules b/.husky/scripts/sync-node-modules deleted file mode 100755 index 20cfb9a0..00000000 --- a/.husky/scripts/sync-node-modules +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash -# -# Copyright (c) 2023 Red Hat, Inc. -# This program and the accompanying materials are made -# available under the terms of the Eclipse Public License 2.0 -# which is available at https://www.eclipse.org/legal/epl-2.0/ -# -# SPDX-License-Identifier: EPL-2.0 -# -# script to perform yarn install if package.json has changed -# triggered by post-checkout, post-merge, post-rewrite hooks - -#shellcheck disable=SC1083 -changed_files="$(git diff-tree -r --name-only --no-commit-id HEAD@{1} HEAD)" - -if [[ $changed_files == *"package.json"* ]]; then - eval "yarn install" -fi diff --git a/.ibm/OWNERS b/.ibm/OWNERS deleted file mode 100644 index 24a56a9c..00000000 --- a/.ibm/OWNERS +++ /dev/null @@ -1,16 +0,0 @@ -reviewers: - - josephca - - gustavolira - - subhashkhileri - - albarbaro - - nilgaar - - zdrapela - - psrna -approvers: - - josephca - - gustavolira - - subhashkhileri - - albarbaro - - nilgaar - - zdrapela - - psrna diff --git a/.ibm/images/Dockerfile b/.ibm/images/Dockerfile deleted file mode 100644 index 10af6110..00000000 --- a/.ibm/images/Dockerfile +++ /dev/null @@ -1,97 +0,0 @@ -FROM mcr.microsoft.com/playwright:v1.47.2-jammy - -ENV CI=1 \ - QT_X11_NO_MITSHM=1 \ - _X11_NO_MITSHM=1 \ - _MITSHM=0 \ - NODE_PATH=/usr/local/lib/node_modules - -# Define Helm and OpenShift CLI (oc) versions -ENV HELM_VERSION="v3.12.3" -ENV OC_VERSION="4.14.3" - -ARG CI_XBUILD - -RUN apt-get update && \ - apt-get install -y nodejs-dev nodejs \ - openssl libssl-dev ca-certificates make cmake cpp gcc g++ zlib1g zlib1g-dev brotli libbrotli-dev python3 && \ - apt-get clean && rm -rf /var/lib/apt/lists/* - -# should be root user -RUN echo "whoami: $(whoami)" \ - # command "id" should print: - # uid=0(root) gid=0(root) groups=0(root) - # which means the current user is root - && id \ - && npm install -g typescript \ - # give every user read access to the "/root" folder where the binary is cached - # we really only need to worry about the top folder, fortunately - && ls -la /root \ - && chmod 755 /root \ - # always grab the latest Yarn - # otherwise the base image might have old versions - # NPM does not need to be installed as it is already included with Node. - && npm i -g yarn@latest \ - # Show where Node loads required modules from - && node -p 'module.paths' -# plus Electron and bundled Node versions - -RUN echo " node version: $(node -v) \n" \ - "npm version: $(npm -v) \n" \ - "yarn version: $(yarn -v) \n" \ - "typescript version: $(tsc -v) \n" \ - "debian version: $(cat /etc/debian_version) \n" \ - "user: $(whoami) \n" - -RUN curl -fsSL https://clis.cloud.ibm.com/install/linux | sh && \ - curl -sLO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && \ - chmod +x kubectl && \ - mv kubectl /usr/local/bin/ && \ - apt-get update -y && \ - apt-get install -y sshpass jq colorized-logs && \ - rm -rf /var/lib/apt/lists/* - -# Set Go version and the expected SHA256 hash for verification -ENV GO_VERSION 1.19 -ENV GO_SHA256 464b6b66591f6cf055bc5df90a9750bf5fbc9d038722bb84a9d56a2bea974be6 - -# Install Go and other tools used by the pipeline -RUN apt-get update && \ - apt-get install -y curl && \ - curl -LO "https://golang.org/dl/go${GO_VERSION}.linux-amd64.tar.gz" && \ - echo "${GO_SHA256} go${GO_VERSION}.linux-amd64.tar.gz" | sha256sum -c - && \ - tar -C /usr/local -xzf go${GO_VERSION}.linux-amd64.tar.gz && \ - rm go${GO_VERSION}.linux-amd64.tar.gz && \ - apt-get clean && \ - rm -rf /var/lib/apt/lists/* - -# Install Helm -RUN curl -fsSL -o /tmp/helm.tar.gz "https://get.helm.sh/helm-${HELM_VERSION}-linux-amd64.tar.gz" \ - && tar -xzvf /tmp/helm.tar.gz -C /tmp \ - && mv /tmp/linux-amd64/helm /usr/local/bin/helm \ - && rm -rf /tmp/* - -# Install OpenShift CLI (oc) -RUN curl -fsSL -o /tmp/openshift-client-linux.tar.gz "https://mirror.openshift.com/pub/openshift-v4/clients/ocp/${OC_VERSION}/openshift-client-linux-${OC_VERSION}.tar.gz" \ - && tar -xzvf /tmp/openshift-client-linux.tar.gz -C /usr/local/bin oc kubectl \ - && rm -rf /tmp/* - -# Install rsync -RUN apt-get update -y && \ - apt-get install -y rsync - -# Install yq -RUN wget https://github.com/mikefarah/yq/releases/download/v4.43.1/yq_linux_amd64.tar.gz -O - | tar xz && mv yq_linux_amd64 /usr/bin/yq - -# Install Azure CLI -RUN curl -sL https://aka.ms/InstallAzureCLIDeb | bash - -# Set environment variables to make Go work correctly -ENV GOPATH /go -ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH - -RUN go install github.com/kadel/pr-commenter@latest && \ - ibmcloud plugin install -f cloud-object-storage && \ - ibmcloud plugin install -f kubernetes-service - -WORKDIR /tmp/ diff --git a/.ibm/images/README b/.ibm/images/README deleted file mode 100644 index a311addd..00000000 --- a/.ibm/images/README +++ /dev/null @@ -1 +0,0 @@ -This Dockerfile creates an image to be used by the IBM Cloud pipelines diff --git a/.ibm/manual-tests/postgres/README.md b/.ibm/manual-tests/postgres/README.md deleted file mode 100644 index 1725ec13..00000000 --- a/.ibm/manual-tests/postgres/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Project Setup Instructions - -## Reference Document - -Please refer to the [project documentation](https://docs.google.com/document/d/1OUA5uhsZN0KhUSAln_ohvBRg3hyVx3wyYyddUB-fjlQ/edit#heading=h.hg9hpw7e08uo) and -[documentation link](https://github.com/janus-idp/operator/pull/368) for detailed information and guidelines. - -## Database Setup - -You can use either Azure Database for PostgreSQL - Flexible Server or Amazon RDS for PostgreSQL for this project. Please follow the respective setup guides: - -- [Azure Database for PostgreSQL - Flexible Server](https://learn.microsoft.com/en-gb/azure/postgresql/flexible-server/overview) -- [Amazon RDS for PostgreSQL](https://aws.amazon.com/rds/postgresql/) - -## Configuration - -### Database Connection - -Define the values for the database connection in the `postgress-cred-secret.yaml` file. Here is a template: - -```yaml -apiVersion: v1 -kind: Secret -metadata: - name: postgress-cred-secret -type: Opaque -data: - POSTGRES_PASSWORD: '' - POSTGRES_PORT: '' - POSTGRES_USER: '' - POSTGRES_HOST: '' -``` - -Fill in the values for **POSTGRES_PASSWORD**, **POSTGRES_PORT**, **POSTGRES_USER**, and **POSTGRES_HOST** with the appropriate credentials and connection details. - -### Cluster Configuration - -Replace the values for OCM_CLUSTER_TOKEN and K8S_CLUSTER_URL in the install.sh script. - -Run install.sh - -Verify if the installation was succeeded diff --git a/.ibm/manual-tests/postgres/install.sh b/.ibm/manual-tests/postgres/install.sh deleted file mode 100755 index d602f172..00000000 --- a/.ibm/manual-tests/postgres/install.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh - -set -e -set -x - -HELM_IMAGE_NAME=backstage -HELM_REPO_NAME=rhdh-chart -HELM_REPO_URL="https://redhat-developer.github.io/rhdh-chart" -K8S_CLUSTER_URL= -RELEASE_NAME=rhdh -NAME_SPACE=external-postgres -OCM_CLUSTER_TOKEN= - -oc login --token="${OCM_CLUSTER_TOKEN}" --server="${K8S_CLUSTER_URL}" -oc delete namespace "${NAME_SPACE}" -oc create namespace "${NAME_SPACE}" -oc config set-context --current --namespace="${NAME_SPACE}" -K8S_CLUSTER_ROUTER_BASE=$(oc get ingresses.config/cluster -o jsonpath='{.spec.domain}') - -oc apply -f "./postgres-crt-secrets.yaml" -oc apply -f "./postgress-cred-secret.yaml" -helm upgrade -i "${RELEASE_NAME}" -n "${NAME_SPACE}" "${HELM_REPO_NAME}/${HELM_IMAGE_NAME}" -f "./values.yaml" --set global.clusterRouterBase="${K8S_CLUSTER_ROUTER_BASE}" --set upstream.backstage.image.tag="next" diff --git a/.ibm/manual-tests/postgres/postgres-crt-secrets.yaml b/.ibm/manual-tests/postgres/postgres-crt-secrets.yaml deleted file mode 100644 index c42e4fc4..00000000 --- a/.ibm/manual-tests/postgres/postgres-crt-secrets.yaml +++ /dev/null @@ -1,62 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: postgres-crt -type: Opaque -stringData: - postgres-crt.pem: |- - -----BEGIN CERTIFICATE----- - MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh - MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 - d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD - QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT - MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j - b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG - 9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB - CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97 - nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt - 43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P - T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4 - gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO - BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR - TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw - DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr - hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg - 06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF - PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls - YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk - CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= - -----END CERTIFICATE----- - -----BEGIN CERTIFICATE----- - MIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl - MQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw - NAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2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NsiMwEAYJKwYBBAGC - NxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC - LgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC - gMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6 - tZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh - SnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2 - TaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3 - pvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR - xpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp - GWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9 - dOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN - AHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB - RA+GsCyRxj3qrg+E - -----END CERTIFICATE----- diff --git a/.ibm/manual-tests/postgres/postgress-cred-secret.yaml b/.ibm/manual-tests/postgres/postgress-cred-secret.yaml deleted file mode 100644 index c45f50a9..00000000 --- a/.ibm/manual-tests/postgres/postgress-cred-secret.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: postgres-cred -type: Opaque -stringData: - POSTGRES_PASSWORD: "" - POSTGRES_PORT: "" - POSTGRES_USER: "" - POSTGRES_HOST: "" - PGSSLMODE: "require" - NODE_EXTRA_CA_CERTS: "/opt/app-root/src/postgres-crt.pem" diff --git a/.ibm/manual-tests/postgres/values.yaml b/.ibm/manual-tests/postgres/values.yaml deleted file mode 100644 index 2ca256d3..00000000 --- a/.ibm/manual-tests/postgres/values.yaml +++ /dev/null @@ -1,51 +0,0 @@ -upstream: - postgresql: - enabled: false # disable PostgreSQL instance creation - auth: - existingSecret: postgres-cred - backstage: - appConfig: - backend: - database: - connection: # configure Backstage DB connection parameters - host: ${POSTGRES_HOST} - port: ${POSTGRES_PORT} - user: ${POSTGRES_USER} - password: ${POSTGRES_PASSWORD} - extraEnvVarsSecrets: - - postgres-cred # inject credentials secret to Backstage cont. - extraEnvVars: - - name: BACKEND_SECRET - valueFrom: - secretKeyRef: - key: backend-secret - name: '{{ include "janus-idp.backend-secret-name" $ }}' - extraVolumeMounts: - - mountPath: /opt/app-root/src/dynamic-plugins-root - name: dynamic-plugins-root - - mountPath: /opt/app-root/src/postgres-crt.pem - name: postgres-crt # inject certificate secret to Backstage cont. - subPath: postgres-crt.pem - extraVolumes: - - ephemeral: - volumeClaimTemplate: - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 1Gi - name: dynamic-plugins-root - - configMap: - defaultMode: 420 - name: dynamic-plugins - optional: true - name: dynamic-plugins - - name: dynamic-plugins-npmrc - secret: - defaultMode: 420 - optional: true - secretName: dynamic-plugins-npmrc - - name: postgres-crt - secret: - secretName: postgres-crt diff --git a/.ibm/pipelines/README.md b/.ibm/pipelines/README.md deleted file mode 100644 index d3c261de..00000000 --- a/.ibm/pipelines/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Installation Instructions for Tests - -For tests dependent on `backstage-community-plugin-ocm-backend-dynamic` and `backstage-community-plugin-ocm`, it's necessary to install **Advanced Cluster Management for Kubernetes "MultiClusterHub"**. - -Please follow these steps for installation: - -1. Visit [Installing Advanced Cluster Management for Kubernetes "MultiClusterHub"](https://access.redhat.com/documentation/en-us/red_hat_advanced_cluster_management_for_kubernetes/2.10/html/install/installing#installing-from-the-operatorhub) for detailed instructions on installing from the OperatorHub. diff --git a/.ibm/pipelines/auth/secrets-rhdh-secrets.yaml b/.ibm/pipelines/auth/secrets-rhdh-secrets.yaml deleted file mode 100644 index 0ec98ab1..00000000 --- a/.ibm/pipelines/auth/secrets-rhdh-secrets.yaml +++ /dev/null @@ -1,35 +0,0 @@ -kind: Secret -apiVersion: v1 -metadata: - name: rhdh-secrets -data: - # the followings are place holders with dummy values that will be overwritten by CI - GITHUB_APP_APP_ID: Mzc2ODY2 - GITHUB_APP_CLIENT_ID: SXYxLjdiZDNlZDFmZjY3MmY3ZDg= - GITHUB_APP_PRIVATE_KEY: dGVtcA== - GITHUB_APP_CLIENT_SECRET: dGVtcA== - GITHUB_APP_JANUS_TEST_APP_ID: OTE3NjM5 - GITHUB_APP_JANUS_TEST_CLIENT_ID: SXYyM2xpSEdtU1l6SUFEbHFIakw= - GITHUB_APP_JANUS_TEST_PRIVATE_KEY: dGVtcA== - GITHUB_APP_JANUS_TEST_CLIENT_SECRET: dGVtcA== - GITHUB_APP_WEBHOOK_URL: aHR0cHM6Ly9zbWVlLmlvL0NrRUNLYVgwNzhyZVhobEpEVzA= - GITHUB_APP_WEBHOOK_SECRET: dGVtcA== - GITHUB_URL: aHR0cHM6Ly9naXRodWIuY29t - GITHUB_ORG: amFudXMtcWU= - GITHUB_ORG_2: amFudXMtdGVzdA== - GITLAB_TOKEN: dGVtcA== - K8S_CLUSTER_NAME: bXktY2x1c3Rlcgo= - K8S_CLUSTER_API_SERVER_URL: dGVtcA== - K8S_CLUSTER_TOKEN_ENCODED: dGVtcA== - OCM_CLUSTER_URL: dGVtcA== - OCM_CLUSTER_TOKEN: dGVtcA== - KEYCLOAK_BASE_URL: dGVtcA== - KEYCLOAK_LOGIN_REALM: bXlyZWFsbQ== - KEYCLOAK_REALM: bXlyZWFsbQ== - KEYCLOAK_CLIENT_ID: bXljbGllbnQ= - KEYCLOAK_CLIENT_SECRET: dGVtcA== - ACR_SECRET: dGVtcA== - DH_TARGET_URL: aHR0cDovL3Rlc3QtYmFja3N0YWdlLWN1c3RvbWl6YXRpb24tcHJvdmlkZXItc2hvd2Nhc2UtY2kucmhkaC1wci1vcy1hOTgwNTY1MDgzMGIyMmMzYWVlMjQzZTUxZDc5NTY1ZC0wMDAwLnVzLWVhc3QuY29udGFpbmVycy5hcHBkb21haW4uY2xvdWQ= - GOOGLE_CLIENT_ID: dGVtcA== - GOOGLE_CLIENT_SECRET: dGVtcA== -type: Opaque diff --git a/.ibm/pipelines/auth/service-account-rhdh-secret.yaml b/.ibm/pipelines/auth/service-account-rhdh-secret.yaml deleted file mode 100644 index 85580895..00000000 --- a/.ibm/pipelines/auth/service-account-rhdh-secret.yaml +++ /dev/null @@ -1,7 +0,0 @@ -apiVersion: v1 -kind: Secret -metadata: - name: rhdh-k8s-plugin-secret - annotations: - kubernetes.io/service-account.name: rhdh-k8s-plugin -type: kubernetes.io/service-account-token diff --git a/.ibm/pipelines/env_variables.sh b/.ibm/pipelines/env_variables.sh deleted file mode 100755 index 9b442ce4..00000000 --- a/.ibm/pipelines/env_variables.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/bash -set -a # Automatically export all variables - -#ENVS and Vault Secrets -HELM_CHART_VALUE_FILE_NAME="values_showcase.yaml" -HELM_CHART_RBAC_VALUE_FILE_NAME="values_showcase-rbac.yaml" -HELM_CHART_AKS_DIFF_VALUE_FILE_NAME="diff-values_showcase_AKS.yaml" -HELM_CHART_RBAC_AKS_DIFF_VALUE_FILE_NAME="diff-values_showcase-rbac_AKS.yaml" -HELM_CHART_AKS_MERGED_VALUE_FILE_NAME="merged-values_showcase_AKS.yaml" -HELM_CHART_RBAC_AKS_MERGED_VALUE_FILE_NAME="merged-values_showcase-rbac_AKS.yaml" -HELM_IMAGE_NAME=backstage -HELM_REPO_NAME=rhdh-chart -HELM_REPO_URL="https://redhat-developer.github.io/rhdh-chart" -K8S_CLUSTER_TOKEN_ENCODED=$(printf "%s" $K8S_CLUSTER_TOKEN | base64 | tr -d '\n') -QUAY_REPO="${QUAY_REPO:-janus-idp/backstage-showcase}" - -RELEASE_NAME=rhdh -RELEASE_NAME_RBAC=rhdh-rbac -NAME_SPACE="${NAME_SPACE:-showcase}" -NAME_SPACE_RBAC="${NAME_SPACE_RBAC:-showcase-rbac}" -NAME_SPACE_POSTGRES_DB="${NAME_SPACE_POSTGRES_DB:-postgress-external-db}" -CHART_VERSION="2.15.2" -GITHUB_APP_APP_ID=$(cat /tmp/secrets/GITHUB_APP_APP_ID) -GITHUB_APP_CLIENT_ID=$(cat /tmp/secrets/GITHUB_APP_CLIENT_ID) -GITHUB_APP_PRIVATE_KEY=$(cat /tmp/secrets/GITHUB_APP_PRIVATE_KEY) -GITHUB_APP_CLIENT_SECRET=$(cat /tmp/secrets/GITHUB_APP_CLIENT_SECRET) -GITHUB_APP_2_APP_ID=$(cat /tmp/secrets/GITHUB_APP_2_APP_ID) -GITHUB_APP_2_CLIENT_ID=$(cat /tmp/secrets/GITHUB_APP_2_CLIENT_ID) -GITHUB_APP_2_PRIVATE_KEY=$(cat /tmp/secrets/GITHUB_APP_2_PRIVATE_KEY) -GITHUB_APP_2_CLIENT_SECRET=$(cat /tmp/secrets/GITHUB_APP_2_CLIENT_SECRET) -GITHUB_APP_JANUS_TEST_APP_ID=OTE3NjM5 -GITHUB_APP_JANUS_TEST_CLIENT_ID=SXYyM2xpSEdtU1l6SUFEbHFIakw= -GITHUB_APP_JANUS_TEST_PRIVATE_KEY=$(cat /tmp/secrets/GITHUB_APP_JANUS_TEST_PRIVATE_KEY) -GITHUB_APP_JANUS_TEST_CLIENT_SECRET=$(cat /tmp/secrets/GITHUB_APP_JANUS_TEST_CLIENT_SECRET) -GITHUB_APP_WEBHOOK_URL=aHR0cHM6Ly9zbWVlLmlvL0NrRUNLYVgwNzhyZVhobEpEVzA= -GITHUB_APP_WEBHOOK_SECRET=$(cat /tmp/secrets/GITHUB_APP_WEBHOOK_SECRET) -GITHUB_URL=aHR0cHM6Ly9naXRodWIuY29t -GITHUB_ORG=amFudXMtcWU= -GITHUB_ORG_2=amFudXMtdGVzdA== -GH_USER_ID=$(cat /tmp/secrets/GH_USER_ID) -GH_USER_PASS=$(cat /tmp/secrets/GH_USER_PASS) -GH_2FA_SECRET=$(cat /tmp/secrets/GH_2FA_SECRET) -GH_USER2_ID=$(cat /tmp/secrets/GH_USER2_ID) -GH_USER2_PASS=$(cat /tmp/secrets/GH_USER2_PASS) -GH_USER2_2FA_SECRET=$(cat /tmp/secrets/GH_USER2_2FA_SECRET) -GH_RHDH_QE_USER_TOKEN=$(cat /tmp/secrets/GH_RHDH_QE_USER_TOKEN) - -GITLAB_TOKEN=$(cat /tmp/secrets/GITLAB_TOKEN) - -RHDH_PR_OS_CLUSTER_URL=$(cat /tmp/secrets/RHDH_PR_OS_CLUSTER_URL) -RHDH_PR_OS_CLUSTER_TOKEN=$(cat /tmp/secrets/RHDH_PR_OS_CLUSTER_TOKEN) -K8S_CLUSTER_API_SERVER_URL=$(printf "%s" "$K8S_CLUSTER_URL" | base64 | tr -d '\n') -K8S_SERVICE_ACCOUNT_TOKEN=$K8S_CLUSTER_TOKEN_ENCODED -OCM_CLUSTER_URL=$(printf "%s" "$K8S_CLUSTER_URL" | base64 | tr -d '\n') -OCM_CLUSTER_TOKEN=$K8S_CLUSTER_TOKEN_ENCODED -KEYCLOAK_BASE_URL=$(cat /tmp/secrets/KEYCLOAK_BASE_URL) -KEYCLOAK_LOGIN_REALM='myrealm' -KEYCLOAK_REALM='myrealm' -KEYCLOAK_CLIENT_ID='myclient' -KEYCLOAK_CLIENT_SECRET=$(cat /tmp/secrets/KEYCLOAK_CLIENT_SECRET) -ACR_SECRET=$(cat /tmp/secrets/ACR_SECRET) -DH_TARGET_URL=aHR0cDovL3Rlc3QtYmFja3N0YWdlLWN1c3RvbWl6YXRpb24tcHJvdmlkZXItc2hvd2Nhc2UtY2kucmhkaC1wci1vcy1hOTgwNTY1MDgzMGIyMmMzYWVlMjQzZTUxZDc5NTY1ZC0wMDAwLnVzLWVhc3QuY29udGFpbmVycy5hcHBkb21haW4uY2xvdWQ= -GOOGLE_CLIENT_ID=$(cat /tmp/secrets/GOOGLE_CLIENT_ID) -GOOGLE_CLIENT_SECRET=$(cat /tmp/secrets/GOOGLE_CLIENT_SECRET) -GOOGLE_ACC_COOKIE=$(cat /tmp/secrets/GOOGLE_ACC_COOKIE) -GOOGLE_USER_ID=$(cat /tmp/secrets/GOOGLE_USER_ID) -GOOGLE_USER_PASS=$(cat /tmp/secrets/GOOGLE_USER_PASS) -GOOGLE_2FA_SECRET=$(cat /tmp/secrets/GOOGLE_2FA_SECRET) - -JUNIT_RESULTS="junit-results.xml" -DATA_ROUTER_URL=$(cat /tmp/secrets/DATA_ROUTER_URL) -DATA_ROUTER_USERNAME=$(cat /tmp/secrets/DATA_ROUTER_USERNAME) -DATA_ROUTER_PASSWORD=$(cat /tmp/secrets/DATA_ROUTER_PASSWORD) -DATA_ROUTER_PROJECT="main" -DATA_ROUTER_AUTO_FINALIZATION_TRESHOLD=$(cat /tmp/secrets/DATA_ROUTER_AUTO_FINALIZATION_TRESHOLD) -DATA_ROUTER_NEXUS_HOSTNAME=$(cat /tmp/secrets/DATA_ROUTER_NEXUS_HOSTNAME) -REPORTPORTAL_HOSTNAME=$(cat /tmp/secrets/REPORTPORTAL_HOSTNAME) -SLACK_DATA_ROUTER_WEBHOOK_URL=$(cat /tmp/secrets/SLACK_DATA_ROUTER_WEBHOOK_URL) -REDIS_TEMP_USER=temp -REDIS_TEMP_PASS=test123 - -ARM_TENANT_ID=$(cat /tmp/secrets/ARM_TENANT_ID) -ARM_SUBSCRIPTION_ID=$(cat /tmp/secrets/ARM_SUBSCRIPTION_ID) -ARM_CLIENT_ID=$(cat /tmp/secrets/ARM_CLIENT_ID) -ARM_CLIENT_SECRET=$(cat /tmp/secrets/ARM_CLIENT_SECRET) -AKS_NIGHTLY_CLUSTER_NAME=$(cat /tmp/secrets/AKS_NIGHTLY_CLUSTER_NAME) -AKS_NIGHTLY_CLUSTER_RESOURCEGROUP=$(cat /tmp/secrets/AKS_NIGHTLY_CLUSTER_RESOURCEGROUP) - -set +a # Stop automatically exporting variables diff --git a/.ibm/pipelines/kubernetes-tests.sh b/.ibm/pipelines/kubernetes-tests.sh deleted file mode 100755 index dee82da9..00000000 --- a/.ibm/pipelines/kubernetes-tests.sh +++ /dev/null @@ -1,108 +0,0 @@ -#!/bin/bash -LOGFILE="pr-${GIT_PR_NUMBER}-kubernetes-tests-${BUILD_NUMBER}" -echo "Log file: ${LOGFILE}" -# source ./.ibm/pipelines/functions.sh - -# install the latest ibmcloud cli on Linux -install_ibmcloud() { - if [[ -x "$(command -v ibmcloud)" ]]; then - echo "ibmcloud is already installed." - else - curl -fsSL https://clis.cloud.ibm.com/install/linux | sh - echo "the latest ibmcloud cli installed successfully." - fi -} - -# Call the function to install oc -install_ibmcloud - -ibmcloud version -ibmcloud config --check-version=false -ibmcloud plugin install -f container-registry -ibmcloud plugin install -f kubernetes-service - -ibmcloud login -r "${IBM_REGION}" -g "${IBM_RSC_GROUP}" --apikey "${SERVICE_ID_API_KEY}" -ibmcloud ks cluster config --cluster "${IKS_CLUSTER_ID}" - -install_kubectl() { - if [[ -x "$(command -v kubectl)" ]]; then - echo "kubectl is already installed." - else - # install kubectl - curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl" \ - && chmod +x kubectl \ - && mv kubectl /usr/local/bin/ - echo "kubectl installed successfully." - fi -} - -# Call the function to install kubectl -install_kubectl - -kubectl version -kubectl config current-context - -install_helm() { - if [[ -x "$(command -v helm)" ]]; then - echo "Helm is already installed." - else - echo "Installing Helm 3 client" - - WORKING_DIR=$(pwd) - mkdir ~/tmpbin && cd ~/tmpbin - - HELM_INSTALL_DIR=$(pwd) - curl -sL https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash -f - export PATH=${HELM_INSTALL_DIR}:$PATH - - cd $WORKING_DIR - echo "helm client installed successfully." - fi -} - -install_helm - -# check installed helm version -helm version - -helm repo add bitnami https://charts.bitnami.com/bitnami -helm repo add backstage https://backstage.github.io/charts -helm repo add janus-idp https://janus-idp.github.io/helm-backstage -helm repo update - -helm upgrade -i backstage backstage/backstage -n backstage -f ./helm/values-k8s-ingress.yaml --wait - -echo "Waiting for backstage deployment..." -sleep 45 - -kubectl get pods -n backstage -kubectl port-forward -n backstage svc/backstage 7007:7007 & -# Store the PID of the background process -PID=$! - -sleep 15 - -# Check if Backstage is up and running -BACKSTAGE_URL="http://localhost:7007" -BACKSTAGE_URL_RESPONSE=$(curl -Is "$BACKSTAGE_URL" | head -n 1) -echo "$BACKSTAGE_URL_RESPONSE" - -cd $WORKING_DIR/e2e-tests -yarn install - -Xvfb :99 & -export DISPLAY=:99 - -# yarn cypress run --headless --browser chrome -yarn run cypress:run - -pkill Xvfb - -cd $WORKING_DIR - -# Send Ctrl+C to the process -kill -INT $PID - -helm uninstall backstage -n backstage - -rm -rf ~/tmpbin diff --git a/.ibm/pipelines/openshift-ci-tests.sh b/.ibm/pipelines/openshift-ci-tests.sh deleted file mode 100755 index 532cdc30..00000000 --- a/.ibm/pipelines/openshift-ci-tests.sh +++ /dev/null @@ -1,455 +0,0 @@ -#!/bin/sh - -set -xe -export PS4='[$(date "+%Y-%m-%d %H:%M:%S")] ' # logs timestamp for every cmd. - -LOGFILE="test-log" -DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -secret_name="rhdh-k8s-plugin-secret" -OVERALL_RESULT=0 - -cleanup() { - echo "Cleaning up before exiting" - if [[ "$JOB_NAME" == *aks* ]]; then - az_aks_stop "${AKS_NIGHTLY_CLUSTER_NAME}" "${AKS_NIGHTLY_CLUSTER_RESOURCEGROUP}" - fi - rm -rf ~/tmpbin -} - -trap cleanup EXIT - -source "${DIR}/utils.sh" - -set_cluster_info() { - export K8S_CLUSTER_URL=$(cat /tmp/secrets/RHDH_PR_OS_CLUSTER_URL) - export K8S_CLUSTER_TOKEN=$(cat /tmp/secrets/RHDH_PR_OS_CLUSTER_TOKEN) - - if [[ "$JOB_NAME" == *ocp-v4-14 ]]; then - K8S_CLUSTER_URL=$(cat /tmp/secrets/RHDH_OS_1_CLUSTER_URL) - K8S_CLUSTER_TOKEN=$(cat /tmp/secrets/RHDH_OS_1_CLUSTER_TOKEN) - elif [[ "$JOB_NAME" == *ocp-v4-13 ]]; then - K8S_CLUSTER_URL=$(cat /tmp/secrets/RHDH_OS_2_CLUSTER_URL) - K8S_CLUSTER_TOKEN=$(cat /tmp/secrets/RHDH_OS_2_CLUSTER_TOKEN) - elif [[ "$JOB_NAME" == *aks* ]]; then - K8S_CLUSTER_URL=$(cat /tmp/secrets/RHDH_AKS_CLUSTER_URL) - K8S_CLUSTER_TOKEN=$(cat /tmp/secrets/RHDH_AKS_CLUSTER_TOKEN) - fi -} - -add_helm_repos() { - helm version - - local repos=( - "bitnami=https://charts.bitnami.com/bitnami" - "backstage=https://backstage.github.io/charts" - "${HELM_REPO_NAME}=${HELM_REPO_URL}" - ) - - for repo in "${repos[@]}"; do - local key="${repo%%=*}" - local value="${repo##*=}" - - if ! helm repo list | grep -q "^$key"; then - helm repo add "$key" "$value" - else - echo "Repository $key already exists - updating repository instead." - fi - done - - helm repo update -} - -install_oc() { - if command -v oc >/dev/null 2>&1; then - echo "oc is already installed." - else - curl -LO https://mirror.openshift.com/pub/openshift-v4/clients/oc/latest/linux/oc.tar.gz - tar -xf oc.tar.gz - mv oc /usr/local/bin/ - rm oc.tar.gz - echo "oc installed successfully." - fi -} - -install_helm() { - if command -v helm >/dev/null 2>&1; then - echo "Helm is already installed." - else - echo "Installing Helm 3 client" - mkdir ~/tmpbin && cd ~/tmpbin - curl -sL https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash -f - export PATH=$(pwd):$PATH - echo "Helm client installed successfully." - fi -} - -uninstall_helmchart() { - local project=$1 - local release=$2 - if helm list -n "${project}" | grep -q "${release}"; then - echo "Chart already exists. Removing it before install." - helm uninstall "${release}" -n "${project}" - fi -} - -configure_namespace() { - local project=$1 - delete_namespace $project - oc create namespace "${project}" - oc config set-context --current --namespace="${project}" -} - -delete_namespace() { - local project=$1 - if oc get namespace "$project" >/dev/null 2>&1; then - echo "Namespace ${project} exists. Attempting to delete..." - - # Remove blocking finalizers - remove_finalizers_from_resources "$project" - - # Attempt to delete the namespace - oc delete namespace "$project" --grace-period=0 --force || true - - # Check if namespace is still stuck in 'Terminating' and force removal if necessary - if oc get namespace "$project" -o jsonpath='{.status.phase}' | grep -q 'Terminating'; then - echo "Namespace ${project} is stuck in Terminating. Forcing deletion..." - force_delete_namespace "$project" - fi - fi -} - -configure_external_postgres_db() { - local project=$1 - oc apply -f "${DIR}/resources/postgres-db/postgres.yaml" --namespace="${NAME_SPACE_POSTGRES_DB}" - sleep 5 - - oc get secret postgress-external-db-cluster-cert -n "${NAME_SPACE_POSTGRES_DB}" -o jsonpath='{.data.ca\.crt}' | base64 --decode > postgres-ca - oc get secret postgress-external-db-cluster-cert -n "${NAME_SPACE_POSTGRES_DB}" -o jsonpath='{.data.tls\.crt}' | base64 --decode > postgres-tls-crt - oc get secret postgress-external-db-cluster-cert -n "${NAME_SPACE_POSTGRES_DB}" -o jsonpath='{.data.tls\.key}' | base64 --decode > postgres-tsl-key - - oc create secret generic postgress-external-db-cluster-cert \ - --from-file=ca.crt=postgres-ca \ - --from-file=tls.crt=postgres-tls-crt \ - --from-file=tls.key=postgres-tsl-key \ - --dry-run=client -o yaml | oc apply -f - --namespace="${project}" - - POSTGRES_PASSWORD=$(oc get secret/postgress-external-db-pguser-janus-idp -n "${NAME_SPACE_POSTGRES_DB}" -o jsonpath={.data.password}) - sed -i "s|POSTGRES_PASSWORD:.*|POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}|g" "${DIR}/resources/postgres-db/postgres-cred.yaml" - POSTGRES_HOST=$(echo -n "postgress-external-db-primary.$NAME_SPACE_POSTGRES_DB.svc.cluster.local" | base64 | tr -d '\n') - sed -i "s|POSTGRES_HOST:.*|POSTGRES_HOST: ${POSTGRES_HOST}|g" "${DIR}/resources/postgres-db/postgres-cred.yaml" - oc apply -f "${DIR}/resources/postgres-db/postgres-cred.yaml" --namespace="${project}" -} - -apply_yaml_files() { - local dir=$1 - local project=$2 - echo "Applying YAML files to namespace ${project}" - - oc config set-context --current --namespace="${project}" - - local files=( - "$dir/resources/service_account/service-account-rhdh.yaml" - "$dir/resources/cluster_role_binding/cluster-role-binding-k8s.yaml" - "$dir/resources/cluster_role/cluster-role-k8s.yaml" - "$dir/resources/cluster_role/cluster-role-ocm.yaml" - "$dir/auth/secrets-rhdh-secrets.yaml" - ) - - for file in "${files[@]}"; do - sed -i "s/namespace:.*/namespace: ${project}/g" "$file" - done - - if [[ "$JOB_NAME" == *aks* ]]; then - GITHUB_APP_APP_ID=$GITHUB_APP_2_APP_ID - GITHUB_APP_CLIENT_ID=$GITHUB_APP_2_CLIENT_ID - GITHUB_APP_PRIVATE_KEY=$GITHUB_APP_2_PRIVATE_KEY - GITHUB_APP_CLIENT_SECRET=$GITHUB_APP_2_CLIENT_SECRET - fi - - for key in GITHUB_APP_APP_ID GITHUB_APP_CLIENT_ID GITHUB_APP_PRIVATE_KEY GITHUB_APP_CLIENT_SECRET GITHUB_APP_JANUS_TEST_APP_ID GITHUB_APP_JANUS_TEST_CLIENT_ID GITHUB_APP_JANUS_TEST_CLIENT_SECRET GITHUB_APP_JANUS_TEST_PRIVATE_KEY GITHUB_APP_WEBHOOK_URL GITHUB_APP_WEBHOOK_SECRET KEYCLOAK_CLIENT_SECRET ACR_SECRET GOOGLE_CLIENT_ID GOOGLE_CLIENT_SECRET K8S_CLUSTER_TOKEN_ENCODED OCM_CLUSTER_URL GITLAB_TOKEN; do - sed -i "s|${key}:.*|${key}: ${!key}|g" "$dir/auth/secrets-rhdh-secrets.yaml" - done - - oc apply -f "$dir/resources/service_account/service-account-rhdh.yaml" --namespace="${project}" - oc apply -f "$dir/auth/service-account-rhdh-secret.yaml" --namespace="${project}" - oc apply -f "$dir/auth/secrets-rhdh-secrets.yaml" --namespace="${project}" - if [[ "$JOB_NAME" != *aks* ]]; then - oc new-app https://github.com/janus-qe/test-backstage-customization-provider --namespace="${project}" - oc expose svc/test-backstage-customization-provider --namespace="${project}" - fi - oc apply -f "$dir/resources/cluster_role/cluster-role-k8s.yaml" --namespace="${project}" - oc apply -f "$dir/resources/cluster_role_binding/cluster-role-binding-k8s.yaml" --namespace="${project}" - oc apply -f "$dir/resources/cluster_role/cluster-role-ocm.yaml" --namespace="${project}" - oc apply -f "$dir/resources/cluster_role_binding/cluster-role-binding-ocm.yaml" --namespace="${project}" - - if [[ "$JOB_NAME" != *aks* ]]; then # Skip for AKS, because of strange `sed: -e expression #1, char 136: unterminated `s' command` - sed -i "s/K8S_CLUSTER_API_SERVER_URL:.*/K8S_CLUSTER_API_SERVER_URL: ${ENCODED_API_SERVER_URL}/g" "$dir/auth/secrets-rhdh-secrets.yaml" - fi - sed -i "s/K8S_CLUSTER_NAME:.*/K8S_CLUSTER_NAME: ${ENCODED_CLUSTER_NAME}/g" "$dir/auth/secrets-rhdh-secrets.yaml" - - token=$(oc get secret "${secret_name}" -n "${project}" -o=jsonpath='{.data.token}') - sed -i "s/OCM_CLUSTER_TOKEN: .*/OCM_CLUSTER_TOKEN: ${token}/" "$dir/auth/secrets-rhdh-secrets.yaml" - - if [[ "${project}" == *rbac* ]]; then - oc apply -f "$dir/resources/config_map/configmap-app-config-rhdh-rbac.yaml" --namespace="${project}" - else - oc apply -f "$dir/resources/config_map/configmap-app-config-rhdh.yaml" --namespace="${project}" - fi - oc apply -f "$dir/resources/config_map/configmap-rbac-policy-rhdh.yaml" --namespace="${project}" - oc apply -f "$dir/auth/secrets-rhdh-secrets.yaml" --namespace="${project}" - - sleep 20 # wait for Pipeline Operator/Tekton pipelines to be ready - # Renable when namespace termination issue is solved - # oc apply -f "$dir/resources/pipeline-run/hello-world-pipeline.yaml" - # oc apply -f "$dir/resources/pipeline-run/hello-world-pipeline-run.yaml" -} - -run_tests() { - local release_name=$1 - local project=$2 - cd "${DIR}/../../e2e-tests" - yarn install - yarn playwright install - - Xvfb :99 & - export DISPLAY=:99 - - ( - set -e - echo "Using PR container image: ${TAG_NAME}" - yarn "$project" - ) 2>&1 | tee "/tmp/${LOGFILE}" - - local RESULT=${PIPESTATUS[0]} - - pkill Xvfb - - mkdir -p "${ARTIFACT_DIR}/${project}/test-results" - mkdir -p "${ARTIFACT_DIR}/${project}/attachments/screenshots" - cp -a /tmp/backstage-showcase/e2e-tests/test-results/* "${ARTIFACT_DIR}/${project}/test-results" - cp -a /tmp/backstage-showcase/e2e-tests/${JUNIT_RESULTS} "${ARTIFACT_DIR}/${project}/${JUNIT_RESULTS}" - - if [ -d "/tmp/backstage-showcase/e2e-tests/screenshots" ]; then - cp -a /tmp/backstage-showcase/e2e-tests/screenshots/* "${ARTIFACT_DIR}/${project}/attachments/screenshots/" - fi - - ansi2html <"/tmp/${LOGFILE}" >"/tmp/${LOGFILE}.html" - cp -a "/tmp/${LOGFILE}.html" "${ARTIFACT_DIR}/${project}" - cp -a /tmp/backstage-showcase/e2e-tests/playwright-report/* "${ARTIFACT_DIR}/${project}" - - droute_send "${release_name}" "${project}" - - echo "${project} RESULT: ${RESULT}" - if [ "${RESULT}" -ne 0 ]; then - OVERALL_RESULT=1 - fi -} - -check_backstage_running() { - local release_name=$1 - local namespace=$2 - local url="https://${release_name}-backstage-${namespace}.${K8S_CLUSTER_ROUTER_BASE}" - if [[ "$JOB_NAME" == *aks* ]]; then - local url="https://${K8S_CLUSTER_ROUTER_BASE}" - fi - - local max_attempts=30 - local wait_seconds=30 - - echo "Checking if Backstage is up and running at ${url}" - - for ((i = 1; i <= max_attempts; i++)); do - local http_status - http_status=$(curl --insecure -I -s "${url}" | grep HTTP | awk '{print $2}') - - if [ "${http_status}" -eq 200 ]; then - echo "Backstage is up and running!" - export BASE_URL="${url}" - echo "######## BASE URL ########" - echo "${BASE_URL}" - return 0 - else - echo "Attempt ${i} of ${max_attempts}: Backstage not yet available (HTTP Status: ${http_status})" - sleep "${wait_seconds}" - fi - done - - echo "Failed to reach Backstage at ${BASE_URL} after ${max_attempts} attempts." | tee -a "/tmp/${LOGFILE}" - cp -a "/tmp/${LOGFILE}" "${ARTIFACT_DIR}/${namespace}/" - return 1 -} - -install_pipelines_operator() { - local dir=$1 - DISPLAY_NAME="Red Hat OpenShift Pipelines" - - if oc get csv -n "openshift-operators" | grep -q "${DISPLAY_NAME}"; then - echo "Red Hat OpenShift Pipelines operator is already installed." - else - echo "Red Hat OpenShift Pipelines operator is not installed. Installing..." - oc apply -f "${dir}/resources/pipeline-run/pipelines-operator.yaml" - fi -} - -install_tekton_pipelines() { - local dir=$1 - - if oc get pods -n "tekton-pipelines" | grep -q "tekton-pipelines"; then - echo "Tekton Pipelines are already installed." - else - echo "Tekton Pipelines is not installed. Installing..." - oc apply --filename https://storage.googleapis.com/tekton-releases/pipeline/latest/release.yaml - fi -} - -initiate_deployments() { - add_helm_repos - install_helm - - configure_namespace "${NAME_SPACE}" - install_pipelines_operator "${DIR}" - uninstall_helmchart "${NAME_SPACE}" "${RELEASE_NAME}" - - # Deploy redis cache db. - oc apply -f "$DIR/resources/redis-cache/redis-deployment.yaml" --namespace="${NAME_SPACE}" - - cd "${DIR}" - apply_yaml_files "${DIR}" "${NAME_SPACE}" - echo "Deploying image from repository: ${QUAY_REPO}, TAG_NAME: ${TAG_NAME}, in NAME_SPACE: ${NAME_SPACE}" - helm upgrade -i "${RELEASE_NAME}" -n "${NAME_SPACE}" "${HELM_REPO_NAME}/${HELM_IMAGE_NAME}" --version "${CHART_VERSION}" -f "${DIR}/value_files/${HELM_CHART_VALUE_FILE_NAME}" --set global.clusterRouterBase="${K8S_CLUSTER_ROUTER_BASE}" --set upstream.backstage.image.repository="${QUAY_REPO}" --set upstream.backstage.image.tag="${TAG_NAME}" - - configure_namespace "${NAME_SPACE_POSTGRES_DB}" - configure_namespace "${NAME_SPACE_RBAC}" - configure_external_postgres_db "${NAME_SPACE_RBAC}" - - install_pipelines_operator "${DIR}" - uninstall_helmchart "${NAME_SPACE_RBAC}" "${RELEASE_NAME_RBAC}" - apply_yaml_files "${DIR}" "${NAME_SPACE_RBAC}" - echo "Deploying image from repository: ${QUAY_REPO}, TAG_NAME: ${TAG_NAME}, in NAME_SPACE: ${RELEASE_NAME_RBAC}" - helm upgrade -i "${RELEASE_NAME_RBAC}" -n "${NAME_SPACE_RBAC}" "${HELM_REPO_NAME}/${HELM_IMAGE_NAME}" --version "${CHART_VERSION}" -f "${DIR}/value_files/${HELM_CHART_RBAC_VALUE_FILE_NAME}" --set global.clusterRouterBase="${K8S_CLUSTER_ROUTER_BASE}" --set upstream.backstage.image.repository="${QUAY_REPO}" --set upstream.backstage.image.tag="${TAG_NAME}" -} - -initiate_aks_deployment() { - add_helm_repos - install_helm - delete_namespace "${NAME_SPACE_RBAC_AKS}" - configure_namespace "${NAME_SPACE_AKS}" - # Renable when namespace termination issue is solved - # install_tekton_pipelines - uninstall_helmchart "${NAME_SPACE_AKS}" "${RELEASE_NAME}" - cd "${DIR}" - apply_yaml_files "${DIR}" "${NAME_SPACE_AKS}" - yq_merge_value_files "${DIR}/value_files/${HELM_CHART_VALUE_FILE_NAME}" "${DIR}/value_files/${HELM_CHART_AKS_DIFF_VALUE_FILE_NAME}" "/tmp/${HELM_CHART_AKS_MERGED_VALUE_FILE_NAME}" - echo "Deploying image from repository: ${QUAY_REPO}, TAG_NAME: ${TAG_NAME}, in NAME_SPACE: ${NAME_SPACE_AKS}" - helm upgrade -i "${RELEASE_NAME}" -n "${NAME_SPACE_AKS}" "${HELM_REPO_NAME}/${HELM_IMAGE_NAME}" --version "${CHART_VERSION}" -f "/tmp/${HELM_CHART_AKS_MERGED_VALUE_FILE_NAME}" --set global.host="${K8S_CLUSTER_ROUTER_BASE}" --set upstream.backstage.image.repository="${QUAY_REPO}" --set upstream.backstage.image.tag="${TAG_NAME}" -} - -initiate_rbac_aks_deployment() { - add_helm_repos - install_helm - delete_namespace "${NAME_SPACE_AKS}" - configure_namespace "${NAME_SPACE_RBAC_AKS}" - # Renable when namespace termination issue is solved - # install_tekton_pipelines - uninstall_helmchart "${NAME_SPACE_RBAC_AKS}" "${RELEASE_NAME_RBAC}" - cd "${DIR}" - apply_yaml_files "${DIR}" "${NAME_SPACE_RBAC_AKS}" - yq_merge_value_files "${DIR}/value_files/${HELM_CHART_RBAC_VALUE_FILE_NAME}" "${DIR}/value_files/${HELM_CHART_RBAC_AKS_DIFF_VALUE_FILE_NAME}" "/tmp/${HELM_CHART_RBAC_AKS_MERGED_VALUE_FILE_NAME}" - echo "Deploying image from repository: ${QUAY_REPO}, TAG_NAME: ${TAG_NAME}, in NAME_SPACE: ${NAME_SPACE_RBAC_AKS}" - helm upgrade -i "${RELEASE_NAME_RBAC}" -n "${NAME_SPACE_RBAC_AKS}" "${HELM_REPO_NAME}/${HELM_IMAGE_NAME}" --version "${CHART_VERSION}" -f "/tmp/${HELM_CHART_RBAC_AKS_MERGED_VALUE_FILE_NAME}" --set global.host="${K8S_CLUSTER_ROUTER_BASE}" --set upstream.backstage.image.repository="${QUAY_REPO}" --set upstream.backstage.image.tag="${TAG_NAME}" -} - -check_and_test() { - local release_name=$1 - local namespace=$2 - if check_backstage_running "${release_name}" "${namespace}"; then - echo "Display pods for verification..." - oc get pods -n "${namespace}" - run_tests "${release_name}" "${namespace}" - else - echo "Backstage is not running. Exiting..." - OVERALL_RESULT=1 - fi - save_all_pod_logs $namespace -} - -# Function to remove finalizers from specific resources in a namespace that are blocking deletion. -remove_finalizers_from_resources() { - local project=$1 - echo "Removing finalizers from resources in namespace ${project} that are blocking deletion." - - # Remove finalizers from stuck PipelineRuns and TaskRuns - for resource_type in "pipelineruns.tekton.dev" "taskruns.tekton.dev"; do - for resource in $(oc get "$resource_type" -n "$project" -o name); do - oc patch "$resource" -n "$project" --type='merge' -p '{"metadata":{"finalizers":[]}}' || true - echo "Removed finalizers from $resource in $project." - done - done - - # Check and remove specific finalizers stuck on 'chains.tekton.dev' resources - for chain_resource in $(oc get pipelineruns.tekton.dev,taskruns.tekton.dev -n "$project" -o name); do - oc patch "$chain_resource" -n "$project" --type='json' -p='[{"op": "remove", "path": "/metadata/finalizers"}]' || true - echo "Removed Tekton finalizers from $chain_resource in $project." - done -} - -# Function to forcibly delete a namespace stuck in 'Terminating' status -force_delete_namespace() { - local project=$1 - echo "Forcefully deleting namespace ${project}." - oc get namespace "$project" -o json | jq '.spec = {"finalizers":[]}' | oc replace --raw "/api/v1/namespaces/$project/finalize" -f - -} - -main() { - echo "Log file: ${LOGFILE}" - set_cluster_info - source "${DIR}/env_variables.sh" - if [[ "$JOB_NAME" == *periodic-* ]]; then - NAME_SPACE="showcase-ci-nightly" - NAME_SPACE_RBAC="showcase-rbac-nightly" - NAME_SPACE_POSTGRES_DB="postgress-external-db-nightly" - NAME_SPACE_AKS="showcase-aks-ci-nightly" - NAME_SPACE_RBAC_AKS="showcase-rbac-aks-ci-nightly" - fi - if [[ "$JOB_NAME" == *aks* ]]; then - az_login - az_aks_start "${AKS_NIGHTLY_CLUSTER_NAME}" "${AKS_NIGHTLY_CLUSTER_RESOURCEGROUP}" - az_aks_approuting_enable "${AKS_NIGHTLY_CLUSTER_NAME}" "${AKS_NIGHTLY_CLUSTER_RESOURCEGROUP}" - fi - - install_oc - if [[ "$JOB_NAME" == *aks* ]]; then - az aks get-credentials --name="${AKS_NIGHTLY_CLUSTER_NAME}" --resource-group="${AKS_NIGHTLY_CLUSTER_RESOURCEGROUP}" --overwrite-existing - else - oc login --token="${K8S_CLUSTER_TOKEN}" --server="${K8S_CLUSTER_URL}" - fi - echo "OCP version: $(oc version)" - - API_SERVER_URL=$(oc whoami --show-server) - if [[ "$JOB_NAME" == *aks* ]]; then - K8S_CLUSTER_ROUTER_BASE=$(kubectl get svc nginx --namespace app-routing-system -o jsonpath='{.status.loadBalancer.ingress[0].ip}') - else - K8S_CLUSTER_ROUTER_BASE=$(oc get route console -n openshift-console -o=jsonpath='{.spec.host}' | sed 's/^[^.]*\.//') - fi - - echo "K8S_CLUSTER_ROUTER_BASE : $K8S_CLUSTER_ROUTER_BASE" - - ENCODED_API_SERVER_URL=$(echo "${API_SERVER_URL}" | base64) - ENCODED_CLUSTER_NAME=$(echo "my-cluster" | base64) - - if [[ "$JOB_NAME" == *aks* ]]; then - initiate_aks_deployment - check_and_test "${RELEASE_NAME}" "${NAME_SPACE_AKS}" - delete_namespace "${NAME_SPACE_AKS}" - initiate_rbac_aks_deployment - check_and_test "${RELEASE_NAME_RBAC}" "${NAME_SPACE_RBAC_AKS}" - delete_namespace "${NAME_SPACE_RBAC_AKS}" - else - initiate_deployments - check_and_test "${RELEASE_NAME}" "${NAME_SPACE}" - check_and_test "${RELEASE_NAME_RBAC}" "${NAME_SPACE_RBAC}" - fi - exit "${OVERALL_RESULT}" -} - -main diff --git a/.ibm/pipelines/resources/cluster_role/cluster-role-k8s.yaml b/.ibm/pipelines/resources/cluster_role/cluster-role-k8s.yaml deleted file mode 100644 index 4409d561..00000000 --- a/.ibm/pipelines/resources/cluster_role/cluster-role-k8s.yaml +++ /dev/null @@ -1,86 +0,0 @@ -kind: ClusterRole -apiVersion: rbac.authorization.k8s.io/v1 -metadata: - name: rhdh-k8s-plugin -rules: - # Base for Kubernetes plugin - - apiGroups: - - '' - resources: - - pods - - pods/log - - services - - configmaps - - limitranges - verbs: - - get - - watch - - list - - apiGroups: - - route.openshift.io - resources: - - routes - verbs: - - get - - list - - apiGroups: - - metrics.k8s.io - resources: - - pods - verbs: - - get - - watch - - list - - apiGroups: - - apps - resources: - - daemonsets - - deployments - - replicasets - - statefulsets - verbs: - - get - - watch - - list - - apiGroups: - - autoscaling - resources: - - horizontalpodautoscalers - verbs: - - get - - watch - - list - - apiGroups: - - networking.k8s.io - resources: - - ingresses - verbs: - - get - - watch - - list - - apiGroups: - - batch - resources: - - jobs - - cronjobs - verbs: - - get - - watch - - list - - apiGroups: - - org.eclipse.che - resources: - - checlusters - verbs: - - get - - list - # Additional permissions for the @janus-idp/backstage-plugin-tekton - - apiGroups: - - tekton.dev - resources: - - pipelines - - pipelineruns - - taskruns - verbs: - - get - - list diff --git a/.ibm/pipelines/resources/cluster_role/cluster-role-ocm.yaml b/.ibm/pipelines/resources/cluster_role/cluster-role-ocm.yaml deleted file mode 100644 index 1eefdbf8..00000000 --- a/.ibm/pipelines/resources/cluster_role/cluster-role-ocm.yaml +++ /dev/null @@ -1,22 +0,0 @@ -kind: ClusterRole -apiVersion: rbac.authorization.k8s.io/v1 -metadata: - name: rhdh-k8s-plugin-ocm -rules: -- apiGroups: - - cluster.open-cluster-management.io - resources: - - managedclusters - verbs: - - get - - watch - - list - - create -- apiGroups: - - internal.open-cluster-management.io - resources: - - managedclusterinfos - verbs: - - get - - watch - - list diff --git a/.ibm/pipelines/resources/cluster_role_binding/cluster-role-binding-k8s.yaml b/.ibm/pipelines/resources/cluster_role_binding/cluster-role-binding-k8s.yaml deleted file mode 100644 index 999c4c23..00000000 --- a/.ibm/pipelines/resources/cluster_role_binding/cluster-role-binding-k8s.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: rhdh-k8s-plugin -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: rhdh-k8s-plugin -subjects: -- kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase diff --git a/.ibm/pipelines/resources/cluster_role_binding/cluster-role-binding-ocm.yaml b/.ibm/pipelines/resources/cluster_role_binding/cluster-role-binding-ocm.yaml deleted file mode 100644 index a935bea9..00000000 --- a/.ibm/pipelines/resources/cluster_role_binding/cluster-role-binding-ocm.yaml +++ /dev/null @@ -1,34 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: ClusterRoleBinding -metadata: - name: rhdh-k8s-plugin-ocm -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: ClusterRole - name: rhdh-k8s-plugin-ocm -subjects: - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase-rbac - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase-ci-nightly - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase-rbac-nightly - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase-1-2-x - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase-rbac-1-2-x - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase-1-3-x - - kind: ServiceAccount - name: rhdh-k8s-plugin - namespace: showcase-rbac-1-3-x - diff --git a/.ibm/pipelines/resources/config_map/configmap-app-config-rhdh-rbac.yaml b/.ibm/pipelines/resources/config_map/configmap-app-config-rhdh-rbac.yaml deleted file mode 100644 index d3c477a3..00000000 --- a/.ibm/pipelines/resources/config_map/configmap-app-config-rhdh-rbac.yaml +++ /dev/null @@ -1,123 +0,0 @@ -kind: ConfigMap -apiVersion: v1 -metadata: - name: app-config-rhdh - -data: - app-config-rhdh.yaml: | - app: - title: Red Hat Developer Hub - backend: - auth: - keys: - - secret: temp - integrations: - # Plugin: GitHub - github: - - host: github.com - apps: - - appId: ${GITHUB_APP_APP_ID} - clientId: ${GITHUB_APP_CLIENT_ID} - clientSecret: ${GITHUB_APP_CLIENT_SECRET} - webhookUrl: ${GITHUB_APP_WEBHOOK_URL} - webhookSecret: ${GITHUB_APP_WEBHOOK_SECRET} - privateKey: | - ${GITHUB_APP_PRIVATE_KEY} - bitbucketServer: - - host: bitbucket.com - apiBaseUrl: temp - username: temp - password: temp - gitlab: - - host: gitlab.com - token: temp - auth: - # see https://backstage.io/docs/auth/ to learn about auth providers - environment: development - providers: - # Plugin: GitHub - github: - development: - clientId: ${GITHUB_APP_CLIENT_ID} - clientSecret: ${GITHUB_APP_CLIENT_SECRET} - google: - development: - clientId: ${GOOGLE_CLIENT_ID} - clientSecret: ${GOOGLE_CLIENT_SECRET} - - proxy: - skipInvalidProxies: true - # endpoints: {} - endpoints: - # Other Proxies - # customize developer hub instance - '/developer-hub': - target: ${DH_TARGET_URL} - changeOrigin: true - # Change to "false" in case of using self hosted cluster with a self-signed certificate - secure: false - '/acr/api': - target: 'https://rhdhqetest.azurecr.io/acr/v1/' - changeOrigin: true - headers: - # If you use Bearer Token for authorization, please replace the 'Basic' with 'Bearer' in the following line. - Authorization: '${ACR_SECRET}' - # Change to "false" in case of using self hosted artifactory instance with a self-signed certificate - secure: false - - catalog: - import: - entityFilename: catalog-info.yaml - # pullRequestBranchName: rhdh-integration - pullRequestBranchName: backstage-integration - rules: - - allow: [API, Component, Group, Location, Resource, System, Template] - locations: - - type: url - target: https://github.com/janus-idp/backstage-showcase/blob/main/catalog-entities/all.yaml - - type: url - target: https://github.com/redhat-developer/red-hat-developer-hub-software-templates/blob/main/templates.yaml - - type: url - target: https://github.com/janus-test/janus-test-3-bulk-import/blob/main/catalog-info.yaml - - type: url - target: https://github.com/janus-qe/rhdh-test/blob/main/user.yml - rules: - - allow: [User] - - type: url - target: https://github.com/backstage/backstage/blob/master/packages/catalog-model/examples/acme-corp.yaml - rules: - - allow: [User, Group] - providers: - githubOrg: - id: production - githubUrl: "${GITHUB_URL}" - orgs: ["${GITHUB_ORG}", "${GITHUB_ORG_2}"] - - dynatrace: - baseUrl: temp - argocd: - appLocatorMethods: - - type: 'config' - instances: - - name: argoInstance1 - url: temp - token: temp - - name: argoInstance2 - url: temp - token: temp - permission: - enabled: true - rbac: - maxDepth: 1 - policyFileReload: true - policies-csv-file: './rbac/rbac-policy.csv' - conditionalPoliciesFile: './rbac-conditions/conditional-policies.yaml' - - pluginsWithPermission: - - catalog - - permission - - scaffolder - - admin: - users: - - name: user:default/rhdh-qe diff --git a/.ibm/pipelines/resources/config_map/configmap-app-config-rhdh.yaml b/.ibm/pipelines/resources/config_map/configmap-app-config-rhdh.yaml deleted file mode 100644 index 3a07b6e3..00000000 --- a/.ibm/pipelines/resources/config_map/configmap-app-config-rhdh.yaml +++ /dev/null @@ -1,174 +0,0 @@ -kind: ConfigMap -apiVersion: v1 -metadata: - name: app-config-rhdh - -data: - app-config-rhdh.yaml: | - app: - title: Red Hat Developer Hub - branding: - fullLogo: "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBzdGFuZGFsb25lPSJubyI/Pgo8IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDIwMDEwOTA0Ly9FTiIgImh0dHA6Ly93d3cudzMub3JnL1RSLzIwMDEvUkVDLVNWRy0yMDAxMDkwNC9EVEQvc3ZnMTAuZHRkIj4KPCEtLSBDcmVhdGVkIHVzaW5nIEtyaXRhOiBodHRwczovL2tyaXRhLm9yZyAtLT4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIAogICAgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiCiAgICB4bWxuczprcml0YT0iaHR0cDovL2tyaXRhLm9yZy9uYW1lc3BhY2VzL3N2Zy9rcml0YSIKICAgIHhtbG5zOnNvZGlwb2RpPSJodHRwOi8vc29kaXBvZGkuc291cmNlZm9yZ2UubmV0L0RURC9zb2RpcG9kaS0wLmR0ZCIKICAgIHdpZHRoPSIxNjBwdCIKICAgIGhlaWdodD0iODBwdCIKICAgIHZpZXdCb3g9IjAgMCAxNjAgODAiPgo8ZGVmcy8+Cjx0ZXh0IGlkPSJzaGFwZTAiIGtyaXRhOnVzZVJpY2hUZXh0PSJ0cnVlIiB0ZXh0LXJlbmRlcmluZz0iYXV0byIga3JpdGE6dGV4dFZlcnNpb249IjMiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0wLjE3NzMyMDYxNTAzNDE1NSwgNTQuMjYyNSkiIGZpbGw9IiNmZmZmZmYiIHN0cm9rZS1vcGFjaXR5PSIwIiBzdHJva2U9IiMwMDAwMDAiIHN0cm9rZS13aWR0aD0iMCIgc3Ryb2tlLW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mb250LXdlaWdodDogNzAwOyI+PHRzcGFuIHg9IjAiPlFFPC90c3Bhbj48L3RleHQ+Cjwvc3ZnPgo=" - theme: - light: - primaryColor: "rgb(255, 95, 21)" - headerColor1: "rgb(248, 248, 248)" - headerColor2: "rgb(248, 248, 248)" - navigationIndicatorColor: "rgb(255,95,21)" - dark: - primaryColor: '#ab75cf' - headerColor1: 'rgb(0, 0, 208)' - headerColor2: 'rgb(255, 246, 140)' - navigationIndicatorColor: 'rgb(244, 238, 169)' - dynamicPlugins: - rootDirectory: dynamic-plugins-root - frontend: - default.main-menu-items: - menuItems: - default.list: - title: References - icon: bookmarks - default.apis: - parent: default.list - default.learning-path: - parent: default.list - backstage.plugin-techdocs: - menuItems: - favorites: - title: Favorites - icon: star - priority: 10 - docs: - parent: favorites - priority: 1 - backend: - auth: - keys: - - secret: temp - cache: - store: redis - connection: redis://${REDIS_USERNAME}:${REDIS_PASSWORD}@redis:6379 - useRedisSets: true - integrations: - # Plugin: GitHub - github: - - host: github.com - apps: - - appId: ${GITHUB_APP_APP_ID} - clientId: ${GITHUB_APP_CLIENT_ID} - clientSecret: ${GITHUB_APP_CLIENT_SECRET} - webhookUrl: ${GITHUB_APP_WEBHOOK_URL} - webhookSecret: ${GITHUB_APP_WEBHOOK_SECRET} - privateKey: | - ${GITHUB_APP_PRIVATE_KEY} - - appId: ${GITHUB_APP_JANUS_TEST_APP_ID} - clientId: ${GITHUB_APP_JANUS_TEST_CLIENT_ID} - clientSecret: ${GITHUB_APP_JANUS_TEST_CLIENT_SECRET} - webhookUrl: ${GITHUB_APP_WEBHOOK_URL} - webhookSecret: ${GITHUB_APP_WEBHOOK_SECRET} - privateKey: | - ${GITHUB_APP_JANUS_TEST_PRIVATE_KEY} - bitbucketServer: - - host: bitbucket.com - apiBaseUrl: temp - username: temp - password: temp - gitlab: - - host: gitlab.com - token: ${GITLAB_TOKEN} - auth: - environment: development - providers: - guest: - dangerouslyAllowOutsideDevelopment: true - # Plugin: GitHub - github: - development: - clientId: ${GITHUB_APP_CLIENT_ID} - clientSecret: ${GITHUB_APP_CLIENT_SECRET} - google: - development: - clientId: ${GOOGLE_CLIENT_ID} - clientSecret: ${GOOGLE_CLIENT_SECRET} - - proxy: - skipInvalidProxies: true - # endpoints: {} - endpoints: - # Other Proxies - # customize developer hub instance - '/developer-hub': - target: ${DH_TARGET_URL} - changeOrigin: true - # Change to "false" in case of using self hosted cluster with a self-signed certificate - secure: false - '/acr/api': - target: 'https://rhdhqetest.azurecr.io/acr/v1/' - changeOrigin: true - headers: - # If you use Bearer Token for authorization, please replace the 'Basic' with 'Bearer' in the following line. - Authorization: '${ACR_SECRET}' - # Change to "false" in case of using self hosted artifactory instance with a self-signed certificate - secure: false - - catalog: - import: - entityFilename: catalog-info.yaml - # pullRequestBranchName: rhdh-integration - pullRequestBranchName: backstage-integration - rules: - - allow: [API, Component, Group, Location, Resource, System, Template] - locations: - - type: url - target: https://github.com/janus-idp/backstage-showcase/blob/main/catalog-entities/all.yaml - - type: url - target: https://github.com/redhat-developer/red-hat-developer-hub-software-templates/blob/main/templates.yaml - - type: url - target: https://github.com/janus-qe/acr-catalog/blob/main/catalog-info.yaml - - type: url - target: https://github.com/janus-qe/rhdh-test/blob/main/user.yml - rules: - - allow: [User] - - type: url - target: https://github.com/backstage/backstage/blob/master/packages/catalog-model/examples/acme-corp.yaml - rules: - - allow: [User, Group] - providers: - github: - providerId: - organization: '${GITHUB_ORG}' - schedule: - frequency: { minutes: 30} - timeout: { minutes: 30} - githubOrg: - id: production - githubUrl: "${GITHUB_URL}" - orgs: ["${GITHUB_ORG}", "${GITHUB_ORG_2}"] - - gitlab: - my-test-provider: - group: rhdhqetest - host: gitlab.com - schedule: - frequency: - minutes: 1 - initialDelay: - seconds: 15 - timeout: - minutes: 1 - - dynatrace: - baseUrl: temp - argocd: - appLocatorMethods: - - type: 'config' - instances: - - name: argoInstance1 - url: temp - token: temp - - name: argoInstance2 - url: temp - token: temp - permission: - enabled: false diff --git a/.ibm/pipelines/resources/config_map/configmap-rbac-policy-rhdh.yaml b/.ibm/pipelines/resources/config_map/configmap-rbac-policy-rhdh.yaml deleted file mode 100644 index d91ff12e..00000000 --- a/.ibm/pipelines/resources/config_map/configmap-rbac-policy-rhdh.yaml +++ /dev/null @@ -1,26 +0,0 @@ -kind: ConfigMap -apiVersion: v1 -metadata: - name: rbac-policy -data: - rbac-policy.csv: | - p, role:default/guests, catalog.entity.create, create, allow - p, role:default/team_a, catalog-entity, read, allow - g, user:xyz/user, role:xyz/team_a - g, group:janus-qe/rhdh-qe-2-team, role:default/test2-role - - p, role:xyz/team_a, catalog-entity, read, allow - p, role:xyz/team_a, catalog.entity.create, create, allow - p, role:xyz/team_a, catalog.location.create, create, allow - p, role:xyz/team_a, catalog.location.read, read, allow - - g, user:default/rhdh-qe-user, role:default/qe_rbac_admin - p, role:default/qe_rbac_admin, kubernetes.proxy, use, allow - p, role:default/qe_rbac_admin, catalog.entity.create, create, allow - p, role:default/qe_rbac_admin, catalog.location.create, create, allow - p, role:default/qe_rbac_admin, catalog.location.read, read, allow - - p, role:default/bulk_import, bulk.import, use, allow - p, role:default/bulk_import, catalog.location.create, create, allow - p, role:default/bulk_import, catalog.entity.create, create, allow - g, group:janus-qe/rhdh-qe-2-team, role:default/bulk_import diff --git a/.ibm/pipelines/resources/pipeline-run/hello-world-pipeline-run.yaml b/.ibm/pipelines/resources/pipeline-run/hello-world-pipeline-run.yaml deleted file mode 100644 index e2e252be..00000000 --- a/.ibm/pipelines/resources/pipeline-run/hello-world-pipeline-run.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: tekton.dev/v1beta1 -kind: PipelineRun -metadata: - name: hello-world-pipeline-run - labels: - # this should match https://github.com/janus-qe/nationalparks-py/blob/master/catalog-info.yaml#L10 - backstage.io/kubernetes-id: developer-hub -spec: - pipelineRef: - name: hello-world-pipeline diff --git a/.ibm/pipelines/resources/pipeline-run/hello-world-pipeline.yaml b/.ibm/pipelines/resources/pipeline-run/hello-world-pipeline.yaml deleted file mode 100644 index 7fc89429..00000000 --- a/.ibm/pipelines/resources/pipeline-run/hello-world-pipeline.yaml +++ /dev/null @@ -1,25 +0,0 @@ -apiVersion: tekton.dev/v1beta1 -kind: Pipeline -metadata: - name: hello-world-pipeline - labels: - # this should match https://github.com/janus-qe/nationalparks-py/blob/master/catalog-info.yaml#L10 - backstage.io/kubernetes-id: developer-hub -spec: - tasks: - - name: echo-hello-world - taskSpec: - steps: - - name: echo-hello-world - image: ubuntu - script: | - #!/usr/bin/env bash - echo "Hello, World!" - - name: echo-bye - taskSpec: - steps: - - name: echo-goodbye - image: ubuntu - script: | - #!/usr/bin/env bash - echo "Good Bye!" diff --git a/.ibm/pipelines/resources/pipeline-run/pipelines-operator.yaml b/.ibm/pipelines/resources/pipeline-run/pipelines-operator.yaml deleted file mode 100644 index af4a54e4..00000000 --- a/.ibm/pipelines/resources/pipeline-run/pipelines-operator.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: operators.coreos.com/v1alpha1 -kind: Subscription -metadata: - name: openshift-pipelines-operator - namespace: openshift-operators -spec: - channel: latest - name: openshift-pipelines-operator-rh - source: redhat-operators - sourceNamespace: openshift-marketplace diff --git a/.ibm/pipelines/resources/postgres-db/postgres-cred.yaml b/.ibm/pipelines/resources/postgres-db/postgres-cred.yaml deleted file mode 100644 index 1a4b2433..00000000 --- a/.ibm/pipelines/resources/postgres-db/postgres-cred.yaml +++ /dev/null @@ -1,10 +0,0 @@ -kind: Secret -apiVersion: v1 -metadata: - name: postgres-cred -data: - POSTGRES_PASSWORD: dG1w - POSTGRES_PORT: NTQzMg== - POSTGRES_USER: amFudXMtaWRw - POSTGRES_HOST: dG1w - PGSSLMODE: cmVxdWlyZQ== diff --git a/.ibm/pipelines/resources/postgres-db/postgres.yaml b/.ibm/pipelines/resources/postgres-db/postgres.yaml deleted file mode 100644 index 308673b0..00000000 --- a/.ibm/pipelines/resources/postgres-db/postgres.yaml +++ /dev/null @@ -1,74 +0,0 @@ -apiVersion: postgres-operator.crunchydata.com/v1beta1 -kind: PostgresCluster -metadata: - name: postgress-external-db -spec: - image: registry.developers.crunchydata.com/crunchydata/crunchy-postgres:ubi8-16.3-1 - postgresVersion: 16 - instances: - - name: instance1 - dataVolumeClaimSpec: - accessModes: - - "ReadWriteOnce" - resources: - requests: - storage: 2Gi - resources: - limits: - cpu: 300m - requests: - cpu: 200m - sidecars: - replicaCertCopy: - resources: - limits: - cpu: 300m - requests: - cpu: 200m - backups: - pgbackrest: - image: registry.developers.crunchydata.com/crunchydata/crunchy-pgbackrest:ubi8-2.51-1 - global: - # Save backups for 7 days, this means 1 full backups with 6 differential ones in between - repo1-retention-full: "1" - repo1-retention-full-type: count - repoHost: - resources: - limits: - cpu: 300m - requests: - cpu: 200m - repos: - - name: repo1 - schedules: - # Every sunday at 01:00 full backup - full: "0 1 * * 0" - # Monday through saturday at 01:00 differential backup - differential: "0 1 * * 1-6" - volume: - volumeClaimSpec: - accessModes: - - "ReadWriteOnce" - resources: - requests: - storage: 2Gi - sidecars: - pgbackrest: - resources: - limits: - cpu: 300m - requests: - cpu: 200m - pgbackrestConfig: - resources: - limits: - cpu: 300m - requests: - cpu: 200m - users: - - name: janus-idp - options: "SUPERUSER" - - name: sonarqube - databases: - - sonarqube - options: "NOSUPERUSER" diff --git a/.ibm/pipelines/resources/redis-cache/redis-deployment.yaml b/.ibm/pipelines/resources/redis-cache/redis-deployment.yaml deleted file mode 100644 index 312e5268..00000000 --- a/.ibm/pipelines/resources/redis-cache/redis-deployment.yaml +++ /dev/null @@ -1,73 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: redis - labels: - app: redis -spec: - replicas: 1 - selector: - matchLabels: - app: redis - template: - metadata: - labels: - app: redis - spec: - containers: - - name: redis - image: redis:6.2 - ports: - - containerPort: 6379 - resources: - requests: - memory: "64Mi" - cpu: "250m" - limits: - memory: "256Mi" - cpu: "500m" - env: - - name: REDIS_USERNAME - valueFrom: - secretKeyRef: - name: redis-secret - key: REDIS_USERNAME - - name: REDIS_PASSWORD - valueFrom: - secretKeyRef: - name: redis-secret - key: REDIS_PASSWORD - command: - - /bin/sh - - -c - - | - echo "user ${REDIS_USERNAME} on >${REDIS_PASSWORD} allcommands allkeys" > /data/redis.conf - redis-server /data/redis.conf - volumeMounts: - - name: redis-data - mountPath: /data - volumes: - - name: redis-data - emptyDir: {} ---- -apiVersion: v1 -kind: Service -metadata: - name: redis - labels: - app: redis -spec: - ports: - - port: 6379 - targetPort: 6379 - selector: - app: redis ---- -apiVersion: v1 -kind: Secret -metadata: - name: redis-secret -type: Opaque -data: - REDIS_USERNAME: dGVtcA== # base64 encoded - REDIS_PASSWORD: dGVzdDEyMw== # base64 encoded diff --git a/.ibm/pipelines/resources/service_account/service-account-rhdh.yaml b/.ibm/pipelines/resources/service_account/service-account-rhdh.yaml deleted file mode 100644 index 5ff80064..00000000 --- a/.ibm/pipelines/resources/service_account/service-account-rhdh.yaml +++ /dev/null @@ -1,5 +0,0 @@ -apiVersion: v1 -kind: ServiceAccount -metadata: - name: rhdh-k8s-plugin - namespace: showcase diff --git a/.ibm/pipelines/utils.sh b/.ibm/pipelines/utils.sh deleted file mode 100755 index fdea84f9..00000000 --- a/.ibm/pipelines/utils.sh +++ /dev/null @@ -1,225 +0,0 @@ -#!/bin/sh - -retrieve_pod_logs() { - local pod_name=$1; local container=$2; local namespace=$3 - echo " Retrieving logs for container: $container" - # Save logs for the current and previous container - kubectl logs $pod_name -c $container -n $namespace > "pod_logs/${pod_name}_${container}.log" || { echo " logs for container $container not found"; } - kubectl logs $pod_name -c $container -n $namespace --previous > "pod_logs/${pod_name}_${container}-previous.log" 2>/dev/null || { echo " Previous logs for container $container not found"; rm -f "pod_logs/${pod_name}_${container}-previous.log"; } -} - -save_all_pod_logs(){ - set +e - local namespace=$1 - mkdir -p pod_logs - - # Get all pod names in the namespace - pod_names=$(kubectl get pods -n $namespace -o jsonpath='{.items[*].metadata.name}') - for pod_name in $pod_names; do - echo "Retrieving logs for pod: $pod_name in namespace $namespace" - - init_containers=$(kubectl get pod $pod_name -n $namespace -o jsonpath='{.spec.initContainers[*].name}') - # Loop through each init container and retrieve logs - for init_container in $init_containers; do - retrieve_pod_logs $pod_name $init_container $namespace - done - - containers=$(kubectl get pod $pod_name -n $namespace -o jsonpath='{.spec.containers[*].name}') - for container in $containers; do - retrieve_pod_logs $pod_name $container $namespace - done - done - - mkdir -p "${ARTIFACT_DIR}/${namespace}/pod_logs" - cp -a pod_logs/* "${ARTIFACT_DIR}/${namespace}/pod_logs" - set -e -} - -droute_send() { - temp_kubeconfig=$(mktemp) # Create temporary KUBECONFIG to open second `oc` session - ( # Open subshell - export KUBECONFIG="$temp_kubeconfig" - local droute_version="1.2.2" - local release_name=$1 - local project=$2 - local droute_project="droute" - METEDATA_OUTPUT="data_router_metadata_output.json" - - oc login --token="${RHDH_PR_OS_CLUSTER_TOKEN}" --server="${RHDH_PR_OS_CLUSTER_URL}" - oc whoami --show-server - local droute_pod_name=$(oc get pods -n droute --no-headers -o custom-columns=":metadata.name" | grep ubi9-cert-rsync) - local temp_droute=$(oc exec -n "${droute_project}" "${droute_pod_name}" -- /bin/bash -c "mktemp -d") - - JOB_BASE_URL="https://prow.ci.openshift.org/view/gs/test-platform-results" - if [ -n "${PULL_NUMBER:-}" ]; then - JOB_URL="${JOB_BASE_URL}/pr-logs/pull/${REPO_OWNER}_${REPO_NAME}/${PULL_NUMBER}/${JOB_NAME}/${BUILD_ID}" - ARTIFACTS_URL="https://gcsweb-ci.apps.ci.l2s4.p1.openshiftapps.com/gcs/test-platform-results/pr-logs/pull/${REPO_OWNER}_${REPO_NAME}/${PULL_NUMBER}/${JOB_NAME}/${BUILD_ID}/artifacts/e2e-tests/${REPO_OWNER}-${REPO_NAME}/artifacts/${project}" - else - JOB_URL="${JOB_BASE_URL}/logs/${JOB_NAME}/${BUILD_ID}" - ARTIFACTS_URL="https://gcsweb-ci.apps.ci.l2s4.p1.openshiftapps.com/gcs/test-platform-results/logs/${JOB_NAME}/${BUILD_ID}/artifacts/${JOB_NAME##periodic-ci-janus-idp-backstage-showcase-main-}/${REPO_OWNER}-${REPO_NAME}/artifacts/${project}" - fi - - # Remove properties (only used for skipped test and invalidates the file if empty) - sed -i '//,/<\/properties>/d' "${ARTIFACT_DIR}/${project}/${JUNIT_RESULTS}" - # Replace attachments with link to OpenShift CI storage - sed -iE "s#\[\[ATTACHMENT|\(.*\)\]\]#${ARTIFACTS_URL}/\1#g" "${ARTIFACT_DIR}/${project}/${JUNIT_RESULTS}" - - jq \ - --arg hostname "$REPORTPORTAL_HOSTNAME" \ - --arg project "$DATA_ROUTER_PROJECT" \ - --arg name "$JOB_NAME" \ - --arg description "[View job run details](${JOB_URL})" \ - --arg key1 "job_type" \ - --arg value1 "$JOB_TYPE" \ - --arg key2 "pr" \ - --arg value2 "$GIT_PR_NUMBER" \ - --arg key3 "job_name" \ - --arg value3 "$JOB_NAME" \ - --arg key4 "tag_name" \ - --arg value4 "$TAG_NAME" \ - --arg auto_finalization_treshold $DATA_ROUTER_AUTO_FINALIZATION_TRESHOLD \ - '.targets.reportportal.config.hostname = $hostname | - .targets.reportportal.config.project = $project | - .targets.reportportal.processing.launch.name = $name | - .targets.reportportal.processing.launch.description = $description | - .targets.reportportal.processing.launch.attributes += [ - {"key": $key1, "value": $value1}, - {"key": $key2, "value": $value2}, - {"key": $key3, "value": $value3}, - {"key": $key4, "value": $value4} - ] | - .targets.reportportal.processing.tfa.auto_finalization_threshold = ($auto_finalization_treshold | tonumber) - ' data_router/data_router_metadata_template.json > "${ARTIFACT_DIR}/${project}/${METEDATA_OUTPUT}" - - oc rsync --include="${METEDATA_OUTPUT}" --include="${JUNIT_RESULTS}" --exclude="*" -n "${droute_project}" "${ARTIFACT_DIR}/${project}/" "${droute_project}/${droute_pod_name}:${temp_droute}/" - - # "Install" Data Router - oc exec -n "${droute_project}" "${droute_pod_name}" -- /bin/bash -c " - curl -fsSLk -o /tmp/droute-linux-amd64 'https://${DATA_ROUTER_NEXUS_HOSTNAME}/nexus/repository/dno-raw/droute-client/${droute_version}/droute-linux-amd64' \ - && chmod +x /tmp/droute-linux-amd64 \ - && /tmp/droute-linux-amd64 version" - - # Send test results through DataRouter and save the request ID. - DATA_ROUTER_REQUEST_ID=$(oc exec -n "${droute_project}" "${droute_pod_name}" -- /bin/bash -c " - /tmp/droute-linux-amd64 send --metadata ${temp_droute}/${METEDATA_OUTPUT} \ - --url '${DATA_ROUTER_URL}' \ - --username '${DATA_ROUTER_USERNAME}' \ - --password '${DATA_ROUTER_PASSWORD}' \ - --results '${temp_droute}/${JUNIT_RESULTS}' \ - --verbose" | grep "request:" | awk '{print $2}') - - if [[ "$JOB_NAME" == *periodic-* ]]; then - local max_attempts=30 - local wait_seconds=2 - set +e - for ((i = 1; i <= max_attempts; i++)); do - # Get DataRouter request information. - DATA_ROUTER_REQUEST_OUTPUT=$(oc exec -n "${droute_project}" "${droute_pod_name}" -- /bin/bash -c " - /tmp/droute-linux-amd64 request get \ - --url ${DATA_ROUTER_URL} \ - --username ${DATA_ROUTER_USERNAME} \ - --password ${DATA_ROUTER_PASSWORD} \ - ${DATA_ROUTER_REQUEST_ID}") - # Try to extract the ReportPortal launch URL from the request. This fails if it doesn't contain the launch URL. - REPORTPORTAL_LAUNCH_URL=$(echo "$DATA_ROUTER_REQUEST_OUTPUT" | yq e '.targets[0].events[] | select(.component == "reportportal-connector") | .message | fromjson | .[0].launch_url' -) - if [[ $? -eq 0 ]]; then - if [[ "$release_name" == *rbac* ]]; then - RUN_TYPE="rbac-nightly" - else - RUN_TYPE="nightly" - fi - if [[ ${PIPESTATUS[0]} -eq 0 ]]; then - RUN_STATUS_EMOJI=":done-circle-check:" - RUN_STATUS="passed" - else - RUN_STATUS_EMOJI=":failed:" - RUN_STATUS="failed" - fi - jq -n \ - --arg run_status "$RUN_STATUS" \ - --arg run_type "$RUN_TYPE" \ - --arg reportportal_launch_url "$REPORTPORTAL_LAUNCH_URL" \ - --arg job_name "$JOB_NAME" \ - --arg run_status_emoji "$RUN_STATUS_EMOJI" \ - '{ - "RUN_STATUS": $run_status, - "RUN_TYPE": $run_type, - "REPORTPORTAL_LAUNCH_URL": $reportportal_launch_url, - "JOB_NAME": $job_name, - "RUN_STATUS_EMOJI": $run_status_emoji - }' > /tmp/data_router_slack_message.json - curl -X POST -H 'Content-type: application/json' --data @/tmp/data_router_slack_message.json $SLACK_DATA_ROUTER_WEBHOOK_URL - return 0 - else - echo "Attempt ${i} of ${max_attempts}: ReportPortal launch URL not ready yet." - sleep "${wait_seconds}" - fi - done - set -e - fi - oc exec -n "${droute_project}" "${droute_pod_name}" -- /bin/bash -c "rm -rf ${temp_droute}/*" - ) # Close subshell - rm -f "$temp_kubeconfig" # Destroy temporary KUBECONFIG - oc whoami --show-server -} - -az_login() { - az login --service-principal -u $ARM_CLIENT_ID -p $ARM_CLIENT_SECRET --tenant $ARM_TENANT_ID - az account set --subscription $ARM_SUBSCRIPTION_ID -} - -az_aks_start() { - local name=$1 - local resource_group=$2 - az aks start --name $name --resource-group $resource_group -} - -az_aks_stop() { - local name=$1 - local resource_group=$2 - az aks stop --name $name --resource-group $resource_group -} - -az_aks_approuting_enable() { - local name=$1 - local resource_group=$2 - set +xe - local output=$(az aks approuting enable --name $name --resource-group $resource_group 2>&1 | sed 's/^ERROR: //') - set -xe - exit_status=$? - - if [ $exit_status -ne 0 ]; then - if [[ "$output" == *"App Routing is already enabled"* ]]; then - echo "App Routing is already enabled. Continuing..." - else - echo "Error: $output" - exit 1 - fi - fi -} - -# Merge the base YAML value file with the differences file for Kubernetes -yq_merge_value_files() { - local base_file=$1 - local diff_file=$2 - local step_1_file="/tmp/step-without-plugins.yaml" - local step_2_file="/tmp/step-only-plugins.yaml" - local final_file=$3 - # Step 1: Merge files, excluding the .global.dynamic.plugins key - # Values from `diff_file` override those in `base_file` - yq eval-all ' - select(fileIndex == 0) * select(fileIndex == 1) | - del(.global.dynamic.plugins) - ' "${base_file}" "${diff_file}" > "${step_1_file}" - # Step 2: Merge files, combining the .global.dynamic.plugins key - # Values from `diff_file` take precedence; plugins are merged and deduplicated by the .package field - yq eval-all ' - select(fileIndex == 0) *+ select(fileIndex == 1) | - .global.dynamic.plugins |= (reverse | unique_by(.package) | reverse) - ' "${base_file}" "${diff_file}" > "${step_2_file}" - # Step 3: Combine results from the previous steps and remove null values - # Values from `step_2_file` override those in `step_1_file` - yq eval-all ' - select(fileIndex == 0) * select(fileIndex == 1) | del(.. | select(. == null)) - ' "${step_2_file}" "${step_1_file}" > "${final_file}" -} \ No newline at end of file diff --git a/.ibm/pipelines/value_files/diff-values_showcase-rbac_AKS.yaml b/.ibm/pipelines/value_files/diff-values_showcase-rbac_AKS.yaml deleted file mode 100644 index fc9a8c7e..00000000 --- a/.ibm/pipelines/value_files/diff-values_showcase-rbac_AKS.yaml +++ /dev/null @@ -1,115 +0,0 @@ -# This file is for AKS installation only. -# It is applied by `helm upgrade` after the `values-showcase.yaml` is applied and only contains complementary differences for AKS. -# Note, that it overwrites the whole key that is present in this file. -# e.g. global.dynamic.plugins key is completely overwritten by the content of this file. -global: - dynamic: - plugins: [] -upstream: - backstage: - appConfig: - app: - # Please update to match host in case you don't want to configure hostname via `global.clusterRouterBase` or `global.host`. - baseUrl: 'https://{{- include "janus-idp.hostname" . }}' - backend: - baseUrl: 'https://{{- include "janus-idp.hostname" . }}' - cors: - origin: 'https://{{- include "janus-idp.hostname" . }}' - database: - connection: - host: null - port: null - password: ${POSTGRESQL_ADMIN_PASSWORD} - user: postgres - ssl: null - auth: - keys: - - secret: ${BACKEND_SECRET} - extraEnvVars: - - name: BACKEND_SECRET - valueFrom: - secretKeyRef: - key: backend-secret - name: '{{ include "janus-idp.backend-secret-name" $ }}' - - name: POSTGRESQL_ADMIN_PASSWORD - valueFrom: - secretKeyRef: - key: postgres-password - name: '{{ .Release.Name }}-postgresql' - # disable telemetry in CI - - name: SEGMENT_TEST_MODE - value: 'true' - extraVolumeMounts: - # The initContainer below will install dynamic plugins in this volume mount. - - name: dynamic-plugins-root - mountPath: /opt/app-root/src/dynamic-plugins-root - - name: rbac-policy - mountPath: /opt/app-root/src/rbac - - name: rbac-conditions - mountPath: /opt/app-root/src/rbac-conditions - extraVolumes: - # -- Ephemeral volume that will contain the dynamic plugins installed by the initContainer below at start. - # To have more control on underlying storage, the [emptyDir](https://docs.openshift.com/container-platform/4.13/storage/understanding-ephemeral-storage.html) - # could be changed to a [generic ephemeral volume](https://docs.openshift.com/container-platform/4.13/storage/generic-ephemeral-vols.html#generic-ephemeral-vols-procedure_generic-ephemeral-volumes). - - name: dynamic-plugins-root - emptyDir: {} - - name: rbac-policy - configMap: - defaultMode: 420 - name: rbac-policy - - name: rbac-conditions - emptyDir: {} - # Volume that will expose the `dynamic-plugins.yaml` file from the `dynamic-plugins` config map. - # The `dynamic-plugins` config map is created by the helm chart from the content of the `global.dynamic` field. - - name: dynamic-plugins - configMap: - defaultMode: 420 - name: dynamic-plugins - optional: true - # Optional volume that allows exposing the `.npmrc` file (through a `dynamic-plugins-npmrc` secret) - # to be used when running `npm pack` during the dynamic plugins installation by the initContainer. - - name: dynamic-plugins-npmrc - secret: - defaultMode: 420 - optional: true - secretName: dynamic-plugins-npmrc - extraEnvVarsSecrets: - - rhdh-secrets - postgresql: - enabled: true - postgresqlDataDir: /var/lib/pgsql/data/userdata - image: - registry: quay.io - repository: fedora/postgresql-15 - tag: latest - auth: - secretKeys: - adminPasswordKey: postgres-password - userPasswordKey: password - existingSecret: null - primary: - securityContext: - enabled: false - podSecurityContext: - enabled: true - fsGroup: 3000 - containerSecurityContext: - enabled: false - persistence: - enabled: true - size: 1Gi - mountPath: /var/lib/pgsql/data - extraEnvVars: - - name: POSTGRESQL_ADMIN_PASSWORD - valueFrom: - secretKeyRef: - key: postgres-password - name: '{{ .Release.Name }}-postgresql' - volumePermissions: - enabled: true - ingress: - enabled: true - className: webapprouting.kubernetes.azure.com - host: '' -route: - enabled: false \ No newline at end of file diff --git a/.ibm/pipelines/value_files/diff-values_showcase_AKS.yaml b/.ibm/pipelines/value_files/diff-values_showcase_AKS.yaml deleted file mode 100644 index 9e2b37c5..00000000 --- a/.ibm/pipelines/value_files/diff-values_showcase_AKS.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# This file is for AKS installation only. -# It is applied by `helm upgrade` after the `values-showcase.yaml` is applied and only contains complementary differences for AKS. -# Note, that it overwrites the whole key that is present in this file. -# e.g. global.dynamic.plugins key is completely overwritten by the content of this file. -route: - enabled: false -global: - dynamic: - plugins: - - package: ./dynamic-plugins/dist/roadiehq-scaffolder-backend-module-http-request-dynamic - disabled: true - - package: ./dynamic-plugins/dist/backstage-community-plugin-catalog-backend-module-scaffolder-relation-processor-dynamic - disabled: true -upstream: - backstage: - extraEnvVarsSecrets: - - rhdh-secrets - postgresql: - primary: - podSecurityContext: - enabled: true - fsGroup: 3000 - volumePermissions: - enabled: true - ingress: - enabled: true - className: webapprouting.kubernetes.azure.com - host: '' \ No newline at end of file diff --git a/.ibm/pipelines/value_files/values_showcase-auth-providers.yaml b/.ibm/pipelines/value_files/values_showcase-auth-providers.yaml deleted file mode 100644 index 53bca94a..00000000 --- a/.ibm/pipelines/value_files/values_showcase-auth-providers.yaml +++ /dev/null @@ -1,239 +0,0 @@ -global: - dynamic: - includes: - - dynamic-plugins.default.yaml - plugins: - - package: ./dynamic-plugins/dist/backstage-community-plugin-catalog-backend-module-keycloak-dynamic - disabled: true - - package: ./dynamic-plugins/dist/backstage-plugin-catalog-backend-module-github-org-dynamic - disabled: true - - package: ./dynamic-plugins/dist/backstage-plugin-catalog-backend-module-msgraph-dynamic - disabled: true - - package: ./dynamic-plugins/dist/janus-idp-backstage-plugin-rbac - disabled: true -upstream: - backstage: - appConfig: - signInPage: oidc - auth: - environment: production - session: - secret: superSecretSecret - providers: - guest: - dangerouslyAllowOutsideDevelopment: true - microsoft: - development: - clientId: ${AUTH_PROVIDERS_AZURE_CLIENT_ID} - clientSecret: ${AUTH_PROVIDERS_AZURE_CLIENT_SECRET} - tenantId: ${AUTH_PROVIDERS_AZURE_TENANT_ID} - domainHint: ${AUTH_PROVIDERS_AZURE_TENANT_ID} - production: - clientId: ${AUTH_PROVIDERS_AZURE_CLIENT_ID} - clientSecret: ${AUTH_PROVIDERS_AZURE_CLIENT_SECRET} - tenantId: ${AUTH_PROVIDERS_AZURE_TENANT_ID} - domainHint: ${AUTH_PROVIDERS_AZURE_TENANT_ID} - github: - production: - clientSecret: ${AUTH_ORG_CLIENT_SECRET} - clientId: ${AUTH_ORG_CLIENT_ID} - oidc: - production: - metadataUrl: ${RHSSO76_METADATA_URL} - clientId: ${RHSSO76_CLIENT_ID} - clientSecret: ${RHSSO76_CLIENT_SECRET} - prompt: auto - callbackUrl: ${RHSSO76_CALLBACK_URL} - integrations: - github: - - host: github.com - apps: - - appId: ${AUTH_ORG_APP_ID} - clientId: ${AUTH_ORG_CLIENT_ID} - clientSecret: ${AUTH_ORG_CLIENT_SECRET} - privateKey: ${AUTH_ORG1_PRIVATE_KEY} - webhookSecret: ${AUTH_ORG_WEBHOOK_SECRET} - catalog: - locations: - - type: url - target: https://github.com/janus-qe/auth-providers/blob/main/location.yaml - rules: - - allow: [Component, Group, User, Resource, Location, Template] - providers: - githubOrg: - - id: github - githubUrl: https://github.com - orgs: ['${AUTH_PROVIDERS_GH_ORG_NAME}'] - schedule: - initialDelay: { seconds: 10 } - frequency: { minutes: 1 } - timeout: { minutes: 1 } - microsoftGraphOrg: - default: - target: https://graph.microsoft.com/v1.0 - authority: https://login.microsoftonline.com - tenantId: ${AUTH_PROVIDERS_AZURE_TENANT_ID} - clientId: ${AUTH_PROVIDERS_AZURE_CLIENT_ID} - clientSecret: ${AUTH_PROVIDERS_AZURE_CLIENT_SECRET} - user: - filter: accountEnabled eq true and userType eq 'member' and startswith(displayName,'QE') - group: - filter: > - securityEnabled eq true - and mailEnabled eq false - and startswith(displayName,'rhdh_test_group_') - schedule: - frequency: PT1M - timeout: PT1M - keycloakOrg: - default: - baseUrl: ${RHSSO76_URL} - loginRealm: ${AUTH_PROVIDERS_REALM_NAME} - realm: ${AUTH_PROVIDERS_REALM_NAME} - clientId: ${RHSSO76_CLIENT_ID} - clientSecret: ${RHSSO76_CLIENT_SECRET} - schedule: - frequency: { minutes: 1 } - timeout: { minutes: 1 } - permission: - enabled: true - rbac: - policyFileReload: true - policies-csv-file: './rbac/rbac-policy.csv' - admin: - users: - - name: user:default/qeadmin_rhdhtesting.onmicrosoft.com - - name: user:default/rhsso_admin - - name: user:default/rhdhqeauthadmin - extraEnvVarsSecrets: - - rhdh-secrets - image: - registry: quay.io - repository: rhdh/rhdh-hub-rhel9 - tag: '1.3' - readinessProbe: - failureThreshold: 3 - httpGet: - path: /healthcheck - port: 7007 - scheme: HTTP - initialDelaySeconds: 30 - periodSeconds: 10 - successThreshold: 2 - timeoutSeconds: 2 - livenessProbe: - failureThreshold: 3 - httpGet: - path: /healthcheck - port: 7007 - scheme: HTTP - initialDelaySeconds: 60 - periodSeconds: 10 - successThreshold: 1 - timeoutSeconds: 2 - extraEnvVars: - - name: BACKEND_SECRET - valueFrom: - secretKeyRef: - key: backend-secret - name: '{{ include "janus-idp.backend-secret-name" $ }}' - - name: POSTGRESQL_ADMIN_PASSWORD - valueFrom: - secretKeyRef: - key: postgres-password - name: '{{ .Release.Name }}-postgresql' - # disable telemetry in CI - - name: SEGMENT_TEST_MODE - value: 'true' - - name: NODE_OPTIONS - value: '--no-node-snapshot' - args: - # This additional `app-config`` file is generated by the initContainer below, and contains the merged configuration of installed dynamic plugins. - - '--config' - - dynamic-plugins-root/app-config.dynamic-plugins.yaml - extraVolumeMounts: - - mountPath: /opt/app-root/src/dynamic-plugins-root - name: dynamic-plugins-root - - name: rbac-policy - mountPath: /opt/app-root/src/rbac - extraVolumes: - - ephemeral: - volumeClaimTemplate: - spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 2Gi - name: dynamic-plugins-root - - name: rbac-policy - configMap: - defaultMode: 420 - name: rbac-policy - - configMap: - defaultMode: 420 - name: dynamic-plugins - optional: true - name: dynamic-plugins - - name: dynamic-plugins-npmrc - secret: - defaultMode: 420 - optional: true - secretName: dynamic-plugins-npmrc - initContainers: - - command: - - ./install-dynamic-plugins.sh - - /dynamic-plugins-root - env: - - name: NPM_CONFIG_USERCONFIG - value: /opt/app-root/src/.npmrc.dynamic-plugins - image: '{{ include "backstage.image" . }}' - imagePullPolicy: Always - name: install-dynamic-plugins - volumeMounts: - - mountPath: /dynamic-plugins-root - name: dynamic-plugins-root - - mountPath: /opt/app-root/src/dynamic-plugins.yaml - name: dynamic-plugins - readOnly: true - subPath: dynamic-plugins.yaml - - mountPath: /opt/app-root/src/.npmrc.dynamic-plugins - name: dynamic-plugins-npmrc - readOnly: true - subPath: .npmrc - workingDir: /opt/app-root/src - installDir: /opt/app-root/src - podAnnotations: - checksum/dynamic-plugins: >- - {{- include "common.tplvalues.render" ( dict "value" - .Values.global.dynamic "context" $) | sha256sum }} - postgresql: - enabled: true - postgresqlDataDir: /var/lib/pgsql/data/userdata - image: - registry: quay.io - repository: fedora/postgresql-15 - tag: latest - auth: - secretKeys: - adminPasswordKey: postgres-password - userPasswordKey: password - primary: - securityContext: - enabled: false - podSecurityContext: - enabled: false - containerSecurityContext: - enabled: false - persistence: - enabled: false - size: 1Gi - mountPath: /var/lib/pgsql/data - extraEnvVars: - - name: POSTGRESQL_ADMIN_PASSWORD - valueFrom: - secretKeyRef: - key: postgres-password - name: '{{ .Release.Name }}-postgresql' - ingress: - host: '{{ .Values.global.host }}' diff --git a/.ibm/pipelines/value_files/values_showcase-rbac.yaml b/.ibm/pipelines/value_files/values_showcase-rbac.yaml deleted file mode 100644 index 4020ab1f..00000000 --- a/.ibm/pipelines/value_files/values_showcase-rbac.yaml +++ /dev/null @@ -1,274 +0,0 @@ -global: - dynamic: - # -- Array of YAML files listing dynamic plugins to include with those listed in the `plugins` field. - # Relative paths are resolved from the working directory of the initContainer that will install the plugins (`/opt/app-root/src`). - includes: - # -- List of dynamic plugins included inside the `janus-idp/backstage-showcase` container image, some of which are disabled by default. - # This file ONLY works with the `janus-idp/backstage-showcase` container image. - - 'dynamic-plugins.default.yaml' - - # -- List of dynamic plugins, possibly overriding the plugins listed in `includes` files. - # Every item defines the plugin `package` as a [NPM package spec](https://docs.npmjs.com/cli/v10/using-npm/package-spec), - # an optional `pluginConfig` with plugin-specific backstage configuration, and an optional `disabled` flag to disable/enable a plugin - # listed in `includes` files. It also includes an `integrity` field that is used to verify the plugin package [integrity](https://w3c.github.io/webappsec-subresource-integrity/#integrity-metadata-description). - plugins: - - package: ./dynamic-plugins/dist/backstage-plugin-catalog-backend-module-github-dynamic - disabled: false - pluginConfig: - catalog: - providers: - github: - my-test-org: - organization: janus-qe - catalogPath: '/catalog-info.yaml' - schedule: - frequency: - minutes: 1 - timeout: - minutes: 1 - initialDelay: - seconds: 15 - - package: ./dynamic-plugins/dist/backstage-plugin-catalog-backend-module-github-org-dynamic - disabled: false - - package: ./dynamic-plugins/dist/backstage-community-plugin-github-issues - disabled: false - - package: ./dynamic-plugins/dist/roadiehq-backstage-plugin-github-pull-requests - disabled: false - - package: ./dynamic-plugins/dist/backstage-community-plugin-github-actions - disabled: false - - package: ./dynamic-plugins/dist/janus-idp-backstage-plugin-quay - disabled: false - - package: ./dynamic-plugins/dist/backstage-community-plugin-catalog-backend-module-keycloak-dynamic - disabled: false - - package: ./dynamic-plugins/dist/janus-idp-backstage-plugin-tekton - disabled: false - - package: ./dynamic-plugins/dist/backstage-plugin-kubernetes - disabled: false - - package: ./dynamic-plugins/dist/backstage-plugin-kubernetes-backend-dynamic - disabled: false - pluginConfig: - kubernetes: - clusterLocatorMethods: - - clusters: - - authProvider: serviceAccount - name: 'my-cluster' - serviceAccountToken: ${K8S_SERVICE_ACCOUNT_TOKEN} - url: ${K8S_CLUSTER_API_SERVER_URL} - type: config - customResources: - # Add for tekton - - apiVersion: 'v1beta1' - group: 'tekton.dev' - plural: 'pipelines' - - apiVersion: v1beta1 - group: tekton.dev - plural: pipelineruns - - apiVersion: v1beta1 - group: tekton.dev - plural: taskruns - # Add for topology plugin - - apiVersion: 'v1' - group: 'route.openshift.io' - plural: 'routes' - # Add to view topology code decorators - - group: 'org.eclipse.che' - apiVersion: 'v2' - plural: 'checlusters' - serviceLocatorMethod: - type: multiTenant - # Enable OCM plugins. - - package: ./dynamic-plugins/dist/backstage-community-plugin-ocm-backend-dynamic - disabled: false - pluginConfig: - catalog: - providers: - ocm: - default: - name: testCluster # Can be any arbitrary name supported by kubernetes - url: ${OCM_CLUSTER_URL} - serviceAccountToken: ${OCM_CLUSTER_TOKEN} - skipTLSVerify: true - owner: janus-authors - - package: ./dynamic-plugins/dist/backstage-community-plugin-ocm - disabled: false - # Enable Bulk import plugins. - - package: ./dynamic-plugins/dist/red-hat-developer-hub-backstage-plugin-bulk-import-backend-dynamic - disabled: false - - package: ./dynamic-plugins/dist/red-hat-developer-hub-backstage-plugin-bulk-import - disabled: false - # Enable tech-radar plugin. - - package: ./dynamic-plugins/dist/backstage-community-plugin-tech-radar - disabled: false - - package: ./dynamic-plugins/dist/backstage-community-plugin-tech-radar-backend-dynamic - disabled: true - - package: ./dynamic-plugins/dist/janus-idp-backstage-plugin-rbac - disabled: false - - package: ./dynamic-plugins/dist/janus-idp-backstage-plugin-analytics-provider-segment - disabled: true - -# -- Upstream Backstage [chart configuration](https://github.com/backstage/charts/blob/main/charts/backstage/values.yaml) -# @default -- Use Openshift compatible settings -upstream: - nameOverride: backstage - commonLabels: - backstage.io/kubernetes-id: developer-hub - backstage: - image: - pullPolicy: Always - # using test image from https://quay.io/repository/janus-idp/backstage-showcase - registry: quay.io - repository: janus-idp/backstage-showcase - tag: next - appConfig: - app: - # Please update to match host in case you don't want to configure hostname via `global.clusterRouterBase` or `global.host`. - baseUrl: 'https://{{- include "janus-idp.hostname" . }}' - backend: - baseUrl: 'https://{{- include "janus-idp.hostname" . }}' - cors: - origin: 'https://{{- include "janus-idp.hostname" . }}' - database: - connection: # configure Backstage DB connection parameters - host: ${POSTGRES_HOST} - port: ${POSTGRES_PORT} - user: ${POSTGRES_USER} - password: ${POSTGRES_PASSWORD} - ssl: - rejectUnauthorized: true, - ca: - $file: /opt/app-root/src/postgres-ca.pem - key: - $file: /opt/app-root/src/postgres-key.key - cert: - $file: /opt/app-root/src/postgres-crt.pem - auth: - keys: - - secret: ${BACKEND_SECRET} - extraEnvVars: - - name: BACKEND_SECRET - valueFrom: - secretKeyRef: - key: backend-secret - name: '{{ include "janus-idp.backend-secret-name" $ }}' - # disable telemetry in CI - - name: SEGMENT_TEST_MODE - value: 'true' - extraVolumeMounts: - # The initContainer below will install dynamic plugins in this volume mount. - - name: dynamic-plugins-root - mountPath: /opt/app-root/src/dynamic-plugins-root - - name: rbac-policy - mountPath: /opt/app-root/src/rbac - - name: rbac-conditions - mountPath: /opt/app-root/src/rbac-conditions - - mountPath: /opt/app-root/src/postgres-crt.pem - name: postgress-external-db-cluster-cert - subPath: tls.crt - - mountPath: /opt/app-root/src/postgres-ca.pem - name: postgress-external-db-cluster-cert - subPath: ca.crt - - mountPath: /opt/app-root/src/postgres-key.key - name: postgress-external-db-cluster-cert - subPath: tls.key - extraVolumes: - # -- Ephemeral volume that will contain the dynamic plugins installed by the initContainer below at start. - # To have more control on underlying storage, the [emptyDir](https://docs.openshift.com/container-platform/4.13/storage/understanding-ephemeral-storage.html) - # could be changed to a [generic ephemeral volume](https://docs.openshift.com/container-platform/4.13/storage/generic-ephemeral-vols.html#generic-ephemeral-vols-procedure_generic-ephemeral-volumes). - - name: dynamic-plugins-root - emptyDir: {} - # Volume that will expose the `dynamic-plugins.yaml` file from the `dynamic-plugins` config map. - # The `dynamic-plugins` config map is created by the helm chart from the content of the `global.dynamic` field. - - name: dynamic-plugins - configMap: - defaultMode: 420 - name: dynamic-plugins - optional: true - # Optional volume that allows exposing the `.npmrc` file (through a `dynamic-plugins-npmrc` secret) - # to be used when running `npm pack` during the dynamic plugins installation by the initContainer. - - name: dynamic-plugins-npmrc - secret: - defaultMode: 420 - optional: true - secretName: dynamic-plugins-npmrc - - name: postgress-external-db-cluster-cert - secret: - secretName: postgress-external-db-cluster-cert - - name: rbac-policy - configMap: - defaultMode: 420 - name: rbac-policy - - name: rbac-conditions - emptyDir: {} - initContainers: - - name: install-dynamic-plugins - # -- Image used by the initContainer to install dynamic plugins into the `dynamic-plugins-root` volume mount. - # It could be replaced by a custom image based on this one. - # @default -- `quay.io/janus-idp/backstage-showcase:latest` - image: '{{ include "backstage.image" . }}' - command: - - sh - - '-c' - - | - cat > /rbac-conditions/conditional-policies.yaml <=1.4, see ../../docker/Dockerfile -# -# Copyright (c) 2023-2024 Red Hat, Inc. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# To transform into Brew-friendly Dockerfile: -# 1. comment out lines with EXTERNAL_SOURCE_NESTED=. and CONTAINER_SOURCE=/opt/app-root/src -# 2. uncomment lines with EXTERNAL_SOURCE_NESTED and CONTAINER_SOURCE pointing at $REMOTE_SOURCES and $REMOTE_SOURCES_DIR instead (Brew defines these paths) -# 3. uncomment lines with RUN source .../cachito.env -# 4. add Brew metadata - -# Stage 1 - Build nodejs skeleton -#@follow_tag(registry.access.redhat.com/ubi9/nodejs-20:1) -# https://registry.access.redhat.com/ubi9/nodejs-20 -FROM registry.access.redhat.com/ubi9/nodejs-20:1-59.1726663413 AS build -# hadolint ignore=DL3002 -USER 0 - -# Install isolated-vm dependencies -# hadolint ignore=DL3041 -RUN dnf install -y -q --allowerasing --nobest nodejs-devel nodejs-libs \ - # already installed or installed as deps: - openssl openssl-devel ca-certificates make cmake cpp gcc gcc-c++ zlib zlib-devel brotli brotli-devel python3 nodejs-packaging && \ - dnf update -y && dnf clean all - -# Downstream sources -ENV EXTERNAL_SOURCE_NESTED=$REMOTE_SOURCES/upstream1/app/distgit/containers/rhdh-hub -# /remote-source/ -ENV CONTAINER_SOURCE=$REMOTE_SOURCES_DIR - -# Env vars -ENV YARN=$CONTAINER_SOURCE/.yarn/releases/yarn-3.8.6.cjs - -WORKDIR $CONTAINER_SOURCE/ -COPY $EXTERNAL_SOURCE_NESTED/.yarn ./.yarn -COPY $EXTERNAL_SOURCE_NESTED/.yarnrc.yml ./ - -# Add execute permissions to yarn; add yarn to path via symlink -RUN chmod +x "$YARN" && ln -s "$YARN" /usr/local/bin/yarn - -# Stage 2 - Install dependencies -COPY $EXTERNAL_SOURCE_NESTED/yarn.lock ./ -# BEGIN COPY package.json files -COPY $EXTERNAL_SOURCE_NESTED/plugins/scalprum-backend/package.json ./plugins/scalprum-backend/package.json -COPY $EXTERNAL_SOURCE_NESTED/plugins/licensed-users-info-backend/package.json ./plugins/licensed-users-info-backend/package.json -COPY $EXTERNAL_SOURCE_NESTED/plugins/dynamic-plugins-info/package.json ./plugins/dynamic-plugins-info/package.json -COPY $EXTERNAL_SOURCE_NESTED/plugins/dynamic-plugins-info-backend/package.json ./plugins/dynamic-plugins-info-backend/package.json -COPY $EXTERNAL_SOURCE_NESTED/plugins/dynamic-home-page/package.json ./plugins/dynamic-home-page/package.json -COPY $EXTERNAL_SOURCE_NESTED/packages/backend/package.json ./packages/backend/package.json -COPY $EXTERNAL_SOURCE_NESTED/packages/app/package.json ./packages/app/package.json -COPY $EXTERNAL_SOURCE_NESTED/package.json ./package.json -COPY $EXTERNAL_SOURCE_NESTED/e2e-tests/package.json ./e2e-tests/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/_utils/package.json ./dynamic-plugins/_utils/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-utils-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-utils-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-utils-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-utils-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-http-request-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-http-request-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-http-request-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-scaffolder-backend-module-http-request-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-scaffolder-backend-argocd-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-scaffolder-backend-argocd-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-scaffolder-backend-argocd-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-scaffolder-backend-argocd-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-security-insights/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-security-insights/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-jira/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-jira/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-github-pull-requests/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-github-pull-requests/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-github-insights/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-github-insights/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-datadog/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-datadog/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-argo-cd/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-argo-cd/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-argo-cd-backend-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-argo-cd-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/roadiehq-backstage-plugin-argo-cd-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/roadiehq-backstage-plugin-argo-cd-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/red-hat-developer-hub-backstage-plugin-bulk-import/package.json ./dynamic-plugins/wrappers/red-hat-developer-hub-backstage-plugin-bulk-import/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/red-hat-developer-hub-backstage-plugin-bulk-import-backend-dynamic/package.json ./dynamic-plugins/wrappers/red-hat-developer-hub-backstage-plugin-bulk-import-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/red-hat-developer-hub-backstage-plugin-bulk-import-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/red-hat-developer-hub-backstage-plugin-bulk-import-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/parfuemerie-douglas-scaffolder-backend-module-azure-repositories-dynamic/package.json ./dynamic-plugins/wrappers/parfuemerie-douglas-scaffolder-backend-module-azure-repositories-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/parfuemerie-douglas-scaffolder-backend-module-azure-repositories-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/parfuemerie-douglas-scaffolder-backend-module-azure-repositories-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/pagerduty-backstage-plugin/package.json ./dynamic-plugins/wrappers/pagerduty-backstage-plugin/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/pagerduty-backstage-plugin-backend-dynamic/package.json ./dynamic-plugins/wrappers/pagerduty-backstage-plugin-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/pagerduty-backstage-plugin-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/pagerduty-backstage-plugin-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-regex-dynamic/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-regex-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-regex-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-regex-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-quay-dynamic/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-quay-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-quay-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-scaffolder-backend-module-quay-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-plugin-topology/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-plugin-topology/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-plugin-tekton/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-plugin-tekton/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-plugin-rbac/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-plugin-rbac/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-plugin-quay/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-plugin-quay/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-plugin-analytics-provider-segment/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-plugin-analytics-provider-segment/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-plugin-aap-backend-dynamic/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-plugin-aap-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/janus-idp-backstage-plugin-aap-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/janus-idp-backstage-plugin-aap-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/immobiliarelabs-backstage-plugin-gitlab/package.json ./dynamic-plugins/wrappers/immobiliarelabs-backstage-plugin-gitlab/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/immobiliarelabs-backstage-plugin-gitlab-backend-dynamic/package.json ./dynamic-plugins/wrappers/immobiliarelabs-backstage-plugin-gitlab-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/immobiliarelabs-backstage-plugin-gitlab-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/immobiliarelabs-backstage-plugin-gitlab-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-techdocs/package.json ./dynamic-plugins/wrappers/backstage-plugin-techdocs/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-techdocs-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-techdocs-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-techdocs-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-techdocs-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gitlab-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gitlab-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gitlab-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gitlab-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-github-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-github-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-github-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-github-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gerrit-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gerrit-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gerrit-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-gerrit-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-server-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-server-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-server-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-server-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-cloud-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-cloud-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-cloud-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-bitbucket-cloud-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-azure-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-azure-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-azure-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-scaffolder-backend-module-azure-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-kubernetes/package.json ./dynamic-plugins/wrappers/backstage-plugin-kubernetes/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-kubernetes-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-kubernetes-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-kubernetes-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-kubernetes-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-msgraph-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-msgraph-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-msgraph-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-msgraph-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-ldap-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-ldap-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-ldap-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-ldap-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-org-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-org-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-org-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-org-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-gitlab-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-org-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-org-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-org-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-org-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-github-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-server-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-server-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-server-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-server-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-cloud-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-cloud-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-cloud-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-plugin-catalog-backend-module-bitbucket-cloud-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-scaffolder-backend-module-sonarqube-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-scaffolder-backend-module-sonarqube-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-scaffolder-backend-module-sonarqube-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-scaffolder-backend-module-sonarqube-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-tech-radar/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-tech-radar/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-tech-radar-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-tech-radar-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-tech-radar-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-tech-radar-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-sonarqube/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-sonarqube/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-sonarqube-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-sonarqube-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-sonarqube-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-sonarqube-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-scaffolder-backend-module-servicenow-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-scaffolder-backend-module-servicenow-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-scaffolder-backend-module-servicenow-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-scaffolder-backend-module-servicenow-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-redhat-argocd/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-redhat-argocd/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-ocm/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-ocm/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-ocm-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-ocm-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-ocm-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-ocm-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-nexus-repository-manager/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-nexus-repository-manager/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-lighthouse/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-lighthouse/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-jfrog-artifactory/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-jfrog-artifactory/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-jenkins/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-jenkins/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-jenkins-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-jenkins-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-jenkins-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-jenkins-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-github-issues/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-github-issues/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-github-actions/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-github-actions/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-dynatrace/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-dynatrace/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-scaffolder-relation-processor-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-scaffolder-relation-processor-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-scaffolder-relation-processor-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-scaffolder-relation-processor-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-pingidentity-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-pingidentity-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-pingidentity-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-pingidentity-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-keycloak-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-keycloak-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-keycloak-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-catalog-backend-module-keycloak-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-azure-devops/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-azure-devops/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-azure-devops-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-azure-devops-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-azure-devops-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-azure-devops-backend-dynamic/dist-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-acr/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-acr/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-3scale-backend-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-3scale-backend-dynamic/package.json -COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins/wrappers/backstage-community-plugin-3scale-backend-dynamic/dist-dynamic/package.json ./dynamic-plugins/wrappers/backstage-community-plugin-3scale-backend-dynamic/dist-dynamic/package.json -# END COPY package.json files - -# Downstream only - debugging -# COPY $REMOTE_SOURCES/ ./ -# hadolint ignore=SC2086 -# RUN for d in $(find / -name ".npmrc" -o -name ".yarnrc" 2>/dev/null); do echo; echo "==== $d ===="; cat $d; done -# # ls -la ./ upstream1 upstream1/app/ upstream1/app/distgit/containers/ upstream1/app/distgit/containers/rhdh-hub/ || true -# # debug contents of /remote-source/ -# echo "###### /tmp/tls-ca-bundle.pem ######>>"; cat /tmp/tls-ca-bundle.pem; echo "<<###### /tmp/tls-ca-bundle.pem ######" -# echo "###### $CONTAINER_SOURCE/registry-ca.pem ######>>"; cat $CONTAINER_SOURCE/registry-ca.pem; echo "<<###### $CONTAINER_SOURCE/registry-ca.pem ######" - -# Downstream only - Cachito configuration -# see https://docs.engineering.redhat.com/pages/viewpage.action?pageId=228017926#UpstreamSources(Cachito,ContainerFirst)-CachitoIntegrationfornpm -COPY $REMOTE_SOURCES/upstream1/cachito.env \ - $REMOTE_SOURCES/upstream1/app/registry-ca.pem \ - $REMOTE_SOURCES/upstream1/app/distgit/containers/rhdh-hub/.npmrc \ - ./ -# registry=https://cachito-nexus.engineering.redhat.com/repository/cachito-yarn-814335/ -# email=noreply@domain.local -# always-auth=true -# //cachito-nexus.engineering.redhat.com/repository/cachito-yarn-814335/:_auth=SHA-goes-here== -# fetch-retries=5 -# fetch-retry-factor=2 -# strict-ssl=true -# cafile="../../../registry-ca.pem" -# NOTE: this is overridden to "/remote-source/registry-ca.pem" below -# hadolint ignore=SC1091,SC2046 -RUN \ - # debug - # cat $CONTAINER_SOURCE/cachito.env; \ - # load envs - source "$CONTAINER_SOURCE/cachito.env"; \ - \ - # load cert - cert_path="$CONTAINER_SOURCE/registry-ca.pem"; \ - # debug - # ls -la "${cert_path}"; \ - npm config set cafile "${cert_path}"; "$YARN" config set cafile "${cert_path}" -g; \ - \ - # set longer timeouts - # npm config set fetch-retry-maxtimeout 6000000; \ - # npm config set fetch-retry-mintimeout 1000000; \ - # set cachito as default registry - "$YARN" config set registry $(npm config get registry) -g; \ - \ - # debug - # ls -l /usr/; \ - # set up node dir with common.gypi and unsafe-perms=true - ln -s /usr/include/node/common.gypi /usr/common.gypi; "$YARN" config set nodedir /usr; "$YARN" config set unsafe-perm true - -# Downstream only - debug -# RUN echo $PATH; ls -la /usr/local/bin/yarn; whereis yarn;which yarn; yarn --version; \ -# cat "$CONTAINER_SOURCE"/.npmrc || true; \ -# "$YARN" config list --verbose; npm config list; npm config list -l - -# Increate timeout for yarn install -RUN "$YARN" config set httpTimeout 600000 - -RUN "$YARN" install --immutable - -# Stage 3 - Build packages -COPY $EXTERNAL_SOURCE_NESTED ./ - -RUN git config --global --add safe.directory ./ -# Upstream only -# RUN rm app-config.yaml && mv app-config.example.yaml app-config.yaml - -# Downstream only - replace midstream build-metadata.json with the version from downstream (where we include the midstream SHA) -COPY packages/app/src/build-metadata.json ./packages/app/src/ - -# hadolint ignore=DL3059,DL4006,SC2086 -RUN \ - # Downstream only - relabel upstream + append build time into packages/app/src/build-metadata.json - now=$(date -u +%FT%TZ); sed -i packages/app/src/build-metadata.json -r \ - -e "s/\"Last Commit: (.+)\"/\"Upstream: \1\", \"Build Time: $now\"/" && \ - cat packages/app/src/build-metadata.json; echo && \ - "$YARN" build --filter=backend && \ - # Downstream only - replace registry refs with cachito ones - cachitoRegistry=$(npm config get registry); echo "cachito registry: $cachitoRegistry"; \ - for d in $(find . -name yarn.lock); do echo; echo "===== $d ====="; \ - sed -i "$d" -r -e "s#(https://registry.yarnpkg.com|https://registry.npmjs.org)#${cachitoRegistry}#g"; \ - grep resolved "$d" | head -1; echo "Total $(grep resolved $d | wc -l) resolution lines in $d"; \ - done; \ - # Already imported the packages above; need to `yarn install` on the `dist-dynamic` sub-folder for backend plugins - "$YARN" export-dynamic --filter=./dynamic-plugins/wrappers/* && \ - "$YARN" copy-dynamic-plugins dist - -# Downstream only - debug -# hadolint ignore=SC3010,DL4006 -RUN echo "=== Check for yarn.lock files that don't use cachito registry ===>"; \ - for d in $(find . -name yarn.lock); do \ - found=$(grep -E "yarnpkg.com|npmjs.org" "$d" | head -1); \ - if [[ "$found" ]]; then echo;echo "$d : $found"; fi; \ - done; \ - echo "<=== Check for yarn.lock files that don't use cachito registry ===" - -# Downstream only - clean up dynamic plugins sources: -# Only keep the dist sub-folder in the dynamic-plugins folder -RUN find dynamic-plugins -maxdepth 1 -mindepth 1 -type d -not -name dist -exec rm -Rf {} \; - -# Stage 4 - Build the actual backend image and install production dependencies - -# Downstream only - files already exist, nothing to copy; next line for debugging only -# RUN ls -l "$CONTAINER_SOURCE"/ "$CONTAINER_SOURCE"/packages/backend/dist/ -ENV TARBALL_PATH=./packages/backend/dist - -RUN tar xzf "$TARBALL_PATH"/skeleton.tar.gz; tar xzf "$TARBALL_PATH"/bundle.tar.gz; \ - rm -f "$TARBALL_PATH"/skeleton.tar.gz "$TARBALL_PATH"/bundle.tar.gz - -# Copy app-config files needed in runtime -# Upstream only -# COPY $EXTERNAL_SOURCE_NESTED/app-config*.yaml ./ -# COPY $EXTERNAL_SOURCE_NESTED/dynamic-plugins.default.yaml ./ - -# Install production dependencies -# hadolint ignore=DL3059 -RUN "$YARN" workspaces focus --all --production && \ - # delete all the nested .npmrc files and set default values - find . -type f -name .npmrc -exec rm -Rf {} \; && \ - # reset npm config to the default registry and absolute path to .pem file - npm config set registry=https://registry.npmjs.org/ && \ - npm config set cafile /opt/app-root/src/registry-ca.pem - -# Stage 5 - Build the runner image -#@follow_tag(registry.access.redhat.com/ubi9/nodejs-20-minimal:1) -# https://registry.access.redhat.com/ubi9/nodejs-20-minimal -FROM registry.access.redhat.com/ubi9/nodejs-20-minimal:1-63.1725851021 AS runner -USER 0 - -# Downstream sources -ENV EXTERNAL_SOURCE_NESTED=$REMOTE_SOURCES/upstream1/app/distgit/containers/rhdh-hub - -ENV CONTAINER_SOURCE=/opt/app-root/src -WORKDIR $CONTAINER_SOURCE/ - -# Downstream only - install techdocs dependencies using cachito sources -COPY $REMOTE_SOURCES/upstream2 $REMOTE_SOURCES_DIR/upstream2/ -# hadolint ignore=DL3013,DL3041,SC2086 -RUN microdnf update --setopt=install_weak_deps=0 -y && \ - microdnf install -y python3.11 python3.11-pip python3.11-devel make cmake cpp gcc gcc-c++ skopeo; \ - ln -s /usr/bin/pip3.11 /usr/bin/pip3; \ - ln -s /usr/bin/pip3.11 /usr/bin/pip; \ - # ls -la $REMOTE_SOURCES_DIR/ $REMOTE_SOURCES_DIR/upstream2/ $REMOTE_SOURCES_DIR/upstream2/app/distgit/containers/rhdh-hub/docker/ || true; \ - # cat $REMOTE_SOURCES_DIR/upstream2/cachito.env && \ - # cachito.env contains path to cert: - # export PIP_CERT=/remote-source/upstream2/app/package-index-ca.pem - source "$REMOTE_SOURCES_DIR"/upstream2/cachito.env && \ - # fix ownership for pip install folder - mkdir -p /opt/app-root/src/.cache/pip && chown -R root:root /opt/app-root && \ - # ls -ld /opt/ /opt/app-root /opt/app-root/src/ /opt/app-root/src/.cache /opt/app-root/src/.cache/pip || true; \ - pushd "$REMOTE_SOURCES_DIR"/upstream2/app/distgit/containers/rhdh-hub/docker/ >/dev/null && \ - set -xe; \ - python3.11 -V; pip3.11 -V; \ - pip3.11 install --no-cache-dir --upgrade pip setuptools pyyaml; \ - pip3.11 install --no-cache-dir -r requirements.txt -r requirements-build.txt; mkdocs --version; \ - popd >/dev/null; \ - microdnf clean all; rm -fr "$REMOTE_SOURCES_DIR"/upstream2 - -# Downstream only - Make python3.11 the default python -RUN alternatives --install /usr/bin/python python /usr/bin/python3.11 1 - -# Downstream only - copy from build, not cleanup stage -COPY --from=build --chown=1001:1001 "$REMOTE_SOURCES_DIR"/ ./ -# Downstream only - copy embedded dynamic plugins from "$REMOTE_SOURCES_DIR" -COPY --from=build "$REMOTE_SOURCES_DIR"/dynamic-plugins/dist/ ./dynamic-plugins/dist/ - -# RHIDP-4220 - make Konflux preflight and EC checks happy - [check-container] Create a directory named /licenses and include all relevant licensing -COPY $EXTERNAL_SOURCE/LICENSE /licenses/ - -# Copy script to gather dynamic plugins; copy embedded dynamic plugins to root folder; fix permissions -COPY docker/install-dynamic-plugins.py docker/install-dynamic-plugins.sh ./ -RUN chmod -R a+r ./dynamic-plugins/ ./install-dynamic-plugins.py; \ - chmod -R a+rx ./install-dynamic-plugins.sh; - -# Downstream only - fix for https://issues.redhat.com/browse/RHIDP-728 -RUN mkdir /opt/app-root/src/.npm -RUN chown -R 1001:1001 /opt/app-root/src/.npm - -# The fix-permissions script is important when operating in environments that dynamically use a random UID at runtime, such as OpenShift. -# The upstream backstage image does not account for this and it causes the container to fail at runtime. -RUN fix-permissions ./ - -# Switch to nodejs user -USER 1001 - -# Temporary workaround to avoid triggering issue -# https://github.com/backstage/backstage/issues/20644 -ENV CHOKIDAR_USEPOLLING='1' CHOKIDAR_INTERVAL='10000' - -# To avoid running scripts when using `npm pack` to install dynamic plugins -ENV NPM_CONFIG_ignore-scripts='true' - -# gGVM6sYRK0D0ndVX22BOtS7NRcxPej8t is key for dev environment -# Use production key in stable 1.yy.x branch; use dev key in main for CI/next builds -ENV SEGMENT_WRITE_KEY=gGVM6sYRK0D0ndVX22BOtS7NRcxPej8t -ENV SEGMENT_TEST_MODE=false - -# RHIDP-2217: corporate proxy support (configured using 'global-agent') -# This is to avoid having to define several environment variables for the same purpose, -# i.e, GLOBAL_AGENT_HTTP(S)_PROXY (for 'global-agent') and the conventional HTTP(S)_PROXY (honored by other libraries like Axios). -# By setting GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE to an empty value, -# 'global-agent' will use the same HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables. -ENV GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE='' - -# The `--no-node-snapshot` node option enables the usage of the backstage scaffolder on nodejs 20 -# https://github.com/backstage/backstage/issues/20661 - -ENTRYPOINT ["node", "packages/backend", "--no-node-snapshot", "--config", "app-config.yaml", "--config", "app-config.example.yaml", "--config", "app-config.example.production.yaml"] - -# append Brew metadata here diff --git a/.rhdh/docker/README.requirements.md b/.rhdh/docker/README.requirements.md deleted file mode 100644 index 7b10c090..00000000 --- a/.rhdh/docker/README.requirements.md +++ /dev/null @@ -1,66 +0,0 @@ -# To iteratively add/fix requirements: - -Add more dependencies to `requirements.in`, then: - -``` -pip-compile --allow-unsafe --strip-extras requirements.in -o requirements.txt -``` - -If it passes, you can run `cachito_hash.sh` to fix the sha256sums. - -Try to install everything in `requirements.txt`: - -``` -rm -rf pyvenv.cfg lib* bin/* -virtualenv .; . bin/activate -pip install -r requirements.txt -``` - -If it fails, repeat previous step to add more dependencies `requirements.in` and repeat. - -Now, set up BUILD requirements, see https://github.com/containerbuildsystem/cachito/blob/master/docs/pip.md#build-dependencies to get `pip_find_builddeps.py`, then run: - -``` -rm -fr /tmp/pip_find_builddeps.py* -pip_find_builddeps.py requirements.txt -o requirements-build.in --append --no-cache -``` - -Review the contents of `requirements-build.in` to remove dupes. Then regenerate `requirements-build.txt` - -``` -pip-compile --allow-unsafe --strip-extras requirements-build.in -o requirements-build.txt -``` - -If it passes, you can run `cachito_hash.sh` to fix the sha256sums. - -Finally, MAKE SURE YOU OVERRIDE what's in the .txt files to add in the cachito_hash values, as pip-compile will remove them. This can be done by running `cachito_hash.sh`. - -``` -mkdocs-techdocs-core @ https://github.com/backstage/mkdocs-techdocs-core/archive/bbdab44e0d3aecfdc4e77b14c72b57791d4902b2.zip#cachito_hash=sha256:40421a5f43b11fd9ea9f92e107f91089b6bfa326967ad497666ab5a451fcf136 -plantuml-markdown @ https://github.com/mikitex70/plantuml-markdown/archive/fcf62aa930708368ec1daaad8b5b5dbe1d1b2014.zip#cachito_hash=sha256:a487c2312a53fe47a0947e8624290b2c8ea51e373140d02950531966b1db5caa -``` - -To test in a [container build](https://pkgs.devel.redhat.com/cgit/containers/rhdh-hub/tree/Dockerfile?h=private-nboldt-cachito-pip#n155) in Brew, using something like: - -``` -pip3.11 install --user --no-cache-dir -r requirements.txt -r requirements-build.txt -``` - -- commit changes to midstream (gitlab) repo, in a specific branch like [add-pip-deps](https://gitlab.cee.redhat.com/rhidp/rhdh/-/commits/add-pip-deps) -- collect the latest SHA for that branch -- create a topic branch in https://pkgs.devel.redhat.com/cgit/containers/rhdh-hub -- copy the above SHA into the container.yaml for the remote_source.ref values. For example: https://pkgs.devel.redhat.com/cgit/containers/rhdh-hub/commit/?h=private-nboldt-cachito-pip&id=dd6db447ee228be14f9de2c940b5e3efee4890e9 -- run a [scratch build](https://gist.github.com/nickboldt/5b674f75934e7bba5a38486e17a18cfa) and wait for results. -- review cachito and build logs to see what happened. - -If the build fails, add more dependencies to the requirements file, and try again. - -When the build passes, commit changes to midstream and downstream, and trigger sync to cause a downstream build to verify your changes. - -Note that some files are transformed between up/mid/downstream, so you may have to apply changes in more than one file. - -- Upstream: `docker/Dockerfile` (upstream) and `.rhdh/docker/Dockerfile` (mid + downstream) - -- Midstream: `distgit/containers/rhdh-hub/.rhdh/docker/Dockerfile` is transformed to `distgit/containers/rhdh-hub/Dockerfile.in` via [sync.sh](https://gitlab.cee.redhat.com/rhidp/rhdh/-/blob/rhdh-1.1-rhel-9/sync.sh) - -- Downstream: `Dockerfile.in` becomes `Dockerfile` automatically, injecting the product version from [`gcp_env/product_version`](https://gitlab.cee.redhat.com/rhidp/rhdh/-/blob/rhdh-1.1-rhel-9/gcp_env/product-version) diff --git a/.rhdh/docker/cachito_hash.sh b/.rhdh/docker/cachito_hash.sh deleted file mode 100755 index 5dbe0ee0..00000000 --- a/.rhdh/docker/cachito_hash.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/bash -# -# Copyright (c) 2023 Red Hat, Inc. -# This program and the accompanying materials are made -# available under the terms of the Eclipse Public License 2.0 -# which is available at https://www.eclipse.org/legal/epl-2.0/ -# -# see README.requirements.md -- this is used to regenerate the sha256 sums in the .in and .txt files - -SCRIPT_DIR=$(cd "$(dirname "$0")" || exit; pwd) -pushd "$SCRIPT_DIR" >/dev/null || exit -# update the sha256: values in requirements.in and requirements-build.in files -for file in requirements.in requirements-build.in; do - echo "Update $file ..." - #shellcheck disable=SC2013 - pip-compile --quiet --allow-unsafe --output-file="${file/\.in/\.txt}" --strip-extras "${file}" - for d in $(grep https://github $file); do - oldSHA=${d#*sha256:}; # echo $oldSHA - url=${d%#egg=*}; # echo $url - archive=${url%/*.zip} - zip=${url##*/} - echo " Fetch $url" - curl -sSLo dep.zip "$url" - SHA=$(sha256sum dep.zip); SHA=${SHA% dep.zip} - rm -f dep.zip - echo " Set new SHA = $SHA" - sed -i "$file" -r -e "s/sha256:${oldSHA}/sha256:${SHA}/" - # now regen and update the .txt versions of the .in files, plus the readme examples too - echo " Set $archive/$zip#cachito_hash=sha256:$SHA" - for hashed in "${file/\.in/\.txt}" "README.requirements.md"; do - sed -i "$hashed" -r -e "s@(${archive}).+@\1\/$zip#cachito_hash=sha256:${SHA}@" - done - done -done -popd >/dev/null || exit diff --git a/.rhdh/docker/requirements-build.in b/.rhdh/docker/requirements-build.in deleted file mode 100644 index d506d7a0..00000000 --- a/.rhdh/docker/requirements-build.in +++ /dev/null @@ -1,53 +0,0 @@ -# to use this file, `pip install pip-tools -U` first (need >= 7.3), then -# pip-compile --allow-unsafe --output-file=requirements-build.txt --strip-extras requirements-build.in - -babel -calver==2022.6.26 -certifi==2024.7.4 -charset-normalizer==3.3.2 -click==8.1.7 -colorama==0.4.6 -Cython==0.29.37 -editables==0.5 -flit_core==3.9.0 -ghp-import==2.1.0 -hatch-nodejs-version==0.3.2 -hatch-requirements-txt -hatch-vcs==0.4.0 -hatchling==1.25.0 -idna==3.7 -jinja2==3.1.4 -markdown-inline-graphviz-extension==1.1.2 -markdown==3.3.7 -markupsafe==2.1.5 -mdx-truly-sane-lists==1.3 -mergedeep==1.3.4 -mkdocs-material-extensions==1.3.1 -mkdocs-material>=9.5.27 -mkdocs-monorepo-plugin==1.1.0 -mkdocs-techdocs-core==1.4.0 -mkdocs==1.6.0 -packaging==24.1 -pathspec==0.12.1 -plantuml-markdown @ https://github.com/mikitex70/plantuml-markdown/archive/fcf62aa930708368ec1daaad8b5b5dbe1d1b2014.zip#cachito_hash=sha256:a487c2312a53fe47a0947e8624290b2c8ea51e373140d02950531966b1db5caa -platformdirs==3.11.0 -pluggy==1.5.0 -pygments==2.17.2 -pymdown-extensions==10.3.1 -python-dateutil>=2.9.0.post0 -python-slugify==8.0.4 -pyyaml-env-tag==0.1 -pyyaml==6.0.1 -regex==2023.12.25 -requests==2.32.3 -setuptools -setuptools_scm<8.0 -six==1.16.0 -text-unidecode==1.3 -tomli==2.0.1 -trove-classifiers -typing-extensions -urllib3==2.2.2 -watchdog==3.0.0 -wheel -wheel==0.43.0 diff --git a/.rhdh/docker/requirements-build.txt b/.rhdh/docker/requirements-build.txt deleted file mode 100644 index a37a3876..00000000 --- a/.rhdh/docker/requirements-build.txt +++ /dev/null @@ -1,215 +0,0 @@ -# -# This file is autogenerated by pip-compile with Python 3.10 -# by the following command: -# -# pip-compile --allow-unsafe --output-file=requirements-build.txt --strip-extras requirements-build.in -# -babel==2.15.0 - # via - # -r requirements-build.in - # mkdocs-material -calver==2022.6.26 - # via -r requirements-build.in -certifi==2024.7.4 - # via - # -r requirements-build.in - # requests -charset-normalizer==3.3.2 - # via - # -r requirements-build.in - # requests -click==8.1.7 - # via - # -r requirements-build.in - # mkdocs -colorama==0.4.6 - # via - # -r requirements-build.in - # mkdocs-material -cython==0.29.37 - # via -r requirements-build.in -editables==0.5 - # via -r requirements-build.in -flit-core==3.9.0 - # via -r requirements-build.in -ghp-import==2.1.0 - # via - # -r requirements-build.in - # mkdocs -hatch-nodejs-version==0.3.2 - # via -r requirements-build.in -hatch-requirements-txt==0.4.1 - # via -r requirements-build.in -hatch-vcs==0.4.0 - # via -r requirements-build.in -hatchling==1.25.0 - # via - # -r requirements-build.in - # hatch-nodejs-version - # hatch-requirements-txt - # hatch-vcs -idna==3.7 - # via - # -r requirements-build.in - # requests -jinja2==3.1.4 - # via - # -r requirements-build.in - # mkdocs - # mkdocs-material -markdown==3.3.7 - # via - # -r requirements-build.in - # markdown-inline-graphviz-extension - # mdx-truly-sane-lists - # mkdocs - # mkdocs-material - # mkdocs-techdocs-core - # plantuml-markdown - # pymdown-extensions -markdown-inline-graphviz-extension==1.1.2 - # via - # -r requirements-build.in - # mkdocs-techdocs-core -markupsafe==2.1.5 - # via - # -r requirements-build.in - # jinja2 - # mkdocs -mdx-truly-sane-lists==1.3 - # via - # -r requirements-build.in - # mkdocs-techdocs-core -mergedeep==1.3.4 - # via - # -r requirements-build.in - # mkdocs - # mkdocs-get-deps -mkdocs==1.6.0 - # via - # -r requirements-build.in - # mkdocs-material - # mkdocs-monorepo-plugin - # mkdocs-techdocs-core -mkdocs-get-deps==0.2.0 - # via mkdocs -mkdocs-material==9.5.27 - # via - # -r requirements-build.in - # mkdocs-techdocs-core -mkdocs-material-extensions==1.3.1 - # via - # -r requirements-build.in - # mkdocs-material -mkdocs-monorepo-plugin==1.1.0 - # via - # -r requirements-build.in - # mkdocs-techdocs-core -mkdocs-techdocs-core==1.4.0 - # via -r requirements-build.in -packaging==24.1 - # via - # -r requirements-build.in - # hatch-requirements-txt - # hatchling - # mkdocs - # setuptools-scm -paginate==0.5.6 - # via mkdocs-material -pathspec==0.12.1 - # via - # -r requirements-build.in - # hatchling - # mkdocs -plantuml-markdown @ https://github.com/mikitex70/plantuml-markdown/archive/fcf62aa930708368ec1daaad8b5b5dbe1d1b2014.zip#cachito_hash=sha256:a487c2312a53fe47a0947e8624290b2c8ea51e373140d02950531966b1db5caa - # via - # -r requirements-build.in - # mkdocs-techdocs-core -platformdirs==3.11.0 - # via - # -r requirements-build.in - # mkdocs-get-deps -pluggy==1.5.0 - # via - # -r requirements-build.in - # hatchling -pygments==2.17.2 - # via - # -r requirements-build.in - # mkdocs-material - # mkdocs-techdocs-core -pymdown-extensions==10.3.1 - # via - # -r requirements-build.in - # mkdocs-material - # mkdocs-techdocs-core -python-dateutil==2.9.0.post0 - # via - # -r requirements-build.in - # ghp-import -python-slugify==8.0.4 - # via - # -r requirements-build.in - # mkdocs-monorepo-plugin -pyyaml==6.0.1 - # via - # -r requirements-build.in - # mkdocs - # mkdocs-get-deps - # pymdown-extensions - # pyyaml-env-tag -pyyaml-env-tag==0.1 - # via - # -r requirements-build.in - # mkdocs -regex==2023.12.25 - # via - # -r requirements-build.in - # mkdocs-material -requests==2.32.3 - # via - # -r requirements-build.in - # mkdocs-material - # plantuml-markdown -setuptools-scm==7.1.0 - # via - # -r requirements-build.in - # hatch-vcs -six==1.16.0 - # via - # -r requirements-build.in - # plantuml-markdown - # python-dateutil -text-unidecode==1.3 - # via - # -r requirements-build.in - # python-slugify -tomli==2.0.1 - # via - # -r requirements-build.in - # hatchling - # setuptools-scm -trove-classifiers==2024.7.2 - # via - # -r requirements-build.in - # hatchling -typing-extensions==4.12.2 - # via - # -r requirements-build.in - # setuptools-scm -urllib3==2.2.2 - # via - # -r requirements-build.in - # requests -watchdog==3.0.0 - # via - # -r requirements-build.in - # mkdocs -wheel==0.43.0 - # via -r requirements-build.in - -# The following packages are considered to be unsafe in a requirements file: -setuptools==70.1.1 - # via - # -r requirements-build.in - # setuptools-scm diff --git a/.rhdh/docker/requirements.in b/.rhdh/docker/requirements.in deleted file mode 100644 index c910cb5a..00000000 --- a/.rhdh/docker/requirements.in +++ /dev/null @@ -1,53 +0,0 @@ -# to use this file, `pip install pip-tools -U` first (need >= 7.3), then -# pip-compile --allow-unsafe --output-file=requirements.txt --strip-extras requirements.in - -babel -calver==2022.6.26 -certifi==2024.7.4 -charset-normalizer==3.3.2 -click==8.1.7 -colorama==0.4.6 -Cython==0.29.37 -editables==0.5 -flit_core==3.9.0 -ghp-import==2.1.0 -hatch-nodejs-version==0.3.2 -hatch-requirements-txt -hatch-vcs==0.4.0 -hatchling==1.25.0 -idna==3.7 -jinja2==3.1.4 -markdown-inline-graphviz-extension==1.1.2 -markdown==3.3.7 -markupsafe==2.1.5 -mdx-truly-sane-lists==1.3 -mergedeep==1.3.4 -mkdocs-material-extensions==1.3.1 -mkdocs-material>=9.5.27 -mkdocs-monorepo-plugin==1.1.0 -mkdocs-techdocs-core==1.4.0 -mkdocs==1.6.0 -packaging==24.1 -pathspec==0.12.1 -plantuml-markdown @ https://github.com/mikitex70/plantuml-markdown/archive/fcf62aa930708368ec1daaad8b5b5dbe1d1b2014.zip#cachito_hash=sha256:a487c2312a53fe47a0947e8624290b2c8ea51e373140d02950531966b1db5caa -platformdirs==3.11.0 -pluggy==1.5.0 -pygments==2.17.2 -pymdown-extensions==10.3.1 -python-dateutil>=2.9.0.post0 -python-slugify==8.0.4 -pyyaml-env-tag==0.1 -pyyaml==6.0.1 -regex==2023.12.25 -requests==2.32.3 -setuptools -setuptools_scm<8.0 -six==1.16.0 -text-unidecode==1.3 -tomli==2.0.1 -trove-classifiers -typing-extensions -urllib3==2.2.2 -watchdog==3.0.0 -wheel -wheel==0.43.0 diff --git a/.rhdh/docker/requirements.txt b/.rhdh/docker/requirements.txt deleted file mode 100644 index a93d9b84..00000000 --- a/.rhdh/docker/requirements.txt +++ /dev/null @@ -1,215 +0,0 @@ -# -# This file is autogenerated by pip-compile with Python 3.10 -# by the following command: -# -# pip-compile --allow-unsafe --output-file=requirements.txt --strip-extras requirements.in -# -babel==2.15.0 - # via - # -r requirements.in - # mkdocs-material -calver==2022.6.26 - # via -r requirements.in -certifi==2024.7.4 - # via - # -r requirements.in - # requests -charset-normalizer==3.3.2 - # via - # -r requirements.in - # requests -click==8.1.7 - # via - # -r requirements.in - # mkdocs -colorama==0.4.6 - # via - # -r requirements.in - # mkdocs-material -cython==0.29.37 - # via -r requirements.in -editables==0.5 - # via -r requirements.in -flit-core==3.9.0 - # via -r requirements.in -ghp-import==2.1.0 - # via - # -r requirements.in - # mkdocs -hatch-nodejs-version==0.3.2 - # via -r requirements.in -hatch-requirements-txt==0.4.1 - # via -r requirements.in -hatch-vcs==0.4.0 - # via -r requirements.in -hatchling==1.25.0 - # via - # -r requirements.in - # hatch-nodejs-version - # hatch-requirements-txt - # hatch-vcs -idna==3.7 - # via - # -r requirements.in - # requests -jinja2==3.1.4 - # via - # -r requirements.in - # mkdocs - # mkdocs-material -markdown==3.3.7 - # via - # -r requirements.in - # markdown-inline-graphviz-extension - # mdx-truly-sane-lists - # mkdocs - # mkdocs-material - # mkdocs-techdocs-core - # plantuml-markdown - # pymdown-extensions -markdown-inline-graphviz-extension==1.1.2 - # via - # -r requirements.in - # mkdocs-techdocs-core -markupsafe==2.1.5 - # via - # -r requirements.in - # jinja2 - # mkdocs -mdx-truly-sane-lists==1.3 - # via - # -r requirements.in - # mkdocs-techdocs-core -mergedeep==1.3.4 - # via - # -r requirements.in - # mkdocs - # mkdocs-get-deps -mkdocs==1.6.0 - # via - # -r requirements.in - # mkdocs-material - # mkdocs-monorepo-plugin - # mkdocs-techdocs-core -mkdocs-get-deps==0.2.0 - # via mkdocs -mkdocs-material==9.5.27 - # via - # -r requirements.in - # mkdocs-techdocs-core -mkdocs-material-extensions==1.3.1 - # via - # -r requirements.in - # mkdocs-material -mkdocs-monorepo-plugin==1.1.0 - # via - # -r requirements.in - # mkdocs-techdocs-core -mkdocs-techdocs-core==1.4.0 - # via -r requirements.in -packaging==24.1 - # via - # -r requirements.in - # hatch-requirements-txt - # hatchling - # mkdocs - # setuptools-scm -paginate==0.5.6 - # via mkdocs-material -pathspec==0.12.1 - # via - # -r requirements.in - # hatchling - # mkdocs -plantuml-markdown @ https://github.com/mikitex70/plantuml-markdown/archive/fcf62aa930708368ec1daaad8b5b5dbe1d1b2014.zip#cachito_hash=sha256:a487c2312a53fe47a0947e8624290b2c8ea51e373140d02950531966b1db5caa - # via - # -r requirements.in - # mkdocs-techdocs-core -platformdirs==3.11.0 - # via - # -r requirements.in - # mkdocs-get-deps -pluggy==1.5.0 - # via - # -r requirements.in - # hatchling -pygments==2.17.2 - # via - # -r requirements.in - # mkdocs-material - # mkdocs-techdocs-core -pymdown-extensions==10.3.1 - # via - # -r requirements.in - # mkdocs-material - # mkdocs-techdocs-core -python-dateutil==2.9.0.post0 - # via - # -r requirements.in - # ghp-import -python-slugify==8.0.4 - # via - # -r requirements.in - # mkdocs-monorepo-plugin -pyyaml==6.0.1 - # via - # -r requirements.in - # mkdocs - # mkdocs-get-deps - # pymdown-extensions - # pyyaml-env-tag -pyyaml-env-tag==0.1 - # via - # -r requirements.in - # mkdocs -regex==2023.12.25 - # via - # -r requirements.in - # mkdocs-material -requests==2.32.3 - # via - # -r requirements.in - # mkdocs-material - # plantuml-markdown -setuptools-scm==7.1.0 - # via - # -r requirements.in - # hatch-vcs -six==1.16.0 - # via - # -r requirements.in - # plantuml-markdown - # python-dateutil -text-unidecode==1.3 - # via - # -r requirements.in - # python-slugify -tomli==2.0.1 - # via - # -r requirements.in - # hatchling - # setuptools-scm -trove-classifiers==2024.7.2 - # via - # -r requirements.in - # hatchling -typing-extensions==4.12.2 - # via - # -r requirements.in - # setuptools-scm -urllib3==2.2.2 - # via - # -r requirements.in - # requests -watchdog==3.0.0 - # via - # -r requirements.in - # mkdocs -wheel==0.43.0 - # via -r requirements.in - -# The following packages are considered to be unsafe in a requirements file: -setuptools==70.1.1 - # via - # -r requirements.in - # setuptools-scm diff --git a/.rhdh/docker/setup.py b/.rhdh/docker/setup.py deleted file mode 100644 index 100b6cab..00000000 --- a/.rhdh/docker/setup.py +++ /dev/null @@ -1,8 +0,0 @@ -from setuptools import setup - -setup(name='Python dependencies', - version='1.0', - description='Python dependencies', - author='Nick Boldt', - author_email='nboldt@redhat.com', - ) diff --git a/.yarn/patches/@backstage-backend-dynamic-feature-service-npm-0.4.3-2650d84cc8.patch b/.yarn/patches/@backstage-backend-dynamic-feature-service-npm-0.4.3-2650d84cc8.patch deleted file mode 100644 index c5bc0e0d..00000000 --- a/.yarn/patches/@backstage-backend-dynamic-feature-service-npm-0.4.3-2650d84cc8.patch +++ /dev/null @@ -1,61 +0,0 @@ -diff --git a/dist/features/features.cjs.js b/dist/features/features.cjs.js -index debb6ce817c7aa0111a3cbc20edeee815ad59759..cea4f6fde4c4c57793db5f9732d6810bdd517256 100644 ---- a/dist/features/features.cjs.js -+++ b/dist/features/features.cjs.js -@@ -1,11 +1,11 @@ - 'use strict'; - - var backendPluginApi = require('@backstage/backend-plugin-api'); -+var pluginManager = require('../manager/plugin-manager.cjs.js'); -+var pluginScanner = require('../scanner/plugin-scanner.cjs.js'); - var schemas = require('../schemas/schemas.cjs.js'); - var frontend = require('../schemas/frontend.cjs.js'); - var rootLogger = require('../schemas/rootLogger.cjs.js'); --var pluginManager = require('../manager/plugin-manager.cjs.js'); --var pluginScanner = require('../scanner/plugin-scanner.cjs.js'); - - const dynamicPluginsFeatureLoaderWithOptions = (options) => backendPluginApi.createBackendFeatureLoader({ - deps: { -@@ -13,13 +13,17 @@ const dynamicPluginsFeatureLoaderWithOptions = (options) => backendPluginApi.cre - }, - *loader({ config }) { - const dynamicPluginsEnabled = config.has(pluginScanner.configKey); -+ let rootLoggerOptions = {}; -+ if (options?.logger) { -+ rootLoggerOptions = options.logger(config); -+ } - yield* [ - schemas.dynamicPluginsSchemasServiceFactory(options), - pluginManager.dynamicPluginsServiceFactory(options) - ]; - if (dynamicPluginsEnabled) { - yield* [ -- rootLogger.dynamicPluginsRootLoggerServiceFactory(options), -+ rootLogger.dynamicPluginsRootLoggerServiceFactory(rootLoggerOptions), - frontend.dynamicPluginsFrontendSchemas, - pluginManager.dynamicPluginsFeatureDiscoveryLoader - ]; -diff --git a/dist/features/features.cjs.js.map b/dist/features/features.cjs.js.map -index 4c36851870462037a9c505eb5b20a7085499c734..400c3205835b46031d0f805140e9f5b2b19c397e 100644 ---- a/dist/features/features.cjs.js.map -+++ b/dist/features/features.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"features.cjs.js","sources":["../../src/features/features.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendFeatureLoader,\n} from '@backstage/backend-plugin-api';\nimport {\n DynamicPluginsSchemasOptions,\n dynamicPluginsFrontendSchemas,\n dynamicPluginsRootLoggerServiceFactory,\n dynamicPluginsSchemasServiceFactory,\n} from '../schemas';\nimport {\n DynamicPluginsFactoryOptions,\n dynamicPluginsFeatureDiscoveryLoader,\n dynamicPluginsServiceFactory,\n} from '../manager';\nimport { DynamicPluginsRootLoggerFactoryOptions } from '../schemas';\nimport { configKey } from '../scanner/plugin-scanner';\n\n/**\n * @public\n */\nexport type DynamicPluginsFeatureLoaderOptions = DynamicPluginsFactoryOptions &\n DynamicPluginsSchemasOptions &\n DynamicPluginsRootLoggerFactoryOptions;\n\nconst dynamicPluginsFeatureLoaderWithOptions = (\n options?: DynamicPluginsFeatureLoaderOptions,\n) =>\n createBackendFeatureLoader({\n deps: {\n config: coreServices.rootConfig,\n },\n *loader({ config }) {\n const dynamicPluginsEnabled = config.has(configKey);\n\n yield* [\n dynamicPluginsSchemasServiceFactory(options),\n dynamicPluginsServiceFactory(options),\n ];\n if (dynamicPluginsEnabled) {\n yield* [\n dynamicPluginsRootLoggerServiceFactory(options),\n dynamicPluginsFrontendSchemas,\n dynamicPluginsFeatureDiscoveryLoader,\n ];\n }\n },\n });\n\n/**\n * A backend feature loader that fully enable backend dynamic plugins.\n * More precisely it:\n * - adds the dynamic plugins root service (typically depended upon by plugins),\n * - adds additional required features to allow supporting dynamic plugins config schemas\n * in the frontend application and the backend root logger,\n * - uses the dynamic plugins service to discover and expose dynamic plugins as features.\n *\n * @public\n *\n * @example\n * Using the `dynamicPluginsFeatureLoader` loader in a backend instance:\n * ```ts\n * //...\n * import { createBackend } from '@backstage/backend-defaults';\n * import { dynamicPluginsFeatureLoader } from '@backstage/backend-dynamic-feature-service';\n *\n * const backend = createBackend();\n * backend.add(dynamicPluginsFeatureLoader);\n * //...\n * backend.start();\n * ```\n *\n * @example\n * Passing options to the `dynamicPluginsFeatureLoader` loader in a backend instance:\n * ```ts\n * //...\n * import { createBackend } from '@backstage/backend-defaults';\n * import { dynamicPluginsFeatureLoader } from '@backstage/backend-dynamic-feature-service';\n * import { myCustomModuleLoader } from './myCustomModuleLoader';\n * import { myCustomSchemaLocator } from './myCustomSchemaLocator';\n *\n * const backend = createBackend();\n * backend.add(dynamicPluginsFeatureLoader({\n * moduleLoader: myCustomModuleLoader,\n * schemaLocator: myCustomSchemaLocator,\n *\n * }));\n * //...\n * backend.start();\n * ```\n */\nexport const dynamicPluginsFeatureLoader = Object.assign(\n dynamicPluginsFeatureLoaderWithOptions,\n dynamicPluginsFeatureLoaderWithOptions(),\n);\n"],"names":["createBackendFeatureLoader","coreServices","configKey","dynamicPluginsSchemasServiceFactory","dynamicPluginsServiceFactory","dynamicPluginsRootLoggerServiceFactory","dynamicPluginsFrontendSchemas","dynamicPluginsFeatureDiscoveryLoader"],"mappings":";;;;;;;;;AAyCA,MAAM,sCAAA,GAAyC,CAC7C,OAAA,KAEAA,2CAA2B,CAAA;AAAA,EACzB,IAAM,EAAA;AAAA,IACJ,QAAQC,6BAAa,CAAA,UAAA;AAAA,GACvB;AAAA,EACA,CAAC,MAAA,CAAO,EAAE,MAAA,EAAU,EAAA;AAClB,IAAM,MAAA,qBAAA,GAAwB,MAAO,CAAA,GAAA,CAAIC,uBAAS,CAAA,CAAA;AAElD,IAAO,OAAA;AAAA,MACLC,4CAAoC,OAAO,CAAA;AAAA,MAC3CC,2CAA6B,OAAO,CAAA;AAAA,KACtC,CAAA;AACA,IAAA,IAAI,qBAAuB,EAAA;AACzB,MAAO,OAAA;AAAA,QACLC,kDAAuC,OAAO,CAAA;AAAA,QAC9CC,sCAAA;AAAA,QACAC,kDAAA;AAAA,OACF,CAAA;AAAA,KACF;AAAA,GACF;AACF,CAAC,CAAA,CAAA;AA4CI,MAAM,8BAA8B,MAAO,CAAA,MAAA;AAAA,EAChD,sCAAA;AAAA,EACA,sCAAuC,EAAA;AACzC;;;;"} -\ No newline at end of file -+{"version":3,"file":"features.cjs.js","sources":["../../src/features/features.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createBackendFeatureLoader,\n} from '@backstage/backend-plugin-api';\nimport type { Config } from '@backstage/config';\nimport {\n DynamicPluginsFactoryOptions,\n dynamicPluginsFeatureDiscoveryLoader,\n dynamicPluginsServiceFactory,\n} from '../manager';\nimport { configKey } from '../scanner/plugin-scanner';\nimport {\n DynamicPluginsRootLoggerFactoryOptions,\n DynamicPluginsSchemasOptions,\n dynamicPluginsFrontendSchemas,\n dynamicPluginsRootLoggerServiceFactory,\n dynamicPluginsSchemasServiceFactory,\n} from '../schemas';\n\n/**\n * @public\n */\nexport type DynamicPluginsFeatureLoaderOptions = DynamicPluginsFactoryOptions &\n DynamicPluginsSchemasOptions &\n{ logger?: (config?: Config) => DynamicPluginsRootLoggerFactoryOptions };\n\nconst dynamicPluginsFeatureLoaderWithOptions = (\n options?: DynamicPluginsFeatureLoaderOptions,\n) =>\n createBackendFeatureLoader({\n deps: {\n config: coreServices.rootConfig,\n },\n *loader({ config }) {\n const dynamicPluginsEnabled = config.has(configKey);\n\n let rootLoggerOptions: DynamicPluginsRootLoggerFactoryOptions = {}\n if (options?.logger) {\n rootLoggerOptions = options.logger(config)\n }\n\n yield* [\n dynamicPluginsSchemasServiceFactory(options),\n dynamicPluginsServiceFactory(options),\n ];\n if (dynamicPluginsEnabled) {\n yield* [\n dynamicPluginsRootLoggerServiceFactory(rootLoggerOptions),\n dynamicPluginsFrontendSchemas,\n dynamicPluginsFeatureDiscoveryLoader,\n ];\n }\n },\n });\n\n/**\n * A backend feature loader that fully enable backend dynamic plugins.\n * More precisely it:\n * - adds the dynamic plugins root service (typically depended upon by plugins),\n * - adds additional required features to allow supporting dynamic plugins config schemas\n * in the frontend application and the backend root logger,\n * - uses the dynamic plugins service to discover and expose dynamic plugins as features.\n *\n * @public\n *\n * @example\n * Using the `dynamicPluginsFeatureLoader` loader in a backend instance:\n * ```ts\n * //...\n * import { createBackend } from '@backstage/backend-defaults';\n * import { dynamicPluginsFeatureLoader } from '@backstage/backend-dynamic-feature-service';\n *\n * const backend = createBackend();\n * backend.add(dynamicPluginsFeatureLoader);\n * //...\n * backend.start();\n * ```\n *\n * @example\n * Passing options to the `dynamicPluginsFeatureLoader` loader in a backend instance:\n * ```ts\n * //...\n * import { createBackend } from '@backstage/backend-defaults';\n * import { dynamicPluginsFeatureLoader } from '@backstage/backend-dynamic-feature-service';\n * import { myCustomModuleLoader } from './myCustomModuleLoader';\n * import { myCustomSchemaLocator } from './myCustomSchemaLocator';\n *\n * const backend = createBackend();\n * backend.add(dynamicPluginsFeatureLoader({\n * moduleLoader: myCustomModuleLoader,\n * schemaLocator: myCustomSchemaLocator,\n *\n * }));\n * //...\n * backend.start();\n * ```\n */\nexport const dynamicPluginsFeatureLoader = Object.assign(\n dynamicPluginsFeatureLoaderWithOptions,\n dynamicPluginsFeatureLoaderWithOptions(),\n);\n"],"names":["createBackendFeatureLoader","coreServices","configKey","dynamicPluginsSchemasServiceFactory","dynamicPluginsServiceFactory","dynamicPluginsRootLoggerServiceFactory","dynamicPluginsFrontendSchemas","dynamicPluginsFeatureDiscoveryLoader"],"mappings":";;;;;;;;;AA0CA,MAAM,sCAAA,GAAyC,CAC7C,OAAA,KAEAA,2CAA2B,CAAA;AAAA,EACzB,IAAM,EAAA;AAAA,IACJ,QAAQC,6BAAa,CAAA,UAAA;AAAA,GACvB;AAAA,EACA,CAAC,MAAA,CAAO,EAAE,MAAA,EAAU,EAAA;AAClB,IAAM,MAAA,qBAAA,GAAwB,MAAO,CAAA,GAAA,CAAIC,uBAAS,CAAA,CAAA;AAElD,IAAA,IAAI,oBAA4D,EAAC,CAAA;AACjE,IAAA,IAAI,SAAS,MAAQ,EAAA;AACnB,MAAoB,iBAAA,GAAA,OAAA,CAAQ,OAAO,MAAM,CAAA,CAAA;AAAA,KAC3C;AAEA,IAAO,OAAA;AAAA,MACLC,4CAAoC,OAAO,CAAA;AAAA,MAC3CC,2CAA6B,OAAO,CAAA;AAAA,KACtC,CAAA;AACA,IAAA,IAAI,qBAAuB,EAAA;AACzB,MAAO,OAAA;AAAA,QACLC,kDAAuC,iBAAiB,CAAA;AAAA,QACxDC,sCAAA;AAAA,QACAC,kDAAA;AAAA,OACF,CAAA;AAAA,KACF;AAAA,GACF;AACF,CAAC,CAAA,CAAA;AA4CI,MAAM,8BAA8B,MAAO,CAAA,MAAA;AAAA,EAChD,sCAAA;AAAA,EACA,sCAAuC,EAAA;AACzC;;;;"} -\ No newline at end of file -diff --git a/dist/index.d.ts b/dist/index.d.ts -index 212ed98b995d33e38f428a108805a6a791bd948f..5af3e7734f58affdd574a4aef61363a8429ff194 100644 ---- a/dist/index.d.ts -+++ b/dist/index.d.ts -@@ -276,7 +276,9 @@ declare const dynamicPluginsRootLoggerServiceFactory: ((options?: DynamicPlugins - /** - * @public - */ --type DynamicPluginsFeatureLoaderOptions = DynamicPluginsFactoryOptions & DynamicPluginsSchemasOptions & DynamicPluginsRootLoggerFactoryOptions; -+type DynamicPluginsFeatureLoaderOptions = DynamicPluginsFactoryOptions & DynamicPluginsSchemasOptions & { -+ logger?: (config?: Config) => DynamicPluginsRootLoggerFactoryOptions; -+}; - /** - * A backend feature loader that fully enable backend dynamic plugins. - * More precisely it: diff --git a/.yarn/patches/@backstage-plugin-auth-backend-module-oidc-provider-npm-0.3.1-6fab98121c.patch b/.yarn/patches/@backstage-plugin-auth-backend-module-oidc-provider-npm-0.3.1-6fab98121c.patch deleted file mode 100644 index 9280ee97..00000000 --- a/.yarn/patches/@backstage-plugin-auth-backend-module-oidc-provider-npm-0.3.1-6fab98121c.patch +++ /dev/null @@ -1,104 +0,0 @@ -diff --git a/config.d.ts b/config.d.ts -index d59c40697ab250330eb71483692def8785142e07..17b26a6eb580921e8a50b3ef87316e6cdb89b7a4 100644 ---- a/config.d.ts -+++ b/config.d.ts -@@ -34,10 +34,11 @@ export interface Config { - signIn?: { - resolvers: Array< - | { -- resolver: 'emailLocalPartMatchingUserEntityName'; -- allowedDomains?: string[]; -- } -+ resolver: 'emailLocalPartMatchingUserEntityName'; -+ allowedDomains?: string[]; -+ } - | { resolver: 'emailMatchingUserEntityProfileEmail' } -+ | { resolver: 'preferredUsernameMatchingUserEntityName' } - >; - }; - }; -diff --git a/dist/authenticator.cjs.js.map b/dist/authenticator.cjs.js.map -index f5838857e575c085b99bec2b558b8d3818b89c9d..92e72750e7e99f74d8aacf56dc8c42a601b97a1c 100644 ---- a/dist/authenticator.cjs.js.map -+++ b/dist/authenticator.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"authenticator.cjs.js","sources":["../src/authenticator.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport crypto from 'crypto';\nimport {\n custom,\n CustomHttpOptionsProvider,\n Issuer,\n ClientAuthMethod,\n TokenSet,\n UserinfoResponse,\n Strategy as OidcStrategy,\n} from 'openid-client';\nimport {\n createOAuthAuthenticator,\n OAuthAuthenticatorResult,\n PassportDoneCallback,\n PassportHelpers,\n PassportOAuthAuthenticatorHelper,\n PassportOAuthPrivateInfo,\n} from '@backstage/plugin-auth-node';\n\nconst HTTP_OPTION_TIMEOUT = 10000;\nconst httpOptionsProvider: CustomHttpOptionsProvider = (_url, options) => {\n return {\n ...options,\n timeout: HTTP_OPTION_TIMEOUT,\n };\n};\n\n/**\n * authentication result for the OIDC which includes the token set and user\n * profile response\n * @public\n */\nexport type OidcAuthResult = {\n tokenset: TokenSet;\n userinfo: UserinfoResponse;\n};\n\n/** @public */\nexport const oidcAuthenticator = createOAuthAuthenticator({\n defaultProfileTransform: async (\n input: OAuthAuthenticatorResult,\n ) => ({\n profile: {\n email: input.fullProfile.userinfo.email,\n picture: input.fullProfile.userinfo.picture,\n displayName: input.fullProfile.userinfo.name,\n },\n }),\n scopes: {\n persist: true,\n required: ['openid', 'profile', 'email'],\n },\n initialize({ callbackUrl, config }) {\n const clientId = config.getString('clientId');\n const clientSecret = config.getString('clientSecret');\n const metadataUrl = config.getString('metadataUrl');\n const customCallbackUrl = config.getOptionalString('callbackUrl');\n const tokenEndpointAuthMethod = config.getOptionalString(\n 'tokenEndpointAuthMethod',\n ) as ClientAuthMethod;\n const tokenSignedResponseAlg = config.getOptionalString(\n 'tokenSignedResponseAlg',\n );\n const initializedPrompt = config.getOptionalString('prompt');\n\n if (config.has('scope')) {\n throw new Error(\n 'The oidc provider no longer supports the \"scope\" configuration option. Please use the \"additionalScopes\" option instead.',\n );\n }\n\n Issuer[custom.http_options] = httpOptionsProvider;\n const promise = Issuer.discover(metadataUrl).then(issuer => {\n issuer[custom.http_options] = httpOptionsProvider;\n issuer.Client[custom.http_options] = httpOptionsProvider;\n\n const client = new issuer.Client({\n access_type: 'offline', // this option must be passed to provider to receive a refresh token\n client_id: clientId,\n client_secret: clientSecret,\n redirect_uris: [customCallbackUrl || callbackUrl],\n response_types: ['code'],\n token_endpoint_auth_method:\n tokenEndpointAuthMethod || 'client_secret_basic',\n id_token_signed_response_alg: tokenSignedResponseAlg || 'RS256',\n });\n client[custom.http_options] = httpOptionsProvider;\n\n const strategy = new OidcStrategy(\n {\n client,\n passReqToCallback: false,\n },\n (\n tokenset: TokenSet,\n userinfo: UserinfoResponse,\n done: PassportDoneCallback,\n ) => {\n if (typeof done !== 'function') {\n throw new Error(\n 'OIDC IdP must provide a userinfo_endpoint in the metadata response',\n );\n }\n\n done(\n undefined,\n { tokenset, userinfo },\n { refreshToken: tokenset.refresh_token },\n );\n },\n );\n\n const helper = PassportOAuthAuthenticatorHelper.from(strategy);\n return { helper, client, strategy };\n });\n\n return { initializedPrompt, promise };\n },\n\n async start(input, ctx) {\n const { initializedPrompt, promise } = ctx;\n const { helper, strategy } = await promise;\n const options: Record = {\n scope: input.scope,\n state: input.state,\n nonce: crypto.randomBytes(16).toString('base64'),\n };\n const prompt = initializedPrompt || 'none';\n if (prompt !== 'auto') {\n options.prompt = prompt;\n }\n\n return new Promise((resolve, reject) => {\n strategy.error = reject;\n\n return helper\n .start(input, {\n ...options,\n })\n .then(resolve);\n });\n },\n\n async authenticate(\n input,\n ctx,\n ): Promise> {\n const { strategy } = await ctx.promise;\n const { result, privateInfo } =\n await PassportHelpers.executeFrameHandlerStrategy<\n OidcAuthResult,\n PassportOAuthPrivateInfo\n >(input.req, strategy);\n\n return {\n fullProfile: result,\n session: {\n accessToken: result.tokenset.access_token!,\n tokenType: result.tokenset.token_type ?? 'bearer',\n scope: result.tokenset.scope!,\n expiresInSeconds: result.tokenset.expires_in,\n idToken: result.tokenset.id_token,\n refreshToken: privateInfo.refreshToken,\n },\n };\n },\n\n async refresh(input, ctx) {\n const { client } = await ctx.promise;\n const tokenset = await client.refresh(input.refreshToken);\n if (!tokenset.access_token) {\n throw new Error('Refresh failed');\n }\n const userinfo = await client.userinfo(tokenset.access_token);\n\n return new Promise((resolve, reject) => {\n if (!tokenset.access_token) {\n reject(new Error('Refresh Failed'));\n }\n resolve({\n fullProfile: { userinfo, tokenset },\n session: {\n accessToken: tokenset.access_token!,\n tokenType: tokenset.token_type ?? 'bearer',\n scope: tokenset.scope!,\n expiresInSeconds: tokenset.expires_in,\n idToken: tokenset.id_token,\n refreshToken: tokenset.refresh_token,\n },\n });\n });\n },\n\n async logout(input, ctx) {\n const { client } = await ctx.promise;\n const issuer = client.issuer;\n /**\n * https://github.com/panva/node-openid-client/blob/main/lib/client.js#L1398\n * client.revoke will check revocation_endpoint and if undefined throw error。\n *\n * if oidc server do not provide revocation_endpoint,we should not call revoke function\n */\n\n if (input.refreshToken && issuer.revocation_endpoint) {\n await client.revoke(input.refreshToken);\n }\n },\n});\n"],"names":["createOAuthAuthenticator","Issuer","custom","OidcStrategy","PassportOAuthAuthenticatorHelper","crypto","PassportHelpers"],"mappings":";;;;;;;;;;AAmCA,MAAM,mBAAsB,GAAA,GAAA,CAAA;AAC5B,MAAM,mBAAA,GAAiD,CAAC,IAAA,EAAM,OAAY,KAAA;AACxE,EAAO,OAAA;AAAA,IACL,GAAG,OAAA;AAAA,IACH,OAAS,EAAA,mBAAA;AAAA,GACX,CAAA;AACF,CAAA,CAAA;AAaO,MAAM,oBAAoBA,uCAAyB,CAAA;AAAA,EACxD,uBAAA,EAAyB,OACvB,KACI,MAAA;AAAA,IACJ,OAAS,EAAA;AAAA,MACP,KAAA,EAAO,KAAM,CAAA,WAAA,CAAY,QAAS,CAAA,KAAA;AAAA,MAClC,OAAA,EAAS,KAAM,CAAA,WAAA,CAAY,QAAS,CAAA,OAAA;AAAA,MACpC,WAAA,EAAa,KAAM,CAAA,WAAA,CAAY,QAAS,CAAA,IAAA;AAAA,KAC1C;AAAA,GACF,CAAA;AAAA,EACA,MAAQ,EAAA;AAAA,IACN,OAAS,EAAA,IAAA;AAAA,IACT,QAAU,EAAA,CAAC,QAAU,EAAA,SAAA,EAAW,OAAO,CAAA;AAAA,GACzC;AAAA,EACA,UAAW,CAAA,EAAE,WAAa,EAAA,MAAA,EAAU,EAAA;AAClC,IAAM,MAAA,QAAA,GAAW,MAAO,CAAA,SAAA,CAAU,UAAU,CAAA,CAAA;AAC5C,IAAM,MAAA,YAAA,GAAe,MAAO,CAAA,SAAA,CAAU,cAAc,CAAA,CAAA;AACpD,IAAM,MAAA,WAAA,GAAc,MAAO,CAAA,SAAA,CAAU,aAAa,CAAA,CAAA;AAClD,IAAM,MAAA,iBAAA,GAAoB,MAAO,CAAA,iBAAA,CAAkB,aAAa,CAAA,CAAA;AAChE,IAAA,MAAM,0BAA0B,MAAO,CAAA,iBAAA;AAAA,MACrC,yBAAA;AAAA,KACF,CAAA;AACA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,IAAA,CAAC,SAAS,YAAc,EAAA;AAC1B,QAAO,MAAA,CAAA,IAAI,KAAM,CAAA,gBAAgB,CAAC,CAAA,CAAA;AAAA,OACpC;AACA,MAAQ,OAAA,CAAA;AAAA,QACN,WAAA,EAAa,EAAE,QAAA,EAAU,QAAS,EAAA;AAAA,QAClC,OAAS,EAAA;AAAA,UACP,aAAa,QAAS,CAAA,YAAA;AAAA,UACtB,SAAA,EAAW,SAAS,UAAc,IAAA,QAAA;AAAA,UAClC,OAAO,QAAS,CAAA,KAAA;AAAA,UAChB,kBAAkB,QAAS,CAAA,UAAA;AAAA,UAC3B,SAAS,QAAS,CAAA,QAAA;AAAA,UAClB,cAAc,QAAS,CAAA,aAAA;AAAA,SACzB;AAAA,OACD,CAAA,CAAA;AAAA,KACF,CAAA,CAAA;AAAA,GACH;AAAA,EAEA,MAAM,MAAO,CAAA,KAAA,EAAO,GAAK,EAAA;AACvB,IAAA,MAAM,EAAE,MAAA,EAAW,GAAA,MAAM,GAAI,CAAA,OAAA,CAAA;AAC7B,IAAA,MAAM,SAAS,MAAO,CAAA,MAAA,CAAA;AAQtB,IAAI,IAAA,KAAA,CAAM,YAAgB,IAAA,MAAA,CAAO,mBAAqB,EAAA;AACpD,MAAM,MAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAM,YAAY,CAAA,CAAA;AAAA,KACxC;AAAA,GACF;AACF,CAAC;;;;"} -\ No newline at end of file -+{"version":3,"file":"authenticator.cjs.js","sources":["../src/authenticator.ts"],"sourcesContent":["/*\r\n * Copyright 2023 The Backstage Authors\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\nimport crypto from 'crypto';\r\nimport {\r\n custom,\r\n CustomHttpOptionsProvider,\r\n Issuer,\r\n ClientAuthMethod,\r\n TokenSet,\r\n UserinfoResponse,\r\n Strategy as OidcStrategy,\r\n} from 'openid-client';\r\nimport {\r\n createOAuthAuthenticator,\r\n OAuthAuthenticatorResult,\r\n PassportDoneCallback,\r\n PassportHelpers,\r\n PassportOAuthAuthenticatorHelper,\r\n PassportOAuthPrivateInfo,\r\n} from '@backstage/plugin-auth-node';\r\n\r\nconst HTTP_OPTION_TIMEOUT = 10000;\r\nconst httpOptionsProvider: CustomHttpOptionsProvider = (_url, options) => {\r\n return {\r\n ...options,\r\n timeout: HTTP_OPTION_TIMEOUT,\r\n };\r\n};\r\n\r\n/**\r\n * authentication result for the OIDC which includes the token set and user\r\n * profile response\r\n * @public\r\n */\r\nexport type OidcAuthResult = {\r\n tokenset: TokenSet;\r\n userinfo: UserinfoResponse;\r\n};\r\n\r\n/** @public */\r\nexport const oidcAuthenticator = createOAuthAuthenticator({\r\n defaultProfileTransform: async (\r\n input: OAuthAuthenticatorResult,\r\n ) => ({\r\n profile: {\r\n email: input.fullProfile.userinfo.email,\r\n picture: input.fullProfile.userinfo.picture,\r\n displayName: input.fullProfile.userinfo.name,\r\n },\r\n }),\r\n scopes: {\r\n persist: true,\r\n required: ['openid', 'profile', 'email'],\r\n },\r\n initialize({ callbackUrl, config }) {\r\n const clientId = config.getString('clientId');\r\n const clientSecret = config.getString('clientSecret');\r\n const metadataUrl = config.getString('metadataUrl');\r\n const customCallbackUrl = config.getOptionalString('callbackUrl');\r\n const tokenEndpointAuthMethod = config.getOptionalString(\r\n 'tokenEndpointAuthMethod',\r\n ) as ClientAuthMethod;\r\n const tokenSignedResponseAlg = config.getOptionalString(\r\n 'tokenSignedResponseAlg',\r\n );\r\n const initializedPrompt = config.getOptionalString('prompt');\r\n\r\n if (config.has('scope')) {\r\n throw new Error(\r\n 'The oidc provider no longer supports the \"scope\" configuration option. Please use the \"additionalScopes\" option instead.',\r\n );\r\n }\r\n\r\n Issuer[custom.http_options] = httpOptionsProvider;\r\n const promise = Issuer.discover(metadataUrl).then(issuer => {\r\n issuer[custom.http_options] = httpOptionsProvider;\r\n issuer.Client[custom.http_options] = httpOptionsProvider;\r\n\r\n const client = new issuer.Client({\r\n access_type: 'offline', // this option must be passed to provider to receive a refresh token\r\n client_id: clientId,\r\n client_secret: clientSecret,\r\n redirect_uris: [customCallbackUrl || callbackUrl],\r\n response_types: ['code'],\r\n token_endpoint_auth_method:\r\n tokenEndpointAuthMethod || 'client_secret_basic',\r\n id_token_signed_response_alg: tokenSignedResponseAlg || 'RS256',\r\n });\r\n client[custom.http_options] = httpOptionsProvider;\r\n\r\n const strategy = new OidcStrategy(\r\n {\r\n client,\r\n passReqToCallback: false,\r\n },\r\n (\r\n tokenset: TokenSet,\r\n userinfo: UserinfoResponse,\r\n done: PassportDoneCallback,\r\n ) => {\r\n if (typeof done !== 'function') {\r\n throw new Error(\r\n 'OIDC IdP must provide a userinfo_endpoint in the metadata response',\r\n );\r\n }\r\n\r\n done(\r\n undefined,\r\n { tokenset, userinfo },\r\n { refreshToken: tokenset.refresh_token },\r\n );\r\n },\r\n );\r\n\r\n const helper = PassportOAuthAuthenticatorHelper.from(strategy);\r\n return { helper, client, strategy };\r\n });\r\n\r\n return { initializedPrompt, promise };\r\n },\r\n\r\n async start(input, ctx) {\r\n const { initializedPrompt, promise } = ctx;\r\n const { helper, strategy } = await promise;\r\n const options: Record = {\r\n scope: input.scope,\r\n state: input.state,\r\n nonce: crypto.randomBytes(16).toString('base64'),\r\n };\r\n const prompt = initializedPrompt || 'none';\r\n if (prompt !== 'auto') {\r\n options.prompt = prompt;\r\n }\r\n\r\n return new Promise((resolve, reject) => {\r\n strategy.error = reject;\r\n\r\n return helper\r\n .start(input, {\r\n ...options,\r\n })\r\n .then(resolve);\r\n });\r\n },\r\n\r\n async authenticate(\r\n input,\r\n ctx,\r\n ): Promise> {\r\n const { strategy } = await ctx.promise;\r\n const { result, privateInfo } =\r\n await PassportHelpers.executeFrameHandlerStrategy<\r\n OidcAuthResult,\r\n PassportOAuthPrivateInfo\r\n >(input.req, strategy);\r\n\r\n return {\r\n fullProfile: result,\r\n session: {\r\n accessToken: result.tokenset.access_token!,\r\n tokenType: result.tokenset.token_type ?? 'bearer',\r\n scope: result.tokenset.scope!,\r\n expiresInSeconds: result.tokenset.expires_in,\r\n idToken: result.tokenset.id_token,\r\n refreshToken: privateInfo.refreshToken,\r\n },\r\n };\r\n },\r\n\r\n async refresh(input, ctx) {\r\n const { client } = await ctx.promise;\r\n const tokenset = await client.refresh(input.refreshToken);\r\n if (!tokenset.access_token) {\r\n throw new Error('Refresh failed');\r\n }\r\n const userinfo = await client.userinfo(tokenset.access_token);\r\n\r\n return new Promise((resolve, reject) => {\r\n if (!tokenset.access_token) {\r\n reject(new Error('Refresh Failed'));\r\n }\r\n resolve({\r\n fullProfile: { userinfo, tokenset },\r\n session: {\r\n accessToken: tokenset.access_token!,\r\n tokenType: tokenset.token_type ?? 'bearer',\r\n scope: tokenset.scope!,\r\n expiresInSeconds: tokenset.expires_in,\r\n idToken: tokenset.id_token,\r\n refreshToken: tokenset.refresh_token,\r\n },\r\n });\r\n });\r\n },\r\n\r\n async logout(input, ctx) {\r\n const { client } = await ctx.promise;\r\n const issuer = client.issuer;\r\n /**\r\n * https://github.com/panva/node-openid-client/blob/main/lib/client.js#L1398\r\n * client.revoke will check revocation_endpoint and if undefined throw error。\r\n *\r\n * if oidc server do not provide revocation_endpoint,we should not call revoke function\r\n */\r\n\r\n if (input.refreshToken && issuer.revocation_endpoint) {\r\n await client.revoke(input.refreshToken);\r\n }\r\n },\r\n});\r\n"],"names":["createOAuthAuthenticator","Issuer","custom","OidcStrategy","PassportOAuthAuthenticatorHelper","crypto","PassportHelpers"],"mappings":";;;;;;;;;;AAmCA,MAAM,mBAAsB,GAAA,GAAA,CAAA;AAC5B,MAAM,mBAAA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;AAAA,QAClC,OAAS,EAAA;AAAA,UACP,aAAa,QAAS,CAAA,YAAA;AAAA,UACtB,SAAA,EAAW,SAAS,UAAc,IAAA,QAAA;AAAA,UAClC,OAAO,QAAS,CAAA,KAAA;AAAA,UAChB,kBAAkB,QAAS,CAAA,UAAA;AAAA,UAC3B,SAAS,QAAS,CAAA,QAAA;AAAA,UAClB,cAAc,QAAS,CAAA,aAAA;AAAA,SACzB;AAAA,OACD,CAAA,CAAA;AAAA,KACF,CAAA,CAAA;AAAA,GACH;AAAA,EAEA,MAAM,MAAO,CAAA,KAAA,EAAO,GAAK,EAAA;AACvB,IAAA,MAAM,EAAE,MAAA,EAAW,GAAA,MAAM,GAAI,CAAA,OAAA,CAAA;AAC7B,IAAA,MAAM,SAAS,MAAO,CAAA,MAAA,CAAA;AAQtB,IAAI,IAAA,KAAA,CAAM,YAAgB,IAAA,MAAA,CAAO,mBAAqB,EAAA;AACpD,MAAM,MAAA,MAAA,CAAO,MAAO,CAAA,KAAA,CAAM,YAAY,CAAA,CAAA;AAAA,KACxC;AAAA,GACF;AACF,CAAC;;;;"} -\ No newline at end of file -diff --git a/dist/index.d.ts b/dist/index.d.ts -index bd2eb330b124be25d60f9dd2bb325a5cf02c1761..b8be7582ab706e90f787ee8349306e70d18ede75 100644 ---- a/dist/index.d.ts -+++ b/dist/index.d.ts -@@ -1,5 +1,5 @@ - import * as _backstage_plugin_auth_node from '@backstage/plugin-auth-node'; --import { PassportOAuthAuthenticatorHelper } from '@backstage/plugin-auth-node'; -+import { PassportOAuthAuthenticatorHelper, OAuthAuthenticatorResult } from '@backstage/plugin-auth-node'; - import * as openid_client from 'openid-client'; - import { TokenSet, UserinfoResponse, Strategy } from 'openid-client'; - import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api'; -@@ -44,6 +44,11 @@ declare namespace oidcSignInResolvers { - * as email of the entity. - */ - const emailMatchingUserEntityProfileEmail: _backstage_plugin_auth_node.SignInResolverFactory; -+ /** -+ * A oidc resolver that looks up the user using their preferred username -+ * as the entity name -+ */ -+ const preferredUsernameMatchingUserEntityName: _backstage_plugin_auth_node.SignInResolverFactory, unknown>; - } - - export { type OidcAuthResult, authModuleOidcProvider as default, oidcAuthenticator, oidcSignInResolvers }; -diff --git a/dist/module.cjs.js b/dist/module.cjs.js -index f9dc2ae601a240550c1f975ddd55b94796ae081f..18c95c0b1b8cee1c3afcfcb035397d587cbcf6b6 100644 ---- a/dist/module.cjs.js -+++ b/dist/module.cjs.js -@@ -19,8 +19,7 @@ const authModuleOidcProvider = backendPluginApi.createBackendModule({ - factory: pluginAuthNode.createOAuthProviderFactory({ - authenticator: authenticator.oidcAuthenticator, - signInResolverFactories: { -- ...resolvers.oidcSignInResolvers, -- ...pluginAuthNode.commonSignInResolvers -+ ...resolvers.oidcSignInResolvers - } - }) - }); -diff --git a/dist/module.cjs.js.map b/dist/module.cjs.js.map -index 1f62b0c3a73d65d0618e2a14c5b9e0244d921955..e225d9f66b84b63d0c676e3fa424efe884d5e4f7 100644 ---- a/dist/module.cjs.js.map -+++ b/dist/module.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"module.cjs.js","sources":["../src/module.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { createBackendModule } from '@backstage/backend-plugin-api';\nimport {\n authProvidersExtensionPoint,\n commonSignInResolvers,\n createOAuthProviderFactory,\n} from '@backstage/plugin-auth-node';\nimport { oidcAuthenticator } from './authenticator';\nimport { oidcSignInResolvers } from './resolvers';\n\n/** @public */\nexport const authModuleOidcProvider = createBackendModule({\n pluginId: 'auth',\n moduleId: 'oidc-provider',\n register(reg) {\n reg.registerInit({\n deps: {\n providers: authProvidersExtensionPoint,\n },\n async init({ providers }) {\n providers.registerProvider({\n providerId: 'oidc',\n factory: createOAuthProviderFactory({\n authenticator: oidcAuthenticator,\n signInResolverFactories: {\n ...oidcSignInResolvers,\n ...commonSignInResolvers,\n },\n }),\n });\n },\n });\n },\n});\n"],"names":["createBackendModule","authProvidersExtensionPoint","createOAuthProviderFactory","oidcAuthenticator","oidcSignInResolvers","commonSignInResolvers"],"mappings":";;;;;;;AAyBO,MAAM,yBAAyBA,oCAAoB,CAAA;AAAA,EACxD,QAAU,EAAA,MAAA;AAAA,EACV,QAAU,EAAA,eAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,SAAW,EAAAC,0CAAA;AAAA,OACb;AAAA,MACA,MAAM,IAAA,CAAK,EAAE,SAAA,EAAa,EAAA;AACxB,QAAA,SAAA,CAAU,gBAAiB,CAAA;AAAA,UACzB,UAAY,EAAA,MAAA;AAAA,UACZ,SAASC,yCAA2B,CAAA;AAAA,YAClC,aAAe,EAAAC,+BAAA;AAAA,YACf,uBAAyB,EAAA;AAAA,cACvB,GAAGC,6BAAA;AAAA,cACH,GAAGC,oCAAA;AAAA,aACL;AAAA,WACD,CAAA;AAAA,SACF,CAAA,CAAA;AAAA,OACH;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;"} -\ No newline at end of file -+{"version":3,"file":"module.cjs.js","sources":["../src/module.ts"],"sourcesContent":["/*\r\n * Copyright 2023 The Backstage Authors\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nimport { createBackendModule } from '@backstage/backend-plugin-api';\r\nimport {\r\n authProvidersExtensionPoint,\r\n createOAuthProviderFactory\r\n} from '@backstage/plugin-auth-node';\r\nimport { oidcAuthenticator } from './authenticator';\r\nimport { oidcSignInResolvers } from './resolvers';\r\n\r\n/** @public */\r\nexport const authModuleOidcProvider = createBackendModule({\r\n pluginId: 'auth',\r\n moduleId: 'oidc-provider',\r\n register(reg) {\r\n reg.registerInit({\r\n deps: {\r\n providers: authProvidersExtensionPoint,\r\n },\r\n async init({ providers }) {\r\n providers.registerProvider({\r\n providerId: 'oidc',\r\n factory: createOAuthProviderFactory({\r\n authenticator: oidcAuthenticator,\r\n signInResolverFactories: {\r\n ...oidcSignInResolvers,\r\n },\r\n }),\r\n });\r\n },\r\n });\r\n },\r\n});\r\n"],"names":["createBackendModule","authProvidersExtensionPoint","createOAuthProviderFactory","oidcAuthenticator","oidcSignInResolvers"],"mappings":";;;;;;;AAwBO,MAAM,yBAAyBA,oCAAoB,CAAA;AAAA,EACxD,QAAU,EAAA,MAAA;AAAA,EACV,QAAU,EAAA,eAAA;AAAA,EACV,SAAS,GAAK,EAAA;AACZ,IAAA,GAAA,CAAI,YAAa,CAAA;AAAA,MACf,IAAM,EAAA;AAAA,QACJ,SAAW,EAAAC,0CAAA;AAAA,OACb;AAAA,MACA,MAAM,IAAA,CAAK,EAAE,SAAA,EAAa,EAAA;AACxB,QAAA,SAAA,CAAU,gBAAiB,CAAA;AAAA,UACzB,UAAY,EAAA,MAAA;AAAA,UACZ,SAASC,yCAA2B,CAAA;AAAA,YAClC,aAAe,EAAAC,+BAAA;AAAA,YACf,uBAAyB,EAAA;AAAA,cACvB,GAAGC,6BAAA;AAAA,aACL;AAAA,WACD,CAAA;AAAA,SACF,CAAA,CAAA;AAAA,OACH;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACF,CAAC;;;;"} -\ No newline at end of file -diff --git a/dist/resolvers.cjs.js b/dist/resolvers.cjs.js -index 380a9624cb461b3782fc319d7722dc1da1c442d7..dc3ebe39b74807c3b0a94835030a89640d7ce976 100644 ---- a/dist/resolvers.cjs.js -+++ b/dist/resolvers.cjs.js -@@ -6,5 +6,16 @@ exports.oidcSignInResolvers = void 0; - ((oidcSignInResolvers2) => { - oidcSignInResolvers2.emailLocalPartMatchingUserEntityName = pluginAuthNode.commonSignInResolvers.emailLocalPartMatchingUserEntityName; - oidcSignInResolvers2.emailMatchingUserEntityProfileEmail = pluginAuthNode.commonSignInResolvers.emailMatchingUserEntityProfileEmail; -+ oidcSignInResolvers2.preferredUsernameMatchingUserEntityName = pluginAuthNode.createSignInResolverFactory({ -+ create() { -+ return async (info, ctx) => { -+ const userId = info.result.fullProfile.userinfo.preferred_username; -+ if (!userId) { -+ throw new Error(`OIDC user profile does not contain a username`); -+ } -+ return ctx.signInWithCatalogUser({ entityRef: { name: userId } }); -+ }; -+ } -+ }); - })(exports.oidcSignInResolvers || (exports.oidcSignInResolvers = {})); - //# sourceMappingURL=resolvers.cjs.js.map -diff --git a/dist/resolvers.cjs.js.map b/dist/resolvers.cjs.js.map -index b345faec13e95559fa23cb3fefb8d657b04a48ff..e631e22279a30f7efe136db9d0ae170bce1b329a 100644 ---- a/dist/resolvers.cjs.js.map -+++ b/dist/resolvers.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"resolvers.cjs.js","sources":["../src/resolvers.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { commonSignInResolvers } from '@backstage/plugin-auth-node';\n\n/**\n * Available sign-in resolvers for the Oidc auth provider.\n *\n * @public\n */\nexport namespace oidcSignInResolvers {\n /**\n * A oidc resolver that looks up the user using the local part of\n * their email address as the entity name.\n */\n export const emailLocalPartMatchingUserEntityName =\n commonSignInResolvers.emailLocalPartMatchingUserEntityName;\n\n /**\n * A oidc resolver that looks up the user using their email address\n * as email of the entity.\n */\n export const emailMatchingUserEntityProfileEmail =\n commonSignInResolvers.emailMatchingUserEntityProfileEmail;\n}\n"],"names":["oidcSignInResolvers","commonSignInResolvers"],"mappings":";;;;AAuBiBA,qCAAA;AAAA,CAAV,CAAUA,oBAAV,KAAA;AAKE,EAAMA,oBAAAA,CAAA,uCACXC,oCAAsB,CAAA,oCAAA,CAAA;AAMjB,EAAMD,oBAAAA,CAAA,sCACXC,oCAAsB,CAAA,mCAAA,CAAA;AAAA,CAbT,EAAAD,2BAAA,KAAAA,2BAAA,GAAA,EAAA,CAAA,CAAA;;"} -\ No newline at end of file -+{"version":3,"file":"resolvers.cjs.js","sources":["../src/resolvers.ts"],"sourcesContent":["/*\r\n * Copyright 2023 The Backstage Authors\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n\r\nimport {\r\n AuthResolverContext,\r\n OAuthAuthenticatorResult,\r\n SignInInfo,\r\n commonSignInResolvers,\r\n createSignInResolverFactory,\r\n} from '@backstage/plugin-auth-node';\r\nimport { OidcAuthResult } from './authenticator';\r\n\r\n/**\r\n * Available sign-in resolvers for the Oidc auth provider.\r\n *\r\n * @public\r\n */\r\nexport namespace oidcSignInResolvers {\r\n /**\r\n * A oidc resolver that looks up the user using the local part of\r\n * their email address as the entity name.\r\n */\r\n export const emailLocalPartMatchingUserEntityName =\r\n commonSignInResolvers.emailLocalPartMatchingUserEntityName;\r\n\r\n /**\r\n * A oidc resolver that looks up the user using their email address\r\n * as email of the entity.\r\n */\r\n export const emailMatchingUserEntityProfileEmail =\r\n commonSignInResolvers.emailMatchingUserEntityProfileEmail;\r\n\r\n /**\r\n* A oidc resolver that looks up the user using their preferred username\r\n* as the entity name\r\n*/\r\n export const preferredUsernameMatchingUserEntityName =\r\n createSignInResolverFactory({\r\n create() {\r\n return async (\r\n info: SignInInfo>,\r\n ctx: AuthResolverContext,\r\n ) => {\r\n const userId = info.result.fullProfile.userinfo.preferred_username;\r\n\r\n if (!userId) {\r\n throw new Error(`OIDC user profile does not contain a username`);\r\n }\r\n return ctx.signInWithCatalogUser({ entityRef: { name: userId } });\r\n };\r\n },\r\n });\r\n}\r\n\r\n"],"names":["oidcSignInResolvers","commonSignInResolvers","createSignInResolverFactory"],"mappings":";;;;AA8BiBA,qCAAA;AAAA,CAAV,CAAUA,oBAAV,KAAA;AAKE,EAAMA,oBAAAA,CAAA,uCACXC,oCAAsB,CAAA,oCAAA,CAAA;AAMjB,EAAMD,oBAAAA,CAAA,sCACXC,oCAAsB,CAAA,mCAAA,CAAA;AAMjB,EAAMD,oBAAAA,CAAA,0CACXE,0CAA4B,CAAA;AAAA,IAC1B,MAAS,GAAA;AACP,MAAO,OAAA,OACL,MACA,GACG,KAAA;AACH,QAAA,MAAM,MAAS,GAAA,IAAA,CAAK,MAAO,CAAA,WAAA,CAAY,QAAS,CAAA,kBAAA,CAAA;AAEhD,QAAA,IAAI,CAAC,MAAQ,EAAA;AACX,UAAM,MAAA,IAAI,MAAM,CAA+C,6CAAA,CAAA,CAAA,CAAA;AAAA,SACjE;AACA,QAAO,OAAA,GAAA,CAAI,sBAAsB,EAAE,SAAA,EAAW,EAAE,IAAM,EAAA,MAAA,IAAU,CAAA,CAAA;AAAA,OAClE,CAAA;AAAA,KACF;AAAA,GACD,CAAA,CAAA;AAAA,CAlCY,EAAAF,2BAAA,KAAAA,2BAAA,GAAA,EAAA,CAAA,CAAA;;"} -\ No newline at end of file diff --git a/.yarn/patches/@backstage-plugin-catalog-backend-npm-1.27.1-4a70d05379.patch b/.yarn/patches/@backstage-plugin-catalog-backend-npm-1.27.1-4a70d05379.patch deleted file mode 100644 index 9f71ddb9..00000000 --- a/.yarn/patches/@backstage-plugin-catalog-backend-npm-1.27.1-4a70d05379.patch +++ /dev/null @@ -1,1225 +0,0 @@ -diff --git a/dist/service/createRouter.cjs.js b/dist/service/createRouter.cjs.js -index 87c8651bca6953c2eb65181a8657f32b2250a017..b3c556992c5f4c14b5ae54c1cc81d46346829abb 100644 ---- a/dist/service/createRouter.cjs.js -+++ b/dist/service/createRouter.cjs.js -@@ -17,6 +17,7 @@ var util = require('./util.cjs.js'); - var openapi_generated = require('../schema/openapi.generated.cjs.js'); - var parseEntityPaginationParams = require('./request/parseEntityPaginationParams.cjs.js'); - var AuthorizedValidationService = require('./AuthorizedValidationService.cjs.js'); -+var backstagePluginAuditLogNode = require('@janus-idp/backstage-plugin-audit-log-node'); - - function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; } - -@@ -43,6 +44,11 @@ async function createRouter(options) { - auth, - httpAuth - } = options; -+ const auditLogger = new backstagePluginAuditLogNode.DefaultAuditLogger({ -+ logger, -+ authService: auth, -+ httpAuthService: httpAuth -+ }); - const readonlyEnabled = config.getOptionalBoolean("catalog.readonly") || false; - if (readonlyEnabled) { - logger.info("Catalog is running in readonly mode"); -@@ -50,12 +56,61 @@ async function createRouter(options) { - if (refreshService) { - router.post("/refresh", async (req, res) => { - const { authorizationToken, ...restBody } = req.body; -- const credentials = authorizationToken ? await auth.authenticate(authorizationToken) : await httpAuth.credentials(req); -- await refreshService.refresh({ -- ...restBody, -- credentials -- }); -- res.status(200).end(); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityRefresh", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ metadata: { -+ entityRef: restBody.entityRef -+ }, -+ request: req, -+ message: `Refresh attempt for ${restBody.entityRef} initiated by ${actorId}` -+ }); -+ const credentials = authorizationToken ? await auth.authenticate(authorizationToken) : await httpAuth.credentials(req); -+ await refreshService.refresh({ -+ ...restBody, -+ credentials -+ }); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityRefresh", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ metadata: { -+ entityRef: restBody.entityRef -+ }, -+ response: { -+ status: 200 -+ }, -+ request: req, -+ message: `Refresh attempt for ${restBody.entityRef} triggered by ${actorId}` -+ }); -+ res.status(200).end(); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityRefresh", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ metadata: { -+ entityRef: restBody.entityRef -+ }, -+ request: req, -+ message: `Refresh attempt for ${restBody.entityRef} by ${actorId} failed` -+ }); -+ throw err; -+ } - }); - } - if (permissionIntegrationRouter) { -@@ -63,217 +118,965 @@ async function createRouter(options) { - } - if (entitiesCatalog) { - router.get("/entities", async (req, res) => { -- const { entities, pageInfo } = await entitiesCatalog.entities({ -- filter: parseEntityFilterParams.parseEntityFilterParams(req.query), -- fields: parseEntityTransformParams.parseEntityTransformParams(req.query), -- order: parseEntityOrderParams.parseEntityOrderParams(req.query), -- pagination: parseEntityPaginationParams.parseEntityPaginationParams(req.query), -- credentials: await httpAuth.credentials(req) -- }); -- if (pageInfo.hasNextPage) { -- const url = new URL(`http://ignored${req.url}`); -- url.searchParams.delete("offset"); -- url.searchParams.set("after", pageInfo.endCursor); -- res.setHeader("link", `<${url.pathname}${url.search}>; rel="next"`); -+ const actorId = await auditLogger.getActorId( -+ req -+ ); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetch", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ message: `Entity fetch attempt initiated by ${actorId}` -+ }); -+ const { entities, pageInfo } = await entitiesCatalog.entities({ -+ filter: parseEntityFilterParams.parseEntityFilterParams(req.query), -+ fields: parseEntityTransformParams.parseEntityTransformParams(req.query), -+ order: parseEntityOrderParams.parseEntityOrderParams(req.query), -+ pagination: parseEntityPaginationParams.parseEntityPaginationParams(req.query), -+ credentials: await httpAuth.credentials(req) -+ }); -+ if (pageInfo.hasNextPage) { -+ const url = new URL(`http://ignored${req.url}`); -+ url.searchParams.delete("offset"); -+ url.searchParams.set("after", pageInfo.endCursor); -+ res.setHeader("link", `<${url.pathname}${url.search}>; rel="next"`); -+ } -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetch", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ // Let's not log out the entities since this can make the log very big due to it not being paged? -+ response: { -+ status: 200 -+ }, -+ message: `Entity fetch attempt by ${actorId} succeeded` -+ }); -+ res.json(entities); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetch", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Entity fetch attempt by ${actorId} failed` -+ }); -+ throw err; - } -- res.json(entities); - }).get("/entities/by-query", async (req, res) => { -- const { items, pageInfo, totalItems } = await entitiesCatalog.queryEntities({ -- limit: req.query.limit, -- offset: req.query.offset, -- ...parseQueryEntitiesParams.parseQueryEntitiesParams(req.query), -- credentials: await httpAuth.credentials(req) -- }); -- res.json({ -- items, -- totalItems, -- pageInfo: { -- ...pageInfo.nextCursor && { -- nextCursor: util.encodeCursor(pageInfo.nextCursor) -- }, -- ...pageInfo.prevCursor && { -- prevCursor: util.encodeCursor(pageInfo.prevCursor) -+ const actorId = await auditLogger.getActorId( -+ req -+ ); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "QueriedCatalogEntityFetch", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ message: `Queried entity fetch attempt initiated by ${actorId}` -+ }); -+ const { items, pageInfo, totalItems } = await entitiesCatalog.queryEntities({ -+ limit: req.query.limit, -+ ...parseQueryEntitiesParams.parseQueryEntitiesParams(req.query), -+ credentials: await httpAuth.credentials(req) -+ }); -+ res.json({ -+ items, -+ totalItems, -+ pageInfo: { -+ ...pageInfo.nextCursor && { -+ nextCursor: util.encodeCursor(pageInfo.nextCursor) -+ }, -+ ...pageInfo.prevCursor && { -+ prevCursor: util.encodeCursor(pageInfo.prevCursor) -+ } - } -- } -- }); -+ }); -+ await auditLogger.auditLog({ -+ eventName: "QueriedCatalogEntityFetch", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ metadata: { -+ totalEntities: totalItems, -+ pageInfo: { -+ ...pageInfo.nextCursor && { -+ nextCursor: util.encodeCursor(pageInfo.nextCursor) -+ }, -+ ...pageInfo.prevCursor && { -+ prevCursor: util.encodeCursor(pageInfo.prevCursor) -+ } -+ } -+ }, -+ // Let's not log out the entities since this can make the log very big -+ response: { -+ status: 200 -+ }, -+ message: `Queried entity fetch attempt by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "QueriedCatalogEntityFetch", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Queried entity fetch attempt by ${actorId} failed` -+ }); -+ throw err; -+ } - }).get("/entities/by-uid/:uid", async (req, res) => { - const { uid } = req.params; -- const { entities } = await entitiesCatalog.entities({ -- filter: basicEntityFilter.basicEntityFilter({ "metadata.uid": uid }), -- credentials: await httpAuth.credentials(req) -- }); -- if (!entities.length) { -- throw new errors.NotFoundError(`No entity with uid ${uid}`); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetchByUid", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ metadata: { -+ uid -+ }, -+ message: `Fetch attempt for entity with uid ${uid} initiated by ${actorId}` -+ }); -+ const { entities } = await entitiesCatalog.entities({ -+ filter: basicEntityFilter.basicEntityFilter({ "metadata.uid": uid }), -+ credentials: await httpAuth.credentials(req) -+ }); -+ if (!entities.length) { -+ throw new errors.NotFoundError(`No entity with uid ${uid}`); -+ } -+ res.status(200).json(entities[0]); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetchByUid", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ metadata: { -+ uid, -+ entityRef: catalogModel.stringifyEntityRef(entities[0]) -+ }, -+ response: { -+ status: 200 -+ }, -+ message: `Fetch attempt for entity with uid ${uid} by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetchByUid", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ request: req, -+ metadata: { -+ uid -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Fetch attempt for entity with uid ${uid} by ${actorId} failed` -+ }); -+ throw err; - } -- res.status(200).json(entities[0]); - }).delete("/entities/by-uid/:uid", async (req, res) => { - const { uid } = req.params; -- await entitiesCatalog.removeEntityByUid(uid, { -- credentials: await httpAuth.credentials(req) -- }); -- res.status(204).end(); -+ const actorId = await auditLogger.getActorId(req); -+ let entityRef; -+ try { -+ const { entities } = await entitiesCatalog.entities({ -+ filter: basicEntityFilter.basicEntityFilter({ "metadata.uid": uid }), -+ credentials: await httpAuth.credentials(req) -+ }); -+ if (entities.length) { -+ entityRef = catalogModel.stringifyEntityRef(entities[0]); -+ } -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityDeletion", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ metadata: { -+ uid, -+ entityRef -+ }, -+ message: `Deletion attempt for entity with uid ${uid} initiated by ${actorId}` -+ }); -+ await entitiesCatalog.removeEntityByUid(uid, { -+ credentials: await httpAuth.credentials(req) -+ }); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityDeletion", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ metadata: { -+ uid, -+ entityRef -+ }, -+ response: { -+ status: 204 -+ }, -+ message: `Deletion attempt for entity with uid ${uid} by ${actorId} succeeded` -+ }); -+ res.status(204).end(); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityDeletion", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Deletion attempt for entity with uid ${uid} by ${actorId} failed` -+ }); -+ throw err; -+ } - }).get("/entities/by-name/:kind/:namespace/:name", async (req, res) => { - const { kind, namespace, name } = req.params; -- const { entities } = await entitiesCatalog.entities({ -- filter: basicEntityFilter.basicEntityFilter({ -- kind, -- "metadata.namespace": namespace, -- "metadata.name": name -- }), -- credentials: await httpAuth.credentials(req) -- }); -- if (!entities.length) { -- throw new errors.NotFoundError( -- `No entity named '${name}' found, with kind '${kind}' in namespace '${namespace}'` -- ); -+ const entityRef = catalogModel.stringifyEntityRef({ kind, namespace, name }); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetchByName", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ metadata: { -+ entityRef -+ }, -+ message: `Fetch attempt for entity with entityRef ${entityRef} initiated by ${actorId}` -+ }); -+ const { entities } = await entitiesCatalog.entities({ -+ filter: basicEntityFilter.basicEntityFilter({ -+ kind, -+ "metadata.namespace": namespace, -+ "metadata.name": name -+ }), -+ credentials: await httpAuth.credentials(req) -+ }); -+ if (!entities.length) { -+ throw new errors.NotFoundError( -+ `No entity named '${name}' found, with kind '${kind}' in namespace '${namespace}'` -+ ); -+ } -+ res.status(200).json(entities[0]); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetchByName", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ metadata: { -+ entityRef -+ }, -+ response: { -+ status: 200 -+ }, -+ message: `Fetch attempt for entity with entityRef ${entityRef} by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFetchByName", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ request: req, -+ metadata: { -+ entityRef -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Fetch attempt for entity with entityRef ${entityRef} by ${actorId} failed` -+ }); -+ throw err; - } -- res.status(200).json(entities[0]); - }).get( - "/entities/by-name/:kind/:namespace/:name/ancestry", - async (req, res) => { - const { kind, namespace, name } = req.params; - const entityRef = catalogModel.stringifyEntityRef({ kind, namespace, name }); -- const response = await entitiesCatalog.entityAncestry(entityRef, { -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityAncestryFetch", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ metadata: { -+ entityRef -+ }, -+ message: `Fetch attempt for entity ancestor of entity ${entityRef} initiated by ${actorId}` -+ }); -+ const response = await entitiesCatalog.entityAncestry(entityRef, { -+ credentials: await httpAuth.credentials(req) -+ }); -+ res.status(200).json(response); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityAncestryFetch", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ metadata: { -+ rootEntityRef: response.rootEntityRef, -+ ancestry: response.items.map((ancestryLink) => { -+ return { -+ entityRef: catalogModel.stringifyEntityRef(ancestryLink.entity), -+ parentEntityRefs: ancestryLink.parentEntityRefs -+ }; -+ }) -+ }, -+ response: { -+ status: 200 -+ }, -+ message: `Fetch attempt for entity ancestor of entity ${entityRef} by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityAncestryFetch", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ request: req, -+ metadata: { -+ entityRef -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Fetch attempt for entity ancestor of entity ${entityRef} by ${actorId} failed` -+ }); -+ throw err; -+ } -+ } -+ ).post("/entities/by-refs", async (req, res) => { -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityBatchFetch", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ message: `Batch entity fetch attempt initiated by ${actorId}` -+ }); -+ const request = entitiesBatchRequest.entitiesBatchRequest(req); -+ const response = await entitiesCatalog.entitiesBatch({ -+ entityRefs: request.entityRefs, -+ filter: parseEntityFilterParams.parseEntityFilterParams(req.query), -+ fields: parseEntityTransformParams.parseEntityTransformParams(req.query, request.fields), - credentials: await httpAuth.credentials(req) - }); - res.status(200).json(response); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityBatchFetch", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ metadata: { -+ ...request -+ }, -+ response: { -+ status: 200 -+ }, -+ message: `Batch entity fetch attempt by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityBatchFetch", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Batch entity fetch attempt by ${actorId} failed` -+ }); -+ throw err; - } -- ).post("/entities/by-refs", async (req, res) => { -- const request = entitiesBatchRequest.entitiesBatchRequest(req); -- const response = await entitiesCatalog.entitiesBatch({ -- entityRefs: request.entityRefs, -- filter: parseEntityFilterParams.parseEntityFilterParams(req.query), -- fields: parseEntityTransformParams.parseEntityTransformParams(req.query, request.fields), -- credentials: await httpAuth.credentials(req) -- }); -- res.status(200).json(response); - }).get("/entity-facets", async (req, res) => { -- const response = await entitiesCatalog.facets({ -- filter: parseEntityFilterParams.parseEntityFilterParams(req.query), -- facets: parseEntityFacetParams.parseEntityFacetParams(req.query), -- credentials: await httpAuth.credentials(req) -- }); -- res.status(200).json(response); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFacetFetch", -+ actorId, -+ status: "succeeded", -+ stage: "initiation", -+ request: req, -+ message: `Entity facet fetch attempt initiated by ${actorId}` -+ }); -+ const response = await entitiesCatalog.facets({ -+ filter: parseEntityFilterParams.parseEntityFilterParams(req.query), -+ facets: parseEntityFacetParams.parseEntityFacetParams(req.query), -+ credentials: await httpAuth.credentials(req) -+ }); -+ res.status(200).json(response); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFacetFetch", -+ actorId, -+ status: "succeeded", -+ stage: "completion", -+ request: req, -+ response: { status: 200 }, -+ message: `Entity facet fetch attempt by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityFacetFetch", -+ actorId, -+ status: "failed", -+ stage: "completion", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Entity facet fetch attempt by ${actorId} failed` -+ }); -+ throw err; -+ } - }); - } - if (locationService) { - router.post("/locations", async (req, res) => { -+ const credentials = await httpAuth.credentials(req); -+ const actorId = await auditLogger.getActorId(req); - const location = await util.validateRequestBody(req, util.locationInput); - const dryRun = yn__default.default(req.query.dryRun, { default: false }); -- if (!dryRun) { -- util.disallowReadonlyMode(readonlyEnabled); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationCreation", -+ status: "succeeded", -+ stage: "initiation", -+ actorId, -+ metadata: { -+ location, -+ isDryRun: dryRun -+ }, -+ request: req, -+ message: `Creation attempt of location entity for ${location.target} initiated by ${actorId}` -+ }); -+ if (!dryRun) { -+ util.disallowReadonlyMode(readonlyEnabled); -+ } -+ const output = await locationService.createLocation( -+ location, -+ dryRun, -+ { -+ credentials -+ } -+ ); -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationCreation", -+ status: "succeeded", -+ stage: "completion", -+ actorId, -+ metadata: { -+ location: output.location, -+ isDryRun: dryRun -+ }, -+ request: req, -+ response: { -+ status: 201 -+ }, -+ message: `Creation of location entity for ${location.target} initiated by ${actorId} succeeded` -+ }); -+ res.status(201).json(output); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationCreation", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ actorId, -+ metadata: { -+ location, -+ isDryRun: dryRun -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ request: req, -+ message: `Creation of location entity for ${location.target} initiated by ${actorId} failed` -+ }); -+ throw err; - } -- const output = await locationService.createLocation(location, dryRun, { -- credentials: await httpAuth.credentials(req) -- }); -- res.status(201).json(output); - }).get("/locations", async (req, res) => { -- const locations = await locationService.listLocations({ -- credentials: await httpAuth.credentials(req) -- }); -- res.status(200).json(locations.map((l) => ({ data: l }))); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetch", -+ status: "succeeded", -+ stage: "initiation", -+ actorId, -+ request: req, -+ message: `Fetch attempt of locations initiated by ${actorId}` -+ }); -+ const locations = await locationService.listLocations({ -+ credentials: await httpAuth.credentials(req) -+ }); -+ res.status(200).json(locations.map((l) => ({ data: l }))); -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetch", -+ status: "succeeded", -+ stage: "completion", -+ actorId, -+ request: req, -+ response: { -+ status: 200 -+ }, -+ message: `Fetch attempt of locations by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetch", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ actorId, -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Fetch attempt of locations by ${actorId} failed` -+ }); -+ throw err; -+ } - }).get("/locations/:id", async (req, res) => { - const { id } = req.params; -- const output = await locationService.getLocation(id, { -- credentials: await httpAuth.credentials(req) -- }); -- res.status(200).json(output); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetchById", -+ status: "succeeded", -+ stage: "initiation", -+ actorId, -+ metadata: { -+ id -+ }, -+ request: req, -+ message: `Fetch attempt of location with id: ${id} initiated by ${actorId}` -+ }); -+ const output = await locationService.getLocation(id, { -+ credentials: await httpAuth.credentials(req) -+ }); -+ res.status(200).json(output); -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetchById", -+ status: "succeeded", -+ stage: "completion", -+ actorId, -+ metadata: { -+ id -+ }, -+ response: { -+ status: 200, -+ body: output -+ }, -+ request: req, -+ message: `Fetch attempt of location with id: ${id} by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetchById", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ actorId, -+ metadata: { -+ id -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ request: req, -+ message: `Fetch attempt of location with id: ${id} by ${actorId} failed` -+ }); -+ throw err; -+ } - }).delete("/locations/:id", async (req, res) => { -- util.disallowReadonlyMode(readonlyEnabled); -+ const actorId = await auditLogger.getActorId(req); - const { id } = req.params; -- await locationService.deleteLocation(id, { -- credentials: await httpAuth.credentials(req) -- }); -- res.status(204).end(); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationDeletion", -+ status: "succeeded", -+ stage: "initiation", -+ actorId, -+ metadata: { -+ id -+ }, -+ request: req, -+ message: `Deletion attempt of location with id: ${id} initiated by ${actorId}` -+ }); -+ util.disallowReadonlyMode(readonlyEnabled); -+ const location = await locationService.getLocation(id, { -+ credentials: await httpAuth.credentials(req) -+ }); -+ await locationService.deleteLocation(id, { -+ credentials: await httpAuth.credentials(req) -+ }); -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationDeletion", -+ status: "succeeded", -+ stage: "completion", -+ actorId, -+ metadata: { -+ location -+ }, -+ response: { -+ status: 204 -+ }, -+ request: req, -+ message: `Deletion attempt of location with id: ${id} by ${actorId} succeeded` -+ }); -+ res.status(204).end(); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationDeletion", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ actorId, -+ metadata: { -+ id -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ request: req, -+ message: `Deletion attempt of location with id: ${id} by ${actorId} failed` -+ }); -+ throw err; -+ } - }).get("/locations/by-entity/:kind/:namespace/:name", async (req, res) => { - const { kind, namespace, name } = req.params; -- const output = await locationService.getLocationByEntity( -- { kind, namespace, name }, -- { credentials: await httpAuth.credentials(req) } -- ); -- res.status(200).json(output); -+ const actorId = await auditLogger.getActorId(req); -+ const locationRef = `${kind}:${namespace}/${name}`; -+ try { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetchByEntityRef", -+ status: "succeeded", -+ stage: "initiation", -+ actorId, -+ metadata: { -+ locationRef -+ }, -+ request: req, -+ message: `Fetch attempt for location ${locationRef} initiated by ${actorId}` -+ }); -+ const output = await locationService.getLocationByEntity( -+ { kind, namespace, name }, -+ { credentials: await httpAuth.credentials(req) } -+ ); -+ res.status(200).json(output); -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetchByEntityRef", -+ status: "succeeded", -+ stage: "completion", -+ actorId, -+ metadata: { -+ locationRef -+ }, -+ response: { -+ status: 200, -+ body: output -+ }, -+ request: req, -+ message: `Fetch attempt for location ${locationRef} by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationFetchByEntityRef", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ actorId, -+ metadata: { -+ locationRef -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ request: req, -+ message: `Fetch attempt for location ${locationRef} by ${actorId} failed` -+ }); -+ throw err; -+ } - }); - } - if (locationAnalyzer) { - router.post("/analyze-location", async (req, res) => { -- const body = await util.validateRequestBody( -- req, -- zod.z.object({ -- location: util.locationInput, -- catalogFilename: zod.z.string().optional() -- }) -- ); -- const schema = zod.z.object({ -- location: util.locationInput, -- catalogFilename: zod.z.string().optional() -- }); -- const credentials = await httpAuth.credentials(req); -- const parsedBody = schema.parse(body); -+ const actorId = await auditLogger.getActorId(req); - try { -- const output = await locationAnalyzer.analyzeLocation( -- parsedBody, -- credentials -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationAnalyze", -+ status: "succeeded", -+ stage: "initiation", -+ actorId, -+ request: req, -+ message: `Analyze location for location initiated by ${actorId}` -+ }); -+ const body = await util.validateRequestBody( -+ req, -+ zod.z.object({ -+ location: util.locationInput, -+ catalogFilename: zod.z.string().optional() -+ }) - ); -- res.status(200).json(output); -- } catch (err) { -- if ( -- // Catch errors from parse-url library. -- err.name === "Error" && "subject_url" in err -- ) { -- throw new errors.InputError("The given location.target is not a URL"); -+ const schema = zod.z.object({ -+ location: util.locationInput, -+ catalogFilename: zod.z.string().optional() -+ }); -+ const credentials = await httpAuth.credentials(req); -+ const parsedBody = schema.parse(body); -+ try { -+ const output = await locationAnalyzer.analyzeLocation( -+ parsedBody, -+ credentials -+ ); -+ res.status(200).json(output); -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationAnalyze", -+ status: "succeeded", -+ stage: "completion", -+ actorId, -+ request: req, -+ response: { -+ status: 200, -+ body: output -+ }, -+ message: `Analyze location for location by ${actorId} succeeded` -+ }); -+ } catch (err) { -+ if ( -+ // Catch errors from parse-url library. -+ err.name === "Error" && "subject_url" in err -+ ) { -+ throw new errors.InputError("The given location.target is not a URL"); -+ } -+ throw err; - } -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogLocationAnalyze", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ actorId, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ request: req, -+ message: `Analyze location for location by ${actorId} failed` -+ }); - throw err; - } - }); - } - if (orchestrator) { - router.post("/validate-entity", async (req, res) => { -- const bodySchema = zod.z.object({ -- entity: zod.z.unknown(), -- location: zod.z.string() -- }); -- let body; -- let entity; -- let location; -+ const actorId = await auditLogger.getActorId(req); - try { -- body = await util.validateRequestBody(req, bodySchema); -- entity = util$1.validateEntityEnvelope(body.entity); -- location = catalogModel.parseLocationRef(body.location); -- if (location.type !== "url") -- throw new TypeError( -- `Invalid location ref ${body.location}, only 'url:' is supported, e.g. url:https://host/path` -- ); -- } catch (err) { -- return res.status(400).json({ -- errors: [errors.serializeError(err)] -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityValidate", -+ status: "succeeded", -+ stage: "initiation", -+ actorId, -+ request: req, -+ message: `Entity validation for entity initiated by ${actorId}` - }); -- } -- const credentials = await httpAuth.credentials(req); -- const authorizedValidationService = new AuthorizedValidationService.AuthorizedValidationService( -- orchestrator, -- permissionsService -- ); -- const processingResult = await authorizedValidationService.process( -- { -- entity: { -- ...entity, -- metadata: { -- ...entity.metadata, -- annotations: { -- [catalogModel.ANNOTATION_LOCATION]: body.location, -- [catalogModel.ANNOTATION_ORIGIN_LOCATION]: body.location, -- ...entity.metadata.annotations -+ const bodySchema = zod.z.object({ -+ entity: zod.z.unknown(), -+ location: zod.z.string() -+ }); -+ let body; -+ let entity; -+ let location; -+ try { -+ body = await util.validateRequestBody(req, bodySchema); -+ entity = util$1.validateEntityEnvelope(body.entity); -+ location = catalogModel.parseLocationRef(body.location); -+ if (location.type !== "url") -+ throw new TypeError( -+ `Invalid location ref ${body.location}, only 'url:' is supported, e.g. url:https://host/path` -+ ); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityValidate", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ actorId, -+ request: req, -+ message: `Entity validation for entity initiated by ${actorId} failed` -+ }); -+ return res.status(400).json({ -+ errors: [errors.serializeError(err)] -+ }); -+ } -+ const credentials = await httpAuth.credentials(req); -+ const authorizedValidationService = new AuthorizedValidationService.AuthorizedValidationService( -+ orchestrator, -+ permissionsService -+ ); -+ const processingResult = await authorizedValidationService.process( -+ { -+ entity: { -+ ...entity, -+ metadata: { -+ ...entity.metadata, -+ annotations: { -+ [catalogModel.ANNOTATION_LOCATION]: body.location, -+ [catalogModel.ANNOTATION_ORIGIN_LOCATION]: body.location, -+ ...entity.metadata.annotations -+ } - } - } -- } -- }, -- credentials -- ); -- if (!processingResult.ok) -- res.status(400).json({ -- errors: processingResult.errors.map((e) => errors.serializeError(e)) -+ }, -+ credentials -+ ); -+ if (!processingResult.ok) { -+ const errors$1 = processingResult.errors.map((e) => errors.serializeError(e)); -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityValidate", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ errors: errors$1, -+ response: { -+ status: 400 -+ }, -+ actorId, -+ request: req, -+ message: `Entity validation for entity initiated by ${actorId} failed` -+ }); -+ return res.status(400).json({ -+ errors: errors$1 -+ }); -+ } -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityValidate", -+ status: "succeeded", -+ stage: "completion", -+ actorId, -+ response: { -+ status: 200 -+ }, -+ request: req, -+ message: `Entity validation for entity by ${actorId} succeeded` - }); -- return res.status(200).end(); -+ return res.status(200).end(); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "CatalogEntityValidate", -+ status: "failed", -+ stage: "completion", -+ level: "error", -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ actorId, -+ request: req, -+ message: `Entity validation for entity initiated by ${actorId} failed` -+ }); -+ throw err; -+ } - }); - } - router.use(backendCommon.errorHandler()); -diff --git a/dist/service/createRouter.cjs.js.map b/dist/service/createRouter.cjs.js.map -index d99c14b522abceb4b397ecb4aede3b53a5f51e04..d4313425f9e28b91aabf58c2434a267879e08d6d 100644 ---- a/dist/service/createRouter.cjs.js.map -+++ b/dist/service/createRouter.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"createRouter.cjs.js","sources":["../../src/service/createRouter.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorHandler } from '@backstage/backend-common';\nimport {\n ANNOTATION_LOCATION,\n ANNOTATION_ORIGIN_LOCATION,\n Entity,\n parseLocationRef,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { InputError, NotFoundError, serializeError } from '@backstage/errors';\nimport express from 'express';\nimport yn from 'yn';\nimport { z } from 'zod';\nimport { EntitiesCatalog } from '../catalog/types';\nimport { CatalogProcessingOrchestrator } from '../processing/types';\nimport { validateEntityEnvelope } from '../processing/util';\nimport {\n basicEntityFilter,\n entitiesBatchRequest,\n parseEntityFilterParams,\n parseEntityTransformParams,\n parseQueryEntitiesParams,\n} from './request';\nimport { parseEntityFacetParams } from './request/parseEntityFacetParams';\nimport { parseEntityOrderParams } from './request/parseEntityOrderParams';\nimport { LocationService, RefreshService } from './types';\nimport {\n disallowReadonlyMode,\n encodeCursor,\n locationInput,\n validateRequestBody,\n} from './util';\nimport { createOpenApiRouter } from '../schema/openapi.generated';\nimport { parseEntityPaginationParams } from './request/parseEntityPaginationParams';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n SchedulerService,\n PermissionsService,\n} from '@backstage/backend-plugin-api';\nimport { LocationAnalyzer } from '@backstage/plugin-catalog-node';\nimport { AuthorizedValidationService } from './AuthorizedValidationService';\n\n/**\n * Options used by {@link createRouter}.\n *\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n entitiesCatalog?: EntitiesCatalog;\n locationAnalyzer?: LocationAnalyzer;\n locationService: LocationService;\n orchestrator?: CatalogProcessingOrchestrator;\n refreshService?: RefreshService;\n scheduler?: SchedulerService;\n logger: LoggerService;\n config: Config;\n permissionIntegrationRouter?: express.Router;\n auth: AuthService;\n httpAuth: HttpAuthService;\n permissionsService: PermissionsService;\n}\n\n/**\n * Creates a catalog router.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise {\n const router = await createOpenApiRouter({\n validatorOptions: {\n // We want the spec to be up to date with the expected value, but the return type needs\n // to be controlled by the router implementation not the request validator.\n ignorePaths: /^\\/validate-entity\\/?$/,\n },\n });\n const {\n entitiesCatalog,\n locationAnalyzer,\n locationService,\n orchestrator,\n refreshService,\n config,\n logger,\n permissionIntegrationRouter,\n permissionsService,\n auth,\n httpAuth,\n } = options;\n\n const readonlyEnabled =\n config.getOptionalBoolean('catalog.readonly') || false;\n if (readonlyEnabled) {\n logger.info('Catalog is running in readonly mode');\n }\n\n if (refreshService) {\n router.post('/refresh', async (req, res) => {\n const { authorizationToken, ...restBody } = req.body;\n\n const credentials = authorizationToken\n ? await auth.authenticate(authorizationToken)\n : await httpAuth.credentials(req);\n\n await refreshService.refresh({\n ...restBody,\n credentials,\n });\n res.status(200).end();\n });\n }\n\n if (permissionIntegrationRouter) {\n router.use(permissionIntegrationRouter);\n }\n\n if (entitiesCatalog) {\n router\n .get('/entities', async (req, res) => {\n const { entities, pageInfo } = await entitiesCatalog.entities({\n filter: parseEntityFilterParams(req.query),\n fields: parseEntityTransformParams(req.query),\n order: parseEntityOrderParams(req.query),\n pagination: parseEntityPaginationParams(req.query),\n credentials: await httpAuth.credentials(req),\n });\n\n // Add a Link header to the next page\n if (pageInfo.hasNextPage) {\n const url = new URL(`http://ignored${req.url}`);\n url.searchParams.delete('offset');\n url.searchParams.set('after', pageInfo.endCursor);\n res.setHeader('link', `<${url.pathname}${url.search}>; rel=\"next\"`);\n }\n\n // TODO(freben): encode the pageInfo in the response\n res.json(entities);\n })\n .get('/entities/by-query', async (req, res) => {\n const { items, pageInfo, totalItems } =\n await entitiesCatalog.queryEntities({\n limit: req.query.limit,\n offset: req.query.offset,\n ...parseQueryEntitiesParams(req.query),\n credentials: await httpAuth.credentials(req),\n });\n\n res.json({\n items,\n totalItems,\n pageInfo: {\n ...(pageInfo.nextCursor && {\n nextCursor: encodeCursor(pageInfo.nextCursor),\n }),\n ...(pageInfo.prevCursor && {\n prevCursor: encodeCursor(pageInfo.prevCursor),\n }),\n },\n });\n })\n .get('/entities/by-uid/:uid', async (req, res) => {\n const { uid } = req.params;\n const { entities } = await entitiesCatalog.entities({\n filter: basicEntityFilter({ 'metadata.uid': uid }),\n credentials: await httpAuth.credentials(req),\n });\n if (!entities.length) {\n throw new NotFoundError(`No entity with uid ${uid}`);\n }\n res.status(200).json(entities[0]);\n })\n .delete('/entities/by-uid/:uid', async (req, res) => {\n const { uid } = req.params;\n await entitiesCatalog.removeEntityByUid(uid, {\n credentials: await httpAuth.credentials(req),\n });\n res.status(204).end();\n })\n .get('/entities/by-name/:kind/:namespace/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const { entities } = await entitiesCatalog.entities({\n filter: basicEntityFilter({\n kind: kind,\n 'metadata.namespace': namespace,\n 'metadata.name': name,\n }),\n credentials: await httpAuth.credentials(req),\n });\n if (!entities.length) {\n throw new NotFoundError(\n `No entity named '${name}' found, with kind '${kind}' in namespace '${namespace}'`,\n );\n }\n res.status(200).json(entities[0]);\n })\n .get(\n '/entities/by-name/:kind/:namespace/:name/ancestry',\n async (req, res) => {\n const { kind, namespace, name } = req.params;\n const entityRef = stringifyEntityRef({ kind, namespace, name });\n const response = await entitiesCatalog.entityAncestry(entityRef, {\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(response);\n },\n )\n .post('/entities/by-refs', async (req, res) => {\n const request = entitiesBatchRequest(req);\n const response = await entitiesCatalog.entitiesBatch({\n entityRefs: request.entityRefs,\n filter: parseEntityFilterParams(req.query),\n fields: parseEntityTransformParams(req.query, request.fields),\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(response);\n })\n .get('/entity-facets', async (req, res) => {\n const response = await entitiesCatalog.facets({\n filter: parseEntityFilterParams(req.query),\n facets: parseEntityFacetParams(req.query),\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(response);\n });\n }\n\n if (locationService) {\n router\n .post('/locations', async (req, res) => {\n const location = await validateRequestBody(req, locationInput);\n const dryRun = yn(req.query.dryRun, { default: false });\n\n // when in dryRun addLocation is effectively a read operation so we don't\n // need to disallow readonly\n if (!dryRun) {\n disallowReadonlyMode(readonlyEnabled);\n }\n\n const output = await locationService.createLocation(location, dryRun, {\n credentials: await httpAuth.credentials(req),\n });\n res.status(201).json(output);\n })\n .get('/locations', async (req, res) => {\n const locations = await locationService.listLocations({\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(locations.map(l => ({ data: l })));\n })\n\n .get('/locations/:id', async (req, res) => {\n const { id } = req.params;\n const output = await locationService.getLocation(id, {\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(output);\n })\n .delete('/locations/:id', async (req, res) => {\n disallowReadonlyMode(readonlyEnabled);\n\n const { id } = req.params;\n await locationService.deleteLocation(id, {\n credentials: await httpAuth.credentials(req),\n });\n res.status(204).end();\n })\n .get('/locations/by-entity/:kind/:namespace/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const output = await locationService.getLocationByEntity(\n { kind, namespace, name },\n { credentials: await httpAuth.credentials(req) },\n );\n res.status(200).json(output);\n });\n }\n\n if (locationAnalyzer) {\n router.post('/analyze-location', async (req, res) => {\n const body = await validateRequestBody(\n req,\n z.object({\n location: locationInput,\n catalogFilename: z.string().optional(),\n }),\n );\n const schema = z.object({\n location: locationInput,\n catalogFilename: z.string().optional(),\n });\n const credentials = await httpAuth.credentials(req);\n const parsedBody = schema.parse(body);\n try {\n const output = await locationAnalyzer.analyzeLocation(\n parsedBody,\n credentials,\n );\n res.status(200).json(output);\n } catch (err) {\n if (\n // Catch errors from parse-url library.\n err.name === 'Error' &&\n 'subject_url' in err\n ) {\n throw new InputError('The given location.target is not a URL');\n }\n throw err;\n }\n });\n }\n\n if (orchestrator) {\n router.post('/validate-entity', async (req, res) => {\n const bodySchema = z.object({\n entity: z.unknown(),\n location: z.string(),\n });\n\n let body: z.infer;\n let entity: Entity;\n let location: { type: string; target: string };\n try {\n body = await validateRequestBody(req, bodySchema);\n entity = validateEntityEnvelope(body.entity);\n location = parseLocationRef(body.location);\n if (location.type !== 'url')\n throw new TypeError(\n `Invalid location ref ${body.location}, only 'url:' is supported, e.g. url:https://host/path`,\n );\n } catch (err) {\n return res.status(400).json({\n errors: [serializeError(err)],\n });\n }\n\n const credentials = await httpAuth.credentials(req);\n const authorizedValidationService = new AuthorizedValidationService(\n orchestrator,\n permissionsService,\n );\n const processingResult = await authorizedValidationService.process(\n {\n entity: {\n ...entity,\n metadata: {\n ...entity.metadata,\n annotations: {\n [ANNOTATION_LOCATION]: body.location,\n [ANNOTATION_ORIGIN_LOCATION]: body.location,\n ...entity.metadata.annotations,\n },\n },\n },\n },\n credentials,\n );\n\n if (!processingResult.ok)\n res.status(400).json({\n errors: processingResult.errors.map(e => serializeError(e)),\n });\n return res.status(200).end();\n });\n }\n\n router.use(errorHandler());\n return router;\n}\n"],"names":["createOpenApiRouter","parseEntityFilterParams","parseEntityTransformParams","parseEntityOrderParams","parseEntityPaginationParams","parseQueryEntitiesParams","encodeCursor","basicEntityFilter","NotFoundError","stringifyEntityRef","entitiesBatchRequest","parseEntityFacetParams","validateRequestBody","locationInput","yn","disallowReadonlyMode","z","InputError","validateEntityEnvelope","parseLocationRef","serializeError","AuthorizedValidationService","ANNOTATION_LOCATION","ANNOTATION_ORIGIN_LOCATION","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoFA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA,MAAA,GAAS,MAAMA,qCAAoB,CAAA;AAAA,IACvC,gBAAkB,EAAA;AAAA;AAAA;AAAA,MAGhB,WAAa,EAAA,wBAAA;AAAA,KACf;AAAA,GACD,CAAA,CAAA;AACD,EAAM,MAAA;AAAA,IACJ,eAAA;AAAA,IACA,gBAAA;AAAA,IACA,eAAA;AAAA,IACA,YAAA;AAAA,IACA,cAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,2BAAA;AAAA,IACA,kBAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,GACE,GAAA,OAAA,CAAA;AAEJ,EAAA,MAAM,eACJ,GAAA,MAAA,CAAO,kBAAmB,CAAA,kBAAkB,CAAK,IAAA,KAAA,CAAA;AACnD,EAAA,IAAI,eAAiB,EAAA;AACnB,IAAA,MAAA,CAAO,KAAK,qCAAqC,CAAA,CAAA;AAAA,GACnD;AAEA,EAAA,IAAI,cAAgB,EAAA;AAClB,IAAA,MAAA,CAAO,IAAK,CAAA,UAAA,EAAY,OAAO,GAAA,EAAK,GAAQ,KAAA;AAC1C,MAAA,MAAM,EAAE,kBAAA,EAAoB,GAAG,QAAA,KAAa,GAAI,CAAA,IAAA,CAAA;AAEhD,MAAM,MAAA,WAAA,GAAc,kBAChB,GAAA,MAAM,IAAK,CAAA,YAAA,CAAa,kBAAkB,CAC1C,GAAA,MAAM,Q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AAM,8BAA8B,IAAIC,uDAAA;AAAA,QACtC,YAAA;AAAA,QACA,kBAAA;AAAA,OACF,CAAA;AACA,MAAM,MAAA,gBAAA,GAAmB,MAAM,2BAA4B,CAAA,OAAA;AAAA,QACzD;AAAA,UACE,MAAQ,EAAA;AAAA,YACN,GAAG,MAAA;AAAA,YACH,QAAU,EAAA;AAAA,cACR,GAAG,MAAO,CAAA,QAAA;AAAA,cACV,WAAa,EAAA;AAAA,gBACX,CAACC,gCAAmB,GAAG,IAAK,CAAA,QAAA;AAAA,gBAC5B,CAACC,uCAA0B,GAAG,IAAK,CAAA,QAAA;AAAA,gBACnC,GAAG,OAAO,QAAS,CAAA,WAAA;AAAA,eACrB;AAAA,aACF;AAAA,WACF;AAAA,SACF;AAAA,QACA,WAAA;AAAA,OACF,CAAA;AAEA,MAAA,IAAI,CAAC,gBAAiB,CAAA,EAAA;AACpB,QAAI,GAAA,CAAA,MAAA,CAAO,GAAG,CAAA,CAAE,IAAK,CAAA;AAAA,UACnB,QAAQ,gBAAiB,CAAA,MAAA,CAAO,IAAI,CAAK,CAAA,KAAAH,qBAAA,CAAe,CAAC,CAAC,CAAA;AAAA,SAC3D,CAAA,CAAA;AACH,MAAA,OAAO,GAAI,CAAA,MAAA,CAAO,GAAG,CAAA,CAAE,GAAI,EAAA,CAAA;AAAA,KAC5B,CAAA,CAAA;AAAA,GACH;AAEA,EAAO,MAAA,CAAA,GAAA,CAAII,4BAAc,CAAA,CAAA;AACzB,EAAO,OAAA,MAAA,CAAA;AACT;;;;"} -\ No newline at end of file -+{"version":3,"file":"createRouter.cjs.js","sources":["../../src/service/createRouter.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorHandler } from '@backstage/backend-common';\nimport {\n ANNOTATION_LOCATION,\n ANNOTATION_ORIGIN_LOCATION,\n Entity,\n parseLocationRef,\n stringifyEntityRef,\n} from '@backstage/catalog-model';\nimport { Config } from '@backstage/config';\nimport { InputError, NotFoundError, serializeError } from '@backstage/errors';\nimport express from 'express';\nimport yn from 'yn';\nimport { z } from 'zod';\nimport { EntitiesCatalog } from '../catalog/types';\nimport { CatalogProcessingOrchestrator } from '../processing/types';\nimport { validateEntityEnvelope } from '../processing/util';\nimport {\n basicEntityFilter,\n entitiesBatchRequest,\n parseEntityFilterParams,\n parseEntityTransformParams,\n parseQueryEntitiesParams,\n} from './request';\nimport { parseEntityFacetParams } from './request/parseEntityFacetParams';\nimport { parseEntityOrderParams } from './request/parseEntityOrderParams';\nimport { LocationService, RefreshService } from './types';\nimport {\n disallowReadonlyMode,\n encodeCursor,\n locationInput,\n validateRequestBody,\n} from './util';\nimport { createOpenApiRouter } from '../schema/openapi.generated';\nimport { parseEntityPaginationParams } from './request/parseEntityPaginationParams';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n SchedulerService,\n PermissionsService,\n} from '@backstage/backend-plugin-api';\nimport { LocationAnalyzer } from '@backstage/plugin-catalog-node';\nimport { AuthorizedValidationService } from './AuthorizedValidationService';\n\nimport { DefaultAuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\n\n/**\n * Options used by {@link createRouter}.\n *\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n entitiesCatalog?: EntitiesCatalog;\n locationAnalyzer?: LocationAnalyzer;\n locationService: LocationService;\n orchestrator?: CatalogProcessingOrchestrator;\n refreshService?: RefreshService;\n scheduler?: SchedulerService;\n logger: LoggerService;\n config: Config;\n permissionIntegrationRouter?: express.Router;\n auth: AuthService;\n httpAuth: HttpAuthService;\n permissionsService: PermissionsService;\n}\n\n/**\n * Creates a catalog router.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise {\n const router = await createOpenApiRouter({\n validatorOptions: {\n // We want the spec to be up to date with the expected value, but the return type needs\n // to be controlled by the router implementation not the request validator.\n ignorePaths: /^\\/validate-entity\\/?$/,\n },\n });\n const {\n entitiesCatalog,\n locationAnalyzer,\n locationService,\n orchestrator,\n refreshService,\n config,\n logger,\n permissionIntegrationRouter,\n permissionsService,\n auth,\n httpAuth,\n } = options;\n\n const auditLogger = new DefaultAuditLogger({\n logger,\n authService: auth,\n httpAuthService: httpAuth,\n });\n const readonlyEnabled =\n config.getOptionalBoolean('catalog.readonly') || false;\n if (readonlyEnabled) {\n logger.info('Catalog is running in readonly mode');\n }\n\n if (refreshService) {\n // TODO: Potentially find a way to track the ancestor that gets refreshed to refresh this entity (as well as the child of that ancestor?)\n router.post('/refresh', async (req, res) => {\n const { authorizationToken, ...restBody } = req.body;\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityRefresh',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n metadata: {\n entityRef: restBody.entityRef,\n },\n request: req,\n message: `Refresh attempt for ${restBody.entityRef} initiated by ${actorId}`,\n });\n\n const credentials = authorizationToken\n ? await auth.authenticate(authorizationToken)\n : await httpAuth.credentials(req);\n\n await refreshService.refresh({\n ...restBody,\n credentials,\n });\n await auditLogger.auditLog({\n eventName: 'CatalogEntityRefresh',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n metadata: {\n entityRef: restBody.entityRef,\n },\n response: {\n status: 200,\n },\n request: req,\n message: `Refresh attempt for ${restBody.entityRef} triggered by ${actorId}`,\n });\n res.status(200).end();\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityRefresh',\n actorId,\n status: 'failed',\n stage: 'completion',\n level: 'error',\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n metadata: {\n entityRef: restBody.entityRef,\n },\n request: req,\n message: `Refresh attempt for ${restBody.entityRef} by ${actorId} failed`,\n });\n throw err;\n }\n });\n }\n\n if (permissionIntegrationRouter) {\n router.use(permissionIntegrationRouter);\n }\n\n if (entitiesCatalog) {\n router\n .get('/entities', async (req, res) => {\n const actorId = await auditLogger.getActorId(\n req as unknown as express.Request,\n );\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetch',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req as unknown as express.Request,\n message: `Entity fetch attempt initiated by ${actorId}`,\n });\n const { entities, pageInfo } = await entitiesCatalog.entities({\n filter: parseEntityFilterParams(req.query),\n fields: parseEntityTransformParams(req.query),\n order: parseEntityOrderParams(req.query),\n pagination: parseEntityPaginationParams(req.query),\n credentials: await httpAuth.credentials(req),\n });\n\n // Add a Link header to the next page\n if (pageInfo.hasNextPage) {\n const url = new URL(`http://ignored${req.url}`);\n url.searchParams.delete('offset');\n url.searchParams.set('after', pageInfo.endCursor);\n res.setHeader('link', `<${url.pathname}${url.search}>; rel=\"next\"`);\n }\n\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetch',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req as unknown as express.Request,\n // Let's not log out the entities since this can make the log very big due to it not being paged?\n response: {\n status: 200,\n },\n message: `Entity fetch attempt by ${actorId} succeeded`,\n });\n\n // TODO(freben): encode the pageInfo in the response\n res.json(entities);\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetch',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n request: req as unknown as express.Request,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Entity fetch attempt by ${actorId} failed`,\n });\n throw err;\n }\n })\n .get('/entities/by-query', async (req, res) => {\n const actorId = await auditLogger.getActorId(\n req as unknown as express.Request,\n );\n try {\n await auditLogger.auditLog({\n eventName: 'QueriedCatalogEntityFetch',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req as unknown as express.Request,\n message: `Queried entity fetch attempt initiated by ${actorId}`,\n });\n const { items, pageInfo, totalItems } =\n await entitiesCatalog.queryEntities({\n limit: req.query.limit,\n ...parseQueryEntitiesParams(req.query),\n credentials: await httpAuth.credentials(req),\n });\n\n res.json({\n items,\n totalItems,\n pageInfo: {\n ...(pageInfo.nextCursor && {\n nextCursor: encodeCursor(pageInfo.nextCursor),\n }),\n ...(pageInfo.prevCursor && {\n prevCursor: encodeCursor(pageInfo.prevCursor),\n }),\n },\n });\n await auditLogger.auditLog({\n eventName: 'QueriedCatalogEntityFetch',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req as unknown as express.Request,\n metadata: {\n totalEntities: totalItems,\n pageInfo: {\n ...(pageInfo.nextCursor && {\n nextCursor: encodeCursor(pageInfo.nextCursor),\n }),\n ...(pageInfo.prevCursor && {\n prevCursor: encodeCursor(pageInfo.prevCursor),\n }),\n },\n },\n // Let's not log out the entities since this can make the log very big\n response: {\n status: 200,\n },\n message: `Queried entity fetch attempt by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'QueriedCatalogEntityFetch',\n actorId,\n status: 'failed',\n stage: 'completion',\n level: 'error',\n request: req as unknown as express.Request,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Queried entity fetch attempt by ${actorId} failed`,\n });\n throw err;\n }\n })\n .get('/entities/by-uid/:uid', async (req, res) => {\n const { uid } = req.params;\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetchByUid',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req,\n metadata: {\n uid: uid,\n },\n message: `Fetch attempt for entity with uid ${uid} initiated by ${actorId}`,\n });\n const { entities } = await entitiesCatalog.entities({\n filter: basicEntityFilter({ 'metadata.uid': uid }),\n credentials: await httpAuth.credentials(req),\n });\n if (!entities.length) {\n throw new NotFoundError(`No entity with uid ${uid}`);\n }\n res.status(200).json(entities[0]);\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetchByUid',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req,\n metadata: {\n uid: uid,\n entityRef: stringifyEntityRef(entities[0]),\n },\n response: {\n status: 200,\n },\n message: `Fetch attempt for entity with uid ${uid} by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetchByUid',\n actorId,\n status: 'failed',\n stage: 'completion',\n level: 'error',\n request: req,\n metadata: {\n uid: uid,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Fetch attempt for entity with uid ${uid} by ${actorId} failed`,\n });\n throw err;\n }\n })\n .delete('/entities/by-uid/:uid', async (req, res) => {\n const { uid } = req.params;\n const actorId = await auditLogger.getActorId(req);\n let entityRef: string | undefined;\n try {\n // Get the entityRef of the UID so users can more easily identity the entity\n const { entities } = await entitiesCatalog.entities({\n filter: basicEntityFilter({ 'metadata.uid': uid }),\n credentials: await httpAuth.credentials(req),\n });\n if (entities.length) {\n entityRef = stringifyEntityRef(entities[0]);\n }\n await auditLogger.auditLog({\n eventName: 'CatalogEntityDeletion',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req,\n metadata: {\n uid: uid,\n entityRef: entityRef,\n },\n message: `Deletion attempt for entity with uid ${uid} initiated by ${actorId}`,\n });\n await entitiesCatalog.removeEntityByUid(uid, {\n credentials: await httpAuth.credentials(req),\n });\n await auditLogger.auditLog({\n eventName: 'CatalogEntityDeletion',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req,\n metadata: {\n uid: uid,\n entityRef: entityRef,\n },\n response: {\n status: 204,\n },\n message: `Deletion attempt for entity with uid ${uid} by ${actorId} succeeded`,\n });\n res.status(204).end();\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityDeletion',\n actorId,\n status: 'failed',\n stage: 'completion',\n level: 'error',\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Deletion attempt for entity with uid ${uid} by ${actorId} failed`,\n });\n throw err;\n }\n })\n .get('/entities/by-name/:kind/:namespace/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const entityRef = stringifyEntityRef({ kind, namespace, name });\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetchByName',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req,\n metadata: {\n entityRef: entityRef,\n },\n message: `Fetch attempt for entity with entityRef ${entityRef} initiated by ${actorId}`,\n });\n const { entities } = await entitiesCatalog.entities({\n filter: basicEntityFilter({\n kind: kind,\n 'metadata.namespace': namespace,\n 'metadata.name': name,\n }),\n credentials: await httpAuth.credentials(req),\n });\n if (!entities.length) {\n throw new NotFoundError(\n `No entity named '${name}' found, with kind '${kind}' in namespace '${namespace}'`,\n );\n }\n res.status(200).json(entities[0]);\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetchByName',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req,\n metadata: {\n entityRef: entityRef,\n },\n response: {\n status: 200,\n },\n message: `Fetch attempt for entity with entityRef ${entityRef} by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFetchByName',\n actorId,\n status: 'failed',\n stage: 'completion',\n level: 'error',\n request: req,\n metadata: {\n entityRef: entityRef,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Fetch attempt for entity with entityRef ${entityRef} by ${actorId} failed`,\n });\n throw err;\n }\n })\n .get(\n '/entities/by-name/:kind/:namespace/:name/ancestry',\n async (req, res) => {\n const { kind, namespace, name } = req.params;\n const entityRef = stringifyEntityRef({ kind, namespace, name });\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityAncestryFetch',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req,\n metadata: {\n entityRef: entityRef,\n },\n message: `Fetch attempt for entity ancestor of entity ${entityRef} initiated by ${actorId}`,\n });\n const response = await entitiesCatalog.entityAncestry(entityRef, {\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(response);\n await auditLogger.auditLog({\n eventName: 'CatalogEntityAncestryFetch',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req,\n metadata: {\n rootEntityRef: response.rootEntityRef,\n ancestry: response.items.map(ancestryLink => {\n return {\n entityRef: stringifyEntityRef(ancestryLink.entity),\n parentEntityRefs: ancestryLink.parentEntityRefs,\n };\n }),\n },\n response: {\n status: 200,\n },\n message: `Fetch attempt for entity ancestor of entity ${entityRef} by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityAncestryFetch',\n actorId,\n status: 'failed',\n stage: 'completion',\n level: 'error',\n request: req,\n metadata: {\n entityRef: entityRef,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Fetch attempt for entity ancestor of entity ${entityRef} by ${actorId} failed`,\n });\n throw err;\n }\n },\n )\n .post('/entities/by-refs', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityBatchFetch',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req,\n message: `Batch entity fetch attempt initiated by ${actorId}`,\n });\n const request = entitiesBatchRequest(req);\n const response = await entitiesCatalog.entitiesBatch({\n entityRefs: request.entityRefs,\n filter: parseEntityFilterParams(req.query),\n fields: parseEntityTransformParams(req.query, request.fields),\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(response);\n await auditLogger.auditLog({\n eventName: 'CatalogEntityBatchFetch',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req,\n metadata: {\n ...request,\n },\n response: {\n status: 200,\n },\n message: `Batch entity fetch attempt by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityBatchFetch',\n actorId,\n status: 'failed',\n stage: 'completion',\n level: 'error',\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Batch entity fetch attempt by ${actorId} failed`,\n });\n throw err;\n }\n })\n .get('/entity-facets', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFacetFetch',\n actorId,\n status: 'succeeded',\n stage: 'initiation',\n request: req,\n message: `Entity facet fetch attempt initiated by ${actorId}`,\n });\n const response = await entitiesCatalog.facets({\n filter: parseEntityFilterParams(req.query),\n facets: parseEntityFacetParams(req.query),\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(response);\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFacetFetch',\n actorId,\n status: 'succeeded',\n stage: 'completion',\n request: req,\n response: { status: 200 },\n message: `Entity facet fetch attempt by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityFacetFetch',\n actorId,\n status: 'failed',\n stage: 'completion',\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Entity facet fetch attempt by ${actorId} failed`,\n });\n throw err;\n }\n });\n }\n\n if (locationService) {\n router\n .post('/locations', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n const actorId = await auditLogger.getActorId(req);\n const location = await validateRequestBody(req, locationInput);\n const dryRun = yn(req.query.dryRun, { default: false });\n\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationCreation',\n status: 'succeeded',\n stage: 'initiation',\n actorId,\n metadata: {\n location: location,\n isDryRun: dryRun,\n },\n request: req,\n message: `Creation attempt of location entity for ${location.target} initiated by ${actorId}`,\n });\n\n // when in dryRun addLocation is effectively a read operation so we don't\n // need to disallow readonly\n if (!dryRun) {\n disallowReadonlyMode(readonlyEnabled);\n }\n\n const output = await locationService.createLocation(\n location,\n dryRun,\n {\n credentials,\n },\n );\n await auditLogger.auditLog({\n eventName: 'CatalogLocationCreation',\n status: 'succeeded',\n stage: 'completion',\n actorId,\n metadata: {\n location: output.location,\n isDryRun: dryRun,\n },\n request: req,\n response: {\n status: 201,\n },\n message: `Creation of location entity for ${location.target} initiated by ${actorId} succeeded`,\n });\n res.status(201).json(output);\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationCreation',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n actorId,\n metadata: {\n location: location,\n isDryRun: dryRun,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n request: req,\n message: `Creation of location entity for ${location.target} initiated by ${actorId} failed`,\n });\n throw err;\n }\n })\n .get('/locations', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetch',\n status: 'succeeded',\n stage: 'initiation',\n actorId,\n request: req,\n message: `Fetch attempt of locations initiated by ${actorId}`,\n });\n const locations = await locationService.listLocations({\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(locations.map(l => ({ data: l })));\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetch',\n status: 'succeeded',\n stage: 'completion',\n actorId,\n request: req,\n response: {\n status: 200,\n },\n message: `Fetch attempt of locations by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetch',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n actorId,\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Fetch attempt of locations by ${actorId} failed`,\n });\n throw err;\n }\n })\n\n .get('/locations/:id', async (req, res) => {\n const { id } = req.params;\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetchById',\n status: 'succeeded',\n stage: 'initiation',\n actorId,\n metadata: {\n id: id,\n },\n request: req,\n message: `Fetch attempt of location with id: ${id} initiated by ${actorId}`,\n });\n const output = await locationService.getLocation(id, {\n credentials: await httpAuth.credentials(req),\n });\n res.status(200).json(output);\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetchById',\n status: 'succeeded',\n stage: 'completion',\n actorId,\n metadata: {\n id: id,\n },\n response: {\n status: 200,\n body: output,\n },\n request: req,\n message: `Fetch attempt of location with id: ${id} by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetchById',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n actorId,\n metadata: {\n id: id,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n request: req,\n message: `Fetch attempt of location with id: ${id} by ${actorId} failed`,\n });\n throw err;\n }\n })\n .delete('/locations/:id', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n const { id } = req.params;\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationDeletion',\n status: 'succeeded',\n stage: 'initiation',\n actorId,\n metadata: {\n id: id,\n },\n request: req,\n message: `Deletion attempt of location with id: ${id} initiated by ${actorId}`,\n });\n disallowReadonlyMode(readonlyEnabled);\n // Grabbing the information of the location begin deleted\n const location = await locationService.getLocation(id, {\n credentials: await httpAuth.credentials(req),\n });\n await locationService.deleteLocation(id, {\n credentials: await httpAuth.credentials(req),\n });\n await auditLogger.auditLog({\n eventName: 'CatalogLocationDeletion',\n status: 'succeeded',\n stage: 'completion',\n actorId,\n metadata: {\n location,\n },\n response: {\n status: 204,\n },\n request: req,\n message: `Deletion attempt of location with id: ${id} by ${actorId} succeeded`,\n });\n res.status(204).end();\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationDeletion',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n actorId,\n metadata: {\n id: id,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n request: req,\n message: `Deletion attempt of location with id: ${id} by ${actorId} failed`,\n });\n throw err;\n }\n })\n .get('/locations/by-entity/:kind/:namespace/:name', async (req, res) => {\n const { kind, namespace, name } = req.params;\n const actorId = await auditLogger.getActorId(req);\n const locationRef = `${kind}:${namespace}/${name}`;\n\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetchByEntityRef',\n status: 'succeeded',\n stage: 'initiation',\n actorId,\n metadata: {\n locationRef: locationRef,\n },\n request: req,\n message: `Fetch attempt for location ${locationRef} initiated by ${actorId}`,\n });\n\n const output = await locationService.getLocationByEntity(\n { kind, namespace, name },\n { credentials: await httpAuth.credentials(req) },\n );\n res.status(200).json(output);\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetchByEntityRef',\n status: 'succeeded',\n stage: 'completion',\n actorId,\n metadata: {\n locationRef: locationRef,\n },\n response: {\n status: 200,\n body: output,\n },\n request: req,\n message: `Fetch attempt for location ${locationRef} by ${actorId} succeeded`,\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationFetchByEntityRef',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n actorId,\n metadata: {\n locationRef: locationRef,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n request: req,\n message: `Fetch attempt for location ${locationRef} by ${actorId} failed`,\n });\n throw err;\n }\n });\n }\n\n if (locationAnalyzer) {\n router.post('/analyze-location', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationAnalyze',\n status: 'succeeded',\n stage: 'initiation',\n actorId,\n request: req,\n message: `Analyze location for location initiated by ${actorId}`,\n });\n const body = await validateRequestBody(\n req,\n z.object({\n location: locationInput,\n catalogFilename: z.string().optional(),\n }),\n );\n const schema = z.object({\n location: locationInput,\n catalogFilename: z.string().optional(),\n });\n const credentials = await httpAuth.credentials(req);\n const parsedBody = schema.parse(body);\n try {\n const output = await locationAnalyzer.analyzeLocation(\n parsedBody,\n credentials,\n );\n res.status(200).json(output);\n await auditLogger.auditLog({\n eventName: 'CatalogLocationAnalyze',\n status: 'succeeded',\n stage: 'completion',\n actorId,\n request: req,\n response: {\n status: 200,\n body: output,\n },\n message: `Analyze location for location by ${actorId} succeeded`,\n });\n } catch (err) {\n if (\n // Catch errors from parse-url library.\n err.name === 'Error' &&\n 'subject_url' in err\n ) {\n throw new InputError('The given location.target is not a URL');\n }\n throw err;\n }\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogLocationAnalyze',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n actorId,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n request: req,\n message: `Analyze location for location by ${actorId} failed`,\n });\n throw err;\n }\n });\n }\n\n if (orchestrator) {\n router.post('/validate-entity', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n\n try {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityValidate',\n status: 'succeeded',\n stage: 'initiation',\n actorId,\n request: req,\n message: `Entity validation for entity initiated by ${actorId}`,\n });\n const bodySchema = z.object({\n entity: z.unknown(),\n location: z.string(),\n });\n\n let body: z.infer;\n let entity: Entity;\n let location: { type: string; target: string };\n try {\n body = await validateRequestBody(req, bodySchema);\n entity = validateEntityEnvelope(body.entity);\n location = parseLocationRef(body.location);\n if (location.type !== 'url')\n throw new TypeError(\n `Invalid location ref ${body.location}, only 'url:' is supported, e.g. url:https://host/path`,\n );\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityValidate',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n actorId,\n request: req,\n message: `Entity validation for entity initiated by ${actorId} failed`,\n });\n return res.status(400).json({\n errors: [serializeError(err)],\n });\n }\n\n const credentials = await httpAuth.credentials(req);\n const authorizedValidationService = new AuthorizedValidationService(\n orchestrator,\n permissionsService,\n );\n\n const processingResult = await authorizedValidationService.process(\n {\n entity: {\n ...entity,\n metadata: {\n ...entity.metadata,\n annotations: {\n [ANNOTATION_LOCATION]: body.location,\n [ANNOTATION_ORIGIN_LOCATION]: body.location,\n ...entity.metadata.annotations,\n },\n },\n },\n },\n credentials,\n );\n\n if (!processingResult.ok) {\n const errors = processingResult.errors.map(e => serializeError(e));\n await auditLogger.auditLog({\n eventName: 'CatalogEntityValidate',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n errors: errors,\n response: {\n status: 400,\n },\n actorId,\n request: req,\n message: `Entity validation for entity initiated by ${actorId} failed`,\n });\n return res.status(400).json({\n errors,\n });\n }\n await auditLogger.auditLog({\n eventName: 'CatalogEntityValidate',\n status: 'succeeded',\n stage: 'completion',\n actorId,\n response: {\n status: 200,\n },\n request: req,\n message: `Entity validation for entity by ${actorId} succeeded`,\n });\n return res.status(200).end();\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'CatalogEntityValidate',\n status: 'failed',\n stage: 'completion',\n level: 'error',\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n actorId,\n request: req,\n message: `Entity validation for entity initiated by ${actorId} failed`,\n });\n throw err;\n }\n });\n }\n router.use(errorHandler());\n return router;\n}\n"],"names":["createOpenApiRouter","DefaultAuditLogger","parseEntityFilterParams","parseEntityTransformParams","parseEntityOrderParams","parseEntityPaginationParams","parseQueryEntitiesParams","encodeCursor","basicEntityFilter","NotFoundError","stringifyEntityRef","entitiesBatchRequest","parseEntityFacetParams","validateRequestBody","locationInput","yn","disallowReadonlyMode","z","InputError","validateEntityEnvelope","parseLocationRef","serializeError","AuthorizedValidationService","ANNOTATION_LOCATION","ANNOTATION_ORIGIN_LOCATION","errors","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsFA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA,MAAA,GAAS,MAAMA,qCAAoB,CAAA;AAAA,IACvC,gBAAkB,EAAA;AAAA;AAAA;AAAA,MAGhB,WAAa,EAAA,wBAAA;AAAA,KACf;AAAA,GACD,CAAA,CAAA;AACD,EAAM,MA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,QAAS,CAAA;AAAA,UACzB,SAAW,EAAA,uBAAA;AAAA,UACX,MAAQ,EAAA,QAAA;AAAA,UACR,KAAO,EAAA,YAAA;AAAA,UACP,KAAO,EAAA,OAAA;AAAA,UACP,MAAQ,EAAA;AAAA,YACN;AAAA,cACE,MAAM,GAAI,CAAA,IAAA;AAAA,cACV,SAAS,GAAI,CAAA,OAAA;AAAA,cACb,OAAO,GAAI,CAAA,KAAA;AAAA,aACb;AAAA,WACF;AAAA,UACA,OAAA;AAAA,UACA,OAAS,EAAA,GAAA;AAAA,UACT,OAAA,EAAS,6CAA6C,OAAO,CAAA,OAAA,CAAA;AAAA,SAC9D,CAAA,CAAA;AACD,QAAM,MAAA,GAAA,CAAA;AAAA,OACR;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AACA,EAAO,MAAA,CAAA,GAAA,CAAIC,4BAAc,CAAA,CAAA;AACzB,EAAO,OAAA,MAAA,CAAA;AACT;;;;"} -\ No newline at end of file diff --git a/.yarn/patches/@backstage-plugin-scaffolder-backend-npm-1.26.2-309568ee11.patch b/.yarn/patches/@backstage-plugin-scaffolder-backend-npm-1.26.2-309568ee11.patch deleted file mode 100644 index bd3bd966..00000000 --- a/.yarn/patches/@backstage-plugin-scaffolder-backend-npm-1.26.2-309568ee11.patch +++ /dev/null @@ -1,1800 +0,0 @@ -diff --git a/dist/index.d.ts b/dist/index.d.ts -index ff0521a12ae6a15ebf1df629f5971dca68257dfa..dbcb8ad1d6de2958fed9a33d7a678c3473b9007d 100644 ---- a/dist/index.d.ts -+++ b/dist/index.d.ts -@@ -23,6 +23,7 @@ import * as _backstage_plugin_scaffolder_common from '@backstage/plugin-scaffold - import { TaskSpec, TaskRecovery, TemplateEntityStepV1beta3, TemplateParametersV1beta3 } from '@backstage/plugin-scaffolder-common'; - import { Logger } from 'winston'; - import { WorkspaceProvider, AutocompleteHandler } from '@backstage/plugin-scaffolder-node/alpha'; -+import { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node'; - import { PermissionEvaluator, PermissionRuleParams } from '@backstage/plugin-permission-common'; - import { RESOURCE_TYPE_SCAFFOLDER_TEMPLATE, RESOURCE_TYPE_SCAFFOLDER_ACTION } from '@backstage/plugin-scaffolder-common/alpha'; - import express from 'express'; -@@ -378,7 +379,7 @@ declare const createPublishGitlabMergeRequestAction: (options: { - sourcePath?: string | undefined; - targetPath?: string | undefined; - token?: string | undefined; -- commitAction?: "auto" | "update" | "delete" | "create" | "skip" | undefined; -+ commitAction?: "create" | "update" | "delete" | "skip" | "auto" | undefined; - projectid?: string | undefined; - removeSourceBranch?: boolean | undefined; - assignee?: string | undefined; -@@ -711,11 +712,13 @@ declare class TaskManager implements TaskContext$1 { - private readonly signal; - private readonly logger; - private readonly workspaceService; -+ private readonly auditLogger; - private readonly auth?; - private isDone; - private heartbeatTimeoutId?; -- static create(task: CurrentClaimedTask, storage: TaskStore, abortSignal: AbortSignal, logger: Logger, auth?: AuthService, config?: Config, additionalWorkspaceProviders?: Record): TaskManager; -+ static create(task: CurrentClaimedTask, storage: TaskStore, abortSignal: AbortSignal, logger: Logger, auditLogger: AuditLogger, auth?: AuthService, config?: Config, additionalWorkspaceProviders?: Record): TaskManager; - private constructor(); -+ get taskId(): string; - get spec(): _backstage_plugin_scaffolder_common.TaskSpecV1beta3; - get cancelSignal(): AbortSignal; - get secrets(): TaskSecrets$1 | undefined; -@@ -790,6 +793,7 @@ type CreateWorkerOptions = { - integrations: ScmIntegrations; - workingDirectory: string; - logger: Logger; -+ auditLogger: AuditLogger; - additionalTemplateFilters?: Record; - /** - * The number of tasks that can be executed at the same time by the worker -@@ -817,6 +821,7 @@ declare class TaskWorker { - private taskQueue; - private logger; - private stopWorkers; -+ private auditLogger; - private constructor(); - static create(options: CreateWorkerOptions): Promise; - recoverTasks(): Promise; -diff --git a/dist/scaffolder/dryrun/createDryRunner.cjs.js b/dist/scaffolder/dryrun/createDryRunner.cjs.js -index b62685bf4f732cfd5a59448e4806d0886f0f1871..95b283f30d842b47adeeb0f5e0de3635367bd128 100644 ---- a/dist/scaffolder/dryrun/createDryRunner.cjs.js -+++ b/dist/scaffolder/dryrun/createDryRunner.cjs.js -@@ -39,6 +39,7 @@ function createDryRunner(options) { - await pluginScaffolderNode.deserializeDirectoryContents(contentsPath, input.directoryContents); - const abortSignal = new AbortController().signal; - const result = await workflowRunner.execute({ -+ taskId: dryRunId, - spec: { - ...input.spec, - steps: [ -diff --git a/dist/scaffolder/dryrun/createDryRunner.cjs.js.map b/dist/scaffolder/dryrun/createDryRunner.cjs.js.map -index 961ae8d0ca5d4be82c4b52e109b6aa79d59a0467..6d02340804373b8c08d6f7198e8e71c016b1ac79 100644 ---- a/dist/scaffolder/dryrun/createDryRunner.cjs.js.map -+++ b/dist/scaffolder/dryrun/createDryRunner.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"createDryRunner.cjs.js","sources":["../../../src/scaffolder/dryrun/createDryRunner.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ScmIntegrations } from '@backstage/integration';\nimport { TaskSpec } from '@backstage/plugin-scaffolder-common';\nimport { JsonObject } from '@backstage/types';\nimport { v4 as uuid } from 'uuid';\nimport { pathToFileURL } from 'url';\nimport { Logger } from 'winston';\nimport {\n createTemplateAction,\n TaskSecrets,\n TemplateFilter,\n TemplateGlobal,\n deserializeDirectoryContents,\n SerializedFile,\n serializeDirectoryContents,\n} from '@backstage/plugin-scaffolder-node';\nimport { TemplateActionRegistry } from '../actions';\nimport { NunjucksWorkflowRunner } from '../tasks/NunjucksWorkflowRunner';\nimport { DecoratedActionsRegistry } from './DecoratedActionsRegistry';\nimport fs from 'fs-extra';\nimport { PermissionEvaluator } from '@backstage/plugin-permission-common';\nimport {\n BackstageCredentials,\n resolveSafeChildPath,\n} from '@backstage/backend-plugin-api';\nimport type { UserEntity } from '@backstage/catalog-model';\n\ninterface DryRunInput {\n spec: TaskSpec;\n secrets?: TaskSecrets;\n directoryContents: SerializedFile[];\n credentials: BackstageCredentials;\n user?: {\n entity?: UserEntity;\n ref?: string;\n };\n}\n\ninterface DryRunResult {\n log: Array<{ body: JsonObject }>;\n directoryContents: SerializedFile[];\n output: JsonObject;\n}\n\n/** @internal */\nexport type TemplateTesterCreateOptions = {\n logger: Logger;\n integrations: ScmIntegrations;\n actionRegistry: TemplateActionRegistry;\n workingDirectory: string;\n additionalTemplateFilters?: Record;\n additionalTemplateGlobals?: Record;\n permissions?: PermissionEvaluator;\n};\n\n/**\n * Executes a dry-run of the provided template.\n *\n * The provided content will be extracted into a temporary directory\n * which is then use as the base for any relative file fetch paths.\n *\n * @internal\n */\nexport function createDryRunner(options: TemplateTesterCreateOptions) {\n return async function dryRun(input: DryRunInput): Promise {\n let contentPromise;\n\n const workflowRunner = new NunjucksWorkflowRunner({\n ...options,\n actionRegistry: new DecoratedActionsRegistry(options.actionRegistry, [\n createTemplateAction({\n id: 'dry-run:extract',\n supportsDryRun: true,\n async handler(ctx) {\n contentPromise = serializeDirectoryContents(ctx.workspacePath);\n await contentPromise.catch(() => {});\n },\n }),\n ]),\n });\n\n const dryRunId = uuid();\n const log = new Array<{ body: JsonObject }>();\n const contentsPath = resolveSafeChildPath(\n options.workingDirectory,\n `dry-run-content-${dryRunId}`,\n );\n\n try {\n await deserializeDirectoryContents(contentsPath, input.directoryContents);\n\n const abortSignal = new AbortController().signal;\n\n const result = await workflowRunner.execute({\n spec: {\n ...input.spec,\n steps: [\n ...input.spec.steps,\n {\n id: dryRunId,\n name: 'dry-run:extract',\n action: 'dry-run:extract',\n },\n ],\n templateInfo: {\n entityRef: 'template:default/dry-run',\n baseUrl: pathToFileURL(\n resolveSafeChildPath(contentsPath, 'template.yaml'),\n ).toString(),\n },\n },\n secrets: input.secrets,\n getInitiatorCredentials: () => Promise.resolve(input.credentials),\n // No need to update this at the end of the run, so just hard-code it\n done: false,\n isDryRun: true,\n getWorkspaceName: async () => `dry-run-${dryRunId}`,\n cancelSignal: abortSignal,\n async emitLog(message: string, logMetadata?: JsonObject) {\n if (logMetadata?.stepId === dryRunId) {\n return;\n }\n log.push({\n body: {\n ...logMetadata,\n message,\n },\n });\n },\n complete: async () => {\n throw new Error('Not implemented');\n },\n });\n\n if (!contentPromise) {\n throw new Error('Content extraction step was skipped');\n }\n const directoryContents = await contentPromise;\n\n return {\n log,\n directoryContents,\n output: result.output,\n };\n } finally {\n await fs.remove(contentsPath);\n }\n };\n}\n"],"names":["NunjucksWorkflowRunner","DecoratedActionsRegistry","createTemplateAction","serializeDirectoryContents","uuid","resolveSafeChildPath","deserializeDirectoryContents","pathToFileURL","fs"],"mappings":";;;;;;;;;;;;;;AA8EO,SAAS,gBAAgB,OAAsC,EAAA;AACpE,EAAO,OAAA,eAAe,OAAO,KAA2C,EAAA;AACtE,IAAI,IAAA,cAAA,CAAA;AAEJ,IAAM,MAAA,cAAA,GAAiB,IAAIA,6CAAuB,CAAA;AAAA,MAChD,GAAG,OAAA;AAAA,MACH,cAAgB,EAAA,IAAIC,iDAAyB,CAAA,OAAA,CAAQ,cAAgB,EAAA;AAAA,QACnEC,yCAAqB,CAAA;AAAA,UACnB,EAAI,EAAA,iBAAA;AAAA,UACJ,cAAgB,EAAA,IAAA;AAAA,UAChB,MAAM,QAAQ,GAAK,EAAA;AACjB,YAAiB,cAAA,GAAAC,+CAAA,CAA2B,IAAI,aAAa,CAAA,CAAA;AAC7D,YAAM,MAAA,cAAA,CAAe,MAAM,MAAM;AAAA,aAAE,CAAA,CAAA;AAAA,WACrC;AAAA,SACD,CAAA;AAAA,OACF,CAAA;AAAA,KACF,CAAA,CAAA;AAED,I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,WAAW,QAAU,EAAA;AACpC,YAAA,OAAA;AAAA,WACF;AACA,UAAA,GAAA,CAAI,IAAK,CAAA;AAAA,YACP,IAAM,EAAA;AAAA,cACJ,GAAG,WAAA;AAAA,cACH,OAAA;AAAA,aACF;AAAA,WACD,CAAA,CAAA;AAAA,SACH;AAAA,QACA,UAAU,YAAY;AACpB,UAAM,MAAA,IAAI,MAAM,iBAAiB,CAAA,CAAA;AAAA,SACnC;AAAA,OACD,CAAA,CAAA;AAED,MAAA,IAAI,CAAC,cAAgB,EAAA;AACnB,QAAM,MAAA,IAAI,MAAM,qCAAqC,CAAA,CAAA;AAAA,OACvD;AACA,MAAA,MAAM,oBAAoB,MAAM,cAAA,CAAA;AAEhC,MAAO,OAAA;AAAA,QACL,GAAA;AAAA,QACA,iBAAA;AAAA,QACA,QAAQ,MAAO,CAAA,MAAA;AAAA,OACjB,CAAA;AAAA,KACA,SAAA;AACA,MAAM,MAAAG,mBAAA,CAAG,OAAO,YAAY,CAAA,CAAA;AAAA,KAC9B;AAAA,GACF,CAAA;AACF;;;;"} -\ No newline at end of file -+{"version":3,"file":"createDryRunner.cjs.js","sources":["../../../src/scaffolder/dryrun/createDryRunner.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ScmIntegrations } from '@backstage/integration';\nimport { TaskSpec } from '@backstage/plugin-scaffolder-common';\nimport { JsonObject } from '@backstage/types';\nimport { v4 as uuid } from 'uuid';\nimport { pathToFileURL } from 'url';\nimport { Logger } from 'winston';\nimport {\n createTemplateAction,\n TaskSecrets,\n TemplateFilter,\n TemplateGlobal,\n deserializeDirectoryContents,\n SerializedFile,\n serializeDirectoryContents,\n} from '@backstage/plugin-scaffolder-node';\nimport { TemplateActionRegistry } from '../actions';\nimport { NunjucksWorkflowRunner } from '../tasks/NunjucksWorkflowRunner';\nimport { DecoratedActionsRegistry } from './DecoratedActionsRegistry';\nimport fs from 'fs-extra';\nimport { PermissionEvaluator } from '@backstage/plugin-permission-common';\nimport {\n BackstageCredentials,\n resolveSafeChildPath,\n} from '@backstage/backend-plugin-api';\nimport type { UserEntity } from '@backstage/catalog-model';\nimport { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\n\ninterface DryRunInput {\n spec: TaskSpec;\n secrets?: TaskSecrets;\n directoryContents: SerializedFile[];\n credentials: BackstageCredentials;\n user?: {\n entity?: UserEntity;\n ref?: string;\n };\n}\n\ninterface DryRunResult {\n log: Array<{ body: JsonObject }>;\n directoryContents: SerializedFile[];\n output: JsonObject;\n}\n\n/** @internal */\nexport type TemplateTesterCreateOptions = {\n logger: Logger;\n auditLogger: AuditLogger;\n integrations: ScmIntegrations;\n actionRegistry: TemplateActionRegistry;\n workingDirectory: string;\n additionalTemplateFilters?: Record;\n additionalTemplateGlobals?: Record;\n permissions?: PermissionEvaluator;\n};\n\n/**\n * Executes a dry-run of the provided template.\n *\n * The provided content will be extracted into a temporary directory\n * which is then use as the base for any relative file fetch paths.\n *\n * @internal\n */\nexport function createDryRunner(options: TemplateTesterCreateOptions) {\n return async function dryRun(input: DryRunInput): Promise {\n let contentPromise;\n\n const workflowRunner = new NunjucksWorkflowRunner({\n ...options,\n actionRegistry: new DecoratedActionsRegistry(options.actionRegistry, [\n createTemplateAction({\n id: 'dry-run:extract',\n supportsDryRun: true,\n async handler(ctx) {\n contentPromise = serializeDirectoryContents(ctx.workspacePath);\n await contentPromise.catch(() => {});\n },\n }),\n ]),\n });\n\n const dryRunId = uuid();\n const log = new Array<{ body: JsonObject }>();\n const contentsPath = resolveSafeChildPath(\n options.workingDirectory,\n `dry-run-content-${dryRunId}`,\n );\n\n try {\n await deserializeDirectoryContents(contentsPath, input.directoryContents);\n\n const abortSignal = new AbortController().signal;\n\n const result = await workflowRunner.execute({\n taskId: dryRunId,\n spec: {\n ...input.spec,\n steps: [\n ...input.spec.steps,\n {\n id: dryRunId,\n name: 'dry-run:extract',\n action: 'dry-run:extract',\n },\n ],\n templateInfo: {\n entityRef: 'template:default/dry-run',\n baseUrl: pathToFileURL(\n resolveSafeChildPath(contentsPath, 'template.yaml'),\n ).toString(),\n },\n },\n secrets: input.secrets,\n getInitiatorCredentials: () => Promise.resolve(input.credentials),\n // No need to update this at the end of the run, so just hard-code it\n done: false,\n isDryRun: true,\n getWorkspaceName: async () => `dry-run-${dryRunId}`,\n cancelSignal: abortSignal,\n async emitLog(message: string, logMetadata?: JsonObject) {\n if (logMetadata?.stepId === dryRunId) {\n return;\n }\n log.push({\n body: {\n ...logMetadata,\n message,\n },\n });\n },\n complete: async () => {\n throw new Error('Not implemented');\n },\n });\n\n if (!contentPromise) {\n throw new Error('Content extraction step was skipped');\n }\n const directoryContents = await contentPromise;\n\n return {\n log,\n directoryContents,\n output: result.output,\n };\n } finally {\n await fs.remove(contentsPath);\n }\n };\n}\n"],"names":["NunjucksWorkflowRunner","DecoratedActionsRegistry","createTemplateAction","serializeDirectoryContents","uuid","resolveSafeChildPath","deserializeDirectoryContents","pathToFileURL","fs"],"mappings":";;;;;;;;;;;;;;AAgFO,SAAS,gBAAgB,OAAsC,EAAA;AACpE,EAAO,OAAA,eAAe,OAAO,KAA2C,EAAA;AACtE,IAAI,IAAA,cAAA,CAAA;AAEJ,IAAM,MAAA,cAAA,GAAiB,IAAIA,6CAAuB,CAAA;AAAA,MAChD,GAAG,OAAA;AAAA,MACH,cAAgB,EAAA,IAAIC,iDAAyB,CAAA,OAAA,CAAQ,cAAgB,EAAA;AAAA,QACnEC,yCAAqB,CAAA;AAAA,UACnB,EAAI,EAAA,iBAAA;AAAA,UACJ,cAAgB,EAAA,IAAA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CAAQ,MAAM,WAAW,CAAA;AAAA;AAAA,QAEhE,IAAM,EAAA,KAAA;AAAA,QACN,QAAU,EAAA,IAAA;AAAA,QACV,gBAAA,EAAkB,YAAY,CAAA,QAAA,EAAW,QAAQ,CAAA,CAAA;AAAA,QACjD,YAAc,EAAA,WAAA;AAAA,QACd,MAAM,OAAQ,CAAA,OAAA,EAAiB,WAA0B,EAAA;AACvD,UAAI,IAAA,WAAA,EAAa,WAAW,QAAU,EAAA;AACpC,YAAA,OAAA;AAAA,WACF;AACA,UAAA,GAAA,CAAI,IAAK,CAAA;AAAA,YACP,IAAM,EAAA;AAAA,cACJ,GAAG,WAAA;AAAA,cACH,OAAA;AAAA,aACF;AAAA,WACD,CAAA,CAAA;AAAA,SACH;AAAA,QACA,UAAU,YAAY;AACpB,UAAM,MAAA,IAAI,MAAM,iBAAiB,CAAA,CAAA;AAAA,SACnC;AAAA,OACD,CAAA,CAAA;AAED,MAAA,IAAI,CAAC,cAAgB,EAAA;AACnB,QAAM,MAAA,IAAI,MAAM,qCAAqC,CAAA,CAAA;AAAA,OACvD;AACA,MAAA,MAAM,oBAAoB,MAAM,cAAA,CAAA;AAEhC,MAAO,OAAA;AAAA,QACL,GAAA;AAAA,QACA,iBAAA;AAAA,QACA,QAAQ,MAAO,CAAA,MAAA;AAAA,OACjB,CAAA;AAAA,KACA,SAAA;AACA,MAAM,MAAAG,mBAAA,CAAG,OAAO,YAAY,CAAA,CAAA;AAAA,KAC9B;AAAA,GACF,CAAA;AACF;;;;"} -\ No newline at end of file -diff --git a/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js b/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js -index eed6830ca6e3f3dd18cd0bad3dcaf1b3f36bd1ac..0b3eca651b23f6de6384412d62d57c4929fb0166 100644 ---- a/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js -+++ b/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js -@@ -79,9 +79,10 @@ class NunjucksWorkflowRunner { - this.defaultTemplateFilters = filters.createDefaultFilters({ - integrations: this.options.integrations - }); -+ this.tracker = scaffoldingTracker(this.options.auditLogger); - } - defaultTemplateFilters; -- tracker = scaffoldingTracker(); -+ tracker; - isSingleTemplateString(input) { - const { parser, nodes } = nunjucks__default.default; - const parsed = parser.parse( -@@ -133,34 +134,63 @@ class NunjucksWorkflowRunner { - async executeStep(task, step, context, renderTemplate, taskTrack, workspacePath, decision) { - const stepTrack = await this.tracker.stepStart(task, step); - if (task.cancelSignal.aborted) { -- throw new Error(`Step ${step.name} has been cancelled.`); -+ throw new Error( -+ `Step ${step.id} (${step.name}) of task ${task.taskId} has been cancelled.` -+ ); - } - try { -- if (step.if === false || typeof step.if === "string" && !helper.isTruthy(this.render(step.if, context, renderTemplate))) { -- await stepTrack.skipFalsy(); -- return; -- } - const action = this.options.actionRegistry.get(step.action); - const { taskLogger, streamLogger } = createStepLogger({ - task, - step, - rootLogger: this.options.logger - }); -+ const redactedSecrets = Object.fromEntries( -+ Object.entries(task.secrets ?? {}).map((secret) => [secret[0], "***"]) -+ ); -+ const stepInputs = (step.input && this.render( -+ step.input, -+ { -+ ...context, -+ secrets: redactedSecrets -+ }, -+ renderTemplate -+ )) ?? {}; -+ const commonStepAuditMetadata = { -+ templateRef: task.spec.templateInfo?.entityRef || "", -+ taskId: task.taskId, -+ stepId: step.id, -+ stepName: step.name, -+ stepAction: step.action, -+ stepInputs, -+ stepConditional: step.if, -+ stepEach: step.each, -+ isDryRun: task.isDryRun || false -+ }; -+ if (step.if === false || typeof step.if === "string" && !helper.isTruthy(this.render(step.if, context, renderTemplate))) { -+ await stepTrack.skipFalsy(); -+ await this.options.auditLogger.auditLog({ -+ eventName: "ScaffolderTaskStepSkip", -+ actorId: "scaffolder-backend", -+ stage: "completion", -+ status: "succeeded", -+ metadata: commonStepAuditMetadata, -+ message: `Skipped step ${step.name} (id: ${step.id}) of task ${task.taskId}` -+ }); -+ return; -+ } -+ await this.options.auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderTaskStepExecution", -+ stage: "initiation", -+ status: "succeeded", -+ metadata: commonStepAuditMetadata, -+ message: `Started ${step.name} (id: ${step.id}) of task ${task.taskId} triggering the ${step.action} action` -+ }); - if (task.isDryRun) { -- const redactedSecrets = Object.fromEntries( -- Object.entries(task.secrets ?? {}).map((secret) => [secret[0], "***"]) -- ); -- const debugInput = (step.input && this.render( -- step.input, -- { -- ...context, -- secrets: redactedSecrets -- }, -- renderTemplate -- )) ?? {}; - taskLogger.info( - `Running ${action.id} in dry-run mode with inputs (secrets redacted): ${JSON.stringify( -- debugInput, -+ stepInputs, - void 0, - 2 - )}` -@@ -221,6 +251,7 @@ class NunjucksWorkflowRunner { - const tmpDirs = new Array(); - const stepOutput = {}; - const prevTaskState = await task.getTaskState?.(); -+ let iterationCount = 0; - for (const iteration of iterations) { - if (iteration.each) { - taskLogger.info( -@@ -230,6 +261,22 @@ class NunjucksWorkflowRunner { - 0 - )}` - ); -+ await this.options.auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderTaskStepIteration", -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ ...commonStepAuditMetadata, -+ stepInputs: void 0, -+ stepAction: `${step.action}[${iteration.each.key}]`, -+ stepIterationInputs: iteration.input, -+ stepIterationCount: ++iterationCount, -+ stepIterationValue: iteration.each.value, -+ totalIterations: iterations.length -+ }, -+ message: `Iteration ${iterationCount}/${iterations.length} of action ${step.action} of step ${step.name} (id: ${step.id}) of task ${task.taskId} started` -+ }); - } - await action.handler({ - input: iteration.input, -@@ -289,18 +336,38 @@ class NunjucksWorkflowRunner { - signal: task.cancelSignal, - getInitiatorCredentials: () => task.getInitiatorCredentials() - }); -+ if (iteration.each) { -+ await this.options.auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderTaskStepIteration", -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ ...commonStepAuditMetadata, -+ stepInputs: void 0, -+ stepAction: `${step.action}[${iteration.each.key}]`, -+ stepIterationCount: iterationCount, -+ stepIterationValue: iteration.each.value, -+ stepIterationInputs: iteration.input, -+ totalIterations: iterations.length -+ }, -+ message: `Iteration ${iterationCount}/${iterations.length} of action ${step.action} of step ${step.name} (id: ${step.id}) of task ${task.taskId} succeeded` -+ }); -+ } - } - for (const tmpDir of tmpDirs) { - await fs__default.default.remove(tmpDir); - } - context.steps[step.id] = { output: stepOutput }; - if (task.cancelSignal.aborted) { -- throw new Error(`Step ${step.name} has been cancelled.`); -+ throw new Error( -+ `Step ${step.id} (${step.name}) of task ${task.taskId} has been cancelled.` -+ ); - } - await stepTrack.markSuccessful(); - } catch (err) { - await taskTrack.markFailed(step, err); -- await stepTrack.markFailed(); -+ await stepTrack.markFailed(err); - throw err; - } finally { - await task.serializeWorkspace?.({ path: workspacePath }); -@@ -357,7 +424,7 @@ class NunjucksWorkflowRunner { - } - } - } --function scaffoldingTracker() { -+function scaffoldingTracker(auditLogger) { - const promTaskCount = metrics.createCounterMetric({ - name: "scaffolder_task_count", - help: "Count of task runs", -@@ -492,6 +559,21 @@ function scaffoldingTracker() { - stepDuration.record(endTime(), { - result: "ok" - }); -+ await auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderTaskStepExecution", -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ templateRef: template, -+ taskId: task.taskId, -+ stepId: step.id, -+ stepName: step.name, -+ stepAction: step.action, -+ isDryRun: task.isDryRun || false -+ }, -+ message: `Step ${step.name} (id: ${step.id}) of task ${task.taskId} succeeded` -+ }); - } - async function markCancelled() { - promtStepCount.inc({ -@@ -505,7 +587,7 @@ function scaffoldingTracker() { - result: "cancelled" - }); - } -- async function markFailed() { -+ async function markFailed(err) { - promtStepCount.inc({ - template, - step: step.name, -@@ -516,6 +598,29 @@ function scaffoldingTracker() { - stepDuration.record(endTime(), { - result: "failed" - }); -+ await auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderTaskStepExecution", -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ metadata: { -+ templateRef: template, -+ taskId: task.taskId, -+ stepId: step.id, -+ stepName: step.name, -+ stepAction: step.action, -+ isDryRun: task.isDryRun || false -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Step ${step.name} (id: ${step.id}) of task ${task.taskId} failed` -+ }); - } - async function skipFalsy() { - await task.emitLog( -diff --git a/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js.map b/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js.map -index 427b1b440f43e0f5773f93dc44358838162b34f0..ba4def6722d29e51ad274a03a8725fb53f22f33b 100644 ---- a/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js.map -+++ b/dist/scaffolder/tasks/NunjucksWorkflowRunner.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"NunjucksWorkflowRunner.cjs.js","sources":["../../../src/scaffolder/tasks/NunjucksWorkflowRunner.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ScmIntegrations } from '@backstage/integration';\nimport { TaskTrackType, WorkflowResponse, WorkflowRunner } from './types';\nimport * as winston from 'winston';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport nunjucks from 'nunjucks';\nimport { JsonArray, JsonObject, JsonValue } from '@backstage/types';\nimport { InputError, NotAllowedError, stringifyError } from '@backstage/errors';\nimport { PassThrough } from 'stream';\nimport { generateExampleOutput, isTruthy } from './helper';\nimport { validate as validateJsonSchema } from 'jsonschema';\nimport { TemplateActionRegistry } from '../actions';\nimport { metrics } from '@opentelemetry/api';\nimport {\n SecureTemplater,\n SecureTemplateRenderer,\n} from '../../lib/templating/SecureTemplater';\nimport {\n TaskRecovery,\n TaskSpec,\n TaskSpecV1beta3,\n TaskStep,\n} from '@backstage/plugin-scaffolder-common';\n\nimport {\n TemplateAction,\n TemplateFilter,\n TemplateGlobal,\n TaskContext,\n} from '@backstage/plugin-scaffolder-node';\nimport { createConditionAuthorizer } from '@backstage/plugin-permission-node';\nimport { UserEntity } from '@backstage/catalog-model';\nimport { createCounterMetric, createHistogramMetric } from '../../util/metrics';\nimport { createDefaultFilters } from '../../lib/templating/filters';\nimport {\n AuthorizeResult,\n PolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport { scaffolderActionRules } from '../../service/rules';\nimport { actionExecutePermission } from '@backstage/plugin-scaffolder-common/alpha';\nimport { PermissionsService } from '@backstage/backend-plugin-api';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport { BackstageLoggerTransport, WinstonLogger } from './logger';\n\ntype NunjucksWorkflowRunnerOptions = {\n workingDirectory: string;\n actionRegistry: TemplateActionRegistry;\n integrations: ScmIntegrations;\n logger: winston.Logger;\n additionalTemplateFilters?: Record;\n additionalTemplateGlobals?: Record;\n permissions?: PermissionsService;\n};\n\ntype TemplateContext = {\n parameters: JsonObject;\n EXPERIMENTAL_recovery?: TaskRecovery;\n steps: {\n [stepName: string]: { output: { [outputName: string]: JsonValue } };\n };\n secrets?: Record;\n user?: {\n entity?: UserEntity;\n ref?: string;\n };\n each?: JsonValue;\n};\n\ntype CheckpointState =\n | {\n status: 'failed';\n reason: string;\n }\n | {\n status: 'success';\n value: JsonValue;\n };\n\nconst isValidTaskSpec = (taskSpec: TaskSpec): taskSpec is TaskSpecV1beta3 => {\n return taskSpec.apiVersion === 'scaffolder.backstage.io/v1beta3';\n};\n\nconst createStepLogger = ({\n task,\n step,\n rootLogger,\n}: {\n task: TaskContext;\n step: TaskStep;\n rootLogger: winston.Logger;\n}) => {\n const taskLogger = WinstonLogger.create({\n level: process.env.LOG_LEVEL || 'info',\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.simple(),\n ),\n transports: [new BackstageLoggerTransport(rootLogger, task, step.id)],\n });\n\n taskLogger.addRedactions(Object.values(task.secrets ?? {}));\n\n // This stream logger should be deprecated. We're going to replace it with\n // just using the logger directly, as all those logs get written to step logs\n // using the stepLogStream above.\n // Initially this stream used to be the only way to write to the client logs, but that\n // has changed over time, there's not really a need for this anymore.\n // You can just create a simple wrapper like the below in your action to write to the main logger.\n // This way we also get recactions for free.\n const streamLogger = new PassThrough();\n streamLogger.on('data', async data => {\n const message = data.toString().trim();\n if (message?.length > 1) {\n taskLogger.info(message);\n }\n });\n\n return { taskLogger, streamLogger };\n};\n\nconst isActionAuthorized = createConditionAuthorizer(\n Object.values(scaffolderActionRules),\n);\n\nexport class NunjucksWorkflowRunner implements WorkflowRunner {\n private readonly defaultTemplateFilters: Record;\n\n constructor(private readonly options: NunjucksWorkflowRunnerOptions) {\n this.defaultTemplateFilters = createDefaultFilters({\n integrations: this.options.integrations,\n });\n }\n\n private readonly tracker = scaffoldingTracker();\n\n private isSingleTemplateString(input: string) {\n const { parser, nodes } = nunjucks as unknown as {\n parser: {\n parse(\n template: string,\n ctx: object,\n options: nunjucks.ConfigureOptions,\n ): { children: { children?: unknown[] }[] };\n };\n nodes: { TemplateData: Function };\n };\n\n const parsed = parser.parse(\n input,\n {},\n {\n autoescape: false,\n tags: {\n variableStart: '${{',\n variableEnd: '}}',\n },\n },\n );\n\n return (\n parsed.children.length === 1 &&\n !(parsed.children[0]?.children?.[0] instanceof nodes.TemplateData)\n );\n }\n\n private render(\n input: T,\n context: TemplateContext,\n renderTemplate: SecureTemplateRenderer,\n ): T {\n return JSON.parse(JSON.stringify(input), (_key, value) => {\n try {\n if (typeof value === 'string') {\n try {\n if (this.isSingleTemplateString(value)) {\n // Lets convert ${{ parameters.bob }} to ${{ (parameters.bob) | dump }} so we can keep the input type\n const wrappedDumped = value.replace(\n /\\${{(.+)}}/g,\n '${{ ( $1 ) | dump }}',\n );\n\n // Run the templating\n const templated = renderTemplate(wrappedDumped, context);\n\n // If there's an empty string returned, then it's undefined\n if (templated === '') {\n return undefined;\n }\n\n // Reparse the dumped string\n return JSON.parse(templated);\n }\n } catch (ex) {\n this.options.logger.error(\n `Failed to parse template string: ${value} with error ${ex.message}`,\n );\n }\n\n // Fallback to default behaviour\n const templated = renderTemplate(value, context);\n\n if (templated === '') {\n return undefined;\n }\n\n return templated;\n }\n } catch {\n return value;\n }\n return value;\n });\n }\n\n async executeStep(\n task: TaskContext,\n step: TaskStep,\n context: TemplateContext,\n renderTemplate: (template: string, values: unknown) => string,\n taskTrack: TaskTrackType,\n workspacePath: string,\n decision: PolicyDecision,\n ) {\n const stepTrack = await this.tracker.stepStart(task, step);\n\n if (task.cancelSignal.aborted) {\n throw new Error(`Step ${step.name} has been cancelled.`);\n }\n\n try {\n if (\n step.if === false ||\n (typeof step.if === 'string' &&\n !isTruthy(this.render(step.if, context, renderTemplate)))\n ) {\n await stepTrack.skipFalsy();\n return;\n }\n const action: TemplateAction =\n this.options.actionRegistry.get(step.action);\n const { taskLogger, streamLogger } = createStepLogger({\n task,\n step,\n rootLogger: this.options.logger,\n });\n\n if (task.isDryRun) {\n const redactedSecrets = Object.fromEntries(\n Object.entries(task.secrets ?? {}).map(secret => [secret[0], '***']),\n );\n const debugInput =\n (step.input &&\n this.render(\n step.input,\n {\n ...context,\n secrets: redactedSecrets,\n },\n renderTemplate,\n )) ??\n {};\n taskLogger.info(\n `Running ${\n action.id\n } in dry-run mode with inputs (secrets redacted): ${JSON.stringify(\n debugInput,\n undefined,\n 2,\n )}`,\n );\n if (!action.supportsDryRun) {\n await taskTrack.skipDryRun(step, action);\n const outputSchema = action.schema?.output;\n if (outputSchema) {\n context.steps[step.id] = {\n output: generateExampleOutput(outputSchema) as {\n [name in string]: JsonValue;\n },\n };\n } else {\n context.steps[step.id] = { output: {} };\n }\n return;\n }\n }\n const iterations = (\n step.each\n ? Object.entries(this.render(step.each, context, renderTemplate)).map(\n ([key, value]) => ({\n each: { key, value },\n }),\n )\n : [{}]\n ).map(i => ({\n ...i,\n // Secrets are only passed when templating the input to actions for security reasons\n input: step.input\n ? this.render(\n step.input,\n { ...context, secrets: task.secrets ?? {}, ...i },\n renderTemplate,\n )\n : {},\n }));\n for (const iteration of iterations) {\n const actionId = `${action.id}${\n iteration.each ? `[${iteration.each.key}]` : ''\n }`;\n\n if (action.schema?.input) {\n const validateResult = validateJsonSchema(\n iteration.input,\n action.schema.input,\n );\n if (!validateResult.valid) {\n const errors = validateResult.errors.join(', ');\n throw new InputError(\n `Invalid input passed to action ${actionId}, ${errors}`,\n );\n }\n }\n if (\n !isActionAuthorized(decision, {\n action: action.id,\n input: iteration.input,\n })\n ) {\n throw new NotAllowedError(\n `Unauthorized action: ${actionId}. The action is not allowed. Input: ${JSON.stringify(\n iteration.input,\n null,\n 2,\n )}`,\n );\n }\n }\n const tmpDirs = new Array();\n const stepOutput: { [outputName: string]: JsonValue } = {};\n const prevTaskState = await task.getTaskState?.();\n\n for (const iteration of iterations) {\n if (iteration.each) {\n taskLogger.info(\n `Running step each: ${JSON.stringify(\n iteration.each,\n (k, v) => (k ? v.toString() : v),\n 0,\n )}`,\n );\n }\n await action.handler({\n input: iteration.input,\n secrets: task.secrets ?? {},\n // TODO(blam): move to LoggerService and away from Winston\n logger: loggerToWinstonLogger(taskLogger),\n logStream: streamLogger,\n workspacePath,\n async checkpoint(\n keySuffix: string,\n fn: () => Promise,\n ) {\n const key = `v1.task.checkpoint.${step.id}.${keySuffix}`;\n try {\n let prevValue: U | undefined;\n if (prevTaskState) {\n const prevState = (\n prevTaskState.state?.checkpoints as {\n [key: string]: CheckpointState;\n }\n )?.[key];\n if (prevState && prevState.status === 'success') {\n prevValue = prevState.value as U;\n }\n }\n\n const value = prevValue ? prevValue : await fn();\n\n if (!prevValue) {\n task.updateCheckpoint?.({\n key,\n status: 'success',\n value,\n });\n }\n return value;\n } catch (err) {\n task.updateCheckpoint?.({\n key,\n status: 'failed',\n reason: stringifyError(err),\n });\n throw err;\n } finally {\n await task.serializeWorkspace?.({ path: workspacePath });\n }\n },\n createTemporaryDirectory: async () => {\n const tmpDir = await fs.mkdtemp(\n `${workspacePath}_step-${step.id}-`,\n );\n tmpDirs.push(tmpDir);\n return tmpDir;\n },\n output(name: string, value: JsonValue) {\n if (step.each) {\n stepOutput[name] = stepOutput[name] || [];\n (stepOutput[name] as JsonArray).push(value);\n } else {\n stepOutput[name] = value;\n }\n },\n templateInfo: task.spec.templateInfo,\n user: task.spec.user,\n isDryRun: task.isDryRun,\n signal: task.cancelSignal,\n getInitiatorCredentials: () => task.getInitiatorCredentials(),\n });\n }\n\n // Remove all temporary directories that were created when executing the action\n for (const tmpDir of tmpDirs) {\n await fs.remove(tmpDir);\n }\n\n context.steps[step.id] = { output: stepOutput };\n\n if (task.cancelSignal.aborted) {\n throw new Error(`Step ${step.name} has been cancelled.`);\n }\n\n await stepTrack.markSuccessful();\n } catch (err) {\n await taskTrack.markFailed(step, err);\n await stepTrack.markFailed();\n throw err;\n } finally {\n await task.serializeWorkspace?.({ path: workspacePath });\n }\n }\n\n async execute(task: TaskContext): Promise {\n if (!isValidTaskSpec(task.spec)) {\n throw new InputError(\n 'Wrong template version executed with the workflow engine',\n );\n }\n const taskId = await task.getWorkspaceName();\n\n const workspacePath = path.join(this.options.workingDirectory, taskId);\n\n const { additionalTemplateFilters, additionalTemplateGlobals } =\n this.options;\n\n const renderTemplate = await SecureTemplater.loadRenderer({\n templateFilters: {\n ...this.defaultTemplateFilters,\n ...additionalTemplateFilters,\n },\n templateGlobals: additionalTemplateGlobals,\n });\n\n try {\n await task.rehydrateWorkspace?.({ taskId, targetPath: workspacePath });\n\n const taskTrack = await this.tracker.taskStart(task);\n await fs.ensureDir(workspacePath);\n\n const context: TemplateContext = {\n parameters: task.spec.parameters,\n steps: {},\n user: task.spec.user,\n };\n\n const [decision]: PolicyDecision[] =\n this.options.permissions && task.spec.steps.length\n ? await this.options.permissions.authorizeConditional(\n [{ permission: actionExecutePermission }],\n { credentials: await task.getInitiatorCredentials() },\n )\n : [{ result: AuthorizeResult.ALLOW }];\n\n for (const step of task.spec.steps) {\n await this.executeStep(\n task,\n step,\n context,\n renderTemplate,\n taskTrack,\n workspacePath,\n decision,\n );\n }\n\n const output = this.render(task.spec.output, context, renderTemplate);\n await taskTrack.markSuccessful();\n await task.cleanWorkspace?.();\n\n return { output };\n } finally {\n if (workspacePath) {\n await fs.remove(workspacePath);\n }\n }\n }\n}\n\nfunction scaffoldingTracker() {\n // prom-client metrics are deprecated in favour of OpenTelemetry metrics.\n const promTaskCount = createCounterMetric({\n name: 'scaffolder_task_count',\n help: 'Count of task runs',\n labelNames: ['template', 'user', 'result'],\n });\n const promTaskDuration = createHistogramMetric({\n name: 'scaffolder_task_duration',\n help: 'Duration of a task run',\n labelNames: ['template', 'result'],\n });\n const promtStepCount = createCounterMetric({\n name: 'scaffolder_step_count',\n help: 'Count of step runs',\n labelNames: ['template', 'step', 'result'],\n });\n const promStepDuration = createHistogramMetric({\n name: 'scaffolder_step_duration',\n help: 'Duration of a step runs',\n labelNames: ['template', 'step', 'result'],\n });\n\n const meter = metrics.getMeter('default');\n const taskCount = meter.createCounter('scaffolder.task.count', {\n description: 'Count of task runs',\n });\n\n const taskDuration = meter.createHistogram('scaffolder.task.duration', {\n description: 'Duration of a task run',\n unit: 'seconds',\n });\n\n const stepCount = meter.createCounter('scaffolder.step.count', {\n description: 'Count of step runs',\n });\n\n const stepDuration = meter.createHistogram('scaffolder.step.duration', {\n description: 'Duration of a step runs',\n unit: 'seconds',\n });\n\n async function taskStart(task: TaskContext) {\n await task.emitLog(`Starting up task with ${task.spec.steps.length} steps`);\n const template = task.spec.templateInfo?.entityRef || '';\n const user = task.spec.user?.ref || '';\n\n const startTime = process.hrtime();\n const taskTimer = promTaskDuration.startTimer({\n template,\n });\n\n function endTime() {\n const delta = process.hrtime(startTime);\n return delta[0] + delta[1] / 1e9;\n }\n\n async function skipDryRun(\n step: TaskStep,\n action: TemplateAction,\n ) {\n task.emitLog(`Skipping because ${action.id} does not support dry-run`, {\n stepId: step.id,\n status: 'skipped',\n });\n }\n\n async function markSuccessful() {\n promTaskCount.inc({\n template,\n user,\n result: 'ok',\n });\n taskTimer({ result: 'ok' });\n\n taskCount.add(1, { template, user, result: 'ok' });\n taskDuration.record(endTime(), {\n result: 'ok',\n });\n }\n\n async function markFailed(step: TaskStep, err: Error) {\n await task.emitLog(String(err.stack), {\n stepId: step.id,\n status: 'failed',\n });\n promTaskCount.inc({\n template,\n user,\n result: 'failed',\n });\n taskTimer({ result: 'failed' });\n\n taskCount.add(1, { template, user, result: 'failed' });\n taskDuration.record(endTime(), {\n result: 'failed',\n });\n }\n\n async function markCancelled(step: TaskStep) {\n await task.emitLog(`Step ${step.id} has been cancelled.`, {\n stepId: step.id,\n status: 'cancelled',\n });\n promTaskCount.inc({\n template,\n user,\n result: 'cancelled',\n });\n taskTimer({ result: 'cancelled' });\n\n taskCount.add(1, { template, user, result: 'cancelled' });\n taskDuration.record(endTime(), {\n result: 'cancelled',\n });\n }\n\n return {\n skipDryRun,\n markCancelled,\n markSuccessful,\n markFailed,\n };\n }\n\n async function stepStart(task: TaskContext, step: TaskStep) {\n await task.emitLog(`Beginning step ${step.name}`, {\n stepId: step.id,\n status: 'processing',\n });\n const template = task.spec.templateInfo?.entityRef || '';\n\n const startTime = process.hrtime();\n const stepTimer = promStepDuration.startTimer({\n template,\n step: step.name,\n });\n\n function endTime() {\n const delta = process.hrtime(startTime);\n return delta[0] + delta[1] / 1e9;\n }\n\n async function markSuccessful() {\n await task.emitLog(`Finished step ${step.name}`, {\n stepId: step.id,\n status: 'completed',\n });\n promtStepCount.inc({\n template,\n step: step.name,\n result: 'ok',\n });\n stepTimer({ result: 'ok' });\n\n stepCount.add(1, { template, step: step.name, result: 'ok' });\n stepDuration.record(endTime(), {\n result: 'ok',\n });\n }\n\n async function markCancelled() {\n promtStepCount.inc({\n template,\n step: step.name,\n result: 'cancelled',\n });\n stepTimer({ result: 'cancelled' });\n\n stepCount.add(1, { template, step: step.name, result: 'cancelled' });\n stepDuration.record(endTime(), {\n result: 'cancelled',\n });\n }\n\n async function markFailed() {\n promtStepCount.inc({\n template,\n step: step.name,\n result: 'failed',\n });\n stepTimer({ result: 'failed' });\n\n stepCount.add(1, { template, step: step.name, result: 'failed' });\n stepDuration.record(endTime(), {\n result: 'failed',\n });\n }\n\n async function skipFalsy() {\n await task.emitLog(\n `Skipping step ${step.id} because its if condition was false`,\n { stepId: step.id, status: 'skipped' },\n );\n stepTimer({ result: 'skipped' });\n\n stepCount.add(1, { template, step: step.name, result: 'skipped' });\n stepDuration.record(endTime(), {\n result: 'skipped',\n });\n }\n\n return {\n markCancelled,\n markFailed,\n markSuccessful,\n skipFalsy,\n };\n }\n\n return {\n taskStart,\n stepStart,\n };\n}\n"],"names":["WinstonLogger","winston","BackstageLoggerTransport","PassThrough","createConditionAuthorizer","scaffolderActionRules","createDefaultFilters","nunjucks","templated","isTruthy","generateExampleOutput","validateJsonSchema","errors","InputError","NotAllowedError","loggerToWinstonLogger","stringifyError","fs","path","SecureTemplater","actionExecutePermission","AuthorizeResult","createCounterMetric","createHistogramMetric","metrics"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAM,eAAA,GAAkB,CAAC,QAAoD,KAAA;AAC3E,EAAA,OAAO,SAAS,UAAe,KAAA,iCAAA,CAAA;AACjC,CAAA,CAAA;AAEA,MAAM,mBAAmB,CAAC;AAAA,EACxB,IAAA;AAAA,EACA,IAAA;AAAA,EACA,UAAA;AACF,CAIM,KAAA;AACJ,EAAM,MAAA,UAAA,GAAaA,qBAAc,MAAO,CAAA;AAAA,IACtC,KAAA,EAAO,OAAQ,CAAA,GAAA,CAAI,SAAa,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U,CAAA,CAAA;AAChE,MAAa,YAAA,CAAA,MAAA,CAAO,SAAW,EAAA;AAAA,QAC7B,MAAQ,EAAA,QAAA;AAAA,OACT,CAAA,CAAA;AAAA,KACH;AAEA,IAAA,eAAe,SAAY,GAAA;AACzB,MAAA,MAAM,IAAK,CAAA,OAAA;AAAA,QACT,CAAA,cAAA,EAAiB,KAAK,EAAE,CAAA,mCAAA,CAAA;AAAA,QACxB,EAAE,MAAA,EAAQ,IAAK,CAAA,EAAA,EAAI,QAAQ,SAAU,EAAA;AAAA,OACvC,CAAA;AACA,MAAU,SAAA,CAAA,EAAE,MAAQ,EAAA,SAAA,EAAW,CAAA,CAAA;AAE/B,MAAU,SAAA,CAAA,GAAA,CAAI,GAAG,EAAE,QAAA,EAAU,MAAM,IAAK,CAAA,IAAA,EAAM,MAAQ,EAAA,SAAA,EAAW,CAAA,CAAA;AACjE,MAAa,YAAA,CAAA,MAAA,CAAO,SAAW,EAAA;AAAA,QAC7B,MAAQ,EAAA,SAAA;AAAA,OACT,CAAA,CAAA;AAAA,KACH;AAEA,IAAO,OAAA;AAAA,MACL,aAAA;AAAA,MACA,UAAA;AAAA,MACA,cAAA;AAAA,MACA,SAAA;AAAA,KACF,CAAA;AAAA,GACF;AAEA,EAAO,OAAA;AAAA,IACL,SAAA;AAAA,IACA,SAAA;AAAA,GACF,CAAA;AACF;;;;"} -\ No newline at end of file -+{"version":3,"file":"NunjucksWorkflowRunner.cjs.js","sources":["../../../src/scaffolder/tasks/NunjucksWorkflowRunner.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ScmIntegrations } from '@backstage/integration';\nimport { TaskTrackType, WorkflowResponse, WorkflowRunner } from './types';\nimport * as winston from 'winston';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport nunjucks from 'nunjucks';\nimport { JsonArray, JsonObject, JsonValue } from '@backstage/types';\nimport { InputError, NotAllowedError, stringifyError } from '@backstage/errors';\nimport { PassThrough } from 'stream';\nimport { generateExampleOutput, isTruthy } from './helper';\nimport { validate as validateJsonSchema } from 'jsonschema';\nimport { TemplateActionRegistry } from '../actions';\nimport { metrics } from '@opentelemetry/api';\nimport {\n SecureTemplater,\n SecureTemplateRenderer,\n} from '../../lib/templating/SecureTemplater';\nimport {\n TaskRecovery,\n TaskSpec,\n TaskSpecV1beta3,\n TaskStep,\n} from '@backstage/plugin-scaffolder-common';\n\nimport {\n TemplateAction,\n TemplateFilter,\n TemplateGlobal,\n TaskContext,\n} from '@backstage/plugin-scaffolder-node';\nimport { createConditionAuthorizer } from '@backstage/plugin-permission-node';\nimport { UserEntity } from '@backstage/catalog-model';\nimport { createCounterMetric, createHistogramMetric } from '../../util/metrics';\nimport { createDefaultFilters } from '../../lib/templating/filters';\nimport {\n AuthorizeResult,\n PolicyDecision,\n} from '@backstage/plugin-permission-common';\nimport { scaffolderActionRules } from '../../service/rules';\nimport { actionExecutePermission } from '@backstage/plugin-scaffolder-common/alpha';\nimport { PermissionsService } from '@backstage/backend-plugin-api';\nimport { loggerToWinstonLogger } from '@backstage/backend-common';\nimport { BackstageLoggerTransport, WinstonLogger } from './logger';\n\nimport { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\n\ntype NunjucksWorkflowRunnerOptions = {\n workingDirectory: string;\n actionRegistry: TemplateActionRegistry;\n integrations: ScmIntegrations;\n logger: winston.Logger;\n auditLogger: AuditLogger;\n additionalTemplateFilters?: Record;\n additionalTemplateGlobals?: Record;\n permissions?: PermissionsService;\n};\n\ntype TemplateContext = {\n parameters: JsonObject;\n EXPERIMENTAL_recovery?: TaskRecovery;\n steps: {\n [stepName: string]: { output: { [outputName: string]: JsonValue } };\n };\n secrets?: Record;\n user?: {\n entity?: UserEntity;\n ref?: string;\n };\n each?: JsonValue;\n};\n\ntype CheckpointState =\n | {\n status: 'failed';\n reason: string;\n }\n | {\n status: 'success';\n value: JsonValue;\n };\n\nconst isValidTaskSpec = (taskSpec: TaskSpec): taskSpec is TaskSpecV1beta3 => {\n return taskSpec.apiVersion === 'scaffolder.backstage.io/v1beta3';\n};\n\nconst createStepLogger = ({\n task,\n step,\n rootLogger,\n}: {\n task: TaskContext;\n step: TaskStep;\n rootLogger: winston.Logger;\n}) => {\n const taskLogger = WinstonLogger.create({\n level: process.env.LOG_LEVEL || 'info',\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.simple(),\n ),\n transports: [new BackstageLoggerTransport(rootLogger, task, step.id)],\n });\n\n taskLogger.addRedactions(Object.values(task.secrets ?? {}));\n\n // This stream logger should be deprecated. We're going to replace it with\n // just using the logger directly, as all those logs get written to step logs\n // using the stepLogStream above.\n // Initially this stream used to be the only way to write to the client logs, but that\n // has changed over time, there's not really a need for this anymore.\n // You can just create a simple wrapper like the below in your action to write to the main logger.\n // This way we also get redactions for free.\n const streamLogger = new PassThrough();\n streamLogger.on('data', async data => {\n const message = data.toString().trim();\n if (message?.length > 1) {\n taskLogger.info(message);\n }\n });\n\n return { taskLogger, streamLogger };\n};\n\nconst isActionAuthorized = createConditionAuthorizer(\n Object.values(scaffolderActionRules),\n);\n\nexport class NunjucksWorkflowRunner implements WorkflowRunner {\n private readonly defaultTemplateFilters: Record;\n private readonly tracker;\n\n constructor(private readonly options: NunjucksWorkflowRunnerOptions) {\n this.defaultTemplateFilters = createDefaultFilters({\n integrations: this.options.integrations,\n });\n this.tracker = scaffoldingTracker(this.options.auditLogger);\n }\n\n private isSingleTemplateString(input: string) {\n const { parser, nodes } = nunjucks as unknown as {\n parser: {\n parse(\n template: string,\n ctx: object,\n options: nunjucks.ConfigureOptions,\n ): { children: { children?: unknown[] }[] };\n };\n nodes: { TemplateData: Function };\n };\n\n const parsed = parser.parse(\n input,\n {},\n {\n autoescape: false,\n tags: {\n variableStart: '${{',\n variableEnd: '}}',\n },\n },\n );\n\n return (\n parsed.children.length === 1 &&\n !(parsed.children[0]?.children?.[0] instanceof nodes.TemplateData)\n );\n }\n\n private render(\n input: T,\n context: TemplateContext,\n renderTemplate: SecureTemplateRenderer,\n ): T {\n return JSON.parse(JSON.stringify(input), (_key, value) => {\n try {\n if (typeof value === 'string') {\n try {\n if (this.isSingleTemplateString(value)) {\n // Lets convert ${{ parameters.bob }} to ${{ (parameters.bob) | dump }} so we can keep the input type\n const wrappedDumped = value.replace(\n /\\${{(.+)}}/g,\n '${{ ( $1 ) | dump }}',\n );\n\n // Run the templating\n const templated = renderTemplate(wrappedDumped, context);\n\n // If there's an empty string returned, then it's undefined\n if (templated === '') {\n return undefined;\n }\n\n // Reparse the dumped string\n return JSON.parse(templated);\n }\n } catch (ex) {\n this.options.logger.error(\n `Failed to parse template string: ${value} with error ${ex.message}`,\n );\n }\n\n // Fallback to default behaviour\n const templated = renderTemplate(value, context);\n\n if (templated === '') {\n return undefined;\n }\n\n return templated;\n }\n } catch {\n return value;\n }\n return value;\n });\n }\n\n async executeStep(\n task: TaskContext,\n step: TaskStep,\n context: TemplateContext,\n renderTemplate: (template: string, values: unknown) => string,\n taskTrack: TaskTrackType,\n workspacePath: string,\n decision: PolicyDecision,\n ) {\n const stepTrack = await this.tracker.stepStart(task, step);\n\n if (task.cancelSignal.aborted) {\n throw new Error(\n `Step ${step.id} (${step.name}) of task ${task.taskId} has been cancelled.`,\n );\n }\n\n try {\n const action: TemplateAction =\n this.options.actionRegistry.get(step.action);\n const { taskLogger, streamLogger } = createStepLogger({\n task,\n step,\n rootLogger: this.options.logger,\n });\n\n const redactedSecrets = Object.fromEntries(\n Object.entries(task.secrets ?? {}).map(secret => [secret[0], '***']),\n );\n const stepInputs =\n (step.input &&\n this.render(\n step.input,\n {\n ...context,\n secrets: redactedSecrets,\n },\n renderTemplate,\n )) ??\n {};\n const commonStepAuditMetadata = {\n templateRef: task.spec.templateInfo?.entityRef || '',\n taskId: task.taskId,\n stepId: step.id,\n stepName: step.name,\n stepAction: step.action,\n stepInputs: stepInputs,\n stepConditional: step.if,\n stepEach: step.each,\n isDryRun: task.isDryRun || false,\n };\n if (\n step.if === false ||\n (typeof step.if === 'string' &&\n !isTruthy(this.render(step.if, context, renderTemplate)))\n ) {\n await stepTrack.skipFalsy();\n await this.options.auditLogger.auditLog({\n eventName: 'ScaffolderTaskStepSkip',\n actorId: 'scaffolder-backend',\n stage: 'completion',\n status: 'succeeded',\n metadata: commonStepAuditMetadata,\n message: `Skipped step ${step.name} (id: ${step.id}) of task ${task.taskId}`,\n });\n return;\n }\n\n await this.options.auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderTaskStepExecution',\n stage: 'initiation',\n status: 'succeeded',\n metadata: commonStepAuditMetadata,\n message: `Started ${step.name} (id: ${step.id}) of task ${task.taskId} triggering the ${step.action} action`,\n });\n\n if (task.isDryRun) {\n taskLogger.info(\n `Running ${\n action.id\n } in dry-run mode with inputs (secrets redacted): ${JSON.stringify(\n stepInputs,\n undefined,\n 2,\n )}`,\n );\n if (!action.supportsDryRun) {\n await taskTrack.skipDryRun(step, action);\n const outputSchema = action.schema?.output;\n if (outputSchema) {\n context.steps[step.id] = {\n output: generateExampleOutput(outputSchema) as {\n [name in string]: JsonValue;\n },\n };\n } else {\n context.steps[step.id] = { output: {} };\n }\n return;\n }\n }\n const iterations = (\n step.each\n ? Object.entries(this.render(step.each, context, renderTemplate)).map(\n ([key, value]) => ({\n each: { key, value },\n }),\n )\n : [{}]\n ).map(i => ({\n ...i,\n // Secrets are only passed when templating the input to actions for security reasons\n input: step.input\n ? this.render(\n step.input,\n { ...context, secrets: task.secrets ?? {}, ...i },\n renderTemplate,\n )\n : {},\n }));\n for (const iteration of iterations) {\n const actionId = `${action.id}${\n iteration.each ? `[${iteration.each.key}]` : ''\n }`;\n\n if (action.schema?.input) {\n const validateResult = validateJsonSchema(\n iteration.input,\n action.schema.input,\n );\n if (!validateResult.valid) {\n const errors = validateResult.errors.join(', ');\n throw new InputError(\n `Invalid input passed to action ${actionId}, ${errors}`,\n );\n }\n }\n if (\n !isActionAuthorized(decision, {\n action: action.id,\n input: iteration.input,\n })\n ) {\n throw new NotAllowedError(\n `Unauthorized action: ${actionId}. The action is not allowed. Input: ${JSON.stringify(\n iteration.input,\n null,\n 2,\n )}`,\n );\n }\n }\n const tmpDirs = new Array();\n const stepOutput: { [outputName: string]: JsonValue } = {};\n const prevTaskState = await task.getTaskState?.();\n let iterationCount: number = 0;\n for (const iteration of iterations) {\n if (iteration.each) {\n taskLogger.info(\n `Running step each: ${JSON.stringify(\n iteration.each,\n (k, v) => (k ? v.toString() : v),\n 0,\n )}`,\n );\n\n await this.options.auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderTaskStepIteration',\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n ...commonStepAuditMetadata,\n stepInputs: undefined,\n stepAction: `${step.action}[${iteration.each.key}]`,\n stepIterationInputs: iteration.input,\n stepIterationCount: ++iterationCount,\n stepIterationValue: iteration.each.value,\n totalIterations: iterations.length,\n },\n message: `Iteration ${iterationCount}/${iterations.length} of action ${step.action} of step ${step.name} (id: ${step.id}) of task ${task.taskId} started`,\n });\n }\n\n await action.handler({\n input: iteration.input,\n secrets: task.secrets ?? {},\n // TODO(blam): move to LoggerService and away from Winston\n logger: loggerToWinstonLogger(taskLogger),\n logStream: streamLogger,\n workspacePath,\n async checkpoint(\n keySuffix: string,\n fn: () => Promise,\n ) {\n const key = `v1.task.checkpoint.${step.id}.${keySuffix}`;\n try {\n let prevValue: U | undefined;\n if (prevTaskState) {\n const prevState = (\n prevTaskState.state?.checkpoints as {\n [key: string]: CheckpointState;\n }\n )?.[key];\n if (prevState && prevState.status === 'success') {\n prevValue = prevState.value as U;\n }\n }\n\n const value = prevValue ? prevValue : await fn();\n\n if (!prevValue) {\n task.updateCheckpoint?.({\n key,\n status: 'success',\n value,\n });\n }\n return value;\n } catch (err) {\n task.updateCheckpoint?.({\n key,\n status: 'failed',\n reason: stringifyError(err),\n });\n throw err;\n } finally {\n await task.serializeWorkspace?.({ path: workspacePath });\n }\n },\n createTemporaryDirectory: async () => {\n const tmpDir = await fs.mkdtemp(\n `${workspacePath}_step-${step.id}-`,\n );\n tmpDirs.push(tmpDir);\n return tmpDir;\n },\n output(name: string, value: JsonValue) {\n if (step.each) {\n stepOutput[name] = stepOutput[name] || [];\n (stepOutput[name] as JsonArray).push(value);\n } else {\n stepOutput[name] = value;\n }\n },\n templateInfo: task.spec.templateInfo,\n user: task.spec.user,\n isDryRun: task.isDryRun,\n signal: task.cancelSignal,\n getInitiatorCredentials: () => task.getInitiatorCredentials(),\n });\n if (iteration.each) {\n await this.options.auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderTaskStepIteration',\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n ...commonStepAuditMetadata,\n stepInputs: undefined,\n stepAction: `${step.action}[${iteration.each.key}]`,\n stepIterationCount: iterationCount,\n stepIterationValue: iteration.each.value,\n stepIterationInputs: iteration.input,\n totalIterations: iterations.length,\n },\n message: `Iteration ${iterationCount}/${iterations.length} of action ${step.action} of step ${step.name} (id: ${step.id}) of task ${task.taskId} succeeded`,\n });\n }\n }\n\n // Remove all temporary directories that were created when executing the action\n for (const tmpDir of tmpDirs) {\n await fs.remove(tmpDir);\n }\n\n context.steps[step.id] = { output: stepOutput };\n\n if (task.cancelSignal.aborted) {\n throw new Error(\n `Step ${step.id} (${step.name}) of task ${task.taskId} has been cancelled.`,\n );\n }\n\n await stepTrack.markSuccessful();\n } catch (err) {\n await taskTrack.markFailed(step, err);\n await stepTrack.markFailed(err);\n throw err;\n } finally {\n await task.serializeWorkspace?.({ path: workspacePath });\n }\n }\n\n async execute(task: TaskContext): Promise {\n if (!isValidTaskSpec(task.spec)) {\n throw new InputError(\n 'Wrong template version executed with the workflow engine',\n );\n }\n const taskId = await task.getWorkspaceName();\n\n const workspacePath = path.join(this.options.workingDirectory, taskId);\n\n const { additionalTemplateFilters, additionalTemplateGlobals } =\n this.options;\n\n const renderTemplate = await SecureTemplater.loadRenderer({\n templateFilters: {\n ...this.defaultTemplateFilters,\n ...additionalTemplateFilters,\n },\n templateGlobals: additionalTemplateGlobals,\n });\n\n try {\n await task.rehydrateWorkspace?.({ taskId, targetPath: workspacePath });\n\n const taskTrack = await this.tracker.taskStart(task);\n await fs.ensureDir(workspacePath);\n\n const context: TemplateContext = {\n parameters: task.spec.parameters,\n steps: {},\n user: task.spec.user,\n };\n\n const [decision]: PolicyDecision[] =\n this.options.permissions && task.spec.steps.length\n ? await this.options.permissions.authorizeConditional(\n [{ permission: actionExecutePermission }],\n { credentials: await task.getInitiatorCredentials() },\n )\n : [{ result: AuthorizeResult.ALLOW }];\n\n for (const step of task.spec.steps) {\n await this.executeStep(\n task,\n step,\n context,\n renderTemplate,\n taskTrack,\n workspacePath,\n decision,\n );\n }\n\n const output = this.render(task.spec.output, context, renderTemplate);\n await taskTrack.markSuccessful();\n await task.cleanWorkspace?.();\n\n return { output };\n } finally {\n if (workspacePath) {\n await fs.remove(workspacePath);\n }\n }\n }\n}\n\nfunction scaffoldingTracker(auditLogger: AuditLogger) {\n // prom-client metrics are deprecated in favour of OpenTelemetry metrics.\n const promTaskCount = createCounterMetric({\n name: 'scaffolder_task_count',\n help: 'Count of task runs',\n labelNames: ['template', 'user', 'result'],\n });\n const promTaskDuration = createHistogramMetric({\n name: 'scaffolder_task_duration',\n help: 'Duration of a task run',\n labelNames: ['template', 'result'],\n });\n const promtStepCount = createCounterMetric({\n name: 'scaffolder_step_count',\n help: 'Count of step runs',\n labelNames: ['template', 'step', 'result'],\n });\n const promStepDuration = createHistogramMetric({\n name: 'scaffolder_step_duration',\n help: 'Duration of a step runs',\n labelNames: ['template', 'step', 'result'],\n });\n\n const meter = metrics.getMeter('default');\n const taskCount = meter.createCounter('scaffolder.task.count', {\n description: 'Count of task runs',\n });\n\n const taskDuration = meter.createHistogram('scaffolder.task.duration', {\n description: 'Duration of a task run',\n unit: 'seconds',\n });\n\n const stepCount = meter.createCounter('scaffolder.step.count', {\n description: 'Count of step runs',\n });\n\n const stepDuration = meter.createHistogram('scaffolder.step.duration', {\n description: 'Duration of a step runs',\n unit: 'seconds',\n });\n\n async function taskStart(task: TaskContext) {\n await task.emitLog(`Starting up task with ${task.spec.steps.length} steps`);\n const template = task.spec.templateInfo?.entityRef || '';\n const user = task.spec.user?.ref || '';\n\n const startTime = process.hrtime();\n const taskTimer = promTaskDuration.startTimer({\n template,\n });\n\n function endTime() {\n const delta = process.hrtime(startTime);\n return delta[0] + delta[1] / 1e9;\n }\n\n async function skipDryRun(\n step: TaskStep,\n action: TemplateAction,\n ) {\n task.emitLog(`Skipping because ${action.id} does not support dry-run`, {\n stepId: step.id,\n status: 'skipped',\n });\n }\n\n async function markSuccessful() {\n promTaskCount.inc({\n template,\n user,\n result: 'ok',\n });\n taskTimer({ result: 'ok' });\n\n taskCount.add(1, { template, user, result: 'ok' });\n taskDuration.record(endTime(), {\n result: 'ok',\n });\n }\n\n async function markFailed(step: TaskStep, err: Error) {\n await task.emitLog(String(err.stack), {\n stepId: step.id,\n status: 'failed',\n });\n promTaskCount.inc({\n template,\n user,\n result: 'failed',\n });\n taskTimer({ result: 'failed' });\n\n taskCount.add(1, { template, user, result: 'failed' });\n taskDuration.record(endTime(), {\n result: 'failed',\n });\n }\n\n async function markCancelled(step: TaskStep) {\n await task.emitLog(`Step ${step.id} has been cancelled.`, {\n stepId: step.id,\n status: 'cancelled',\n });\n promTaskCount.inc({\n template,\n user,\n result: 'cancelled',\n });\n taskTimer({ result: 'cancelled' });\n\n taskCount.add(1, { template, user, result: 'cancelled' });\n taskDuration.record(endTime(), {\n result: 'cancelled',\n });\n }\n\n return {\n skipDryRun,\n markCancelled,\n markSuccessful,\n markFailed,\n };\n }\n\n async function stepStart(task: TaskContext, step: TaskStep) {\n await task.emitLog(`Beginning step ${step.name}`, {\n stepId: step.id,\n status: 'processing',\n });\n const template = task.spec.templateInfo?.entityRef || '';\n\n const startTime = process.hrtime();\n const stepTimer = promStepDuration.startTimer({\n template,\n step: step.name,\n });\n\n function endTime() {\n const delta = process.hrtime(startTime);\n return delta[0] + delta[1] / 1e9;\n }\n\n async function markSuccessful() {\n await task.emitLog(`Finished step ${step.name}`, {\n stepId: step.id,\n status: 'completed',\n });\n promtStepCount.inc({\n template,\n step: step.name,\n result: 'ok',\n });\n stepTimer({ result: 'ok' });\n\n stepCount.add(1, { template, step: step.name, result: 'ok' });\n stepDuration.record(endTime(), {\n result: 'ok',\n });\n await auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderTaskStepExecution',\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n templateRef: template,\n taskId: task.taskId,\n stepId: step.id,\n stepName: step.name,\n stepAction: step.action,\n isDryRun: task.isDryRun || false,\n },\n message: `Step ${step.name} (id: ${step.id}) of task ${task.taskId} succeeded`,\n });\n }\n\n async function markCancelled() {\n promtStepCount.inc({\n template,\n step: step.name,\n result: 'cancelled',\n });\n stepTimer({ result: 'cancelled' });\n\n stepCount.add(1, { template, step: step.name, result: 'cancelled' });\n stepDuration.record(endTime(), {\n result: 'cancelled',\n });\n }\n\n async function markFailed(err: Error) {\n promtStepCount.inc({\n template,\n step: step.name,\n result: 'failed',\n });\n stepTimer({ result: 'failed' });\n\n stepCount.add(1, { template, step: step.name, result: 'failed' });\n stepDuration.record(endTime(), {\n result: 'failed',\n });\n\n await auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderTaskStepExecution',\n stage: 'completion',\n status: 'failed',\n level: 'error',\n metadata: {\n templateRef: template,\n taskId: task.taskId,\n stepId: step.id,\n stepName: step.name,\n stepAction: step.action,\n isDryRun: task.isDryRun || false,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Step ${step.name} (id: ${step.id}) of task ${task.taskId} failed`,\n });\n }\n\n async function skipFalsy() {\n await task.emitLog(\n `Skipping step ${step.id} because its if condition was false`,\n { stepId: step.id, status: 'skipped' },\n );\n stepTimer({ result: 'skipped' });\n\n stepCount.add(1, { template, step: step.name, result: 'skipped' });\n stepDuration.record(endTime(), {\n result: 'skipped',\n });\n }\n\n return {\n markCancelled,\n markFailed,\n markSuccessful,\n skipFalsy,\n };\n }\n\n return {\n taskStart,\n stepStart,\n };\n}\n"],"names":["WinstonLogger","winston","BackstageLoggerTransport","PassThrough","createConditionAuthorizer","scaffolderActionRules","createDefaultFilters","nunjucks","templated","isTruthy","generateExampleOutput","validateJsonSchema","errors","InputError","NotAllowedError","loggerToWinstonLogger","stringifyError","fs","path","SecureTemplater","actionExecutePermission","AuthorizeResult","createCounterMetric","createHistogramMetric","metrics"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,MAAM,eAAA,GAAkB,CAAC,QAAoD,KAAA;AAC3E,EAAA,OAAO,SAAS,UAAe,KAAA,iCAAA,CAAA;AACjC,CAAA,CAAA;AAEA,MAAM,mBAAmB,CAAC;AAAA,EACxB,IAAA;AAAA,EACA,IAAA;AAAA,EACA,UAAA;AACF,CAIM,KAAA;AACJ,EAAM,MAAA,UAAA,GAAaA,qBAAc,MAAO,CAAA;AAAA,IACtC,KAAA,EAAO,OAAQ,CAAA,GAAA,CAAI,SAAa,IAAA,MAAA;AAAA,IAChC,MAAA,EAAQC,mBAAQ,MAAO,CAAA,OAAA;AAAA,MACrBA,kBAAA,CAAQ,OAAO,QAAS,EAAA;AAAA,MACxBA,kBAAA,CAAQ,OAAO,MAAO,EAAA;AAAA,KACxB;AAAA,IACA,UAAA,EAAY,CAAC,IAAIC,+BAAA,CAAyB,YAAY,IAAM,EAAA,IAAA,CAAK,EAAE,CAAC,CAAA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AA,GACF;AAEA,EAAO,OAAA;AAAA,IACL,SAAA;AAAA,IACA,SAAA;AAAA,GACF,CAAA;AACF;;;;"} -\ No newline at end of file -diff --git a/dist/scaffolder/tasks/StorageTaskBroker.cjs.js b/dist/scaffolder/tasks/StorageTaskBroker.cjs.js -index 7de5b00ad9e1fb519397d91f1989451eb3f89709..c70a5dd1be2443c7dd1ab62c67c1ebde98a20c1b 100644 ---- a/dist/scaffolder/tasks/StorageTaskBroker.cjs.js -+++ b/dist/scaffolder/tasks/StorageTaskBroker.cjs.js -@@ -10,17 +10,18 @@ var ObservableImpl__default = /*#__PURE__*/_interopDefaultCompat(ObservableImpl) - - class TaskManager { - // Runs heartbeat internally -- constructor(task, storage, signal, logger, workspaceService, auth) { -+ constructor(task, storage, signal, logger, workspaceService, auditLogger, auth) { - this.task = task; - this.storage = storage; - this.signal = signal; - this.logger = logger; - this.workspaceService = workspaceService; -+ this.auditLogger = auditLogger; - this.auth = auth; - } - isDone = false; - heartbeatTimeoutId; -- static create(task, storage, abortSignal, logger, auth, config, additionalWorkspaceProviders) { -+ static create(task, storage, abortSignal, logger, auditLogger, auth, config, additionalWorkspaceProviders) { - const workspaceService = WorkspaceService.DefaultWorkspaceService.create( - task, - storage, -@@ -33,11 +34,15 @@ class TaskManager { - abortSignal, - logger, - workspaceService, -+ auditLogger, - auth - ); - agent.startTimeout(); - return agent; - } -+ get taskId() { -+ return this.task.taskId; -+ } - get spec() { - return this.task.spec; - } -@@ -99,6 +104,34 @@ class TaskManager { - if (this.heartbeatTimeoutId) { - clearTimeout(this.heartbeatTimeoutId); - } -+ const commonAuditFields = { -+ eventName: "ScaffolderTaskExecution", -+ actorId: "scaffolder-backend", -+ stage: "completion", -+ metadata: { -+ taskId: this.task.taskId, -+ taskParameters: this.task.spec.parameters -+ } -+ }; -+ if (result === "failed") { -+ await this.auditLogger?.auditLog({ -+ ...commonAuditFields, -+ status: "failed", -+ level: "error", -+ errors: [metadata?.error], -+ message: `Scaffolding task with taskId: ${this.task.taskId} failed` -+ }); -+ } else { -+ await this.auditLogger?.auditLog({ -+ ...commonAuditFields, -+ status: "succeeded", -+ metadata: { -+ ...commonAuditFields.metadata, -+ ...metadata -+ }, -+ message: `Scaffolding task with taskId: ${this.task.taskId} completed successfully` -+ }); -+ } - } - startTimeout() { - this.heartbeatTimeoutId = setTimeout(async () => { -@@ -136,9 +169,10 @@ function defer() { - return { promise, resolve }; - } - class StorageTaskBroker { -- constructor(storage, logger, config, auth, additionalWorkspaceProviders) { -+ constructor(storage, logger, auditLogger, config, auth, additionalWorkspaceProviders) { - this.storage = storage; - this.logger = logger; -+ this.auditLogger = auditLogger; - this.config = config; - this.auth = auth; - this.additionalWorkspaceProviders = additionalWorkspaceProviders; -@@ -175,9 +209,7 @@ class StorageTaskBroker { - }); - } - async recoverTasks() { -- const enabled = (this.config && this.config.getOptionalBoolean( -- "scaffolder.EXPERIMENTAL_recoverTasks" -- )) ?? false; -+ const enabled = this.config?.getOptionalBoolean("scaffolder.EXPERIMENTAL_recoverTasks") ?? false; - if (enabled) { - const defaultTimeout = { seconds: 30 }; - const timeout = helper.readDuration( -@@ -213,6 +245,7 @@ class StorageTaskBroker { - this.storage, - abortController.signal, - this.logger, -+ this.auditLogger, - this.auth, - this.config, - this.additionalWorkspaceProviders -@@ -275,6 +308,16 @@ class StorageTaskBroker { - await Promise.all( - tasks.map(async (task) => { - try { -+ this.auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderStaleTaskCancellation", -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ taskId: task.taskId -+ }, -+ message: `Attempting to cancel Stale scaffolding task ${task.taskId} because the task worker lost connection to the task broker` -+ }); - await this.storage.completeTask({ - taskId: task.taskId, - status: "failed", -@@ -282,8 +325,35 @@ class StorageTaskBroker { - message: "The task was cancelled because the task worker lost connection to the task broker" - } - }); -+ this.auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderStaleTaskCancellation", -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ taskId: task.taskId -+ }, -+ message: `Stale scaffolding task ${task.taskId} successfully cancelled` -+ }); - } catch (error) { -- this.logger.warn(`Failed to cancel task '${task.taskId}', ${error}`); -+ this.auditLogger.auditLog({ -+ actorId: "scaffolder-backend", -+ eventName: "ScaffolderStaleTaskCancellation", -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ metadata: { -+ taskId: task.taskId -+ }, -+ errors: [ -+ { -+ name: error.name, -+ message: error.message, -+ stack: error.stack -+ } -+ ], -+ message: `Failed to cancel stale scaffolding task ${task.taskId}` -+ }); - } - }) - ); -diff --git a/dist/scaffolder/tasks/StorageTaskBroker.cjs.js.map b/dist/scaffolder/tasks/StorageTaskBroker.cjs.js.map -index 2d5bdf995e048b0274465b48cb2e3e4e2bc99980..f43c5fa2454b31f16e0d0ec936739d20c570ee15 100644 ---- a/dist/scaffolder/tasks/StorageTaskBroker.cjs.js.map -+++ b/dist/scaffolder/tasks/StorageTaskBroker.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"StorageTaskBroker.cjs.js","sources":["../../../src/scaffolder/tasks/StorageTaskBroker.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { TaskSpec } from '@backstage/plugin-scaffolder-common';\nimport { JsonObject, JsonValue, Observable } from '@backstage/types';\nimport { Logger } from 'winston';\nimport ObservableImpl from 'zen-observable';\nimport {\n SerializedTask,\n SerializedTaskEvent,\n TaskBroker,\n TaskBrokerDispatchOptions,\n TaskCompletionState,\n TaskContext,\n TaskSecrets,\n TaskStatus,\n} from '@backstage/plugin-scaffolder-node';\nimport { InternalTaskSecrets, TaskStore } from './types';\nimport { readDuration } from './helper';\nimport {\n AuthService,\n BackstageCredentials,\n} from '@backstage/backend-plugin-api';\nimport { DefaultWorkspaceService, WorkspaceService } from './WorkspaceService';\nimport { WorkspaceProvider } from '@backstage/plugin-scaffolder-node/alpha';\n\ntype TaskState = {\n checkpoints: {\n [key: string]:\n | {\n status: 'failed';\n reason: string;\n }\n | {\n status: 'success';\n value: JsonValue;\n };\n };\n};\n/**\n * TaskManager\n *\n * @public\n */\nexport class TaskManager implements TaskContext {\n private isDone = false;\n\n private heartbeatTimeoutId?: ReturnType;\n\n static create(\n task: CurrentClaimedTask,\n storage: TaskStore,\n abortSignal: AbortSignal,\n logger: Logger,\n auth?: AuthService,\n config?: Config,\n additionalWorkspaceProviders?: Record,\n ) {\n const workspaceService = DefaultWorkspaceService.create(\n task,\n storage,\n additionalWorkspaceProviders,\n config,\n );\n\n const agent = new TaskManager(\n task,\n storage,\n abortSignal,\n logger,\n workspaceService,\n auth,\n );\n agent.startTimeout();\n return agent;\n }\n\n // Runs heartbeat internally\n private constructor(\n private readonly task: CurrentClaimedTask,\n private readonly storage: TaskStore,\n private readonly signal: AbortSignal,\n private readonly logger: Logger,\n private readonly workspaceService: WorkspaceService,\n private readonly auth?: AuthService,\n ) {}\n\n get spec() {\n return this.task.spec;\n }\n\n get cancelSignal() {\n return this.signal;\n }\n\n get secrets() {\n return this.task.secrets;\n }\n\n get createdBy() {\n return this.task.createdBy;\n }\n\n async getWorkspaceName() {\n return this.task.taskId;\n }\n\n async rehydrateWorkspace?(options: {\n taskId: string;\n targetPath: string;\n }): Promise {\n await this.workspaceService.rehydrateWorkspace(options);\n }\n\n get done() {\n return this.isDone;\n }\n\n async emitLog(message: string, logMetadata?: JsonObject): Promise {\n await this.storage.emitLogEvent({\n taskId: this.task.taskId,\n body: { message, ...logMetadata },\n });\n }\n\n async getTaskState?(): Promise<\n | {\n state?: JsonObject;\n }\n | undefined\n > {\n return this.storage.getTaskState?.({ taskId: this.task.taskId });\n }\n\n async updateCheckpoint?(\n options:\n | {\n key: string;\n status: 'success';\n value: JsonValue;\n }\n | {\n key: string;\n status: 'failed';\n reason: string;\n },\n ): Promise {\n const { key, ...value } = options;\n if (this.task.state) {\n (this.task.state as TaskState).checkpoints[key] = value;\n } else {\n this.task.state = { checkpoints: { [key]: value } };\n }\n await this.storage.saveTaskState?.({\n taskId: this.task.taskId,\n state: this.task.state,\n });\n }\n\n async serializeWorkspace?(options: { path: string }): Promise {\n await this.workspaceService.serializeWorkspace(options);\n }\n\n async cleanWorkspace?(): Promise {\n await this.workspaceService.cleanWorkspace();\n }\n\n async complete(\n result: TaskCompletionState,\n metadata?: JsonObject,\n ): Promise {\n await this.storage.completeTask({\n taskId: this.task.taskId,\n status: result === 'failed' ? 'failed' : 'completed',\n eventBody: {\n message: `Run completed with status: ${result}`,\n ...metadata,\n },\n });\n this.isDone = true;\n if (this.heartbeatTimeoutId) {\n clearTimeout(this.heartbeatTimeoutId);\n }\n }\n\n private startTimeout() {\n this.heartbeatTimeoutId = setTimeout(async () => {\n try {\n await this.storage.heartbeatTask(this.task.taskId);\n this.startTimeout();\n } catch (error) {\n this.isDone = true;\n\n this.logger.error(\n `Heartbeat for task ${this.task.taskId} failed`,\n error,\n );\n }\n }, 1000);\n }\n\n async getInitiatorCredentials(): Promise {\n const secrets = this.task.secrets as InternalTaskSecrets;\n\n if (secrets && secrets.__initiatorCredentials) {\n return JSON.parse(secrets.__initiatorCredentials);\n }\n if (!this.auth) {\n throw new Error(\n 'Failed to create none credentials in scaffolder task. The TaskManager has not been initialized with an auth service implementation',\n );\n }\n return this.auth.getNoneCredentials();\n }\n}\n\n/**\n * Stores the state of the current claimed task passed to the TaskContext\n *\n * @public\n */\nexport interface CurrentClaimedTask {\n /**\n * The TaskSpec of the current claimed task.\n */\n spec: TaskSpec;\n /**\n * The uuid of the current claimed task.\n */\n taskId: string;\n /**\n * The secrets that are stored with the task.\n */\n secrets?: TaskSecrets;\n /**\n * The state of checkpoints of the task.\n */\n state?: JsonObject;\n /**\n * The creator of the task.\n */\n createdBy?: string;\n /**\n * The workspace of the task.\n */\n workspace?: Promise;\n}\n\nfunction defer() {\n let resolve = () => {};\n const promise = new Promise(_resolve => {\n resolve = _resolve;\n });\n return { promise, resolve };\n}\n\nexport class StorageTaskBroker implements TaskBroker {\n constructor(\n private readonly storage: TaskStore,\n private readonly logger: Logger,\n private readonly config?: Config,\n private readonly auth?: AuthService,\n private readonly additionalWorkspaceProviders?: Record<\n string,\n WorkspaceProvider\n >,\n ) {}\n\n async list(options?: {\n createdBy?: string;\n status?: TaskStatus;\n filters?: {\n createdBy?: string | string[];\n status?: TaskStatus | TaskStatus[];\n };\n pagination?: {\n limit?: number;\n offset?: number;\n };\n order?: { order: 'asc' | 'desc'; field: string }[];\n }): Promise<{ tasks: SerializedTask[]; totalTasks?: number }> {\n if (!this.storage.list) {\n throw new Error(\n 'TaskStore does not implement the list method. Please implement the list method to be able to list tasks',\n );\n }\n return await this.storage.list(options ?? {});\n }\n\n private deferredDispatch = defer();\n\n private async registerCancellable(\n taskId: string,\n abortController: AbortController,\n ) {\n let shouldUnsubscribe = false;\n const subscription = this.event$({ taskId, after: undefined }).subscribe({\n error: _ => {\n subscription.unsubscribe();\n },\n next: ({ events }) => {\n for (const event of events) {\n if (event.type === 'cancelled') {\n abortController.abort();\n shouldUnsubscribe = true;\n }\n\n if (event.type === 'completion' && !event.isTaskRecoverable) {\n shouldUnsubscribe = true;\n }\n }\n if (shouldUnsubscribe) {\n subscription.unsubscribe();\n }\n },\n });\n }\n\n public async recoverTasks(): Promise {\n const enabled =\n (this.config &&\n this.config.getOptionalBoolean(\n 'scaffolder.EXPERIMENTAL_recoverTasks',\n )) ??\n false;\n\n if (enabled) {\n const defaultTimeout = { seconds: 30 };\n const timeout = readDuration(\n this.config,\n 'scaffolder.EXPERIMENTAL_recoverTasksTimeout',\n defaultTimeout,\n );\n const { ids: recoveredTaskIds } = (await this.storage.recoverTasks?.({\n timeout,\n })) ?? { ids: [] };\n if (recoveredTaskIds.length > 0) {\n this.signalDispatch();\n }\n }\n }\n\n /**\n * {@inheritdoc TaskBroker.claim}\n */\n async claim(): Promise {\n for (;;) {\n const pendingTask = await this.storage.claimTask();\n if (pendingTask) {\n const abortController = new AbortController();\n await this.registerCancellable(pendingTask.id, abortController);\n return TaskManager.create(\n {\n taskId: pendingTask.id,\n spec: pendingTask.spec,\n secrets: pendingTask.secrets,\n createdBy: pendingTask.createdBy,\n state: pendingTask.state,\n },\n this.storage,\n abortController.signal,\n this.logger,\n this.auth,\n this.config,\n this.additionalWorkspaceProviders,\n );\n }\n\n await this.waitForDispatch();\n }\n }\n\n /**\n * {@inheritdoc TaskBroker.dispatch}\n */\n async dispatch(\n options: TaskBrokerDispatchOptions,\n ): Promise<{ taskId: string }> {\n const taskRow = await this.storage.createTask(options);\n this.signalDispatch();\n return {\n taskId: taskRow.taskId,\n };\n }\n\n /**\n * {@inheritdoc TaskBroker.get}\n */\n async get(taskId: string): Promise {\n return this.storage.getTask(taskId);\n }\n\n /**\n * {@inheritdoc TaskBroker.event$}\n */\n event$(options: {\n taskId: string;\n after?: number;\n }): Observable<{ events: SerializedTaskEvent[] }> {\n return new ObservableImpl(observer => {\n const { taskId } = options;\n\n let after = options.after;\n let cancelled = false;\n\n (async () => {\n const task = await this.storage.getTask(taskId);\n const isTaskRecoverable =\n task.spec.EXPERIMENTAL_recovery?.EXPERIMENTAL_strategy ===\n 'startOver';\n\n while (!cancelled) {\n const result = await this.storage.listEvents({\n isTaskRecoverable,\n taskId,\n after,\n });\n const { events } = result;\n if (events.length) {\n after = events[events.length - 1].id;\n observer.next(result);\n }\n\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n })();\n\n return () => {\n cancelled = true;\n };\n });\n }\n\n /**\n * {@inheritdoc TaskBroker.vacuumTasks}\n */\n async vacuumTasks(options: { timeoutS: number }): Promise {\n const { tasks } = await this.storage.listStaleTasks(options);\n await Promise.all(\n tasks.map(async task => {\n try {\n await this.storage.completeTask({\n taskId: task.taskId,\n status: 'failed',\n eventBody: {\n message:\n 'The task was cancelled because the task worker lost connection to the task broker',\n },\n });\n } catch (error) {\n this.logger.warn(`Failed to cancel task '${task.taskId}', ${error}`);\n }\n }),\n );\n }\n\n private waitForDispatch() {\n return this.deferredDispatch.promise;\n }\n\n private signalDispatch() {\n this.deferredDispatch.resolve();\n this.deferredDispatch = defer();\n }\n\n async cancel(taskId: string) {\n const { events } = await this.storage.listEvents({ taskId });\n const currentStepId =\n events.length > 0\n ? events\n .filter(({ body }) => body?.stepId)\n .reduce((prev, curr) => (prev.id > curr.id ? prev : curr)).body\n .stepId\n : 0;\n\n await this.storage.cancelTask?.({\n taskId,\n body: {\n message: `Step ${currentStepId} has been cancelled.`,\n stepId: currentStepId,\n status: 'cancelled',\n },\n });\n }\n\n async retry?(taskId: string): Promise {\n await this.storage.retryTask?.({ taskId });\n this.signalDispatch();\n }\n}\n"],"names":["DefaultWorkspaceService","readDuration","ObservableImpl"],"mappings":";;;;;;;;;;AA0DO,MAAM,WAAmC,CAAA;AAAA;AAAA,EAkCtC,YACW,IACA,EAAA,OAAA,EACA,MACA,EAAA,MAAA,EACA,kBACA,IACjB,EAAA;AANiB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA,CAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA,CAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AACA,IAAA,IAAA,CAAA,gBAAA,GAAA,gBAAA,CAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA,CAAA;AAAA,GAChB;AAAA,EAxCK,MAAS,GAAA,KAAA,CAAA;AAAA,EAET,kBAAA,CAAA;AAAA,EAER,OAAO,OACL,IACA,EAAA,OAAA,EACA,aACA,MAC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AA,IAAA,CAAK,QAAQ,UAAa,GAAA;AAAA,MAC9B,MAAA;AAAA,MACA,IAAM,EAAA;AAAA,QACJ,OAAA,EAAS,QAAQ,aAAa,CAAA,oBAAA,CAAA;AAAA,QAC9B,MAAQ,EAAA,aAAA;AAAA,QACR,MAAQ,EAAA,WAAA;AAAA,OACV;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AAAA,EAEA,MAAM,MAAO,MAA+B,EAAA;AAC1C,IAAA,MAAM,IAAK,CAAA,OAAA,CAAQ,SAAY,GAAA,EAAE,QAAQ,CAAA,CAAA;AACzC,IAAA,IAAA,CAAK,cAAe,EAAA,CAAA;AAAA,GACtB;AACF;;;;;"} -\ No newline at end of file -+{"version":3,"file":"StorageTaskBroker.cjs.js","sources":["../../../src/scaffolder/tasks/StorageTaskBroker.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { TaskSpec } from '@backstage/plugin-scaffolder-common';\nimport { JsonObject, JsonValue, Observable } from '@backstage/types';\nimport { Logger } from 'winston';\nimport ObservableImpl from 'zen-observable';\nimport {\n SerializedTask,\n SerializedTaskEvent,\n TaskBroker,\n TaskBrokerDispatchOptions,\n TaskCompletionState,\n TaskContext,\n TaskSecrets,\n TaskStatus,\n} from '@backstage/plugin-scaffolder-node';\nimport { InternalTaskSecrets, TaskStore } from './types';\nimport { readDuration } from './helper';\nimport {\n AuthService,\n BackstageCredentials,\n} from '@backstage/backend-plugin-api';\nimport { DefaultWorkspaceService, WorkspaceService } from './WorkspaceService';\nimport { WorkspaceProvider } from '@backstage/plugin-scaffolder-node/alpha';\n\nimport { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\n\ntype TaskState = {\n checkpoints: {\n [key: string]:\n | {\n status: 'failed';\n reason: string;\n }\n | {\n status: 'success';\n value: JsonValue;\n };\n };\n};\n/**\n * TaskManager\n *\n * @public\n */\nexport class TaskManager implements TaskContext {\n private isDone = false;\n\n private heartbeatTimeoutId?: ReturnType;\n\n static create(\n task: CurrentClaimedTask,\n storage: TaskStore,\n abortSignal: AbortSignal,\n logger: Logger,\n auditLogger: AuditLogger,\n auth?: AuthService,\n config?: Config,\n additionalWorkspaceProviders?: Record,\n ) {\n const workspaceService = DefaultWorkspaceService.create(\n task,\n storage,\n additionalWorkspaceProviders,\n config,\n );\n\n const agent = new TaskManager(\n task,\n storage,\n abortSignal,\n logger,\n workspaceService,\n auditLogger,\n auth,\n );\n agent.startTimeout();\n return agent;\n }\n\n // Runs heartbeat internally\n private constructor(\n private readonly task: CurrentClaimedTask,\n private readonly storage: TaskStore,\n private readonly signal: AbortSignal,\n private readonly logger: Logger,\n private readonly workspaceService: WorkspaceService,\n private readonly auditLogger: AuditLogger,\n private readonly auth?: AuthService,\n ) {}\n\n get taskId() {\n return this.task.taskId;\n }\n\n get spec() {\n return this.task.spec;\n }\n\n get cancelSignal() {\n return this.signal;\n }\n\n get secrets() {\n return this.task.secrets;\n }\n\n get createdBy() {\n return this.task.createdBy;\n }\n\n async getWorkspaceName() {\n return this.task.taskId;\n }\n\n async rehydrateWorkspace?(options: {\n taskId: string;\n targetPath: string;\n }): Promise {\n await this.workspaceService.rehydrateWorkspace(options);\n }\n\n get done() {\n return this.isDone;\n }\n\n async emitLog(message: string, logMetadata?: JsonObject): Promise {\n await this.storage.emitLogEvent({\n taskId: this.task.taskId,\n body: { message, ...logMetadata },\n });\n }\n\n async getTaskState?(): Promise<\n | {\n state?: JsonObject;\n }\n | undefined\n > {\n return this.storage.getTaskState?.({ taskId: this.task.taskId });\n }\n\n async updateCheckpoint?(\n options:\n | {\n key: string;\n status: 'success';\n value: JsonValue;\n }\n | {\n key: string;\n status: 'failed';\n reason: string;\n },\n ): Promise {\n const { key, ...value } = options;\n if (this.task.state) {\n (this.task.state as TaskState).checkpoints[key] = value;\n } else {\n this.task.state = { checkpoints: { [key]: value } };\n }\n await this.storage.saveTaskState?.({\n taskId: this.task.taskId,\n state: this.task.state,\n });\n }\n\n async serializeWorkspace?(options: { path: string }): Promise {\n await this.workspaceService.serializeWorkspace(options);\n }\n\n async cleanWorkspace?(): Promise {\n await this.workspaceService.cleanWorkspace();\n }\n\n async complete(\n result: TaskCompletionState,\n metadata?: JsonObject,\n ): Promise {\n await this.storage.completeTask({\n taskId: this.task.taskId,\n status: result === 'failed' ? 'failed' : 'completed',\n eventBody: {\n message: `Run completed with status: ${result}`,\n ...metadata,\n },\n });\n this.isDone = true;\n if (this.heartbeatTimeoutId) {\n clearTimeout(this.heartbeatTimeoutId);\n }\n const commonAuditFields = {\n eventName: 'ScaffolderTaskExecution',\n actorId: 'scaffolder-backend',\n stage: 'completion',\n metadata: {\n taskId: this.task.taskId,\n taskParameters: this.task.spec.parameters,\n },\n };\n if (result === 'failed') {\n await this.auditLogger?.auditLog({\n ...commonAuditFields,\n status: 'failed',\n level: 'error',\n errors: [metadata?.error],\n message: `Scaffolding task with taskId: ${this.task.taskId} failed`,\n });\n } else {\n await this.auditLogger?.auditLog({\n ...commonAuditFields,\n status: 'succeeded',\n metadata: {\n ...commonAuditFields.metadata,\n ...metadata,\n },\n message: `Scaffolding task with taskId: ${this.task.taskId} completed successfully`,\n });\n }\n }\n\n private startTimeout() {\n this.heartbeatTimeoutId = setTimeout(async () => {\n try {\n await this.storage.heartbeatTask(this.task.taskId);\n this.startTimeout();\n } catch (error) {\n this.isDone = true;\n\n this.logger.error(\n `Heartbeat for task ${this.task.taskId} failed`,\n error,\n );\n }\n }, 1000);\n }\n\n async getInitiatorCredentials(): Promise {\n const secrets = this.task.secrets as InternalTaskSecrets;\n\n if (secrets && secrets.__initiatorCredentials) {\n return JSON.parse(secrets.__initiatorCredentials);\n }\n if (!this.auth) {\n throw new Error(\n 'Failed to create none credentials in scaffolder task. The TaskManager has not been initialized with an auth service implementation',\n );\n }\n return this.auth.getNoneCredentials();\n }\n}\n\n/**\n * Stores the state of the current claimed task passed to the TaskContext\n *\n * @public\n */\nexport interface CurrentClaimedTask {\n /**\n * The TaskSpec of the current claimed task.\n */\n spec: TaskSpec;\n /**\n * The uuid of the current claimed task.\n */\n taskId: string;\n /**\n * The secrets that are stored with the task.\n */\n secrets?: TaskSecrets;\n /**\n * The state of checkpoints of the task.\n */\n state?: JsonObject;\n /**\n * The creator of the task.\n */\n createdBy?: string;\n /**\n * The workspace of the task.\n */\n workspace?: Promise;\n}\n\nfunction defer() {\n let resolve = () => {};\n const promise = new Promise(_resolve => {\n resolve = _resolve;\n });\n return { promise, resolve };\n}\n\nexport class StorageTaskBroker implements TaskBroker {\n constructor(\n private readonly storage: TaskStore,\n private readonly logger: Logger,\n private readonly auditLogger: AuditLogger,\n private readonly config?: Config,\n private readonly auth?: AuthService,\n private readonly additionalWorkspaceProviders?: Record<\n string,\n WorkspaceProvider\n >,\n ) {}\n\n async list(options?: {\n createdBy?: string;\n status?: TaskStatus;\n filters?: {\n createdBy?: string | string[];\n status?: TaskStatus | TaskStatus[];\n };\n pagination?: {\n limit?: number;\n offset?: number;\n };\n order?: { order: 'asc' | 'desc'; field: string }[];\n }): Promise<{ tasks: SerializedTask[]; totalTasks?: number }> {\n if (!this.storage.list) {\n throw new Error(\n 'TaskStore does not implement the list method. Please implement the list method to be able to list tasks',\n );\n }\n return await this.storage.list(options ?? {});\n }\n\n private deferredDispatch = defer();\n\n private async registerCancellable(\n taskId: string,\n abortController: AbortController,\n ) {\n let shouldUnsubscribe = false;\n const subscription = this.event$({ taskId, after: undefined }).subscribe({\n error: _ => {\n subscription.unsubscribe();\n },\n next: ({ events }) => {\n for (const event of events) {\n if (event.type === 'cancelled') {\n abortController.abort();\n shouldUnsubscribe = true;\n }\n\n if (event.type === 'completion' && !event.isTaskRecoverable) {\n shouldUnsubscribe = true;\n }\n }\n if (shouldUnsubscribe) {\n subscription.unsubscribe();\n }\n },\n });\n }\n\n public async recoverTasks(): Promise {\n const enabled =\n this.config?.getOptionalBoolean('scaffolder.EXPERIMENTAL_recoverTasks') ??\n false;\n\n if (enabled) {\n const defaultTimeout = { seconds: 30 };\n const timeout = readDuration(\n this.config,\n 'scaffolder.EXPERIMENTAL_recoverTasksTimeout',\n defaultTimeout,\n );\n const { ids: recoveredTaskIds } = (await this.storage.recoverTasks?.({\n timeout,\n })) ?? { ids: [] };\n if (recoveredTaskIds.length > 0) {\n this.signalDispatch();\n }\n }\n }\n\n /**\n * {@inheritdoc TaskBroker.claim}\n */\n async claim(): Promise {\n for (;;) {\n const pendingTask = await this.storage.claimTask();\n if (pendingTask) {\n const abortController = new AbortController();\n await this.registerCancellable(pendingTask.id, abortController);\n return TaskManager.create(\n {\n taskId: pendingTask.id,\n spec: pendingTask.spec,\n secrets: pendingTask.secrets,\n createdBy: pendingTask.createdBy,\n state: pendingTask.state,\n },\n this.storage,\n abortController.signal,\n this.logger,\n this.auditLogger,\n this.auth,\n this.config,\n this.additionalWorkspaceProviders,\n );\n }\n\n await this.waitForDispatch();\n }\n }\n\n /**\n * {@inheritdoc TaskBroker.dispatch}\n */\n async dispatch(\n options: TaskBrokerDispatchOptions,\n ): Promise<{ taskId: string }> {\n const taskRow = await this.storage.createTask(options);\n this.signalDispatch();\n return {\n taskId: taskRow.taskId,\n };\n }\n\n /**\n * {@inheritdoc TaskBroker.get}\n */\n async get(taskId: string): Promise {\n return this.storage.getTask(taskId);\n }\n\n /**\n * {@inheritdoc TaskBroker.event$}\n */\n event$(options: {\n taskId: string;\n after?: number;\n }): Observable<{ events: SerializedTaskEvent[] }> {\n return new ObservableImpl(observer => {\n const { taskId } = options;\n\n let after = options.after;\n let cancelled = false;\n\n (async () => {\n const task = await this.storage.getTask(taskId);\n const isTaskRecoverable =\n task.spec.EXPERIMENTAL_recovery?.EXPERIMENTAL_strategy ===\n 'startOver';\n\n while (!cancelled) {\n const result = await this.storage.listEvents({\n isTaskRecoverable,\n taskId,\n after,\n });\n const { events } = result;\n if (events.length) {\n after = events[events.length - 1].id;\n observer.next(result);\n }\n\n await new Promise(resolve => setTimeout(resolve, 1000));\n }\n })();\n\n return () => {\n cancelled = true;\n };\n });\n }\n\n /**\n * {@inheritdoc TaskBroker.vacuumTasks}\n */\n async vacuumTasks(options: { timeoutS: number }): Promise {\n const { tasks } = await this.storage.listStaleTasks(options);\n await Promise.all(\n tasks.map(async task => {\n try {\n this.auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderStaleTaskCancellation',\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n taskId: task.taskId,\n },\n message: `Attempting to cancel Stale scaffolding task ${task.taskId} because the task worker lost connection to the task broker`,\n });\n await this.storage.completeTask({\n taskId: task.taskId,\n status: 'failed',\n eventBody: {\n message:\n 'The task was cancelled because the task worker lost connection to the task broker',\n },\n });\n this.auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderStaleTaskCancellation',\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n taskId: task.taskId,\n },\n message: `Stale scaffolding task ${task.taskId} successfully cancelled`,\n });\n } catch (error) {\n this.auditLogger.auditLog({\n actorId: 'scaffolder-backend',\n eventName: 'ScaffolderStaleTaskCancellation',\n stage: 'completion',\n status: 'failed',\n level: 'error',\n metadata: {\n taskId: task.taskId,\n },\n errors: [\n {\n name: error.name,\n message: error.message,\n stack: error.stack,\n },\n ],\n message: `Failed to cancel stale scaffolding task ${task.taskId}`,\n });\n }\n }),\n );\n }\n\n private waitForDispatch() {\n return this.deferredDispatch.promise;\n }\n\n private signalDispatch() {\n this.deferredDispatch.resolve();\n this.deferredDispatch = defer();\n }\n\n async cancel(taskId: string) {\n const { events } = await this.storage.listEvents({ taskId });\n const currentStepId =\n events.length > 0\n ? events\n .filter(({ body }) => body?.stepId)\n .reduce((prev, curr) => (prev.id > curr.id ? prev : curr)).body\n .stepId\n : 0;\n\n await this.storage.cancelTask?.({\n taskId,\n body: {\n message: `Step ${currentStepId} has been cancelled.`,\n stepId: currentStepId,\n status: 'cancelled',\n },\n });\n }\n\n async retry?(taskId: string): Promise {\n await this.storage.retryTask?.({ taskId });\n this.signalDispatch();\n }\n}\n"],"names":["DefaultWorkspaceService","readDuration","ObservableImpl"],"mappings":";;;;;;;;;;AA4DO,MAAM,WAAmC,CAAA;AAAA;AAAA,EAoCtC,YACW,IACA,EAAA,OAAA,EACA,QACA,MACA,EAAA,gBAAA,EACA,aACA,IACjB,EAAA;AAPiB,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA,CAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA,CAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AACA,IAAA,IAAA,CAAA,gBAAA,GAAA,gBAAA,CAAA;AACA,IAAA,IAAA,CAAA,WAAA,GAAA,WAAA,CAAA;AACA,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA,CAAA;AAAA,GAChB;AAAA,EA3CK,MAAS,GAAA,KAAA,CAAA;AAAA,EAET,kBAAA,CAAA;AAAA,EAER,OAAO,OACL,IACA,EAAA,OAAA,EACA,aACA,MACA,EAAA,WAAA,EACA,IACA,EAAA,MAAA,EACA,4BACA,EAAA;AACA,IAAA,MAAM,mBAAmBA,wCAAwB,CAAA,MAAA;AAAA,MAC/C,IAAA;AAAA,MACA,OAAA;AAAA,MACA,4BAAA;AAAA,MACA,MAAA;AAAA,KACF,CAAA;AAEA,IAAA,MAAM,QAAQ,IAAI,WAAA;AAAA,MAChB,IAAA;AAAA,MACA,OAAA;AAAA,MACA,WAAA;AAAA,MACA,MAAA;AAAA,MACA,gBAAA;AAAA,MACA,WAAA;AAA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/dist/scaffolder/tasks/TaskWorker.cjs.js -+++ b/dist/scaffolder/tasks/TaskWorker.cjs.js -@@ -13,6 +13,7 @@ class TaskWorker { - this.options = options; - this.stopWorkers = false; - this.logger = options.logger; -+ this.auditLogger = options.auditLogger; - this.taskQueue = new PQueue__default.default({ - concurrency: options.concurrentTasksLimit - }); -@@ -20,6 +21,7 @@ class TaskWorker { - taskQueue; - logger; - stopWorkers; -+ auditLogger; - static async create(options) { - const { - taskBroker, -@@ -31,12 +33,14 @@ class TaskWorker { - concurrentTasksLimit = 10, - // from 1 to Infinity - additionalTemplateGlobals, -- permissions -+ permissions, -+ auditLogger - } = options; - const workflowRunner = new NunjucksWorkflowRunner.NunjucksWorkflowRunner({ - actionRegistry, - integrations, - logger, -+ auditLogger, - workingDirectory, - additionalTemplateFilters, - additionalTemplateGlobals, -@@ -46,7 +50,8 @@ class TaskWorker { - taskBroker, - runners: { workflowRunner }, - concurrentTasksLimit, -- permissions -+ permissions, -+ auditLogger - }); - } - async recoverTasks() { -@@ -88,6 +93,18 @@ class TaskWorker { - } - async runOneTask(task) { - try { -+ await this.auditLogger?.auditLog({ -+ eventName: "ScaffolderTaskExecution", -+ actorId: "scaffolder-backend", -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ taskId: task.taskId, -+ taskParameters: task.spec.parameters, -+ templateRef: task.spec.templateInfo?.entityRef -+ }, -+ message: `Scaffolding task with taskId: ${task.taskId} initiated` -+ }); - if (task.spec.apiVersion !== "scaffolder.backstage.io/v1beta3") { - throw new Error( - `Unsupported Template apiVersion ${task.spec.apiVersion}` -diff --git a/dist/scaffolder/tasks/TaskWorker.cjs.js.map b/dist/scaffolder/tasks/TaskWorker.cjs.js.map -index f34e0d282f02ad2291a23fd71f864d4740678c2a..20ee2a529cd976e163ad3845eda8785bb90f35fe 100644 ---- a/dist/scaffolder/tasks/TaskWorker.cjs.js.map -+++ b/dist/scaffolder/tasks/TaskWorker.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"TaskWorker.cjs.js","sources":["../../../src/scaffolder/tasks/TaskWorker.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WorkflowRunner } from './types';\nimport {\n TaskContext,\n TaskBroker,\n TemplateFilter,\n TemplateGlobal,\n} from '@backstage/plugin-scaffolder-node';\nimport PQueue from 'p-queue';\nimport { NunjucksWorkflowRunner } from './NunjucksWorkflowRunner';\nimport { Logger } from 'winston';\nimport { TemplateActionRegistry } from '../actions';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { assertError, stringifyError } from '@backstage/errors';\nimport { PermissionEvaluator } from '@backstage/plugin-permission-common';\n\n/**\n * TaskWorkerOptions\n *\n * @public\n */\nexport type TaskWorkerOptions = {\n taskBroker: TaskBroker;\n runners: {\n workflowRunner: WorkflowRunner;\n };\n concurrentTasksLimit: number;\n permissions?: PermissionEvaluator;\n logger?: Logger;\n};\n\n/**\n * CreateWorkerOptions\n *\n * @public\n */\nexport type CreateWorkerOptions = {\n taskBroker: TaskBroker;\n actionRegistry: TemplateActionRegistry;\n integrations: ScmIntegrations;\n workingDirectory: string;\n logger: Logger;\n additionalTemplateFilters?: Record;\n /**\n * The number of tasks that can be executed at the same time by the worker\n * @defaultValue 10\n * @example\n * ```\n * {\n * concurrentTasksLimit: 1,\n * // OR\n * concurrentTasksLimit: Infinity\n * }\n * ```\n */\n concurrentTasksLimit?: number;\n additionalTemplateGlobals?: Record;\n permissions?: PermissionEvaluator;\n};\n\n/**\n * TaskWorker\n *\n * @public\n */\nexport class TaskWorker {\n private taskQueue: PQueue;\n private logger: Logger | undefined;\n private stopWorkers: boolean;\n\n private constructor(private readonly options: TaskWorkerOptions) {\n this.stopWorkers = false;\n this.logger = options.logger;\n this.taskQueue = new PQueue({\n concurrency: options.concurrentTasksLimit,\n });\n }\n\n static async create(options: CreateWorkerOptions): Promise {\n const {\n taskBroker,\n logger,\n actionRegistry,\n integrations,\n workingDirectory,\n additionalTemplateFilters,\n concurrentTasksLimit = 10, // from 1 to Infinity\n additionalTemplateGlobals,\n permissions,\n } = options;\n\n const workflowRunner = new NunjucksWorkflowRunner({\n actionRegistry,\n integrations,\n logger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n permissions,\n });\n\n return new TaskWorker({\n taskBroker: taskBroker,\n runners: { workflowRunner },\n concurrentTasksLimit,\n permissions,\n });\n }\n\n async recoverTasks() {\n try {\n await this.options.taskBroker.recoverTasks?.();\n } catch (err) {\n this.logger?.error(stringifyError(err));\n }\n }\n\n start() {\n (async () => {\n while (!this.stopWorkers) {\n await new Promise(resolve => setTimeout(resolve, 10000));\n await this.recoverTasks();\n }\n })();\n (async () => {\n while (!this.stopWorkers) {\n await this.onReadyToClaimTask();\n if (!this.stopWorkers) {\n const task = await this.options.taskBroker.claim();\n void this.taskQueue.add(() => this.runOneTask(task));\n }\n }\n })();\n }\n\n stop() {\n this.stopWorkers = true;\n }\n\n protected onReadyToClaimTask(): Promise {\n if (this.taskQueue.pending < this.options.concurrentTasksLimit) {\n return Promise.resolve();\n }\n return new Promise(resolve => {\n // \"next\" event emits when a task completes\n // https://github.com/sindresorhus/p-queue#next\n this.taskQueue.once('next', () => {\n resolve();\n });\n });\n }\n\n async runOneTask(task: TaskContext) {\n try {\n if (task.spec.apiVersion !== 'scaffolder.backstage.io/v1beta3') {\n throw new Error(\n `Unsupported Template apiVersion ${task.spec.apiVersion}`,\n );\n }\n\n const { output } = await this.options.runners.workflowRunner.execute(\n task,\n );\n\n await task.complete('completed', { output });\n } catch (error) {\n assertError(error);\n await task.complete('failed', {\n error: { name: error.name, message: error.message },\n });\n }\n }\n}\n"],"names":["PQueue","NunjucksWorkflowRunner","stringifyError","assertError"],"mappings":";;;;;;;;;;AAgFO,MAAM,UAAW,CAAA;AAAA,EAKd,YAA6B,OAA4B,EAAA;AAA5B,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA,CAAA;AACnC,IAAA,IAAA,CAAK,WAAc,GAAA,KAAA,CAAA;AACnB,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAK,IAAA,CAAA,SAAA,GAAY,IAAIA,uBAAO,CAAA;AAAA,MAC1B,aAAa,OAAQ,CAAA,oBAAA;AAAA,KACtB,CAAA,CAAA;AAAA,GACH;AAAA,EAVQ,SAAA,CAAA;AAAA,EACA,MAAA,CAAA;AAAA,EACA,WAAA,CAAA;AAAA,EAUR,aAAa,OAAO,OAAmD,EAAA;AACrE,IAAM,MAAA;AAAA,MACJ,UAAA;AAAA,MACA,MAAA;AAAA,MACA,cAAA;AAAA,MACA,YAAA;AAAA,MACA,gBAAA;AAAA,MACA,yBAAA;AAAA,MACA,oBAAuB,GAAA,EAAA;AAAA;AAAA,MACvB,yBAAA;AAAA,MACA,WAAA;AAAA,KACE,GAAA,OAAA,CAAA;AAEJ,IAAM,MAAA,cAAA,GAAiB,IAAIC,6CAAuB,CAAA;AAAA,MAChD,cAAA;AAAA,MACA,YAAA;AAAA,MACA,MAAA;AAAA,MACA,gBAAA;AAAA,MACA,yBAAA;AAAA,MACA,yBAAA;AAAA,MACA,WAAA;AAAA,KACD,CAAA,CAAA;AAED,IAAA,OAAO,IAAI,UAAW,CAAA;AAAA,MACpB,UAAA;AAAA,MACA,OAAA,EAAS,EAAE,cAAe,EAAA;AAAA,MAC1B,oBAAA;AAAA,MACA,WAAA;AAAA,KACD,CAAA,CAAA;AAAA,GACH;AAAA,EAEA,MAAM,YAAe,GAAA;AACnB,IAAI,IAAA;AACF,MAAM,MAAA,IAAA,CAAK,OAAQ,CAAA,UAAA,C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A,OACT,CAAA,CAAA;AAAA,KACF,CAAA,CAAA;AAAA,GACH;AAAA,EAEA,MAAM,WAAW,IAAmB,EAAA;AAClC,IAAI,IAAA;AACF,MAAI,IAAA,IAAA,CAAK,IAAK,CAAA,UAAA,KAAe,iCAAmC,EAAA;AAC9D,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,CAAA,gCAAA,EAAmC,IAAK,CAAA,IAAA,CAAK,UAAU,CAAA,CAAA;AAAA,SACzD,CAAA;AAAA,OACF;AAEA,MAAA,MAAM,EAAE,MAAO,EAAA,GAAI,MAAM,IAAK,CAAA,OAAA,CAAQ,QAAQ,cAAe,CAAA,OAAA;AAAA,QAC3D,IAAA;AAAA,OACF,CAAA;AAEA,MAAA,MAAM,IAAK,CAAA,QAAA,CAAS,WAAa,EAAA,EAAE,QAAQ,CAAA,CAAA;AAAA,aACpC,KAAO,EAAA;AACd,MAAAC,kBAAA,CAAY,KAAK,CAAA,CAAA;AACjB,MAAM,MAAA,IAAA,CAAK,SAAS,QAAU,EAAA;AAAA,QAC5B,OAAO,EAAE,IAAA,EAAM,MAAM,IAAM,EAAA,OAAA,EAAS,MAAM,OAAQ,EAAA;AAAA,OACnD,CAAA,CAAA;AAAA,KACH;AAAA,GACF;AACF;;;;"} -\ No newline at end of file -+{"version":3,"file":"TaskWorker.cjs.js","sources":["../../../src/scaffolder/tasks/TaskWorker.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { WorkflowRunner } from './types';\nimport {\n TaskContext,\n TaskBroker,\n TemplateFilter,\n TemplateGlobal,\n} from '@backstage/plugin-scaffolder-node';\nimport PQueue from 'p-queue';\nimport { NunjucksWorkflowRunner } from './NunjucksWorkflowRunner';\nimport { Logger } from 'winston';\nimport { TemplateActionRegistry } from '../actions';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { assertError, stringifyError } from '@backstage/errors';\nimport { PermissionEvaluator } from '@backstage/plugin-permission-common';\n\nimport { AuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\n\n/**\n * TaskWorkerOptions\n *\n * @public\n */\nexport type TaskWorkerOptions = {\n taskBroker: TaskBroker;\n runners: {\n workflowRunner: WorkflowRunner;\n };\n concurrentTasksLimit: number;\n permissions?: PermissionEvaluator;\n logger?: Logger;\n auditLogger?: AuditLogger;\n};\n\n/**\n * CreateWorkerOptions\n *\n * @public\n */\nexport type CreateWorkerOptions = {\n taskBroker: TaskBroker;\n actionRegistry: TemplateActionRegistry;\n integrations: ScmIntegrations;\n workingDirectory: string;\n logger: Logger;\n auditLogger: AuditLogger;\n additionalTemplateFilters?: Record;\n /**\n * The number of tasks that can be executed at the same time by the worker\n * @defaultValue 10\n * @example\n * ```\n * {\n * concurrentTasksLimit: 1,\n * // OR\n * concurrentTasksLimit: Infinity\n * }\n * ```\n */\n concurrentTasksLimit?: number;\n additionalTemplateGlobals?: Record;\n permissions?: PermissionEvaluator;\n};\n\n/**\n * TaskWorker\n *\n * @public\n */\nexport class TaskWorker {\n private taskQueue: PQueue;\n private logger: Logger | undefined;\n private stopWorkers: boolean;\n private auditLogger: AuditLogger | undefined;\n\n private constructor(private readonly options: TaskWorkerOptions) {\n this.stopWorkers = false;\n this.logger = options.logger;\n this.auditLogger = options.auditLogger;\n this.taskQueue = new PQueue({\n concurrency: options.concurrentTasksLimit,\n });\n }\n\n static async create(options: CreateWorkerOptions): Promise {\n const {\n taskBroker,\n logger,\n actionRegistry,\n integrations,\n workingDirectory,\n additionalTemplateFilters,\n concurrentTasksLimit = 10, // from 1 to Infinity\n additionalTemplateGlobals,\n permissions,\n auditLogger,\n } = options;\n\n const workflowRunner = new NunjucksWorkflowRunner({\n actionRegistry,\n integrations,\n logger,\n auditLogger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n permissions,\n });\n\n return new TaskWorker({\n taskBroker: taskBroker,\n runners: { workflowRunner },\n concurrentTasksLimit,\n permissions,\n auditLogger,\n });\n }\n\n async recoverTasks() {\n try {\n await this.options.taskBroker.recoverTasks?.();\n } catch (err) {\n this.logger?.error(stringifyError(err));\n }\n }\n\n start() {\n (async () => {\n while (!this.stopWorkers) {\n await new Promise(resolve => setTimeout(resolve, 10000));\n await this.recoverTasks();\n }\n })();\n (async () => {\n while (!this.stopWorkers) {\n await this.onReadyToClaimTask();\n if (!this.stopWorkers) {\n const task = await this.options.taskBroker.claim();\n void this.taskQueue.add(() => this.runOneTask(task));\n }\n }\n })();\n }\n\n stop() {\n this.stopWorkers = true;\n }\n\n protected onReadyToClaimTask(): Promise {\n if (this.taskQueue.pending < this.options.concurrentTasksLimit) {\n return Promise.resolve();\n }\n return new Promise(resolve => {\n // \"next\" event emits when a task completes\n // https://github.com/sindresorhus/p-queue#next\n this.taskQueue.once('next', () => {\n resolve();\n });\n });\n }\n\n async runOneTask(task: TaskContext) {\n try {\n await this.auditLogger?.auditLog({\n eventName: 'ScaffolderTaskExecution',\n actorId: 'scaffolder-backend',\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n taskId: task.taskId,\n taskParameters: task.spec.parameters,\n templateRef: task.spec.templateInfo?.entityRef,\n },\n message: `Scaffolding task with taskId: ${task.taskId} initiated`,\n });\n if (task.spec.apiVersion !== 'scaffolder.backstage.io/v1beta3') {\n throw new Error(\n `Unsupported Template apiVersion ${task.spec.apiVersion}`,\n );\n }\n const { output } = await this.options.runners.workflowRunner.execute(\n task,\n );\n await task.complete('completed', { output });\n } catch (error) {\n assertError(error);\n await task.complete('failed', {\n error: { name: error.name, message: error.message },\n });\n }\n }\n}\n"],"names":["PQueue","NunjucksWorkflowRunner","st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,OAAQ,EAAA;AAAA,OACnD,CAAA,CAAA;AAAA,KACH;AAAA,GACF;AACF;;;;"} -\ No newline at end of file -diff --git a/dist/service/router.cjs.js b/dist/service/router.cjs.js -index 7ecf2b0d18bbbd9f2fc5a571af6d999c0068d37b..6c0a2ecfa0f896b44b3bb7681b680aafba60cdc3 100644 ---- a/dist/service/router.cjs.js -+++ b/dist/service/router.cjs.js -@@ -50,6 +50,8 @@ var helpers = require('./helpers.cjs.js'); - var pluginPermissionNode = require('@backstage/plugin-permission-node'); - var rules = require('./rules.cjs.js'); - var checkPermissions = require('../util/checkPermissions.cjs.js'); -+var lodash = require('lodash'); -+var backstagePluginAuditLogNode = require('@janus-idp/backstage-plugin-audit-log-node'); - - function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; } - -@@ -142,6 +144,11 @@ async function createRouter(options) { - }); - const concurrentTasksLimit = options.concurrentTasksLimit ?? options.config.getOptionalNumber("scaffolder.concurrentTasksLimit"); - const logger = parentLogger.child({ plugin: "scaffolder" }); -+ const auditLogger = new backstagePluginAuditLogNode.DefaultAuditLogger({ -+ logger, -+ authService: auth, -+ httpAuthService: httpAuth -+ }); - const workingDirectory = await helpers.getWorkingDirectory(config, logger); - const integrations = integration.ScmIntegrations.fromConfig(config); - let taskBroker; -@@ -150,6 +157,7 @@ async function createRouter(options) { - taskBroker = new StorageTaskBroker.StorageTaskBroker( - databaseTaskStore, - logger, -+ auditLogger, - config, - auth, - additionalWorkspaceProviders -@@ -196,7 +204,8 @@ async function createRouter(options) { - additionalTemplateFilters, - additionalTemplateGlobals, - concurrentTasksLimit, -- permissions -+ permissions, -+ auditLogger - }); - workers.push(worker); - } -@@ -225,6 +234,7 @@ async function createRouter(options) { - actionRegistry, - integrations, - logger, -+ auditLogger, - workingDirectory, - additionalTemplateFilters, - additionalTemplateGlobals, -@@ -262,40 +272,134 @@ async function createRouter(options) { - router.get( - "/v2/templates/:namespace/:kind/:name/parameter-schema", - async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- const { token } = await auth.getPluginRequestToken({ -- onBehalfOf: credentials, -- targetPluginId: "catalog" -+ const requestedTemplateRef = `${req.params.kind}:${req.params.namespace}/${req.params.name}`; -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ const credentials = await httpAuth.credentials(req); -+ const { token } = await auth.getPluginRequestToken({ -+ onBehalfOf: credentials, -+ targetPluginId: "catalog" -+ }); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderParameterSchemaFetch", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ templateRef: requestedTemplateRef -+ }, -+ request: req, -+ message: `${actorId} requested the parameter schema for ${requestedTemplateRef}` -+ }); -+ const template = await authorizeTemplate( -+ req.params, -+ token, -+ credentials -+ ); -+ const parameters = [template.spec.parameters ?? []].flat(); -+ const presentation = template.spec.presentation; -+ const templateRef = `${template.kind}:${template.metadata.namespace || "default"}/${template.metadata.name}`; -+ const responseBody = { -+ title: template.metadata.title ?? template.metadata.name, -+ ...presentation ? { presentation } : {}, -+ description: template.metadata.description, -+ "ui:options": template.metadata["ui:options"], -+ steps: parameters.map((schema) => ({ -+ title: schema.title ?? "Please enter the following information", -+ description: schema.description, -+ schema -+ })) -+ }; -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderParameterSchemaFetch", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ templateRef -+ }, -+ request: req, -+ response: { -+ status: 200, -+ body: responseBody -+ }, -+ message: `${actorId} successfully requested the parameter schema for ${templateRef}` -+ }); -+ res.json(responseBody); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderParameterSchemaFetch", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ request: req, -+ metadata: { -+ templateRef: requestedTemplateRef -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `${actorId} failed to request the parameter schema for ${requestedTemplateRef}` -+ }); -+ throw err; -+ } -+ } -+ ).get("/v2/actions", async (req, res) => { -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderInstalledActionsFetch", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ request: req, -+ message: `${actorId} requested the list of installed actions` - }); -- const template = await authorizeTemplate( -- req.params, -- token, -- credentials -- ); -- const parameters = [template.spec.parameters ?? []].flat(); -- const presentation = template.spec.presentation; -- res.json({ -- title: template.metadata.title ?? template.metadata.name, -- ...presentation ? { presentation } : {}, -- description: template.metadata.description, -- "ui:options": template.metadata["ui:options"], -- steps: parameters.map((schema) => ({ -- title: schema.title ?? "Please enter the following information", -- description: schema.description, -- schema -- })) -+ const actionsList = actionRegistry.list().map((action) => { -+ return { -+ id: action.id, -+ description: action.description, -+ examples: action.examples, -+ schema: action.schema -+ }; -+ }); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderInstalledActionsFetch", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ request: req, -+ response: { -+ status: 200, -+ body: actionsList -+ }, -+ message: `${actorId} successfully requested the list of installed actions` - }); -+ res.json(actionsList); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderInstalledActionsFetch", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `${actorId} failed to request for the list of installed actions` -+ }); -+ throw err; - } -- ).get("/v2/actions", async (_req, res) => { -- const actionsList = actionRegistry.list().map((action) => { -- return { -- id: action.id, -- description: action.description, -- examples: action.examples, -- schema: action.schema -- }; -- }); -- res.json(actionsList); - }).post("/v2/tasks", async (req, res) => { - const templateRef = req.body.templateRef; - const { kind, namespace, name } = catalogModel.parseEntityRef(templateRef, { -@@ -313,280 +417,762 @@ async function createRouter(options) { - }); - const userEntityRef = auth.isPrincipal(credentials, "user") ? credentials.principal.userEntityRef : void 0; - const userEntity = userEntityRef ? await catalogClient.getEntityByRef(userEntityRef, { token }) : void 0; -- let auditLog = `Scaffolding task for ${templateRef}`; -- if (userEntityRef) { -- auditLog += ` created by ${userEntityRef}`; -- } -- logger.info(auditLog); - const values = req.body.values; -- const template = await authorizeTemplate( -- { kind, namespace, name }, -- token, -- credentials -- ); -- for (const parameters of [template.spec.parameters ?? []].flat()) { -- const result2 = jsonschema.validate(values, parameters); -- if (!result2.valid) { -- res.status(400).json({ errors: result2.errors }); -- return; -+ const redactedRequest = lodash.cloneDeep(req); -+ Object.defineProperty(redactedRequest, "ip", { -+ get: () => { -+ return req.ip; - } -+ }); -+ if (req.body.secrets) { -+ const redactedBody = { -+ ...req.body, -+ secrets: Object.keys(req.body.secrets).reduce((acc, key) => { -+ return { -+ ...acc, -+ [key]: "***" -+ }; -+ }, {}) -+ }; -+ redactedRequest.body = redactedBody; - } -- const baseUrl = helpers.getEntityBaseUrl(template); -- const taskSpec = { -- apiVersion: template.apiVersion, -- steps: template.spec.steps.map((step, index) => ({ -- ...step, -- id: step.id ?? `step-${index + 1}`, -- name: step.name ?? step.action -- })), -- EXPERIMENTAL_recovery: template.spec.EXPERIMENTAL_recovery, -- output: template.spec.output ?? {}, -- parameters: values, -- user: { -- entity: userEntity, -- ref: userEntityRef -- }, -- templateInfo: { -- entityRef: catalogModel.stringifyEntityRef({ kind, name, namespace }), -- baseUrl, -- entity: { -- metadata: template.metadata -+ try { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskCreation", -+ stage: "initiation", -+ status: "succeeded", -+ actorId: userEntityRef, -+ request: redactedRequest, -+ metadata: { -+ templateRef -+ }, -+ message: `Scaffolding task for ${templateRef} creation attempt by ${userEntityRef} initiated` -+ }); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskCreatePermission], -+ permissionService: permissions -+ }); -+ const template = await authorizeTemplate( -+ { kind, namespace, name }, -+ token, -+ credentials -+ ); -+ for (const parameters of [template.spec.parameters ?? []].flat()) { -+ const result2 = jsonschema.validate(values, parameters); -+ if (!result2.valid) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskCreation", -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ actorId: userEntityRef, -+ request: redactedRequest, -+ metadata: { -+ templateRef -+ }, -+ response: { -+ status: 400, -+ body: { errors: result2.errors } -+ }, -+ errors: result2.errors, -+ message: `Scaffolding task for ${templateRef} creation attempt by ${userEntityRef} failed` -+ }); -+ return res.status(400).json({ errors: result2.errors }); - } - } -- }; -- const secrets = { -- ...req.body.secrets, -- backstageToken: token, -- __initiatorCredentials: JSON.stringify({ -- ...credentials, -- // credentials.token is nonenumerable and will not be serialized, so we need to add it explicitly -- token: credentials.token -- }) -- }; -- const result = await taskBroker.dispatch({ -- spec: taskSpec, -- createdBy: userEntityRef, -- secrets -- }); -- res.status(201).json({ id: result.taskId }); -- }).get("/v2/tasks", async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- await checkPermissions.checkPermission({ -- credentials, -- permissions: [alpha.taskReadPermission], -- permissionService: permissions -- }); -- if (!taskBroker.list) { -- throw new Error( -- "TaskBroker does not support listing tasks, please implement the list method on the TaskBroker." -- ); -+ const baseUrl = helpers.getEntityBaseUrl(template); -+ const taskSpec = { -+ apiVersion: template.apiVersion, -+ steps: template.spec.steps.map((step, index) => ({ -+ ...step, -+ id: step.id ?? `step-${index + 1}`, -+ name: step.name ?? step.action -+ })), -+ EXPERIMENTAL_recovery: template.spec.EXPERIMENTAL_recovery, -+ output: template.spec.output ?? {}, -+ parameters: values, -+ user: { -+ entity: userEntity, -+ ref: userEntityRef -+ }, -+ templateInfo: { -+ entityRef: catalogModel.stringifyEntityRef({ kind, name, namespace }), -+ baseUrl, -+ entity: { -+ metadata: template.metadata -+ } -+ } -+ }; -+ const secrets = { -+ ...req.body.secrets, -+ backstageToken: token, -+ __initiatorCredentials: JSON.stringify({ -+ ...credentials, -+ // credentials.token is nonenumerable and will not be serialized, so we need to add it explicitly -+ token: credentials.token -+ }) -+ }; -+ const result = await taskBroker.dispatch({ -+ spec: taskSpec, -+ createdBy: userEntityRef, -+ secrets -+ }); -+ let auditLog = `Scaffolding task for ${templateRef}`; -+ if (userEntityRef) { -+ auditLog += ` created by ${userEntityRef}`; -+ } -+ logger.info(auditLog); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskCreation", -+ stage: "completion", -+ status: "succeeded", -+ actorId: userEntityRef, -+ request: redactedRequest, -+ metadata: { -+ taskId: result.taskId, -+ templateRef -+ }, -+ response: { -+ status: 201, -+ body: { id: result.taskId } -+ }, -+ message: `Scaffolding task for ${templateRef} with taskId: ${result.taskId} successfully created by ${userEntityRef}` -+ }); -+ return res.status(201).json({ id: result.taskId }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskCreation", -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ actorId: userEntityRef, -+ request: redactedRequest, -+ metadata: { -+ templateRef -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Scaffolding task for ${templateRef} creation attempt by ${userEntityRef} failed` -+ }); -+ throw err; - } -- const createdBy = helpers.parseStringsParam(req.query.createdBy, "createdBy"); -- const status = helpers.parseStringsParam(req.query.status, "status"); -- const order = helpers.parseStringsParam(req.query.order, "order")?.map((item) => { -- const match = item.match(/^(asc|desc):(.+)$/); -- if (!match) { -- throw new errors.InputError( -- `Invalid order parameter "${item}", expected ":"` -+ }).get("/v2/tasks", async (req, res) => { -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskListFetch", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ request: req, -+ message: `${actorId} requested for the list of scaffolder tasks` -+ }); -+ const credentials = await httpAuth.credentials(req); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskReadPermission], -+ permissionService: permissions -+ }); -+ if (!taskBroker.list) { -+ throw new Error( -+ "TaskBroker does not support listing tasks, please implement the list method on the TaskBroker." - ); - } -- return { -- order: match[1], -- field: match[2] -- }; -- }); -- const limit = helpers.parseNumberParam(req.query.limit, "limit"); -- const offset = helpers.parseNumberParam(req.query.offset, "offset"); -- const tasks = await taskBroker.list({ -- filters: { -- createdBy, -- status: status ? status : void 0 -- }, -- order, -- pagination: { -- limit: limit ? limit[0] : void 0, -- offset: offset ? offset[0] : void 0 -- } -- }); -- res.status(200).json(tasks); -+ const createdBy = helpers.parseStringsParam(req.query.createdBy, "createdBy"); -+ const status = helpers.parseStringsParam(req.query.status, "status"); -+ const order = helpers.parseStringsParam(req.query.order, "order")?.map((item) => { -+ const match = item.match(/^(asc|desc):(.+)$/); -+ if (!match) { -+ throw new errors.InputError( -+ `Invalid order parameter "${item}", expected ":"` -+ ); -+ } -+ return { -+ order: match[1], -+ field: match[2] -+ }; -+ }); -+ const limit = helpers.parseNumberParam(req.query.limit, "limit"); -+ const offset = helpers.parseNumberParam(req.query.offset, "offset"); -+ const tasks = await taskBroker.list({ -+ filters: { -+ createdBy, -+ status: status ? status : void 0 -+ }, -+ order, -+ pagination: { -+ limit: limit ? limit[0] : void 0, -+ offset: offset ? offset[0] : void 0 -+ } -+ }); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskListFetch", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ request: req, -+ response: { -+ status: 200, -+ body: tasks -+ }, -+ message: `${actorId} successfully requested for the list of scaffolder tasks` -+ }); -+ res.status(200).json(tasks); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskListFetch", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `${actorId} request for the list of scaffolder tasks failed` -+ }); -+ throw err; -+ } - }).get("/v2/tasks/:taskId", async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- await checkPermissions.checkPermission({ -- credentials, -- permissions: [alpha.taskReadPermission], -- permissionService: permissions -- }); - const { taskId } = req.params; -- const task = await taskBroker.get(taskId); -- if (!task) { -- throw new errors.NotFoundError(`Task with id ${taskId} does not exist`); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskFetch", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ message: `${actorId} requested for scaffolder task ${taskId}` -+ }); -+ const credentials = await httpAuth.credentials(req); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskReadPermission], -+ permissionService: permissions -+ }); -+ const task = await taskBroker.get(taskId); -+ if (!task) { -+ throw new errors.NotFoundError(`Task with id ${taskId} does not exist`); -+ } -+ delete task.secrets; -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskFetch", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ request: req, -+ response: { -+ status: 200, -+ body: task -+ }, -+ message: `${actorId} successfully requested for scaffolder tasks ${taskId}` -+ }); -+ res.status(200).json(task); -+ } catch (err) { -+ let status = 500; -+ if (err.name === "NotFoundError") { -+ status = 404; -+ } -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskFetch", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ request: req, -+ response: { -+ status -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `${actorId} request for scaffolder tasks ${taskId} failed` -+ }); -+ throw err; - } -- delete task.secrets; -- res.status(200).json(task); - }).post("/v2/tasks/:taskId/cancel", async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- await checkPermissions.checkPermission({ -- credentials, -- permissions: [alpha.taskCancelPermission, alpha.taskReadPermission], -- permissionService: permissions -- }); - const { taskId } = req.params; -- await taskBroker.cancel?.(taskId); -- res.status(200).json({ status: "cancelled" }); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskCancellation", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ message: `Cancellation request for Scaffolding task with taskId: ${taskId} from ${actorId} received` -+ }); -+ const credentials = await httpAuth.credentials(req); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskCancelPermission], -+ permissionService: permissions -+ }); -+ await taskBroker.cancel?.(taskId); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskCancellation", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ response: { -+ status: 200, -+ body: { status: "cancelled" } -+ }, -+ message: `Scaffolding task with taskId: ${taskId} successfully cancelled by ${actorId}` -+ }); -+ res.status(200).json({ status: "cancelled" }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskCancellation", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `${actorId}'s cancel request for task ${taskId} failed` -+ }); -+ throw err; -+ } - }).post("/v2/tasks/:taskId/retry", async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- await checkPermissions.checkPermission({ -- credentials, -- permissions: [alpha.taskCreatePermission, alpha.taskReadPermission], -- permissionService: permissions -- }); - const { taskId } = req.params; -- await taskBroker.retry?.(taskId); -- res.status(201).json({ id: taskId }); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskRetry", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ message: `Retry request for Scaffolding task with taskId: ${taskId} from ${actorId} received` -+ }); -+ const credentials = await httpAuth.credentials(req); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskCreatePermission, alpha.taskReadPermission], -+ permissionService: permissions -+ }); -+ await taskBroker.retry?.(taskId); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskRetry", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ response: { -+ status: 201, -+ body: { id: taskId } -+ }, -+ message: `Scaffolding task with taskId: ${taskId} successfully retried by ${actorId}` -+ }); -+ res.status(201).json({ id: taskId }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskRetry", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `${actorId}'s retry request for task ${taskId} failed` -+ }); -+ throw err; -+ } - }).get("/v2/tasks/:taskId/eventstream", async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- await checkPermissions.checkPermission({ -- credentials, -- permissions: [alpha.taskReadPermission], -- permissionService: permissions -- }); - const { taskId } = req.params; -- const after = req.query.after !== void 0 ? Number(req.query.after) : void 0; -- logger.debug(`Event stream observing taskId '${taskId}' opened`); -- res.writeHead(200, { -- Connection: "keep-alive", -- "Cache-Control": "no-cache", -- "Content-Type": "text/event-stream" -- }); -- const subscription = taskBroker.event$({ taskId, after }).subscribe({ -- error: (error) => { -- logger.error( -- `Received error from event stream when observing taskId '${taskId}', ${error}` -- ); -- res.end(); -- }, -- next: ({ events }) => { -- let shouldUnsubscribe = false; -- for (const event of events) { -- res.write( -- `event: ${event.type} -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ const after = req.query.after !== void 0 ? Number(req.query.after) : void 0; -+ logger.debug(`Event stream observing taskId '${taskId}' opened`); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskStream", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ message: `Event stream for scaffolding task with taskId: ${taskId} was opened by ${actorId}` -+ }); -+ const credentials = await httpAuth.credentials(req); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskReadPermission], -+ permissionService: permissions -+ }); -+ res.writeHead(200, { -+ Connection: "keep-alive", -+ "Cache-Control": "no-cache", -+ "Content-Type": "text/event-stream" -+ }); -+ const subscription = taskBroker.event$({ taskId, after }).subscribe({ -+ error: async (error) => { -+ logger.error( -+ `Received error from event stream when observing taskId '${taskId}', ${error}` -+ ); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskStream", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ errors: [ -+ { -+ name: error.name, -+ message: error.message, -+ stack: error.stack, -+ cause: error.cause -+ } -+ ], -+ message: `Received error from event stream observing scaffolding task with taskId: ${taskId} requested by ${actorId}` -+ }); -+ res.end(); -+ }, -+ next: ({ events }) => { -+ let shouldUnsubscribe = false; -+ for (const event of events) { -+ res.write( -+ `event: ${event.type} - data: ${JSON.stringify(event)} - - ` -- ); -- if (event.type === "completion" && !event.isTaskRecoverable) { -- shouldUnsubscribe = true; -+ ); -+ if (event.type === "completion") { -+ shouldUnsubscribe = true; -+ } -+ } -+ res.flush?.(); -+ if (shouldUnsubscribe) { -+ subscription.unsubscribe(); -+ res.end(); - } - } -- res.flush?.(); -- if (shouldUnsubscribe) { -- subscription.unsubscribe(); -- res.end(); -- } -- } -- }); -- req.on("close", () => { -- subscription.unsubscribe(); -- logger.debug(`Event stream observing taskId '${taskId}' closed`); -- }); -+ }); -+ req.on("close", async () => { -+ subscription.unsubscribe(); -+ logger.debug(`Event stream observing taskId '${taskId}' closed`); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskStream", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ message: `Event stream observing scaffolding task with taskId: ${taskId} was closed by ${actorId}` -+ }); -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskStream", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Received error from event stream observing scaffolding task with taskId: ${taskId} requested by ${actorId}` -+ }); -+ throw err; -+ } - }).get("/v2/tasks/:taskId/events", async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- await checkPermissions.checkPermission({ -- credentials, -- permissions: [alpha.taskReadPermission], -- permissionService: permissions -- }); - const { taskId } = req.params; -- const after = Number(req.query.after) || void 0; -- const timeout = setTimeout(() => { -- res.json([]); -- }, 3e4); -- const subscription = taskBroker.event$({ taskId, after }).subscribe({ -- error: (error) => { -- logger.error( -- `Received error from event stream when observing taskId '${taskId}', ${error}` -- ); -- }, -- next: ({ events }) => { -- clearTimeout(timeout); -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ const after = Number(req.query.after) || void 0; -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskEventFetch", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} initiated by ${actorId}` -+ }); -+ const credentials = await httpAuth.credentials(req); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskReadPermission], -+ permissionService: permissions -+ }); -+ const timeout = setTimeout(() => { -+ res.json([]); -+ }, 3e4); -+ const subscription = taskBroker.event$({ taskId, after }).subscribe({ -+ error: async (error) => { -+ logger.error( -+ `Received error from event stream when observing taskId '${taskId}', ${error}` -+ ); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskEventFetch", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ errors: [ -+ { -+ name: error.name, -+ message: error.message, -+ stack: error.stack -+ } -+ ], -+ message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} requested by ${actorId} failed` -+ }); -+ }, -+ next: async ({ events }) => { -+ clearTimeout(timeout); -+ subscription.unsubscribe(); -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskEventFetch", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ response: { -+ status: 200, -+ body: events -+ }, -+ message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} by ${actorId} succeeded` -+ }); -+ res.json(events); -+ } -+ }); -+ req.on("close", () => { - subscription.unsubscribe(); -- res.json(events); -- } -- }); -- req.on("close", () => { -- subscription.unsubscribe(); -- clearTimeout(timeout); -- }); -- }).post("/v2/dry-run", async (req, res) => { -- const credentials = await httpAuth.credentials(req); -- await checkPermissions.checkPermission({ -- credentials, -- permissions: [alpha.taskCreatePermission], -- permissionService: permissions -- }); -- const bodySchema = zod.z.object({ -- template: zod.z.unknown(), -- values: zod.z.record(zod.z.unknown()), -- secrets: zod.z.record(zod.z.string()).optional(), -- directoryContents: zod.z.array( -- zod.z.object({ path: zod.z.string(), base64Content: zod.z.string() }) -- ) -- }); -- const body = await bodySchema.parseAsync(req.body).catch((e) => { -- throw new errors.InputError(`Malformed request: ${e}`); -- }); -- const template = body.template; -- if (!await pluginScaffolderCommon.templateEntityV1beta3Validator.check(template)) { -- throw new errors.InputError("Input template is not a template"); -+ clearTimeout(timeout); -+ }); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskEventFetch", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ metadata: { -+ taskId -+ }, -+ request: req, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} requested by ${actorId} failed` -+ }); -+ throw err; - } -- const { token } = await auth.getPluginRequestToken({ -- onBehalfOf: credentials, -- targetPluginId: "catalog" -- }); -- const userEntityRef = auth.isPrincipal(credentials, "user") ? credentials.principal.userEntityRef : void 0; -- const userEntity = userEntityRef ? await catalogClient.getEntityByRef(userEntityRef, { token }) : void 0; -- for (const parameters of [template.spec.parameters ?? []].flat()) { -- const result2 = jsonschema.validate(body.values, parameters); -- if (!result2.valid) { -- res.status(400).json({ errors: result2.errors }); -- return; -+ }).post("/v2/dry-run", async (req, res) => { -+ const actorId = await auditLogger.getActorId(req); -+ try { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskDryRun", -+ actorId, -+ stage: "initiation", -+ status: "succeeded", -+ metadata: { -+ isDryRun: true -+ }, -+ request: req, -+ message: `Dry Run scaffolder task initiated by ${actorId}` -+ }); -+ const credentials = await httpAuth.credentials(req); -+ await checkPermissions.checkPermission({ -+ credentials, -+ permissions: [alpha.taskCreatePermission], -+ permissionService: permissions -+ }); -+ const bodySchema = zod.z.object({ -+ template: zod.z.unknown(), -+ values: zod.z.record(zod.z.unknown()), -+ secrets: zod.z.record(zod.z.string()).optional(), -+ directoryContents: zod.z.array( -+ zod.z.object({ path: zod.z.string(), base64Content: zod.z.string() }) -+ ) -+ }); -+ const body = await bodySchema.parseAsync(req.body).catch((e) => { -+ throw new errors.InputError(`Malformed request: ${e}`); -+ }); -+ const template = body.template; -+ if (!await pluginScaffolderCommon.templateEntityV1beta3Validator.check(template)) { -+ throw new errors.InputError("Input template is not a template"); - } -- } -- const steps = template.spec.steps.map((step, index) => ({ -- ...step, -- id: step.id ?? `step-${index + 1}`, -- name: step.name ?? step.action -- })); -- const result = await dryRunner({ -- spec: { -- apiVersion: template.apiVersion, -- steps, -- output: template.spec.output ?? {}, -- parameters: body.values, -- user: { -- entity: userEntity, -- ref: userEntityRef -+ const templateRef = `${template.kind}:${template.metadata.namespace || "default"}/${template.metadata.name}`; -+ const { token } = await auth.getPluginRequestToken({ -+ onBehalfOf: credentials, -+ targetPluginId: "catalog" -+ }); -+ const userEntityRef = auth.isPrincipal(credentials, "user") ? credentials.principal.userEntityRef : void 0; -+ const userEntity = userEntityRef ? await catalogClient.getEntityByRef(userEntityRef, { token }) : void 0; -+ for (const parameters of [template.spec.parameters ?? []].flat()) { -+ const result2 = jsonschema.validate(body.values, parameters); -+ if (!result2.valid) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskDryRun", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ metadata: { -+ templateRef, -+ parameters: template.spec.parameters, -+ isDryRun: true -+ }, -+ errors: result2.errors, -+ request: req, -+ response: { -+ status: 400, -+ body: { errors: result2.errors } -+ }, -+ message: `Dry Run scaffolder task for ${templateRef} initiated by ${actorId} failed` -+ }); -+ return res.status(400).json({ errors: result2.errors }); - } -- }, -- directoryContents: (body.directoryContents ?? []).map((file) => ({ -- path: file.path, -- content: Buffer.from(file.base64Content, "base64") -- })), -- secrets: { -- ...body.secrets, -- ...token && { backstageToken: token } -- }, -- credentials -- }); -- res.status(200).json({ -- ...result, -- steps, -- directoryContents: result.directoryContents.map((file) => ({ -- path: file.path, -- executable: file.executable, -- base64Content: file.content.toString("base64") -- })) -- }); -+ } -+ const steps = template.spec.steps.map((step, index) => ({ -+ ...step, -+ id: step.id ?? `step-${index + 1}`, -+ name: step.name ?? step.action -+ })); -+ const result = await dryRunner({ -+ spec: { -+ apiVersion: template.apiVersion, -+ steps, -+ output: template.spec.output ?? {}, -+ parameters: body.values, -+ user: { -+ entity: userEntity, -+ ref: userEntityRef -+ } -+ }, -+ directoryContents: (body.directoryContents ?? []).map((file) => ({ -+ path: file.path, -+ content: Buffer.from(file.base64Content, "base64") -+ })), -+ secrets: { -+ ...body.secrets, -+ ...token && { backstageToken: token } -+ }, -+ credentials -+ }); -+ const dryRunResults = { -+ ...result, -+ steps, -+ directoryContents: result.directoryContents.map((file) => ({ -+ path: file.path, -+ executable: file.executable, -+ base64Content: file.content.toString("base64") -+ })) -+ }; -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskDryRun", -+ actorId, -+ stage: "completion", -+ status: "succeeded", -+ metadata: { -+ templateRef, -+ parameters: template.spec.parameters, -+ isDryRun: true -+ }, -+ request: req, -+ response: { -+ status: 200, -+ body: dryRunResults -+ }, -+ message: `Dry Run scaffolder task for ${templateRef} initiated by ${actorId} completed successfully` -+ }); -+ return res.status(200).json(dryRunResults); -+ } catch (err) { -+ await auditLogger.auditLog({ -+ eventName: "ScaffolderTaskDryRun", -+ actorId, -+ stage: "completion", -+ status: "failed", -+ level: "error", -+ request: req, -+ metadata: { -+ isDryRun: true -+ }, -+ errors: [ -+ { -+ name: err.name, -+ message: err.message, -+ stack: err.stack -+ } -+ ], -+ message: `Scaffolder Task Dry Run requested by ${actorId} failed` -+ }); -+ throw err; -+ } - }).post("/v2/autocomplete/:provider/:resource", async (req, res) => { - const { token, context } = req.body; - const { provider, resource } = req.params; -diff --git a/dist/service/router.cjs.js.map b/dist/service/router.cjs.js.map -index f564bdd67f041c9fe90e04ed0b30018b070559e8..8f096c5e96512a6bf05d86c15fc8a4cd7da95cdc 100644 ---- a/dist/service/router.cjs.js.map -+++ b/dist/service/router.cjs.js.map -@@ -1 +1 @@ --{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createLegacyAuthAdapters,\n HostDiscovery,\n} from '@backstage/backend-common';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n CompoundEntityRef,\n Entity,\n parseEntityRef,\n stringifyEntityRef,\n UserEntity,\n} from '@backstage/catalog-model';\nimport { Config, readDurationFromConfig } from '@backstage/config';\nimport { InputError, NotFoundError, stringifyError } from '@backstage/errors';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { HumanDuration, JsonObject, JsonValue } from '@backstage/types';\nimport {\n TaskSpec,\n TemplateEntityStepV1beta3,\n TemplateEntityV1beta3,\n templateEntityV1beta3Validator,\n TemplateParametersV1beta3,\n} from '@backstage/plugin-scaffolder-common';\nimport {\n RESOURCE_TYPE_SCAFFOLDER_ACTION,\n RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n scaffolderActionPermissions,\n scaffolderTaskPermissions,\n scaffolderTemplatePermissions,\n taskCancelPermission,\n taskCreatePermission,\n taskReadPermission,\n templateParameterReadPermission,\n templateStepReadPermission,\n} from '@backstage/plugin-scaffolder-common/alpha';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { validate } from 'jsonschema';\nimport { Logger } from 'winston';\nimport { z } from 'zod';\nimport {\n TaskBroker,\n TaskStatus,\n TemplateAction,\n TemplateFilter,\n TemplateGlobal,\n} from '@backstage/plugin-scaffolder-node';\nimport {\n createBuiltinActions,\n DatabaseTaskStore,\n TaskWorker,\n TemplateActionRegistry,\n} from '../scaffolder';\nimport { createDryRunner } from '../scaffolder/dryrun';\nimport { StorageTaskBroker } from '../scaffolder/tasks/StorageTaskBroker';\nimport {\n findTemplate,\n getEntityBaseUrl,\n getWorkingDirectory,\n parseNumberParam,\n parseStringsParam,\n} from './helpers';\nimport { PermissionRuleParams } from '@backstage/plugin-permission-common';\nimport {\n createConditionAuthorizer,\n createPermissionIntegrationRouter,\n PermissionRule,\n} from '@backstage/plugin-permission-node';\nimport { scaffolderActionRules, scaffolderTemplateRules } from './rules';\nimport { Duration } from 'luxon';\nimport {\n AuthService,\n BackstageCredentials,\n DatabaseService,\n DiscoveryService,\n HttpAuthService,\n LifecycleService,\n PermissionsService,\n SchedulerService,\n UrlReaderService,\n} from '@backstage/backend-plugin-api';\nimport {\n IdentityApi,\n IdentityApiGetIdentityRequest,\n} from '@backstage/plugin-auth-node';\nimport { InternalTaskSecrets } from '../scaffolder/tasks/types';\nimport { checkPermission } from '../util/checkPermissions';\nimport {\n AutocompleteHandler,\n WorkspaceProvider,\n} from '@backstage/plugin-scaffolder-node/alpha';\n\n/**\n *\n * @public\n */\nexport type TemplatePermissionRuleInput<\n TParams extends PermissionRuleParams = PermissionRuleParams,\n> = PermissionRule<\n TemplateEntityStepV1beta3 | TemplateParametersV1beta3,\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n TParams\n>;\nfunction isTemplatePermissionRuleInput(\n permissionRule: TemplatePermissionRuleInput | ActionPermissionRuleInput,\n): permissionRule is TemplatePermissionRuleInput {\n return permissionRule.resourceType === RESOURCE_TYPE_SCAFFOLDER_TEMPLATE;\n}\n\n/**\n *\n * @public\n */\nexport type ActionPermissionRuleInput<\n TParams extends PermissionRuleParams = PermissionRuleParams,\n> = PermissionRule<\n TemplateEntityStepV1beta3 | TemplateParametersV1beta3,\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_ACTION,\n TParams\n>;\nfunction isActionPermissionRuleInput(\n permissionRule: TemplatePermissionRuleInput | ActionPermissionRuleInput,\n): permissionRule is ActionPermissionRuleInput {\n return permissionRule.resourceType === RESOURCE_TYPE_SCAFFOLDER_ACTION;\n}\n\n/**\n * RouterOptions\n *\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n logger: Logger;\n config: Config;\n reader: UrlReaderService;\n lifecycle?: LifecycleService;\n database: DatabaseService;\n catalogClient: CatalogApi;\n scheduler?: SchedulerService;\n actions?: TemplateAction[];\n /**\n * @deprecated taskWorkers is deprecated in favor of concurrentTasksLimit option with a single TaskWorker\n * @defaultValue 1\n */\n taskWorkers?: number;\n /**\n * Sets the number of concurrent tasks that can be run at any given time on the TaskWorker\n * @defaultValue 10\n */\n concurrentTasksLimit?: number;\n taskBroker?: TaskBroker;\n additionalTemplateFilters?: Record;\n additionalTemplateGlobals?: Record;\n additionalWorkspaceProviders?: Record;\n permissions?: PermissionsService;\n permissionRules?: Array<\n TemplatePermissionRuleInput | ActionPermissionRuleInput\n >;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n identity?: IdentityApi;\n discovery?: DiscoveryService;\n\n autocompleteHandlers?: Record;\n}\n\nfunction isSupportedTemplate(entity: TemplateEntityV1beta3) {\n return entity.apiVersion === 'scaffolder.backstage.io/v1beta3';\n}\n\n/*\n * @deprecated This function remains as the DefaultIdentityClient behaves slightly differently to the pre-existing\n * scaffolder behaviour. Specifically if the token fails to parse, the DefaultIdentityClient will raise an error.\n * The scaffolder did not raise an error in this case. As such we chose to allow it to behave as it did previously\n * until someone explicitly passes an IdentityApi. When we have reasonable confidence that most backstage deployments\n * are using the IdentityApi, we can remove this function.\n */\nfunction buildDefaultIdentityClient(options: RouterOptions): IdentityApi {\n return {\n getIdentity: async ({ request }: IdentityApiGetIdentityRequest) => {\n const header = request.headers.authorization;\n const { logger } = options;\n\n if (!header) {\n return undefined;\n }\n\n try {\n const token = header.match(/^Bearer\\s(\\S+\\.\\S+\\.\\S+)$/i)?.[1];\n if (!token) {\n throw new TypeError('Expected Bearer with JWT');\n }\n\n const [_header, rawPayload, _signature] = token.split('.');\n const payload: JsonValue = JSON.parse(\n Buffer.from(rawPayload, 'base64').toString(),\n );\n\n if (\n typeof payload !== 'object' ||\n payload === null ||\n Array.isArray(payload)\n ) {\n throw new TypeError('Malformed JWT payload');\n }\n\n const sub = payload.sub;\n if (typeof sub !== 'string') {\n throw new TypeError('Expected string sub claim');\n }\n\n if (sub === 'backstage-server') {\n return undefined;\n }\n\n // Check that it's a valid ref, otherwise this will throw.\n parseEntityRef(sub);\n\n return {\n identity: {\n userEntityRef: sub,\n ownershipEntityRefs: [],\n type: 'user',\n },\n token,\n };\n } catch (e) {\n logger.error(`Invalid authorization header: ${stringifyError(e)}`);\n return undefined;\n }\n },\n };\n}\n\nconst readDuration = (\n config: Config,\n key: string,\n defaultValue: HumanDuration,\n) => {\n if (config.has(key)) {\n return readDurationFromConfig(config, { key });\n }\n return defaultValue;\n};\n\n/**\n * A method to create a router for the scaffolder backend plugin.\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise {\n const router = Router();\n // Be generous in upload size to support a wide range of templates in dry-run mode.\n router.use(express.json({ limit: '10MB' }));\n\n const {\n logger: parentLogger,\n config,\n reader,\n database,\n catalogClient,\n actions,\n taskWorkers,\n scheduler,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n additionalWorkspaceProviders,\n permissions,\n permissionRules,\n discovery = HostDiscovery.fromConfig(config),\n identity = buildDefaultIdentityClient(options),\n autocompleteHandlers = {},\n } = options;\n\n const { auth, httpAuth } = createLegacyAuthAdapters({\n ...options,\n identity,\n discovery,\n });\n\n const concurrentTasksLimit =\n options.concurrentTasksLimit ??\n options.config.getOptionalNumber('scaffolder.concurrentTasksLimit');\n\n const logger = parentLogger.child({ plugin: 'scaffolder' });\n\n const workingDirectory = await getWorkingDirectory(config, logger);\n const integrations = ScmIntegrations.fromConfig(config);\n\n let taskBroker: TaskBroker;\n if (!options.taskBroker) {\n const databaseTaskStore = await DatabaseTaskStore.create({ database });\n taskBroker = new StorageTaskBroker(\n databaseTaskStore,\n logger,\n config,\n auth,\n additionalWorkspaceProviders,\n );\n\n if (scheduler && databaseTaskStore.listStaleTasks) {\n await scheduler.scheduleTask({\n id: 'close_stale_tasks',\n frequency: readDuration(\n config,\n 'scaffolder.taskTimeoutJanitorFrequency',\n {\n minutes: 5,\n },\n ),\n timeout: { minutes: 15 },\n fn: async () => {\n const { tasks } = await databaseTaskStore.listStaleTasks({\n timeoutS: Duration.fromObject(\n readDuration(config, 'scaffolder.taskTimeout', {\n hours: 24,\n }),\n ).as('seconds'),\n });\n\n for (const task of tasks) {\n await databaseTaskStore.shutdownTask(task);\n logger.info(`Successfully closed stale task ${task.taskId}`);\n }\n },\n });\n }\n } else {\n taskBroker = options.taskBroker;\n }\n\n const actionRegistry = new TemplateActionRegistry();\n\n const workers: TaskWorker[] = [];\n if (concurrentTasksLimit !== 0) {\n for (let i = 0; i < (taskWorkers || 1); i++) {\n const worker = await TaskWorker.create({\n taskBroker,\n actionRegistry,\n integrations,\n logger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n concurrentTasksLimit,\n permissions,\n });\n workers.push(worker);\n }\n }\n\n const actionsToRegister = Array.isArray(actions)\n ? actions\n : createBuiltinActions({\n integrations,\n catalogClient,\n reader,\n config,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n auth,\n });\n\n actionsToRegister.forEach(action => actionRegistry.register(action));\n\n const launchWorkers = () => workers.forEach(worker => worker.start());\n\n const shutdownWorkers = () => {\n workers.forEach(worker => worker.stop());\n };\n\n if (options.lifecycle) {\n options.lifecycle.addStartupHook(launchWorkers);\n options.lifecycle.addShutdownHook(shutdownWorkers);\n } else {\n launchWorkers();\n }\n\n const dryRunner = createDryRunner({\n actionRegistry,\n integrations,\n logger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n permissions,\n });\n\n const templateRules: TemplatePermissionRuleInput[] = Object.values(\n scaffolderTemplateRules,\n );\n const actionRules: ActionPermissionRuleInput[] = Object.values(\n scaffolderActionRules,\n );\n\n if (permissionRules) {\n templateRules.push(\n ...permissionRules.filter(isTemplatePermissionRuleInput),\n );\n actionRules.push(...permissionRules.filter(isActionPermissionRuleInput));\n }\n\n const isAuthorized = createConditionAuthorizer(Object.values(templateRules));\n\n const permissionIntegrationRouter = createPermissionIntegrationRouter({\n resources: [\n {\n resourceType: RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n permissions: scaffolderTemplatePermissions,\n rules: templateRules,\n },\n {\n resourceType: RESOURCE_TYPE_SCAFFOLDER_ACTION,\n permissions: scaffolderActionPermissions,\n rules: actionRules,\n },\n ],\n permissions: scaffolderTaskPermissions,\n });\n\n router.use(permissionIntegrationRouter);\n\n router\n .get(\n '/v2/templates/:namespace/:kind/:name/parameter-schema',\n async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const template = await authorizeTemplate(\n req.params,\n token,\n credentials,\n );\n\n const parameters = [template.spec.parameters ?? []].flat();\n\n const presentation = template.spec.presentation;\n\n res.json({\n title: template.metadata.title ?? template.metadata.name,\n ...(presentation ? { presentation } : {}),\n description: template.metadata.description,\n 'ui:options': template.metadata['ui:options'],\n steps: parameters.map(schema => ({\n title: schema.title ?? 'Please enter the following information',\n description: schema.description,\n schema,\n })),\n });\n },\n )\n .get('/v2/actions', async (_req, res) => {\n const actionsList = actionRegistry.list().map(action => {\n return {\n id: action.id,\n description: action.description,\n examples: action.examples,\n schema: action.schema,\n };\n });\n res.json(actionsList);\n })\n .post('/v2/tasks', async (req, res) => {\n const templateRef: string = req.body.templateRef;\n const { kind, namespace, name } = parseEntityRef(templateRef, {\n defaultKind: 'template',\n });\n\n const credentials = await httpAuth.credentials(req);\n\n await checkPermission({\n credentials,\n permissions: [taskCreatePermission],\n permissionService: permissions,\n });\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const userEntityRef = auth.isPrincipal(credentials, 'user')\n ? credentials.principal.userEntityRef\n : undefined;\n\n const userEntity = userEntityRef\n ? await catalogClient.getEntityByRef(userEntityRef, { token })\n : undefined;\n\n let auditLog = `Scaffolding task for ${templateRef}`;\n if (userEntityRef) {\n auditLog += ` created by ${userEntityRef}`;\n }\n logger.info(auditLog);\n\n const values = req.body.values;\n\n const template = await authorizeTemplate(\n { kind, namespace, name },\n token,\n credentials,\n );\n\n for (const parameters of [template.spec.parameters ?? []].flat()) {\n const result = validate(values, parameters);\n\n if (!result.valid) {\n res.status(400).json({ errors: result.errors });\n return;\n }\n }\n\n const baseUrl = getEntityBaseUrl(template);\n\n const taskSpec: TaskSpec = {\n apiVersion: template.apiVersion,\n steps: template.spec.steps.map((step, index) => ({\n ...step,\n id: step.id ?? `step-${index + 1}`,\n name: step.name ?? step.action,\n })),\n EXPERIMENTAL_recovery: template.spec.EXPERIMENTAL_recovery,\n output: template.spec.output ?? {},\n parameters: values,\n user: {\n entity: userEntity as UserEntity,\n ref: userEntityRef,\n },\n templateInfo: {\n entityRef: stringifyEntityRef({ kind, name, namespace }),\n baseUrl,\n entity: {\n metadata: template.metadata,\n },\n },\n };\n\n const secrets: InternalTaskSecrets = {\n ...req.body.secrets,\n backstageToken: token,\n __initiatorCredentials: JSON.stringify({\n ...credentials,\n // credentials.token is nonenumerable and will not be serialized, so we need to add it explicitly\n token: (credentials as any).token,\n }),\n };\n\n const result = await taskBroker.dispatch({\n spec: taskSpec,\n createdBy: userEntityRef,\n secrets,\n });\n\n res.status(201).json({ id: result.taskId });\n })\n .get('/v2/tasks', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n if (!taskBroker.list) {\n throw new Error(\n 'TaskBroker does not support listing tasks, please implement the list method on the TaskBroker.',\n );\n }\n\n const createdBy = parseStringsParam(req.query.createdBy, 'createdBy');\n const status = parseStringsParam(req.query.status, 'status');\n\n const order = parseStringsParam(req.query.order, 'order')?.map(item => {\n const match = item.match(/^(asc|desc):(.+)$/);\n if (!match) {\n throw new InputError(\n `Invalid order parameter \"${item}\", expected \":\"`,\n );\n }\n\n return {\n order: match[1] as 'asc' | 'desc',\n field: match[2],\n };\n });\n\n const limit = parseNumberParam(req.query.limit, 'limit');\n const offset = parseNumberParam(req.query.offset, 'offset');\n\n const tasks = await taskBroker.list({\n filters: {\n createdBy,\n status: status ? (status as TaskStatus[]) : undefined,\n },\n order,\n pagination: {\n limit: limit ? limit[0] : undefined,\n offset: offset ? offset[0] : undefined,\n },\n });\n\n res.status(200).json(tasks);\n })\n .get('/v2/tasks/:taskId', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n const { taskId } = req.params;\n const task = await taskBroker.get(taskId);\n if (!task) {\n throw new NotFoundError(`Task with id ${taskId} does not exist`);\n }\n // Do not disclose secrets\n delete task.secrets;\n res.status(200).json(task);\n })\n .post('/v2/tasks/:taskId/cancel', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n // Requires both read and cancel permissions\n await checkPermission({\n credentials,\n permissions: [taskCancelPermission, taskReadPermission],\n permissionService: permissions,\n });\n\n const { taskId } = req.params;\n await taskBroker.cancel?.(taskId);\n res.status(200).json({ status: 'cancelled' });\n })\n .post('/v2/tasks/:taskId/retry', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n // Requires both read and cancel permissions\n await checkPermission({\n credentials,\n permissions: [taskCreatePermission, taskReadPermission],\n permissionService: permissions,\n });\n\n const { taskId } = req.params;\n await taskBroker.retry?.(taskId);\n res.status(201).json({ id: taskId });\n })\n .get('/v2/tasks/:taskId/eventstream', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n const { taskId } = req.params;\n const after =\n req.query.after !== undefined ? Number(req.query.after) : undefined;\n\n logger.debug(`Event stream observing taskId '${taskId}' opened`);\n\n // Mandatory headers and http status to keep connection open\n res.writeHead(200, {\n Connection: 'keep-alive',\n 'Cache-Control': 'no-cache',\n 'Content-Type': 'text/event-stream',\n });\n\n // After client opens connection send all events as string\n const subscription = taskBroker.event$({ taskId, after }).subscribe({\n error: error => {\n logger.error(\n `Received error from event stream when observing taskId '${taskId}', ${error}`,\n );\n res.end();\n },\n next: ({ events }) => {\n let shouldUnsubscribe = false;\n for (const event of events) {\n res.write(\n `event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`,\n );\n if (event.type === 'completion' && !event.isTaskRecoverable) {\n shouldUnsubscribe = true;\n }\n }\n // res.flush() is only available with the compression middleware\n res.flush?.();\n if (shouldUnsubscribe) {\n subscription.unsubscribe();\n res.end();\n }\n },\n });\n\n // When client closes connection we update the clients list\n // avoiding the disconnected one\n req.on('close', () => {\n subscription.unsubscribe();\n logger.debug(`Event stream observing taskId '${taskId}' closed`);\n });\n })\n .get('/v2/tasks/:taskId/events', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n const { taskId } = req.params;\n const after = Number(req.query.after) || undefined;\n\n // cancel the request after 30 seconds. this aligns with the recommendations of RFC 6202.\n const timeout = setTimeout(() => {\n res.json([]);\n }, 30_000);\n\n // Get all known events after an id (always includes the completion event) and return the first callback\n const subscription = taskBroker.event$({ taskId, after }).subscribe({\n error: error => {\n logger.error(\n `Received error from event stream when observing taskId '${taskId}', ${error}`,\n );\n },\n next: ({ events }) => {\n clearTimeout(timeout);\n subscription.unsubscribe();\n res.json(events);\n },\n });\n\n // When client closes connection we update the clients list\n // avoiding the disconnected one\n req.on('close', () => {\n subscription.unsubscribe();\n clearTimeout(timeout);\n });\n })\n .post('/v2/dry-run', async (req, res) => {\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskCreatePermission],\n permissionService: permissions,\n });\n\n const bodySchema = z.object({\n template: z.unknown(),\n values: z.record(z.unknown()),\n secrets: z.record(z.string()).optional(),\n directoryContents: z.array(\n z.object({ path: z.string(), base64Content: z.string() }),\n ),\n });\n const body = await bodySchema.parseAsync(req.body).catch(e => {\n throw new InputError(`Malformed request: ${e}`);\n });\n\n const template = body.template as TemplateEntityV1beta3;\n if (!(await templateEntityV1beta3Validator.check(template))) {\n throw new InputError('Input template is not a template');\n }\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const userEntityRef = auth.isPrincipal(credentials, 'user')\n ? credentials.principal.userEntityRef\n : undefined;\n\n const userEntity = userEntityRef\n ? await catalogClient.getEntityByRef(userEntityRef, { token })\n : undefined;\n\n for (const parameters of [template.spec.parameters ?? []].flat()) {\n const result = validate(body.values, parameters);\n if (!result.valid) {\n res.status(400).json({ errors: result.errors });\n return;\n }\n }\n\n const steps = template.spec.steps.map((step, index) => ({\n ...step,\n id: step.id ?? `step-${index + 1}`,\n name: step.name ?? step.action,\n }));\n\n const result = await dryRunner({\n spec: {\n apiVersion: template.apiVersion,\n steps,\n output: template.spec.output ?? {},\n parameters: body.values as JsonObject,\n user: {\n entity: userEntity as UserEntity,\n ref: userEntityRef,\n },\n },\n directoryContents: (body.directoryContents ?? []).map(file => ({\n path: file.path,\n content: Buffer.from(file.base64Content, 'base64'),\n })),\n secrets: {\n ...body.secrets,\n ...(token && { backstageToken: token }),\n },\n credentials,\n });\n\n res.status(200).json({\n ...result,\n steps,\n directoryContents: result.directoryContents.map(file => ({\n path: file.path,\n executable: file.executable,\n base64Content: file.content.toString('base64'),\n })),\n });\n })\n .post('/v2/autocomplete/:provider/:resource', async (req, res) => {\n const { token, context } = req.body;\n const { provider, resource } = req.params;\n\n if (!token) throw new InputError('Missing token query parameter');\n\n if (!autocompleteHandlers[provider]) {\n throw new InputError(`Unsupported provider: ${provider}`);\n }\n\n const { results } = await autocompleteHandlers[provider]({\n resource,\n token,\n context,\n });\n\n res.status(200).json({ results });\n });\n\n const app = express();\n app.set('logger', logger);\n app.use('/', router);\n\n async function authorizeTemplate(\n entityRef: CompoundEntityRef,\n token: string | undefined,\n credentials: BackstageCredentials,\n ) {\n const template = await findTemplate({\n catalogApi: catalogClient,\n entityRef,\n token,\n });\n\n if (!isSupportedTemplate(template)) {\n throw new InputError(\n `Unsupported apiVersion field in schema entity, ${\n (template as Entity).apiVersion\n }`,\n );\n }\n\n if (!permissions) {\n return template;\n }\n\n const [parameterDecision, stepDecision] =\n await permissions.authorizeConditional(\n [\n { permission: templateParameterReadPermission },\n { permission: templateStepReadPermission },\n ],\n { credentials },\n );\n\n // Authorize parameters\n if (Array.isArray(template.spec.parameters)) {\n template.spec.parameters = template.spec.parameters.filter(step =>\n isAuthorized(parameterDecision, step),\n );\n } else if (\n template.spec.parameters &&\n !isAuthorized(parameterDecision, template.spec.parameters)\n ) {\n template.spec.parameters = undefined;\n }\n\n // Authorize steps\n template.spec.steps = template.spec.steps.filter(step =>\n isAuthorized(stepDecision, step),\n );\n\n return template;\n }\n\n return app;\n}\n"],"names":["RESOURCE_TYPE_SCAFFOLDER_TEMPLATE","RESOURCE_TYPE_SCAFFOLDER_ACTION","parseEntityRef","stringifyError","config","readDurationFromConfig","Router","express","HostDiscovery","createLegacyAuthAdapters","getWorkingDirectory","ScmIntegrations","DatabaseTaskStore","StorageTaskBroker","Duration","TemplateActionRegistry","TaskWorker","createBuiltinActions","createDryRunner","scaffolderTemplateRules","scaffolderActionRules","createConditionAuthorizer","createPermissionIntegrationRouter","scaffolderTemplatePermissions","scaffolderActionPermissions","scaffolderTaskPermissions","checkPermission","taskCreatePermission","result","validate","getEntityBaseUrl","stringifyEntityRef","taskReadPermission","parseStringsParam","InputError","parseNumberParam","NotFoundError","taskCancelPermission","z","templateEntityV1beta3Validator","findTemplate","templateParameterReadPermission","templateStepReadPermission"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwHA,SAAS,8BACP,cAC+C,EAAA;AAC/C,EAAA,OAAO,eAAe,YAAiB,KAAAA,uCAAA,CAAA;AACzC,CAAA;AAcA,SAAS,4BACP,cAC6C,EAAA;AAC7C,EAAA,OAAO,eAAe,YAAiB,KAAAC,qCAAA,CAAA;AACzC,CAAA;AA2CA,SAAS,oBAAoB,MAA+B,EAAA;AAC1D,EAAA,OAAO,OAAO,UAAe,KAAA,iCAAA,CAAA;AAC/B,CAAA;AASA,SAAS,2BAA2B,OAAqC,EAAA;AACvE,EAAO,OAAA;AAAA,IACL,WAAa,EAAA,OAAO,EAAE,OAAA,EAA6C,KAAA;AACjE,MAAM,MAAA,MAAA,GAAS,QAAQ,OAAQ,CAAA,aAAA,CAAA;AAC/B,MAAM,MAAA,EAAE,QAAW,GAAA,OAAA,CAAA;AAEnB,MAAA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AA,CAAA;AACT;;;;"} -\ No newline at end of file -+{"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createLegacyAuthAdapters,\n HostDiscovery,\n} from '@backstage/backend-common';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n CompoundEntityRef,\n Entity,\n parseEntityRef,\n stringifyEntityRef,\n UserEntity,\n} from '@backstage/catalog-model';\nimport { Config, readDurationFromConfig } from '@backstage/config';\nimport { InputError, NotFoundError, stringifyError } from '@backstage/errors';\nimport { ScmIntegrations } from '@backstage/integration';\nimport { HumanDuration, JsonObject, JsonValue } from '@backstage/types';\nimport {\n TaskSpec,\n TemplateEntityStepV1beta3,\n TemplateEntityV1beta3,\n templateEntityV1beta3Validator,\n TemplateParametersV1beta3,\n} from '@backstage/plugin-scaffolder-common';\nimport {\n RESOURCE_TYPE_SCAFFOLDER_ACTION,\n RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n scaffolderActionPermissions,\n scaffolderTaskPermissions,\n scaffolderTemplatePermissions,\n taskCancelPermission,\n taskCreatePermission,\n taskReadPermission,\n templateParameterReadPermission,\n templateStepReadPermission,\n} from '@backstage/plugin-scaffolder-common/alpha';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport { validate } from 'jsonschema';\nimport { Logger } from 'winston';\nimport { z } from 'zod';\nimport {\n TaskBroker,\n TaskStatus,\n TemplateAction,\n TaskSecrets,\n TemplateFilter,\n TemplateGlobal,\n} from '@backstage/plugin-scaffolder-node';\nimport {\n createBuiltinActions,\n DatabaseTaskStore,\n TaskWorker,\n TemplateActionRegistry,\n} from '../scaffolder';\nimport { createDryRunner } from '../scaffolder/dryrun';\nimport { StorageTaskBroker } from '../scaffolder/tasks/StorageTaskBroker';\nimport {\n findTemplate,\n getEntityBaseUrl,\n getWorkingDirectory,\n parseNumberParam,\n parseStringsParam,\n} from './helpers';\nimport { PermissionRuleParams } from '@backstage/plugin-permission-common';\nimport {\n createConditionAuthorizer,\n createPermissionIntegrationRouter,\n PermissionRule,\n} from '@backstage/plugin-permission-node';\nimport { scaffolderActionRules, scaffolderTemplateRules } from './rules';\nimport { Duration } from 'luxon';\nimport {\n AuthService,\n BackstageCredentials,\n DatabaseService,\n DiscoveryService,\n HttpAuthService,\n LifecycleService,\n PermissionsService,\n SchedulerService,\n UrlReaderService,\n} from '@backstage/backend-plugin-api';\nimport {\n IdentityApi,\n IdentityApiGetIdentityRequest,\n} from '@backstage/plugin-auth-node';\nimport { InternalTaskSecrets } from '../scaffolder/tasks/types';\nimport { checkPermission } from '../util/checkPermissions';\nimport {\n AutocompleteHandler,\n WorkspaceProvider,\n} from '@backstage/plugin-scaffolder-node/alpha';\nimport { cloneDeep } from 'lodash';\n\nimport { DefaultAuditLogger } from '@janus-idp/backstage-plugin-audit-log-node';\n\n/**\n *\n * @public\n */\nexport type TemplatePermissionRuleInput<\n TParams extends PermissionRuleParams = PermissionRuleParams,\n> = PermissionRule<\n TemplateEntityStepV1beta3 | TemplateParametersV1beta3,\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n TParams\n>;\nfunction isTemplatePermissionRuleInput(\n permissionRule: TemplatePermissionRuleInput | ActionPermissionRuleInput,\n): permissionRule is TemplatePermissionRuleInput {\n return permissionRule.resourceType === RESOURCE_TYPE_SCAFFOLDER_TEMPLATE;\n}\n\n/**\n *\n * @public\n */\nexport type ActionPermissionRuleInput<\n TParams extends PermissionRuleParams = PermissionRuleParams,\n> = PermissionRule<\n TemplateEntityStepV1beta3 | TemplateParametersV1beta3,\n {},\n typeof RESOURCE_TYPE_SCAFFOLDER_ACTION,\n TParams\n>;\nfunction isActionPermissionRuleInput(\n permissionRule: TemplatePermissionRuleInput | ActionPermissionRuleInput,\n): permissionRule is ActionPermissionRuleInput {\n return permissionRule.resourceType === RESOURCE_TYPE_SCAFFOLDER_ACTION;\n}\n\n/**\n * RouterOptions\n *\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n logger: Logger;\n config: Config;\n reader: UrlReaderService;\n lifecycle?: LifecycleService;\n database: DatabaseService;\n catalogClient: CatalogApi;\n scheduler?: SchedulerService;\n actions?: TemplateAction[];\n /**\n * @deprecated taskWorkers is deprecated in favor of concurrentTasksLimit option with a single TaskWorker\n * @defaultValue 1\n */\n taskWorkers?: number;\n /**\n * Sets the number of concurrent tasks that can be run at any given time on the TaskWorker\n * @defaultValue 10\n */\n concurrentTasksLimit?: number;\n taskBroker?: TaskBroker;\n additionalTemplateFilters?: Record;\n additionalTemplateGlobals?: Record;\n additionalWorkspaceProviders?: Record;\n permissions?: PermissionsService;\n permissionRules?: Array<\n TemplatePermissionRuleInput | ActionPermissionRuleInput\n >;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\n identity?: IdentityApi;\n discovery?: DiscoveryService;\n\n autocompleteHandlers?: Record;\n}\n\nfunction isSupportedTemplate(entity: TemplateEntityV1beta3) {\n return entity.apiVersion === 'scaffolder.backstage.io/v1beta3';\n}\n\n/*\n * @deprecated This function remains as the DefaultIdentityClient behaves slightly differently to the pre-existing\n * scaffolder behaviour. Specifically if the token fails to parse, the DefaultIdentityClient will raise an error.\n * The scaffolder did not raise an error in this case. As such we chose to allow it to behave as it did previously\n * until someone explicitly passes an IdentityApi. When we have reasonable confidence that most backstage deployments\n * are using the IdentityApi, we can remove this function.\n */\nfunction buildDefaultIdentityClient(options: RouterOptions): IdentityApi {\n return {\n getIdentity: async ({ request }: IdentityApiGetIdentityRequest) => {\n const header = request.headers.authorization;\n const { logger } = options;\n\n if (!header) {\n return undefined;\n }\n\n try {\n const token = header.match(/^Bearer\\s(\\S+\\.\\S+\\.\\S+)$/i)?.[1];\n if (!token) {\n throw new TypeError('Expected Bearer with JWT');\n }\n\n const [_header, rawPayload, _signature] = token.split('.');\n const payload: JsonValue = JSON.parse(\n Buffer.from(rawPayload, 'base64').toString(),\n );\n\n if (\n typeof payload !== 'object' ||\n payload === null ||\n Array.isArray(payload)\n ) {\n throw new TypeError('Malformed JWT payload');\n }\n\n const sub = payload.sub;\n if (typeof sub !== 'string') {\n throw new TypeError('Expected string sub claim');\n }\n\n if (sub === 'backstage-server') {\n return undefined;\n }\n\n // Check that it's a valid ref, otherwise this will throw.\n parseEntityRef(sub);\n\n return {\n identity: {\n userEntityRef: sub,\n ownershipEntityRefs: [],\n type: 'user',\n },\n token,\n };\n } catch (e) {\n logger.error(`Invalid authorization header: ${stringifyError(e)}`);\n return undefined;\n }\n },\n };\n}\n\nconst readDuration = (\n config: Config,\n key: string,\n defaultValue: HumanDuration,\n) => {\n if (config.has(key)) {\n return readDurationFromConfig(config, { key });\n }\n return defaultValue;\n};\n\n/**\n * A method to create a router for the scaffolder backend plugin.\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise {\n const router = Router();\n // Be generous in upload size to support a wide range of templates in dry-run mode.\n router.use(express.json({ limit: '10MB' }));\n\n const {\n logger: parentLogger,\n config,\n reader,\n database,\n catalogClient,\n actions,\n taskWorkers,\n scheduler,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n additionalWorkspaceProviders,\n permissions,\n permissionRules,\n discovery = HostDiscovery.fromConfig(config),\n identity = buildDefaultIdentityClient(options),\n autocompleteHandlers = {},\n } = options;\n\n const { auth, httpAuth } = createLegacyAuthAdapters({\n ...options,\n identity,\n discovery,\n });\n\n const concurrentTasksLimit =\n options.concurrentTasksLimit ??\n options.config.getOptionalNumber('scaffolder.concurrentTasksLimit');\n\n const logger = parentLogger.child({ plugin: 'scaffolder' });\n const auditLogger = new DefaultAuditLogger({\n logger,\n authService: auth,\n httpAuthService: httpAuth,\n });\n\n const workingDirectory = await getWorkingDirectory(config, logger);\n const integrations = ScmIntegrations.fromConfig(config);\n\n let taskBroker: TaskBroker;\n if (!options.taskBroker) {\n const databaseTaskStore = await DatabaseTaskStore.create({ database });\n taskBroker = new StorageTaskBroker(\n databaseTaskStore,\n logger,\n auditLogger,\n config,\n auth,\n additionalWorkspaceProviders,\n );\n\n if (scheduler && databaseTaskStore.listStaleTasks) {\n await scheduler.scheduleTask({\n id: 'close_stale_tasks',\n frequency: readDuration(\n config,\n 'scaffolder.taskTimeoutJanitorFrequency',\n {\n minutes: 5,\n },\n ),\n timeout: { minutes: 15 },\n fn: async () => {\n const { tasks } = await databaseTaskStore.listStaleTasks({\n timeoutS: Duration.fromObject(\n readDuration(config, 'scaffolder.taskTimeout', {\n hours: 24,\n }),\n ).as('seconds'),\n });\n\n for (const task of tasks) {\n await databaseTaskStore.shutdownTask(task);\n logger.info(`Successfully closed stale task ${task.taskId}`);\n }\n },\n });\n }\n } else {\n taskBroker = options.taskBroker;\n }\n\n const actionRegistry = new TemplateActionRegistry();\n\n const workers: TaskWorker[] = [];\n if (concurrentTasksLimit !== 0) {\n for (let i = 0; i < (taskWorkers || 1); i++) {\n const worker = await TaskWorker.create({\n taskBroker,\n actionRegistry,\n integrations,\n logger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n concurrentTasksLimit,\n permissions,\n auditLogger,\n });\n workers.push(worker);\n }\n }\n\n const actionsToRegister = Array.isArray(actions)\n ? actions\n : createBuiltinActions({\n integrations,\n catalogClient,\n reader,\n config,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n auth,\n });\n\n actionsToRegister.forEach(action => actionRegistry.register(action));\n\n const launchWorkers = () => workers.forEach(worker => worker.start());\n\n const shutdownWorkers = () => {\n workers.forEach(worker => worker.stop());\n };\n\n if (options.lifecycle) {\n options.lifecycle.addStartupHook(launchWorkers);\n options.lifecycle.addShutdownHook(shutdownWorkers);\n } else {\n launchWorkers();\n }\n\n const dryRunner = createDryRunner({\n actionRegistry,\n integrations,\n logger,\n auditLogger,\n workingDirectory,\n additionalTemplateFilters,\n additionalTemplateGlobals,\n permissions,\n });\n\n const templateRules: TemplatePermissionRuleInput[] = Object.values(\n scaffolderTemplateRules,\n );\n const actionRules: ActionPermissionRuleInput[] = Object.values(\n scaffolderActionRules,\n );\n\n if (permissionRules) {\n templateRules.push(\n ...permissionRules.filter(isTemplatePermissionRuleInput),\n );\n actionRules.push(...permissionRules.filter(isActionPermissionRuleInput));\n }\n\n const isAuthorized = createConditionAuthorizer(Object.values(templateRules));\n\n const permissionIntegrationRouter = createPermissionIntegrationRouter({\n resources: [\n {\n resourceType: RESOURCE_TYPE_SCAFFOLDER_TEMPLATE,\n permissions: scaffolderTemplatePermissions,\n rules: templateRules,\n },\n {\n resourceType: RESOURCE_TYPE_SCAFFOLDER_ACTION,\n permissions: scaffolderActionPermissions,\n rules: actionRules,\n },\n ],\n permissions: scaffolderTaskPermissions,\n });\n\n router.use(permissionIntegrationRouter);\n\n router\n .get(\n '/v2/templates/:namespace/:kind/:name/parameter-schema',\n async (req, res) => {\n const requestedTemplateRef = `${req.params.kind}:${req.params.namespace}/${req.params.name}`;\n const actorId = await auditLogger.getActorId(req);\n try {\n const credentials = await httpAuth.credentials(req);\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n await auditLogger.auditLog({\n eventName: 'ScaffolderParameterSchemaFetch',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n templateRef: requestedTemplateRef,\n },\n request: req,\n message: `${actorId} requested the parameter schema for ${requestedTemplateRef}`,\n });\n const template = await authorizeTemplate(\n req.params,\n token,\n credentials,\n );\n\n const parameters = [template.spec.parameters ?? []].flat();\n\n const presentation = template.spec.presentation;\n const templateRef = `${template.kind}:${\n template.metadata.namespace || 'default'\n }/${template.metadata.name}`;\n\n const responseBody = {\n title: template.metadata.title ?? template.metadata.name,\n ...(presentation ? { presentation } : {}),\n description: template.metadata.description,\n 'ui:options': template.metadata['ui:options'],\n steps: parameters.map(schema => ({\n title: schema.title ?? 'Please enter the following information',\n description: schema.description,\n schema,\n })),\n };\n await auditLogger.auditLog({\n eventName: 'ScaffolderParameterSchemaFetch',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n templateRef: templateRef,\n },\n request: req,\n response: {\n status: 200,\n body: responseBody,\n },\n message: `${actorId} successfully requested the parameter schema for ${templateRef}`,\n });\n\n res.json(responseBody);\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderParameterSchemaFetch',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n metadata: {\n templateRef: requestedTemplateRef,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `${actorId} failed to request the parameter schema for ${requestedTemplateRef}`,\n });\n throw err;\n }\n },\n )\n .get('/v2/actions', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'ScaffolderInstalledActionsFetch',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n request: req,\n message: `${actorId} requested the list of installed actions`,\n });\n const actionsList = actionRegistry.list().map(action => {\n return {\n id: action.id,\n description: action.description,\n examples: action.examples,\n schema: action.schema,\n };\n });\n await auditLogger.auditLog({\n eventName: 'ScaffolderInstalledActionsFetch',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n request: req,\n response: {\n status: 200,\n body: actionsList,\n },\n message: `${actorId} successfully requested the list of installed actions`,\n });\n res.json(actionsList);\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderInstalledActionsFetch',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `${actorId} failed to request for the list of installed actions`,\n });\n throw err;\n }\n })\n .post('/v2/tasks', async (req, res) => {\n const templateRef: string = req.body.templateRef;\n const { kind, namespace, name } = parseEntityRef(templateRef, {\n defaultKind: 'template',\n });\n const credentials = await httpAuth.credentials(req);\n\n await checkPermission({\n credentials,\n permissions: [taskCreatePermission],\n permissionService: permissions,\n });\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n const userEntityRef = auth.isPrincipal(credentials, 'user')\n ? credentials.principal.userEntityRef\n : undefined;\n\n const userEntity = userEntityRef\n ? await catalogClient.getEntityByRef(userEntityRef, { token })\n : undefined;\n const values = req.body.values;\n const redactedRequest = cloneDeep(req);\n\n // Workaround ensure that redactedRequest.ip accesses the original req.ip with the correct context, preventing 'Illegal invocation' errors\n Object.defineProperty(redactedRequest, 'ip', {\n get: () => {\n return req.ip;\n },\n });\n if (req.body.secrets) {\n const redactedBody = {\n ...req.body,\n secrets: Object.keys(req.body.secrets).reduce((acc, key) => {\n return {\n ...acc,\n [key]: '***',\n };\n }, {} as TaskSecrets),\n };\n redactedRequest.body = redactedBody;\n }\n try {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskCreation',\n stage: 'initiation',\n status: 'succeeded',\n actorId: userEntityRef,\n request: redactedRequest,\n metadata: {\n templateRef: templateRef,\n },\n\n message: `Scaffolding task for ${templateRef} creation attempt by ${userEntityRef} initiated`,\n });\n await checkPermission({\n credentials,\n permissions: [taskCreatePermission],\n permissionService: permissions,\n });\n const template = await authorizeTemplate(\n { kind, namespace, name },\n token,\n credentials,\n );\n for (const parameters of [template.spec.parameters ?? []].flat()) {\n const result = validate(values, parameters);\n if (!result.valid) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskCreation',\n stage: 'completion',\n status: 'failed',\n level: 'error',\n actorId: userEntityRef,\n request: redactedRequest,\n metadata: {\n templateRef: templateRef,\n },\n response: {\n status: 400,\n body: { errors: result.errors },\n },\n errors: result.errors,\n message: `Scaffolding task for ${templateRef} creation attempt by ${userEntityRef} failed`,\n });\n return res.status(400).json({ errors: result.errors });\n }\n }\n\n const baseUrl = getEntityBaseUrl(template);\n\n const taskSpec: TaskSpec = {\n apiVersion: template.apiVersion,\n steps: template.spec.steps.map((step, index) => ({\n ...step,\n id: step.id ?? `step-${index + 1}`,\n name: step.name ?? step.action,\n })),\n EXPERIMENTAL_recovery: template.spec.EXPERIMENTAL_recovery,\n output: template.spec.output ?? {},\n parameters: values,\n user: {\n entity: userEntity as UserEntity,\n ref: userEntityRef,\n },\n templateInfo: {\n entityRef: stringifyEntityRef({ kind, name, namespace }),\n baseUrl,\n entity: {\n metadata: template.metadata,\n },\n },\n };\n\n const secrets: InternalTaskSecrets = {\n ...req.body.secrets,\n backstageToken: token,\n __initiatorCredentials: JSON.stringify({\n ...credentials,\n // credentials.token is nonenumerable and will not be serialized, so we need to add it explicitly\n token: (credentials as any).token,\n }),\n };\n\n const result = await taskBroker.dispatch({\n spec: taskSpec,\n createdBy: userEntityRef,\n secrets,\n });\n\n let auditLog = `Scaffolding task for ${templateRef}`;\n if (userEntityRef) {\n auditLog += ` created by ${userEntityRef}`;\n }\n\n logger.info(auditLog);\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskCreation',\n stage: 'completion',\n status: 'succeeded',\n actorId: userEntityRef,\n request: redactedRequest,\n metadata: {\n taskId: result.taskId,\n templateRef: templateRef,\n },\n response: {\n status: 201,\n body: { id: result.taskId },\n },\n message: `Scaffolding task for ${templateRef} with taskId: ${result.taskId} successfully created by ${userEntityRef}`,\n });\n return res.status(201).json({ id: result.taskId });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskCreation',\n stage: 'completion',\n status: 'failed',\n level: 'error',\n actorId: userEntityRef,\n request: redactedRequest,\n metadata: {\n templateRef: templateRef,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Scaffolding task for ${templateRef} creation attempt by ${userEntityRef} failed`,\n });\n throw err;\n }\n })\n .get('/v2/tasks', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n\n try {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskListFetch',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n request: req,\n message: `${actorId} requested for the list of scaffolder tasks`,\n });\n const credentials = await httpAuth.credentials(req);\n\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n if (!taskBroker.list) {\n throw new Error(\n 'TaskBroker does not support listing tasks, please implement the list method on the TaskBroker.',\n );\n }\n\n const createdBy = parseStringsParam(req.query.createdBy, 'createdBy');\n const status = parseStringsParam(req.query.status, 'status');\n\n const order = parseStringsParam(req.query.order, 'order')?.map(item => {\n const match = item.match(/^(asc|desc):(.+)$/);\n if (!match) {\n throw new InputError(\n `Invalid order parameter \"${item}\", expected \":\"`,\n );\n }\n\n return {\n order: match[1] as 'asc' | 'desc',\n field: match[2],\n };\n });\n\n const limit = parseNumberParam(req.query.limit, 'limit');\n const offset = parseNumberParam(req.query.offset, 'offset');\n\n const tasks = await taskBroker.list({\n filters: {\n createdBy,\n status: status ? (status as TaskStatus[]) : undefined,\n },\n order,\n pagination: {\n limit: limit ? limit[0] : undefined,\n offset: offset ? offset[0] : undefined,\n },\n });\n\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskListFetch',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n request: req,\n response: {\n status: 200,\n body: tasks,\n },\n message: `${actorId} successfully requested for the list of scaffolder tasks`,\n });\n res.status(200).json(tasks);\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskListFetch',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `${actorId} request for the list of scaffolder tasks failed`,\n });\n throw err;\n }\n })\n .get('/v2/tasks/:taskId', async (req, res) => {\n const { taskId } = req.params;\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskFetch',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n taskId: taskId,\n },\n request: req,\n message: `${actorId} requested for scaffolder task ${taskId}`,\n });\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n const task = await taskBroker.get(taskId);\n if (!task) {\n throw new NotFoundError(`Task with id ${taskId} does not exist`);\n }\n // Do not disclose secrets\n delete task.secrets;\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskFetch',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n request: req,\n response: {\n status: 200,\n body: task,\n },\n message: `${actorId} successfully requested for scaffolder tasks ${taskId}`,\n });\n res.status(200).json(task);\n } catch (err) {\n let status = 500;\n if (err.name === 'NotFoundError') {\n status = 404;\n }\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskFetch',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n response: {\n status: status,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `${actorId} request for scaffolder tasks ${taskId} failed`,\n });\n throw err;\n }\n })\n .post('/v2/tasks/:taskId/cancel', async (req, res) => {\n const { taskId } = req.params;\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskCancellation',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n message: `Cancellation request for Scaffolding task with taskId: ${taskId} from ${actorId} received`,\n });\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskCancelPermission],\n permissionService: permissions,\n });\n await taskBroker.cancel?.(taskId);\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskCancellation',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n response: {\n status: 200,\n body: { status: 'cancelled' },\n },\n message: `Scaffolding task with taskId: ${taskId} successfully cancelled by ${actorId}`,\n });\n res.status(200).json({ status: 'cancelled' });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskCancellation',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `${actorId}'s cancel request for task ${taskId} failed`,\n });\n throw err;\n }\n })\n .post('/v2/tasks/:taskId/retry', async (req, res) => {\n const { taskId } = req.params;\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskRetry',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n message: `Retry request for Scaffolding task with taskId: ${taskId} from ${actorId} received`,\n });\n const credentials = await httpAuth.credentials(req);\n // Requires both read and cancel permissions\n await checkPermission({\n credentials,\n permissions: [taskCreatePermission, taskReadPermission],\n permissionService: permissions,\n });\n await taskBroker.retry?.(taskId);\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskRetry',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n response: {\n status: 201,\n body: { id: taskId },\n },\n message: `Scaffolding task with taskId: ${taskId} successfully retried by ${actorId}`,\n });\n res.status(201).json({ id: taskId });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskRetry',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `${actorId}'s retry request for task ${taskId} failed`,\n });\n throw err;\n }\n })\n .get('/v2/tasks/:taskId/eventstream', async (req, res) => {\n const { taskId } = req.params;\n const actorId = await auditLogger.getActorId(req);\n try {\n const after =\n req.query.after !== undefined ? Number(req.query.after) : undefined;\n\n logger.debug(`Event stream observing taskId '${taskId}' opened`);\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskStream',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n message: `Event stream for scaffolding task with taskId: ${taskId} was opened by ${actorId}`,\n });\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n // Mandatory headers and http status to keep connection open\n res.writeHead(200, {\n Connection: 'keep-alive',\n 'Cache-Control': 'no-cache',\n 'Content-Type': 'text/event-stream',\n });\n\n // After client opens connection send all events as string\n const subscription = taskBroker.event$({ taskId, after }).subscribe({\n error: async error => {\n logger.error(\n `Received error from event stream when observing taskId '${taskId}', ${error}`,\n );\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskStream',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n metadata: {\n taskId,\n },\n request: req,\n errors: [\n {\n name: error.name,\n message: error.message,\n stack: error.stack,\n cause: error.cause,\n },\n ],\n message: `Received error from event stream observing scaffolding task with taskId: ${taskId} requested by ${actorId}`,\n });\n res.end();\n },\n next: ({ events }) => {\n let shouldUnsubscribe = false;\n for (const event of events) {\n res.write(\n `event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`,\n );\n if (event.type === 'completion') {\n shouldUnsubscribe = true;\n }\n }\n // res.flush() is only available with the compression middleware\n res.flush?.();\n if (shouldUnsubscribe) {\n subscription.unsubscribe();\n res.end();\n }\n },\n });\n\n // When client closes connection we update the clients list\n // avoiding the disconnected one\n req.on('close', async () => {\n subscription.unsubscribe();\n logger.debug(`Event stream observing taskId '${taskId}' closed`);\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskStream',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n message: `Event stream observing scaffolding task with taskId: ${taskId} was closed by ${actorId}`,\n });\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskStream',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n metadata: {\n taskId,\n },\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Received error from event stream observing scaffolding task with taskId: ${taskId} requested by ${actorId}`,\n });\n throw err;\n }\n })\n .get('/v2/tasks/:taskId/events', async (req, res) => {\n const { taskId } = req.params;\n const actorId = await auditLogger.getActorId(req);\n try {\n const after = Number(req.query.after) || undefined;\n\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskEventFetch',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} initiated by ${actorId}`,\n });\n const credentials = await httpAuth.credentials(req);\n await checkPermission({\n credentials,\n permissions: [taskReadPermission],\n permissionService: permissions,\n });\n\n // cancel the request after 30 seconds. this aligns with the recommendations of RFC 6202.\n const timeout = setTimeout(() => {\n res.json([]);\n }, 30_000);\n\n // Get all known events after an id (always includes the completion event) and return the first callback\n const subscription = taskBroker.event$({ taskId, after }).subscribe({\n error: async error => {\n logger.error(\n `Received error from event stream when observing taskId '${taskId}', ${error}`,\n );\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskEventFetch',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n metadata: {\n taskId,\n },\n request: req,\n errors: [\n {\n name: error.name,\n message: error.message,\n stack: error.stack,\n },\n ],\n message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} requested by ${actorId} failed`,\n });\n },\n next: async ({ events }) => {\n clearTimeout(timeout);\n subscription.unsubscribe();\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskEventFetch',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n taskId,\n },\n request: req,\n response: {\n status: 200,\n body: events,\n },\n message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} by ${actorId} succeeded`,\n });\n res.json(events);\n },\n });\n\n // When client closes connection we update the clients list\n // avoiding the disconnected one\n req.on('close', () => {\n subscription.unsubscribe();\n clearTimeout(timeout);\n });\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskEventFetch',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n metadata: {\n taskId,\n },\n request: req,\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Task events fetch attempt for scaffolding task with taskId: ${taskId} requested by ${actorId} failed`,\n });\n throw err;\n }\n })\n .post('/v2/dry-run', async (req, res) => {\n const actorId = await auditLogger.getActorId(req);\n try {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskDryRun',\n actorId,\n stage: 'initiation',\n status: 'succeeded',\n metadata: {\n isDryRun: true,\n },\n request: req,\n message: `Dry Run scaffolder task initiated by ${actorId}`,\n });\n const credentials = await httpAuth.credentials(req);\n\n await checkPermission({\n credentials,\n permissions: [taskCreatePermission],\n permissionService: permissions,\n });\n const bodySchema = z.object({\n template: z.unknown(),\n values: z.record(z.unknown()),\n secrets: z.record(z.string()).optional(),\n directoryContents: z.array(\n z.object({ path: z.string(), base64Content: z.string() }),\n ),\n });\n const body = await bodySchema.parseAsync(req.body).catch(e => {\n throw new InputError(`Malformed request: ${e}`);\n });\n\n const template = body.template as TemplateEntityV1beta3;\n if (!(await templateEntityV1beta3Validator.check(template))) {\n throw new InputError('Input template is not a template');\n }\n const templateRef: string = `${template.kind}:${\n template.metadata.namespace || 'default'\n }/${template.metadata.name}`;\n\n const { token } = await auth.getPluginRequestToken({\n onBehalfOf: credentials,\n targetPluginId: 'catalog',\n });\n\n const userEntityRef = auth.isPrincipal(credentials, 'user')\n ? credentials.principal.userEntityRef\n : undefined;\n const userEntity = userEntityRef\n ? await catalogClient.getEntityByRef(userEntityRef, { token })\n : undefined;\n for (const parameters of [template.spec.parameters ?? []].flat()) {\n const result = validate(body.values, parameters);\n if (!result.valid) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskDryRun',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n metadata: {\n templateRef: templateRef,\n parameters: template.spec.parameters,\n isDryRun: true,\n },\n errors: result.errors,\n request: req,\n response: {\n status: 400,\n body: { errors: result.errors },\n },\n message: `Dry Run scaffolder task for ${templateRef} initiated by ${actorId} failed`,\n });\n return res.status(400).json({ errors: result.errors });\n }\n }\n\n const steps = template.spec.steps.map((step, index) => ({\n ...step,\n id: step.id ?? `step-${index + 1}`,\n name: step.name ?? step.action,\n }));\n\n const result = await dryRunner({\n spec: {\n apiVersion: template.apiVersion,\n steps,\n output: template.spec.output ?? {},\n parameters: body.values as JsonObject,\n user: {\n entity: userEntity as UserEntity,\n ref: userEntityRef,\n },\n },\n directoryContents: (body.directoryContents ?? []).map(file => ({\n path: file.path,\n content: Buffer.from(file.base64Content, 'base64'),\n })),\n secrets: {\n ...body.secrets,\n ...(token && { backstageToken: token }),\n },\n credentials,\n });\n\n const dryRunResults = {\n ...result,\n steps,\n directoryContents: result.directoryContents.map(file => ({\n path: file.path,\n executable: file.executable,\n base64Content: file.content.toString('base64'),\n })),\n };\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskDryRun',\n actorId,\n stage: 'completion',\n status: 'succeeded',\n metadata: {\n templateRef: templateRef,\n parameters: template.spec.parameters,\n isDryRun: true,\n },\n request: req,\n response: {\n status: 200,\n body: dryRunResults,\n },\n message: `Dry Run scaffolder task for ${templateRef} initiated by ${actorId} completed successfully`,\n });\n return res.status(200).json(dryRunResults);\n } catch (err) {\n await auditLogger.auditLog({\n eventName: 'ScaffolderTaskDryRun',\n actorId,\n stage: 'completion',\n status: 'failed',\n level: 'error',\n request: req,\n metadata: {\n isDryRun: true,\n },\n errors: [\n {\n name: err.name,\n message: err.message,\n stack: err.stack,\n },\n ],\n message: `Scaffolder Task Dry Run requested by ${actorId} failed`,\n });\n throw err;\n }\n })\n .post('/v2/autocomplete/:provider/:resource', async (req, res) => {\n const { token, context } = req.body;\n const { provider, resource } = req.params;\n\n if (!token) throw new InputError('Missing token query parameter');\n\n if (!autocompleteHandlers[provider]) {\n throw new InputError(`Unsupported provider: ${provider}`);\n }\n\n const { results } = await autocompleteHandlers[provider]({\n resource,\n token,\n context,\n });\n\n res.status(200).json({ results });\n });\n\n const app = express();\n app.set('logger', logger);\n app.use('/', router);\n\n async function authorizeTemplate(\n entityRef: CompoundEntityRef,\n token: string | undefined,\n credentials: BackstageCredentials,\n ) {\n const template = await findTemplate({\n catalogApi: catalogClient,\n entityRef,\n token,\n });\n\n if (!isSupportedTemplate(template)) {\n throw new InputError(\n `Unsupported apiVersion field in schema entity, ${\n (template as Entity).apiVersion\n }`,\n );\n }\n\n if (!permissions) {\n return template;\n }\n\n const [parameterDecision, stepDecision] =\n await permissions.authorizeConditional(\n [\n { permission: templateParameterReadPermission },\n { permission: templateStepReadPermission },\n ],\n { credentials },\n );\n\n // Authorize parameters\n if (Array.isArray(template.spec.parameters)) {\n template.spec.parameters = template.spec.parameters.filter(step =>\n isAuthorized(parameterDecision, step),\n );\n } else if (\n template.spec.parameters &&\n !isAuthorized(parameterDecision, template.spec.parameters)\n ) {\n template.spec.parameters = undefined;\n }\n\n // Authorize steps\n template.spec.steps = template.spec.steps.filter(step =>\n isAuthorized(stepDecision, step),\n );\n\n return template;\n }\n\n return app;\n}\n"],"names":["RESOURCE_TYPE_SCAFFOLDER_TEMPLATE","RESOURCE_TYPE_SCAFFOLDER_ACTION","parseEntityRef","stringifyError","config","readDurationFromConfig","Router","express","HostDiscovery","createLegacyAuthAdapters","DefaultAuditLogger","getWorkingDirectory","ScmIntegrations","DatabaseTaskStore","StorageTaskBroker","Duration","TemplateActionRegistry","TaskWorker","createBuiltinActions","createDryRunner","scaffolderTemplateRules","scaffolderActionRules","createConditionAuthorizer","createPermissionIntegrationRouter","scaffolderTemplatePermissions","scaffolderActionPermissions","scaffolderTaskPermissions","checkPermission","taskCreatePermission","cloneDeep","result","validate","getEntityBaseUrl","stringifyEntityRef","taskReadPermission","parseStringsParam","InputError","parseNumberParam","NotFoundError","taskCancelPermission","z","templ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diff --git a/.yarn/patches/@backstage-plugin-scaffolder-node-npm-0.5.0-ed9dfe74cb.patch b/.yarn/patches/@backstage-plugin-scaffolder-node-npm-0.5.0-ed9dfe74cb.patch deleted file mode 100644 index 20242852..00000000 --- a/.yarn/patches/@backstage-plugin-scaffolder-node-npm-0.5.0-ed9dfe74cb.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/dist/index.d.ts b/dist/index.d.ts -index b88643b24b813cf5d9f1cfd17b182618c0937f8b..2407a197e182d7714607132ff2f306cb4a0ad16a 100644 ---- a/dist/index.d.ts -+++ b/dist/index.d.ts -@@ -89,6 +89,7 @@ type TaskBrokerDispatchOptions = { - * @public - */ - interface TaskContext { -+ taskId: string; - cancelSignal: AbortSignal; - spec: TaskSpec; - secrets?: TaskSecrets; diff --git a/.yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs b/.yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs deleted file mode 100644 index 4e89c7c3..00000000 --- a/.yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs +++ /dev/null @@ -1,28 +0,0 @@ -/* eslint-disable */ -//prettier-ignore -module.exports = { -name: "@yarnpkg/plugin-workspace-tools", -factory: function (require) { -var plugin=(()=>{var yr=Object.create;var we=Object.defineProperty;var _r=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var br=Object.getPrototypeOf,xr=Object.prototype.hasOwnProperty;var W=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var q=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),Cr=(e,r)=>{for(var t in r)we(e,t,{get:r[t],enumerable:!0})},Je=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s of Er(r))!xr.call(e,s)&&s!==t&&we(e,s,{get:()=>r[s],enumerable:!(n=_r(r,s))||n.enumerable});return e};var Be=(e,r,t)=>(t=e!=null?yr(br(e)):{},Je(r||!e||!e.__esModule?we(t,"default",{value:e,enumerable:!0}):t,e)),wr=e=>Je(we({},"__esModule",{value:!0}),e);var ve=q(ee=>{"use strict";ee.isInteger=e=>typeof e=="number"?Number.isInteger(e):typeof e=="string"&&e.trim()!==""?Number.isInteger(Number(e)):!1;ee.find=(e,r)=>e.nodes.find(t=>t.type===r);ee.exceedsLimit=(e,r,t=1,n)=>n===!1||!ee.isInteger(e)||!ee.isInteger(r)?!1:(Number(r)-Number(e))/Number(t)>=n;ee.escapeNode=(e,r=0,t)=>{let n=e.nodes[r];!n||(t&&n.type===t||n.type==="open"||n.type==="close")&&n.escaped!==!0&&(n.value="\\"+n.value,n.escaped=!0)};ee.encloseBrace=e=>e.type!=="brace"?!1:e.commas>>0+e.ranges>>0===0?(e.invalid=!0,!0):!1;ee.isInvalidBrace=e=>e.type!=="brace"?!1:e.invalid===!0||e.dollar?!0:e.commas>>0+e.ranges>>0===0||e.open!==!0||e.close!==!0?(e.invalid=!0,!0):!1;ee.isOpenOrClose=e=>e.type==="open"||e.type==="close"?!0:e.open===!0||e.close===!0;ee.reduce=e=>e.reduce((r,t)=>(t.type==="text"&&r.push(t.value),t.type==="range"&&(t.type="text"),r),[]);ee.flatten=(...e)=>{let r=[],t=n=>{for(let s=0;s{"use strict";var tt=ve();rt.exports=(e,r={})=>{let t=(n,s={})=>{let i=r.escapeInvalid&&tt.isInvalidBrace(s),a=n.invalid===!0&&r.escapeInvalid===!0,c="";if(n.value)return(i||a)&&tt.isOpenOrClose(n)?"\\"+n.value:n.value;if(n.value)return n.value;if(n.nodes)for(let p of n.nodes)c+=t(p);return c};return t(e)}});var st=q((Vn,nt)=>{"use strict";nt.exports=function(e){return typeof e=="number"?e-e===0:typeof e=="string"&&e.trim()!==""?Number.isFinite?Number.isFinite(+e):isFinite(+e):!1}});var ht=q((Jn,pt)=>{"use strict";var at=st(),le=(e,r,t)=>{if(at(e)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(r===void 0||e===r)return String(e);if(at(r)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let n={relaxZeros:!0,...t};typeof n.strictZeros=="boolean"&&(n.relaxZeros=n.strictZeros===!1);let s=String(n.relaxZeros),i=String(n.shorthand),a=String(n.capture),c=String(n.wrap),p=e+":"+r+"="+s+i+a+c;if(le.cache.hasOwnProperty(p))return le.cache[p].result;let m=Math.min(e,r),h=Math.max(e,r);if(Math.abs(m-h)===1){let y=e+"|"+r;return n.capture?`(${y})`:n.wrap===!1?y:`(?:${y})`}let R=ft(e)||ft(r),f={min:e,max:r,a:m,b:h},$=[],_=[];if(R&&(f.isPadded=R,f.maxLen=String(f.max).length),m<0){let y=h<0?Math.abs(h):1;_=it(y,Math.abs(m),f,n),m=f.a=0}return h>=0&&($=it(m,h,f,n)),f.negatives=_,f.positives=$,f.result=Sr(_,$,n),n.capture===!0?f.result=`(${f.result})`:n.wrap!==!1&&$.length+_.length>1&&(f.result=`(?:${f.result})`),le.cache[p]=f,f.result};function Sr(e,r,t){let n=Pe(e,r,"-",!1,t)||[],s=Pe(r,e,"",!1,t)||[],i=Pe(e,r,"-?",!0,t)||[];return n.concat(i).concat(s).join("|")}function vr(e,r){let t=1,n=1,s=ut(e,t),i=new Set([r]);for(;e<=s&&s<=r;)i.add(s),t+=1,s=ut(e,t);for(s=ct(r+1,n)-1;e1&&c.count.pop(),c.count.push(h.count[0]),c.string=c.pattern+lt(c.count),a=m+1;continue}t.isPadded&&(R=Lr(m,t,n)),h.string=R+h.pattern+lt(h.count),i.push(h),a=m+1,c=h}return i}function Pe(e,r,t,n,s){let i=[];for(let a of e){let{string:c}=a;!n&&!ot(r,"string",c)&&i.push(t+c),n&&ot(r,"string",c)&&i.push(t+c)}return i}function $r(e,r){let t=[];for(let n=0;nr?1:r>e?-1:0}function ot(e,r,t){return e.some(n=>n[r]===t)}function ut(e,r){return Number(String(e).slice(0,-r)+"9".repeat(r))}function ct(e,r){return e-e%Math.pow(10,r)}function lt(e){let[r=0,t=""]=e;return t||r>1?`{${r+(t?","+t:"")}}`:""}function kr(e,r,t){return`[${e}${r-e===1?"":"-"}${r}]`}function ft(e){return/^-?(0+)\d/.test(e)}function Lr(e,r,t){if(!r.isPadded)return e;let n=Math.abs(r.maxLen-String(e).length),s=t.relaxZeros!==!1;switch(n){case 0:return"";case 1:return s?"0?":"0";case 2:return s?"0{0,2}":"00";default:return s?`0{0,${n}}`:`0{${n}}`}}le.cache={};le.clearCache=()=>le.cache={};pt.exports=le});var Ue=q((es,Et)=>{"use strict";var Or=W("util"),At=ht(),dt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Nr=e=>r=>e===!0?Number(r):String(r),Me=e=>typeof e=="number"||typeof e=="string"&&e!=="",Ae=e=>Number.isInteger(+e),De=e=>{let r=`${e}`,t=-1;if(r[0]==="-"&&(r=r.slice(1)),r==="0")return!1;for(;r[++t]==="0";);return t>0},Ir=(e,r,t)=>typeof e=="string"||typeof r=="string"?!0:t.stringify===!0,Br=(e,r,t)=>{if(r>0){let n=e[0]==="-"?"-":"";n&&(e=e.slice(1)),e=n+e.padStart(n?r-1:r,"0")}return t===!1?String(e):e},gt=(e,r)=>{let t=e[0]==="-"?"-":"";for(t&&(e=e.slice(1),r--);e.length{e.negatives.sort((a,c)=>ac?1:0),e.positives.sort((a,c)=>ac?1:0);let t=r.capture?"":"?:",n="",s="",i;return e.positives.length&&(n=e.positives.join("|")),e.negatives.length&&(s=`-(${t}${e.negatives.join("|")})`),n&&s?i=`${n}|${s}`:i=n||s,r.wrap?`(${t}${i})`:i},mt=(e,r,t,n)=>{if(t)return At(e,r,{wrap:!1,...n});let s=String.fromCharCode(e);if(e===r)return s;let i=String.fromCharCode(r);return`[${s}-${i}]`},Rt=(e,r,t)=>{if(Array.isArray(e)){let n=t.wrap===!0,s=t.capture?"":"?:";return n?`(${s}${e.join("|")})`:e.join("|")}return At(e,r,t)},yt=(...e)=>new RangeError("Invalid range arguments: "+Or.inspect(...e)),_t=(e,r,t)=>{if(t.strictRanges===!0)throw yt([e,r]);return[]},Mr=(e,r)=>{if(r.strictRanges===!0)throw new TypeError(`Expected step "${e}" to be a number`);return[]},Dr=(e,r,t=1,n={})=>{let s=Number(e),i=Number(r);if(!Number.isInteger(s)||!Number.isInteger(i)){if(n.strictRanges===!0)throw yt([e,r]);return[]}s===0&&(s=0),i===0&&(i=0);let a=s>i,c=String(e),p=String(r),m=String(t);t=Math.max(Math.abs(t),1);let h=De(c)||De(p)||De(m),R=h?Math.max(c.length,p.length,m.length):0,f=h===!1&&Ir(e,r,n)===!1,$=n.transform||Nr(f);if(n.toRegex&&t===1)return mt(gt(e,R),gt(r,R),!0,n);let _={negatives:[],positives:[]},y=T=>_[T<0?"negatives":"positives"].push(Math.abs(T)),E=[],S=0;for(;a?s>=i:s<=i;)n.toRegex===!0&&t>1?y(s):E.push(Br($(s,S),R,f)),s=a?s-t:s+t,S++;return n.toRegex===!0?t>1?Pr(_,n):Rt(E,null,{wrap:!1,...n}):E},Ur=(e,r,t=1,n={})=>{if(!Ae(e)&&e.length>1||!Ae(r)&&r.length>1)return _t(e,r,n);let s=n.transform||(f=>String.fromCharCode(f)),i=`${e}`.charCodeAt(0),a=`${r}`.charCodeAt(0),c=i>a,p=Math.min(i,a),m=Math.max(i,a);if(n.toRegex&&t===1)return mt(p,m,!1,n);let h=[],R=0;for(;c?i>=a:i<=a;)h.push(s(i,R)),i=c?i-t:i+t,R++;return n.toRegex===!0?Rt(h,null,{wrap:!1,options:n}):h},$e=(e,r,t,n={})=>{if(r==null&&Me(e))return[e];if(!Me(e)||!Me(r))return _t(e,r,n);if(typeof t=="function")return $e(e,r,1,{transform:t});if(dt(t))return $e(e,r,0,t);let s={...n};return s.capture===!0&&(s.wrap=!0),t=t||s.step||1,Ae(t)?Ae(e)&&Ae(r)?Dr(e,r,t,s):Ur(e,r,Math.max(Math.abs(t),1),s):t!=null&&!dt(t)?Mr(t,s):$e(e,r,1,t)};Et.exports=$e});var Ct=q((ts,xt)=>{"use strict";var Gr=Ue(),bt=ve(),qr=(e,r={})=>{let t=(n,s={})=>{let i=bt.isInvalidBrace(s),a=n.invalid===!0&&r.escapeInvalid===!0,c=i===!0||a===!0,p=r.escapeInvalid===!0?"\\":"",m="";if(n.isOpen===!0||n.isClose===!0)return p+n.value;if(n.type==="open")return c?p+n.value:"(";if(n.type==="close")return c?p+n.value:")";if(n.type==="comma")return n.prev.type==="comma"?"":c?n.value:"|";if(n.value)return n.value;if(n.nodes&&n.ranges>0){let h=bt.reduce(n.nodes),R=Gr(...h,{...r,wrap:!1,toRegex:!0});if(R.length!==0)return h.length>1&&R.length>1?`(${R})`:R}if(n.nodes)for(let h of n.nodes)m+=t(h,n);return m};return t(e)};xt.exports=qr});var vt=q((rs,St)=>{"use strict";var Kr=Ue(),wt=He(),he=ve(),fe=(e="",r="",t=!1)=>{let n=[];if(e=[].concat(e),r=[].concat(r),!r.length)return e;if(!e.length)return t?he.flatten(r).map(s=>`{${s}}`):r;for(let s of e)if(Array.isArray(s))for(let i of s)n.push(fe(i,r,t));else for(let i of r)t===!0&&typeof i=="string"&&(i=`{${i}}`),n.push(Array.isArray(i)?fe(s,i,t):s+i);return he.flatten(n)},Wr=(e,r={})=>{let t=r.rangeLimit===void 0?1e3:r.rangeLimit,n=(s,i={})=>{s.queue=[];let a=i,c=i.queue;for(;a.type!=="brace"&&a.type!=="root"&&a.parent;)a=a.parent,c=a.queue;if(s.invalid||s.dollar){c.push(fe(c.pop(),wt(s,r)));return}if(s.type==="brace"&&s.invalid!==!0&&s.nodes.length===2){c.push(fe(c.pop(),["{}"]));return}if(s.nodes&&s.ranges>0){let R=he.reduce(s.nodes);if(he.exceedsLimit(...R,r.step,t))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let f=Kr(...R,r);f.length===0&&(f=wt(s,r)),c.push(fe(c.pop(),f)),s.nodes=[];return}let p=he.encloseBrace(s),m=s.queue,h=s;for(;h.type!=="brace"&&h.type!=="root"&&h.parent;)h=h.parent,m=h.queue;for(let R=0;R{"use strict";Ht.exports={MAX_LENGTH:1024*64,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:` -`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var Nt=q((ss,Ot)=>{"use strict";var jr=He(),{MAX_LENGTH:Tt,CHAR_BACKSLASH:Ge,CHAR_BACKTICK:Fr,CHAR_COMMA:Qr,CHAR_DOT:Xr,CHAR_LEFT_PARENTHESES:Zr,CHAR_RIGHT_PARENTHESES:Yr,CHAR_LEFT_CURLY_BRACE:zr,CHAR_RIGHT_CURLY_BRACE:Vr,CHAR_LEFT_SQUARE_BRACKET:kt,CHAR_RIGHT_SQUARE_BRACKET:Lt,CHAR_DOUBLE_QUOTE:Jr,CHAR_SINGLE_QUOTE:en,CHAR_NO_BREAK_SPACE:tn,CHAR_ZERO_WIDTH_NOBREAK_SPACE:rn}=$t(),nn=(e,r={})=>{if(typeof e!="string")throw new TypeError("Expected a string");let t=r||{},n=typeof t.maxLength=="number"?Math.min(Tt,t.maxLength):Tt;if(e.length>n)throw new SyntaxError(`Input length (${e.length}), exceeds max characters (${n})`);let s={type:"root",input:e,nodes:[]},i=[s],a=s,c=s,p=0,m=e.length,h=0,R=0,f,$={},_=()=>e[h++],y=E=>{if(E.type==="text"&&c.type==="dot"&&(c.type="text"),c&&c.type==="text"&&E.type==="text"){c.value+=E.value;return}return a.nodes.push(E),E.parent=a,E.prev=c,c=E,E};for(y({type:"bos"});h0){if(a.ranges>0){a.ranges=0;let E=a.nodes.shift();a.nodes=[E,{type:"text",value:jr(a)}]}y({type:"comma",value:f}),a.commas++;continue}if(f===Xr&&R>0&&a.commas===0){let E=a.nodes;if(R===0||E.length===0){y({type:"text",value:f});continue}if(c.type==="dot"){if(a.range=[],c.value+=f,c.type="range",a.nodes.length!==3&&a.nodes.length!==5){a.invalid=!0,a.ranges=0,c.type="text";continue}a.ranges++,a.args=[];continue}if(c.type==="range"){E.pop();let S=E[E.length-1];S.value+=c.value+f,c=S,a.ranges--;continue}y({type:"dot",value:f});continue}y({type:"text",value:f})}do if(a=i.pop(),a.type!=="root"){a.nodes.forEach(T=>{T.nodes||(T.type==="open"&&(T.isOpen=!0),T.type==="close"&&(T.isClose=!0),T.nodes||(T.type="text"),T.invalid=!0)});let E=i[i.length-1],S=E.nodes.indexOf(a);E.nodes.splice(S,1,...a.nodes)}while(i.length>0);return y({type:"eos"}),s};Ot.exports=nn});var Pt=q((as,Bt)=>{"use strict";var It=He(),sn=Ct(),an=vt(),on=Nt(),Z=(e,r={})=>{let t=[];if(Array.isArray(e))for(let n of e){let s=Z.create(n,r);Array.isArray(s)?t.push(...s):t.push(s)}else t=[].concat(Z.create(e,r));return r&&r.expand===!0&&r.nodupes===!0&&(t=[...new Set(t)]),t};Z.parse=(e,r={})=>on(e,r);Z.stringify=(e,r={})=>It(typeof e=="string"?Z.parse(e,r):e,r);Z.compile=(e,r={})=>(typeof e=="string"&&(e=Z.parse(e,r)),sn(e,r));Z.expand=(e,r={})=>{typeof e=="string"&&(e=Z.parse(e,r));let t=an(e,r);return r.noempty===!0&&(t=t.filter(Boolean)),r.nodupes===!0&&(t=[...new Set(t)]),t};Z.create=(e,r={})=>e===""||e.length<3?[e]:r.expand!==!0?Z.compile(e,r):Z.expand(e,r);Bt.exports=Z});var me=q((is,qt)=>{"use strict";var un=W("path"),se="\\\\/",Mt=`[^${se}]`,ie="\\.",cn="\\+",ln="\\?",Te="\\/",fn="(?=.)",Dt="[^/]",qe=`(?:${Te}|$)`,Ut=`(?:^|${Te})`,Ke=`${ie}{1,2}${qe}`,pn=`(?!${ie})`,hn=`(?!${Ut}${Ke})`,dn=`(?!${ie}{0,1}${qe})`,gn=`(?!${Ke})`,An=`[^.${Te}]`,mn=`${Dt}*?`,Gt={DOT_LITERAL:ie,PLUS_LITERAL:cn,QMARK_LITERAL:ln,SLASH_LITERAL:Te,ONE_CHAR:fn,QMARK:Dt,END_ANCHOR:qe,DOTS_SLASH:Ke,NO_DOT:pn,NO_DOTS:hn,NO_DOT_SLASH:dn,NO_DOTS_SLASH:gn,QMARK_NO_DOT:An,STAR:mn,START_ANCHOR:Ut},Rn={...Gt,SLASH_LITERAL:`[${se}]`,QMARK:Mt,STAR:`${Mt}*?`,DOTS_SLASH:`${ie}{1,2}(?:[${se}]|$)`,NO_DOT:`(?!${ie})`,NO_DOTS:`(?!(?:^|[${se}])${ie}{1,2}(?:[${se}]|$))`,NO_DOT_SLASH:`(?!${ie}{0,1}(?:[${se}]|$))`,NO_DOTS_SLASH:`(?!${ie}{1,2}(?:[${se}]|$))`,QMARK_NO_DOT:`[^.${se}]`,START_ANCHOR:`(?:^|[${se}])`,END_ANCHOR:`(?:[${se}]|$)`},yn={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};qt.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:yn,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:un.sep,extglobChars(e){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===!0?Rn:Gt}}});var Re=q(Q=>{"use strict";var _n=W("path"),En=process.platform==="win32",{REGEX_BACKSLASH:bn,REGEX_REMOVE_BACKSLASH:xn,REGEX_SPECIAL_CHARS:Cn,REGEX_SPECIAL_CHARS_GLOBAL:wn}=me();Q.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Q.hasRegexChars=e=>Cn.test(e);Q.isRegexChar=e=>e.length===1&&Q.hasRegexChars(e);Q.escapeRegex=e=>e.replace(wn,"\\$1");Q.toPosixSlashes=e=>e.replace(bn,"/");Q.removeBackslashes=e=>e.replace(xn,r=>r==="\\"?"":r);Q.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".").map(Number);return e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10};Q.isWindows=e=>e&&typeof e.windows=="boolean"?e.windows:En===!0||_n.sep==="\\";Q.escapeLast=(e,r,t)=>{let n=e.lastIndexOf(r,t);return n===-1?e:e[n-1]==="\\"?Q.escapeLast(e,r,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Q.removePrefix=(e,r={})=>{let t=e;return t.startsWith("./")&&(t=t.slice(2),r.prefix="./"),t};Q.wrapOutput=(e,r={},t={})=>{let n=t.contains?"":"^",s=t.contains?"":"$",i=`${n}(?:${e})${s}`;return r.negated===!0&&(i=`(?:^(?!${i}).*$)`),i}});var Yt=q((us,Zt)=>{"use strict";var Kt=Re(),{CHAR_ASTERISK:We,CHAR_AT:Sn,CHAR_BACKWARD_SLASH:ye,CHAR_COMMA:vn,CHAR_DOT:je,CHAR_EXCLAMATION_MARK:Fe,CHAR_FORWARD_SLASH:Xt,CHAR_LEFT_CURLY_BRACE:Qe,CHAR_LEFT_PARENTHESES:Xe,CHAR_LEFT_SQUARE_BRACKET:Hn,CHAR_PLUS:$n,CHAR_QUESTION_MARK:Wt,CHAR_RIGHT_CURLY_BRACE:Tn,CHAR_RIGHT_PARENTHESES:jt,CHAR_RIGHT_SQUARE_BRACKET:kn}=me(),Ft=e=>e===Xt||e===ye,Qt=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)},Ln=(e,r)=>{let t=r||{},n=e.length-1,s=t.parts===!0||t.scanToEnd===!0,i=[],a=[],c=[],p=e,m=-1,h=0,R=0,f=!1,$=!1,_=!1,y=!1,E=!1,S=!1,T=!1,L=!1,z=!1,I=!1,re=0,K,g,v={value:"",depth:0,isGlob:!1},k=()=>m>=n,l=()=>p.charCodeAt(m+1),H=()=>(K=g,p.charCodeAt(++m));for(;m0&&(B=p.slice(0,h),p=p.slice(h),R-=h),w&&_===!0&&R>0?(w=p.slice(0,R),o=p.slice(R)):_===!0?(w="",o=p):w=p,w&&w!==""&&w!=="/"&&w!==p&&Ft(w.charCodeAt(w.length-1))&&(w=w.slice(0,-1)),t.unescape===!0&&(o&&(o=Kt.removeBackslashes(o)),w&&T===!0&&(w=Kt.removeBackslashes(w)));let u={prefix:B,input:e,start:h,base:w,glob:o,isBrace:f,isBracket:$,isGlob:_,isExtglob:y,isGlobstar:E,negated:L,negatedExtglob:z};if(t.tokens===!0&&(u.maxDepth=0,Ft(g)||a.push(v),u.tokens=a),t.parts===!0||t.tokens===!0){let P;for(let b=0;b{"use strict";var ke=me(),Y=Re(),{MAX_LENGTH:Le,POSIX_REGEX_SOURCE:On,REGEX_NON_SPECIAL_CHARS:Nn,REGEX_SPECIAL_CHARS_BACKREF:In,REPLACEMENTS:zt}=ke,Bn=(e,r)=>{if(typeof r.expandRange=="function")return r.expandRange(...e,r);e.sort();let t=`[${e.join("-")}]`;try{new RegExp(t)}catch{return e.map(s=>Y.escapeRegex(s)).join("..")}return t},de=(e,r)=>`Missing ${e}: "${r}" - use "\\\\${r}" to match literal characters`,Vt=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=zt[e]||e;let t={...r},n=typeof t.maxLength=="number"?Math.min(Le,t.maxLength):Le,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:t.prepend||""},a=[i],c=t.capture?"":"?:",p=Y.isWindows(r),m=ke.globChars(p),h=ke.extglobChars(m),{DOT_LITERAL:R,PLUS_LITERAL:f,SLASH_LITERAL:$,ONE_CHAR:_,DOTS_SLASH:y,NO_DOT:E,NO_DOT_SLASH:S,NO_DOTS_SLASH:T,QMARK:L,QMARK_NO_DOT:z,STAR:I,START_ANCHOR:re}=m,K=A=>`(${c}(?:(?!${re}${A.dot?y:R}).)*?)`,g=t.dot?"":E,v=t.dot?L:z,k=t.bash===!0?K(t):I;t.capture&&(k=`(${k})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let l={input:e,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:a};e=Y.removePrefix(e,l),s=e.length;let H=[],w=[],B=[],o=i,u,P=()=>l.index===s-1,b=l.peek=(A=1)=>e[l.index+A],V=l.advance=()=>e[++l.index]||"",J=()=>e.slice(l.index+1),X=(A="",O=0)=>{l.consumed+=A,l.index+=O},Ee=A=>{l.output+=A.output!=null?A.output:A.value,X(A.value)},mr=()=>{let A=1;for(;b()==="!"&&(b(2)!=="("||b(3)==="?");)V(),l.start++,A++;return A%2===0?!1:(l.negated=!0,l.start++,!0)},be=A=>{l[A]++,B.push(A)},oe=A=>{l[A]--,B.pop()},C=A=>{if(o.type==="globstar"){let O=l.braces>0&&(A.type==="comma"||A.type==="brace"),d=A.extglob===!0||H.length&&(A.type==="pipe"||A.type==="paren");A.type!=="slash"&&A.type!=="paren"&&!O&&!d&&(l.output=l.output.slice(0,-o.output.length),o.type="star",o.value="*",o.output=k,l.output+=o.output)}if(H.length&&A.type!=="paren"&&(H[H.length-1].inner+=A.value),(A.value||A.output)&&Ee(A),o&&o.type==="text"&&A.type==="text"){o.value+=A.value,o.output=(o.output||"")+A.value;return}A.prev=o,a.push(A),o=A},xe=(A,O)=>{let d={...h[O],conditions:1,inner:""};d.prev=o,d.parens=l.parens,d.output=l.output;let x=(t.capture?"(":"")+d.open;be("parens"),C({type:A,value:O,output:l.output?"":_}),C({type:"paren",extglob:!0,value:V(),output:x}),H.push(d)},Rr=A=>{let O=A.close+(t.capture?")":""),d;if(A.type==="negate"){let x=k;A.inner&&A.inner.length>1&&A.inner.includes("/")&&(x=K(t)),(x!==k||P()||/^\)+$/.test(J()))&&(O=A.close=`)$))${x}`),A.inner.includes("*")&&(d=J())&&/^\.[^\\/.]+$/.test(d)&&(O=A.close=`)${d})${x})`),A.prev.type==="bos"&&(l.negatedExtglob=!0)}C({type:"paren",extglob:!0,value:u,output:O}),oe("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let A=!1,O=e.replace(In,(d,x,M,j,G,Ie)=>j==="\\"?(A=!0,d):j==="?"?x?x+j+(G?L.repeat(G.length):""):Ie===0?v+(G?L.repeat(G.length):""):L.repeat(M.length):j==="."?R.repeat(M.length):j==="*"?x?x+j+(G?k:""):k:x?d:`\\${d}`);return A===!0&&(t.unescape===!0?O=O.replace(/\\/g,""):O=O.replace(/\\+/g,d=>d.length%2===0?"\\\\":d?"\\":"")),O===e&&t.contains===!0?(l.output=e,l):(l.output=Y.wrapOutput(O,l,r),l)}for(;!P();){if(u=V(),u==="\0")continue;if(u==="\\"){let d=b();if(d==="/"&&t.bash!==!0||d==="."||d===";")continue;if(!d){u+="\\",C({type:"text",value:u});continue}let x=/^\\+/.exec(J()),M=0;if(x&&x[0].length>2&&(M=x[0].length,l.index+=M,M%2!==0&&(u+="\\")),t.unescape===!0?u=V():u+=V(),l.brackets===0){C({type:"text",value:u});continue}}if(l.brackets>0&&(u!=="]"||o.value==="["||o.value==="[^")){if(t.posix!==!1&&u===":"){let d=o.value.slice(1);if(d.includes("[")&&(o.posix=!0,d.includes(":"))){let x=o.value.lastIndexOf("["),M=o.value.slice(0,x),j=o.value.slice(x+2),G=On[j];if(G){o.value=M+G,l.backtrack=!0,V(),!i.output&&a.indexOf(o)===1&&(i.output=_);continue}}}(u==="["&&b()!==":"||u==="-"&&b()==="]")&&(u=`\\${u}`),u==="]"&&(o.value==="["||o.value==="[^")&&(u=`\\${u}`),t.posix===!0&&u==="!"&&o.value==="["&&(u="^"),o.value+=u,Ee({value:u});continue}if(l.quotes===1&&u!=='"'){u=Y.escapeRegex(u),o.value+=u,Ee({value:u});continue}if(u==='"'){l.quotes=l.quotes===1?0:1,t.keepQuotes===!0&&C({type:"text",value:u});continue}if(u==="("){be("parens"),C({type:"paren",value:u});continue}if(u===")"){if(l.parens===0&&t.strictBrackets===!0)throw new SyntaxError(de("opening","("));let d=H[H.length-1];if(d&&l.parens===d.parens+1){Rr(H.pop());continue}C({type:"paren",value:u,output:l.parens?")":"\\)"}),oe("parens");continue}if(u==="["){if(t.nobracket===!0||!J().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(de("closing","]"));u=`\\${u}`}else be("brackets");C({type:"bracket",value:u});continue}if(u==="]"){if(t.nobracket===!0||o&&o.type==="bracket"&&o.value.length===1){C({type:"text",value:u,output:`\\${u}`});continue}if(l.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(de("opening","["));C({type:"text",value:u,output:`\\${u}`});continue}oe("brackets");let d=o.value.slice(1);if(o.posix!==!0&&d[0]==="^"&&!d.includes("/")&&(u=`/${u}`),o.value+=u,Ee({value:u}),t.literalBrackets===!1||Y.hasRegexChars(d))continue;let x=Y.escapeRegex(o.value);if(l.output=l.output.slice(0,-o.value.length),t.literalBrackets===!0){l.output+=x,o.value=x;continue}o.value=`(${c}${x}|${o.value})`,l.output+=o.value;continue}if(u==="{"&&t.nobrace!==!0){be("braces");let d={type:"brace",value:u,output:"(",outputIndex:l.output.length,tokensIndex:l.tokens.length};w.push(d),C(d);continue}if(u==="}"){let d=w[w.length-1];if(t.nobrace===!0||!d){C({type:"text",value:u,output:u});continue}let x=")";if(d.dots===!0){let M=a.slice(),j=[];for(let G=M.length-1;G>=0&&(a.pop(),M[G].type!=="brace");G--)M[G].type!=="dots"&&j.unshift(M[G].value);x=Bn(j,t),l.backtrack=!0}if(d.comma!==!0&&d.dots!==!0){let M=l.output.slice(0,d.outputIndex),j=l.tokens.slice(d.tokensIndex);d.value=d.output="\\{",u=x="\\}",l.output=M;for(let G of j)l.output+=G.output||G.value}C({type:"brace",value:u,output:x}),oe("braces"),w.pop();continue}if(u==="|"){H.length>0&&H[H.length-1].conditions++,C({type:"text",value:u});continue}if(u===","){let d=u,x=w[w.length-1];x&&B[B.length-1]==="braces"&&(x.comma=!0,d="|"),C({type:"comma",value:u,output:d});continue}if(u==="/"){if(o.type==="dot"&&l.index===l.start+1){l.start=l.index+1,l.consumed="",l.output="",a.pop(),o=i;continue}C({type:"slash",value:u,output:$});continue}if(u==="."){if(l.braces>0&&o.type==="dot"){o.value==="."&&(o.output=R);let d=w[w.length-1];o.type="dots",o.output+=u,o.value+=u,d.dots=!0;continue}if(l.braces+l.parens===0&&o.type!=="bos"&&o.type!=="slash"){C({type:"text",value:u,output:R});continue}C({type:"dot",value:u,output:R});continue}if(u==="?"){if(!(o&&o.value==="(")&&t.noextglob!==!0&&b()==="("&&b(2)!=="?"){xe("qmark",u);continue}if(o&&o.type==="paren"){let x=b(),M=u;if(x==="<"&&!Y.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(o.value==="("&&!/[!=<:]/.test(x)||x==="<"&&!/<([!=]|\w+>)/.test(J()))&&(M=`\\${u}`),C({type:"text",value:u,output:M});continue}if(t.dot!==!0&&(o.type==="slash"||o.type==="bos")){C({type:"qmark",value:u,output:z});continue}C({type:"qmark",value:u,output:L});continue}if(u==="!"){if(t.noextglob!==!0&&b()==="("&&(b(2)!=="?"||!/[!=<:]/.test(b(3)))){xe("negate",u);continue}if(t.nonegate!==!0&&l.index===0){mr();continue}}if(u==="+"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){xe("plus",u);continue}if(o&&o.value==="("||t.regex===!1){C({type:"plus",value:u,output:f});continue}if(o&&(o.type==="bracket"||o.type==="paren"||o.type==="brace")||l.parens>0){C({type:"plus",value:u});continue}C({type:"plus",value:f});continue}if(u==="@"){if(t.noextglob!==!0&&b()==="("&&b(2)!=="?"){C({type:"at",extglob:!0,value:u,output:""});continue}C({type:"text",value:u});continue}if(u!=="*"){(u==="$"||u==="^")&&(u=`\\${u}`);let d=Nn.exec(J());d&&(u+=d[0],l.index+=d[0].length),C({type:"text",value:u});continue}if(o&&(o.type==="globstar"||o.star===!0)){o.type="star",o.star=!0,o.value+=u,o.output=k,l.backtrack=!0,l.globstar=!0,X(u);continue}let A=J();if(t.noextglob!==!0&&/^\([^?]/.test(A)){xe("star",u);continue}if(o.type==="star"){if(t.noglobstar===!0){X(u);continue}let d=o.prev,x=d.prev,M=d.type==="slash"||d.type==="bos",j=x&&(x.type==="star"||x.type==="globstar");if(t.bash===!0&&(!M||A[0]&&A[0]!=="/")){C({type:"star",value:u,output:""});continue}let G=l.braces>0&&(d.type==="comma"||d.type==="brace"),Ie=H.length&&(d.type==="pipe"||d.type==="paren");if(!M&&d.type!=="paren"&&!G&&!Ie){C({type:"star",value:u,output:""});continue}for(;A.slice(0,3)==="/**";){let Ce=e[l.index+4];if(Ce&&Ce!=="/")break;A=A.slice(3),X("/**",3)}if(d.type==="bos"&&P()){o.type="globstar",o.value+=u,o.output=K(t),l.output=o.output,l.globstar=!0,X(u);continue}if(d.type==="slash"&&d.prev.type!=="bos"&&!j&&P()){l.output=l.output.slice(0,-(d.output+o.output).length),d.output=`(?:${d.output}`,o.type="globstar",o.output=K(t)+(t.strictSlashes?")":"|$)"),o.value+=u,l.globstar=!0,l.output+=d.output+o.output,X(u);continue}if(d.type==="slash"&&d.prev.type!=="bos"&&A[0]==="/"){let Ce=A[1]!==void 0?"|$":"";l.output=l.output.slice(0,-(d.output+o.output).length),d.output=`(?:${d.output}`,o.type="globstar",o.output=`${K(t)}${$}|${$}${Ce})`,o.value+=u,l.output+=d.output+o.output,l.globstar=!0,X(u+V()),C({type:"slash",value:"/",output:""});continue}if(d.type==="bos"&&A[0]==="/"){o.type="globstar",o.value+=u,o.output=`(?:^|${$}|${K(t)}${$})`,l.output=o.output,l.globstar=!0,X(u+V()),C({type:"slash",value:"/",output:""});continue}l.output=l.output.slice(0,-o.output.length),o.type="globstar",o.output=K(t),o.value+=u,l.output+=o.output,l.globstar=!0,X(u);continue}let O={type:"star",value:u,output:k};if(t.bash===!0){O.output=".*?",(o.type==="bos"||o.type==="slash")&&(O.output=g+O.output),C(O);continue}if(o&&(o.type==="bracket"||o.type==="paren")&&t.regex===!0){O.output=u,C(O);continue}(l.index===l.start||o.type==="slash"||o.type==="dot")&&(o.type==="dot"?(l.output+=S,o.output+=S):t.dot===!0?(l.output+=T,o.output+=T):(l.output+=g,o.output+=g),b()!=="*"&&(l.output+=_,o.output+=_)),C(O)}for(;l.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing","]"));l.output=Y.escapeLast(l.output,"["),oe("brackets")}for(;l.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing",")"));l.output=Y.escapeLast(l.output,"("),oe("parens")}for(;l.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(de("closing","}"));l.output=Y.escapeLast(l.output,"{"),oe("braces")}if(t.strictSlashes!==!0&&(o.type==="star"||o.type==="bracket")&&C({type:"maybe_slash",value:"",output:`${$}?`}),l.backtrack===!0){l.output="";for(let A of l.tokens)l.output+=A.output!=null?A.output:A.value,A.suffix&&(l.output+=A.suffix)}return l};Vt.fastpaths=(e,r)=>{let t={...r},n=typeof t.maxLength=="number"?Math.min(Le,t.maxLength):Le,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=zt[e]||e;let i=Y.isWindows(r),{DOT_LITERAL:a,SLASH_LITERAL:c,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOTS:R,NO_DOTS_SLASH:f,STAR:$,START_ANCHOR:_}=ke.globChars(i),y=t.dot?R:h,E=t.dot?f:h,S=t.capture?"":"?:",T={negated:!1,prefix:""},L=t.bash===!0?".*?":$;t.capture&&(L=`(${L})`);let z=g=>g.noglobstar===!0?L:`(${S}(?:(?!${_}${g.dot?m:a}).)*?)`,I=g=>{switch(g){case"*":return`${y}${p}${L}`;case".*":return`${a}${p}${L}`;case"*.*":return`${y}${L}${a}${p}${L}`;case"*/*":return`${y}${L}${c}${p}${E}${L}`;case"**":return y+z(t);case"**/*":return`(?:${y}${z(t)}${c})?${E}${p}${L}`;case"**/*.*":return`(?:${y}${z(t)}${c})?${E}${L}${a}${p}${L}`;case"**/.*":return`(?:${y}${z(t)}${c})?${a}${p}${L}`;default:{let v=/^(.*?)\.(\w+)$/.exec(g);if(!v)return;let k=I(v[1]);return k?k+a+v[2]:void 0}}},re=Y.removePrefix(e,T),K=I(re);return K&&t.strictSlashes!==!0&&(K+=`${c}?`),K};Jt.exports=Vt});var rr=q((ls,tr)=>{"use strict";var Pn=W("path"),Mn=Yt(),Ze=er(),Ye=Re(),Dn=me(),Un=e=>e&&typeof e=="object"&&!Array.isArray(e),D=(e,r,t=!1)=>{if(Array.isArray(e)){let h=e.map(f=>D(f,r,t));return f=>{for(let $ of h){let _=$(f);if(_)return _}return!1}}let n=Un(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=r||{},i=Ye.isWindows(r),a=n?D.compileRe(e,r):D.makeRe(e,r,!1,!0),c=a.state;delete a.state;let p=()=>!1;if(s.ignore){let h={...r,ignore:null,onMatch:null,onResult:null};p=D(s.ignore,h,t)}let m=(h,R=!1)=>{let{isMatch:f,match:$,output:_}=D.test(h,a,r,{glob:e,posix:i}),y={glob:e,state:c,regex:a,posix:i,input:h,output:_,match:$,isMatch:f};return typeof s.onResult=="function"&&s.onResult(y),f===!1?(y.isMatch=!1,R?y:!1):p(h)?(typeof s.onIgnore=="function"&&s.onIgnore(y),y.isMatch=!1,R?y:!1):(typeof s.onMatch=="function"&&s.onMatch(y),R?y:!0)};return t&&(m.state=c),m};D.test=(e,r,t,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return{isMatch:!1,output:""};let i=t||{},a=i.format||(s?Ye.toPosixSlashes:null),c=e===n,p=c&&a?a(e):e;return c===!1&&(p=a?a(e):e,c=p===n),(c===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?c=D.matchBase(e,r,t,s):c=r.exec(p)),{isMatch:Boolean(c),match:c,output:p}};D.matchBase=(e,r,t,n=Ye.isWindows(t))=>(r instanceof RegExp?r:D.makeRe(r,t)).test(Pn.basename(e));D.isMatch=(e,r,t)=>D(r,t)(e);D.parse=(e,r)=>Array.isArray(e)?e.map(t=>D.parse(t,r)):Ze(e,{...r,fastpaths:!1});D.scan=(e,r)=>Mn(e,r);D.compileRe=(e,r,t=!1,n=!1)=>{if(t===!0)return e.output;let s=r||{},i=s.contains?"":"^",a=s.contains?"":"$",c=`${i}(?:${e.output})${a}`;e&&e.negated===!0&&(c=`^(?!${c}).*$`);let p=D.toRegex(c,r);return n===!0&&(p.state=e),p};D.makeRe=(e,r={},t=!1,n=!1)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return r.fastpaths!==!1&&(e[0]==="."||e[0]==="*")&&(s.output=Ze.fastpaths(e,r)),s.output||(s=Ze(e,r)),D.compileRe(s,r,t,n)};D.toRegex=(e,r)=>{try{let t=r||{};return new RegExp(e,t.flags||(t.nocase?"i":""))}catch(t){if(r&&r.debug===!0)throw t;return/$^/}};D.constants=Dn;tr.exports=D});var sr=q((fs,nr)=>{"use strict";nr.exports=rr()});var cr=q((ps,ur)=>{"use strict";var ir=W("util"),or=Pt(),ae=sr(),ze=Re(),ar=e=>e===""||e==="./",N=(e,r,t)=>{r=[].concat(r),e=[].concat(e);let n=new Set,s=new Set,i=new Set,a=0,c=h=>{i.add(h.output),t&&t.onResult&&t.onResult(h)};for(let h=0;h!n.has(h));if(t&&m.length===0){if(t.failglob===!0)throw new Error(`No matches found for "${r.join(", ")}"`);if(t.nonull===!0||t.nullglob===!0)return t.unescape?r.map(h=>h.replace(/\\/g,"")):r}return m};N.match=N;N.matcher=(e,r)=>ae(e,r);N.isMatch=(e,r,t)=>ae(r,t)(e);N.any=N.isMatch;N.not=(e,r,t={})=>{r=[].concat(r).map(String);let n=new Set,s=[],a=N(e,r,{...t,onResult:c=>{t.onResult&&t.onResult(c),s.push(c.output)}});for(let c of s)a.includes(c)||n.add(c);return[...n]};N.contains=(e,r,t)=>{if(typeof e!="string")throw new TypeError(`Expected a string: "${ir.inspect(e)}"`);if(Array.isArray(r))return r.some(n=>N.contains(e,n,t));if(typeof r=="string"){if(ar(e)||ar(r))return!1;if(e.includes(r)||e.startsWith("./")&&e.slice(2).includes(r))return!0}return N.isMatch(e,r,{...t,contains:!0})};N.matchKeys=(e,r,t)=>{if(!ze.isObject(e))throw new TypeError("Expected the first argument to be an object");let n=N(Object.keys(e),r,t),s={};for(let i of n)s[i]=e[i];return s};N.some=(e,r,t)=>{let n=[].concat(e);for(let s of[].concat(r)){let i=ae(String(s),t);if(n.some(a=>i(a)))return!0}return!1};N.every=(e,r,t)=>{let n=[].concat(e);for(let s of[].concat(r)){let i=ae(String(s),t);if(!n.every(a=>i(a)))return!1}return!0};N.all=(e,r,t)=>{if(typeof e!="string")throw new TypeError(`Expected a string: "${ir.inspect(e)}"`);return[].concat(r).every(n=>ae(n,t)(e))};N.capture=(e,r,t)=>{let n=ze.isWindows(t),i=ae.makeRe(String(e),{...t,capture:!0}).exec(n?ze.toPosixSlashes(r):r);if(i)return i.slice(1).map(a=>a===void 0?"":a)};N.makeRe=(...e)=>ae.makeRe(...e);N.scan=(...e)=>ae.scan(...e);N.parse=(e,r)=>{let t=[];for(let n of[].concat(e||[]))for(let s of or(String(n),r))t.push(ae.parse(s,r));return t};N.braces=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");return r&&r.nobrace===!0||!/\{.*\}/.test(e)?[e]:or(e,r)};N.braceExpand=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");return N.braces(e,{...r,expand:!0})};ur.exports=N});var fr=q((hs,lr)=>{"use strict";lr.exports=(e,...r)=>new Promise(t=>{t(e(...r))})});var hr=q((ds,Ve)=>{"use strict";var Gn=fr(),pr=e=>{if(e<1)throw new TypeError("Expected `concurrency` to be a number from 1 and up");let r=[],t=0,n=()=>{t--,r.length>0&&r.shift()()},s=(c,p,...m)=>{t++;let h=Gn(c,...m);p(h),h.then(n,n)},i=(c,p,...m)=>{tnew Promise(m=>i(c,m,...p));return Object.defineProperties(a,{activeCount:{get:()=>t},pendingCount:{get:()=>r.length}}),a};Ve.exports=pr;Ve.exports.default=pr});var jn={};Cr(jn,{default:()=>Wn});var Se=W("@yarnpkg/cli"),ne=W("@yarnpkg/core"),et=W("@yarnpkg/core"),ue=W("clipanion"),ce=class extends Se.BaseCommand{constructor(){super(...arguments);this.json=ue.Option.Boolean("--json",!1,{description:"Format the output as an NDJSON stream"});this.production=ue.Option.Boolean("--production",!1,{description:"Only install regular dependencies by omitting dev dependencies"});this.all=ue.Option.Boolean("-A,--all",!1,{description:"Install the entire project"});this.workspaces=ue.Option.Rest()}async execute(){let t=await ne.Configuration.find(this.context.cwd,this.context.plugins),{project:n,workspace:s}=await ne.Project.find(t,this.context.cwd),i=await ne.Cache.find(t);await n.restoreInstallState({restoreResolutions:!1});let a;if(this.all)a=new Set(n.workspaces);else if(this.workspaces.length===0){if(!s)throw new Se.WorkspaceRequiredError(n.cwd,this.context.cwd);a=new Set([s])}else a=new Set(this.workspaces.map(p=>n.getWorkspaceByIdent(et.structUtils.parseIdent(p))));for(let p of a)for(let m of this.production?["dependencies"]:ne.Manifest.hardDependencies)for(let h of p.manifest.getForScope(m).values()){let R=n.tryWorkspaceByDescriptor(h);R!==null&&a.add(R)}for(let p of n.workspaces)a.has(p)?this.production&&p.manifest.devDependencies.clear():(p.manifest.installConfig=p.manifest.installConfig||{},p.manifest.installConfig.selfReferences=!1,p.manifest.dependencies.clear(),p.manifest.devDependencies.clear(),p.manifest.peerDependencies.clear(),p.manifest.scripts.clear());return(await ne.StreamReport.start({configuration:t,json:this.json,stdout:this.context.stdout,includeLogs:!0},async p=>{await n.install({cache:i,report:p,persistProject:!1})})).exitCode()}};ce.paths=[["workspaces","focus"]],ce.usage=ue.Command.Usage({category:"Workspace-related commands",description:"install a single workspace and its dependencies",details:"\n This command will run an install as if the specified workspaces (and all other workspaces they depend on) were the only ones in the project. If no workspaces are explicitly listed, the active one will be assumed.\n\n Note that this command is only very moderately useful when using zero-installs, since the cache will contain all the packages anyway - meaning that the only difference between a full install and a focused install would just be a few extra lines in the `.pnp.cjs` file, at the cost of introducing an extra complexity.\n\n If the `-A,--all` flag is set, the entire project will be installed. Combine with `--production` to replicate the old `yarn install --production`.\n "});var Ne=W("@yarnpkg/cli"),ge=W("@yarnpkg/core"),_e=W("@yarnpkg/core"),F=W("@yarnpkg/core"),gr=W("@yarnpkg/plugin-git"),U=W("clipanion"),Oe=Be(cr()),Ar=Be(hr()),te=Be(W("typanion")),pe=class extends Ne.BaseCommand{constructor(){super(...arguments);this.recursive=U.Option.Boolean("-R,--recursive",!1,{description:"Find packages via dependencies/devDependencies instead of using the workspaces field"});this.from=U.Option.Array("--from",[],{description:"An array of glob pattern idents from which to base any recursion"});this.all=U.Option.Boolean("-A,--all",!1,{description:"Run the command on all workspaces of a project"});this.verbose=U.Option.Boolean("-v,--verbose",!1,{description:"Prefix each output line with the name of the originating workspace"});this.parallel=U.Option.Boolean("-p,--parallel",!1,{description:"Run the commands in parallel"});this.interlaced=U.Option.Boolean("-i,--interlaced",!1,{description:"Print the output of commands in real-time instead of buffering it"});this.jobs=U.Option.String("-j,--jobs",{description:"The maximum number of parallel tasks that the execution will be limited to; or `unlimited`",validator:te.isOneOf([te.isEnum(["unlimited"]),te.applyCascade(te.isNumber(),[te.isInteger(),te.isAtLeast(1)])])});this.topological=U.Option.Boolean("-t,--topological",!1,{description:"Run the command after all workspaces it depends on (regular) have finished"});this.topologicalDev=U.Option.Boolean("--topological-dev",!1,{description:"Run the command after all workspaces it depends on (regular + dev) have finished"});this.include=U.Option.Array("--include",[],{description:"An array of glob pattern idents; only matching workspaces will be traversed"});this.exclude=U.Option.Array("--exclude",[],{description:"An array of glob pattern idents; matching workspaces won't be traversed"});this.publicOnly=U.Option.Boolean("--no-private",{description:"Avoid running the command on private workspaces"});this.since=U.Option.String("--since",{description:"Only include workspaces that have been changed since the specified ref.",tolerateBoolean:!0});this.commandName=U.Option.String();this.args=U.Option.Proxy()}async execute(){let t=await ge.Configuration.find(this.context.cwd,this.context.plugins),{project:n,workspace:s}=await ge.Project.find(t,this.context.cwd);if(!this.all&&!s)throw new Ne.WorkspaceRequiredError(n.cwd,this.context.cwd);await n.restoreInstallState();let i=this.cli.process([this.commandName,...this.args]),a=i.path.length===1&&i.path[0]==="run"&&typeof i.scriptName<"u"?i.scriptName:null;if(i.path.length===0)throw new U.UsageError("Invalid subcommand name for iteration - use the 'run' keyword if you wish to execute a script");let c=this.all?n.topLevelWorkspace:s,p=this.since?Array.from(await gr.gitUtils.fetchChangedWorkspaces({ref:this.since,project:n})):[c,...this.from.length>0?c.getRecursiveWorkspaceChildren():[]],m=g=>Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.from),h=this.from.length>0?p.filter(m):p,R=new Set([...h,...h.map(g=>[...this.recursive?this.since?g.getRecursiveWorkspaceDependents():g.getRecursiveWorkspaceDependencies():g.getRecursiveWorkspaceChildren()]).flat()]),f=[],$=!1;if(a!=null&&a.includes(":")){for(let g of n.workspaces)if(g.manifest.scripts.has(a)&&($=!$,$===!1))break}for(let g of R)a&&!g.manifest.scripts.has(a)&&!$&&!(await ge.scriptUtils.getWorkspaceAccessibleBinaries(g)).has(a)||a===process.env.npm_lifecycle_event&&g.cwd===s.cwd||this.include.length>0&&!Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.include)||this.exclude.length>0&&Oe.default.isMatch(F.structUtils.stringifyIdent(g.locator),this.exclude)||this.publicOnly&&g.manifest.private===!0||f.push(g);let _=this.parallel?this.jobs==="unlimited"?1/0:Number(this.jobs)||Math.ceil(F.nodeUtils.availableParallelism()/2):1,y=_===1?!1:this.parallel,E=y?this.interlaced:!0,S=(0,Ar.default)(_),T=new Map,L=new Set,z=0,I=null,re=!1,K=await _e.StreamReport.start({configuration:t,stdout:this.context.stdout,includePrefix:!1},async g=>{let v=async(k,{commandIndex:l})=>{if(re)return-1;!y&&this.verbose&&l>1&&g.reportSeparator();let H=qn(k,{configuration:t,verbose:this.verbose,commandIndex:l}),[w,B]=dr(g,{prefix:H,interlaced:E}),[o,u]=dr(g,{prefix:H,interlaced:E});try{this.verbose&&g.reportInfo(null,`${H} Process started`);let P=Date.now(),b=await this.cli.run([this.commandName,...this.args],{cwd:k.cwd,stdout:w,stderr:o})||0;w.end(),o.end(),await B,await u;let V=Date.now();if(this.verbose){let J=t.get("enableTimers")?`, completed in ${F.formatUtils.pretty(t,V-P,F.formatUtils.Type.DURATION)}`:"";g.reportInfo(null,`${H} Process exited (exit code ${b})${J}`)}return b===130&&(re=!0,I=b),b}catch(P){throw w.end(),o.end(),await B,await u,P}};for(let k of f)T.set(k.anchoredLocator.locatorHash,k);for(;T.size>0&&!g.hasErrors();){let k=[];for(let[w,B]of T){if(L.has(B.anchoredDescriptor.descriptorHash))continue;let o=!0;if(this.topological||this.topologicalDev){let u=this.topologicalDev?new Map([...B.manifest.dependencies,...B.manifest.devDependencies]):B.manifest.dependencies;for(let P of u.values()){let b=n.tryWorkspaceByDescriptor(P);if(o=b===null||!T.has(b.anchoredLocator.locatorHash),!o)break}}if(!!o&&(L.add(B.anchoredDescriptor.descriptorHash),k.push(S(async()=>{let u=await v(B,{commandIndex:++z});return T.delete(w),L.delete(B.anchoredDescriptor.descriptorHash),u})),!y))break}if(k.length===0){let w=Array.from(T.values()).map(B=>F.structUtils.prettyLocator(t,B.anchoredLocator)).join(", ");g.reportError(_e.MessageName.CYCLIC_DEPENDENCIES,`Dependency cycle detected (${w})`);return}let H=(await Promise.all(k)).find(w=>w!==0);I===null&&(I=typeof H<"u"?1:I),(this.topological||this.topologicalDev)&&typeof H<"u"&&g.reportError(_e.MessageName.UNNAMED,"The command failed for workspaces that are depended upon by other workspaces; can't satisfy the dependency graph")}});return I!==null?I:K.exitCode()}};pe.paths=[["workspaces","foreach"]],pe.usage=U.Command.Usage({category:"Workspace-related commands",description:"run a command on all workspaces",details:"\n This command will run a given sub-command on current and all its descendant workspaces. Various flags can alter the exact behavior of the command:\n\n - If `-p,--parallel` is set, the commands will be ran in parallel; they'll by default be limited to a number of parallel tasks roughly equal to half your core number, but that can be overridden via `-j,--jobs`, or disabled by setting `-j unlimited`.\n\n - If `-p,--parallel` and `-i,--interlaced` are both set, Yarn will print the lines from the output as it receives them. If `-i,--interlaced` wasn't set, it would instead buffer the output from each process and print the resulting buffers only after their source processes have exited.\n\n - If `-t,--topological` is set, Yarn will only run the command after all workspaces that it depends on through the `dependencies` field have successfully finished executing. If `--topological-dev` is set, both the `dependencies` and `devDependencies` fields will be considered when figuring out the wait points.\n\n - If `-A,--all` is set, Yarn will run the command on all the workspaces of a project. By default yarn runs the command only on current and all its descendant workspaces.\n\n - If `-R,--recursive` is set, Yarn will find workspaces to run the command on by recursively evaluating `dependencies` and `devDependencies` fields, instead of looking at the `workspaces` fields.\n\n - If `--from` is set, Yarn will use the packages matching the 'from' glob as the starting point for any recursive search.\n\n - If `--since` is set, Yarn will only run the command on workspaces that have been modified since the specified ref. By default Yarn will use the refs specified by the `changesetBaseRefs` configuration option.\n\n - The command may apply to only some workspaces through the use of `--include` which acts as a whitelist. The `--exclude` flag will do the opposite and will be a list of packages that mustn't execute the script. Both flags accept glob patterns (if valid Idents and supported by [micromatch](https://github.com/micromatch/micromatch)). Make sure to escape the patterns, to prevent your own shell from trying to expand them.\n\n Adding the `-v,--verbose` flag will cause Yarn to print more information; in particular the name of the workspace that generated the output will be printed at the front of each line.\n\n If the command is `run` and the script being run does not exist the child workspace will be skipped without error.\n ",examples:[["Publish current and all descendant packages","yarn workspaces foreach npm publish --tolerate-republish"],["Run build script on current and all descendant packages","yarn workspaces foreach run build"],["Run build script on current and all descendant packages in parallel, building package dependencies first","yarn workspaces foreach -pt run build"],["Run build script on several packages and all their dependencies, building dependencies first","yarn workspaces foreach -ptR --from '{workspace-a,workspace-b}' run build"]]});function dr(e,{prefix:r,interlaced:t}){let n=e.createStreamReporter(r),s=new F.miscUtils.DefaultStream;s.pipe(n,{end:!1}),s.on("finish",()=>{n.end()});let i=new Promise(c=>{n.on("finish",()=>{c(s.active)})});if(t)return[s,i];let a=new F.miscUtils.BufferStream;return a.pipe(s,{end:!1}),a.on("finish",()=>{s.end()}),[a,i]}function qn(e,{configuration:r,commandIndex:t,verbose:n}){if(!n)return null;let i=`[${F.structUtils.stringifyIdent(e.locator)}]:`,a=["#2E86AB","#A23B72","#F18F01","#C73E1D","#CCE2A3"],c=a[t%a.length];return F.formatUtils.pretty(r,i,c)}var Kn={commands:[ce,pe]},Wn=Kn;return wr(jn);})(); -/*! - * fill-range - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Licensed under the MIT License. - */ -/*! - * is-number - * - * Copyright (c) 2014-present, Jon Schlinkert. - * Released under the MIT License. - */ -/*! - * to-regex-range - * - * Copyright (c) 2015-present, Jon Schlinkert. - * Released under the MIT License. - */ -return plugin; -} -}; diff --git a/.yarn/releases/yarn-3.8.6.cjs b/.yarn/releases/yarn-3.8.6.cjs deleted file mode 100755 index fe324cc9..00000000 --- a/.yarn/releases/yarn-3.8.6.cjs +++ /dev/null @@ -1,875 +0,0 @@ -#!/usr/bin/env node -/* eslint-disable */ -//prettier-ignore -(()=>{var Lge=Object.create;var lS=Object.defineProperty;var Oge=Object.getOwnPropertyDescriptor;var Mge=Object.getOwnPropertyNames;var Kge=Object.getPrototypeOf,Uge=Object.prototype.hasOwnProperty;var J=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+r+'" is not supported')});var Hge=(r,e)=>()=>(r&&(e=r(r=0)),e);var I=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ct=(r,e)=>{for(var t in e)lS(r,t,{get:e[t],enumerable:!0})},jge=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Mge(e))!Uge.call(r,n)&&n!==t&&lS(r,n,{get:()=>e[n],enumerable:!(i=Oge(e,n))||i.enumerable});return r};var ve=(r,e,t)=>(t=r!=null?Lge(Kge(r)):{},jge(e||!r||!r.__esModule?lS(t,"default",{value:r,enumerable:!0}):t,r));var kK=I((nZe,PK)=>{PK.exports=xK;xK.sync=lfe;var SK=J("fs");function Afe(r,e){var t=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!t||(t=t.split(";"),t.indexOf("")!==-1))return!0;for(var i=0;i{TK.exports=RK;RK.sync=cfe;var DK=J("fs");function RK(r,e,t){DK.stat(r,function(i,n){t(i,i?!1:FK(n,e))})}function cfe(r,e){return FK(DK.statSync(r),e)}function FK(r,e){return r.isFile()&&ufe(r,e)}function ufe(r,e){var t=r.mode,i=r.uid,n=r.gid,s=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),l=parseInt("010",8),c=parseInt("001",8),u=a|l,g=t&c||t&l&&n===o||t&a&&i===s||t&u&&s===0;return g}});var OK=I((aZe,LK)=>{var oZe=J("fs"),AI;process.platform==="win32"||global.TESTING_WINDOWS?AI=kK():AI=NK();LK.exports=SS;SS.sync=gfe;function SS(r,e,t){if(typeof e=="function"&&(t=e,e={}),!t){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,n){SS(r,e||{},function(s,o){s?n(s):i(o)})})}AI(r,e||{},function(i,n){i&&(i.code==="EACCES"||e&&e.ignoreErrors)&&(i=null,n=!1),t(i,n)})}function gfe(r,e){try{return AI.sync(r,e||{})}catch(t){if(e&&e.ignoreErrors||t.code==="EACCES")return!1;throw t}}});var YK=I((AZe,GK)=>{var kg=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",MK=J("path"),ffe=kg?";":":",KK=OK(),UK=r=>Object.assign(new Error(`not found: ${r}`),{code:"ENOENT"}),HK=(r,e)=>{let t=e.colon||ffe,i=r.match(/\//)||kg&&r.match(/\\/)?[""]:[...kg?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(t)],n=kg?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=kg?n.split(t):[""];return kg&&r.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:i,pathExt:s,pathExtExe:n}},jK=(r,e,t)=>{typeof e=="function"&&(t=e,e={}),e||(e={});let{pathEnv:i,pathExt:n,pathExtExe:s}=HK(r,e),o=[],a=c=>new Promise((u,g)=>{if(c===i.length)return e.all&&o.length?u(o):g(UK(r));let h=i[c],p=/^".*"$/.test(h)?h.slice(1,-1):h,d=MK.join(p,r),m=!p&&/^\.[\\\/]/.test(r)?r.slice(0,2)+d:d;u(l(m,c,0))}),l=(c,u,g)=>new Promise((h,p)=>{if(g===n.length)return h(a(u+1));let d=n[g];KK(c+d,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)o.push(c+d);else return h(c+d);return h(l(c,u,g+1))})});return t?a(0).then(c=>t(null,c),t):a(0)},hfe=(r,e)=>{e=e||{};let{pathEnv:t,pathExt:i,pathExtExe:n}=HK(r,e),s=[];for(let o=0;o{"use strict";var qK=(r={})=>{let e=r.env||process.env;return(r.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(i=>i.toUpperCase()==="PATH")||"Path"};vS.exports=qK;vS.exports.default=qK});var XK=I((cZe,VK)=>{"use strict";var WK=J("path"),pfe=YK(),dfe=JK();function zK(r,e){let t=r.options.env||process.env,i=process.cwd(),n=r.options.cwd!=null,s=n&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(r.options.cwd)}catch{}let o;try{o=pfe.sync(r.command,{path:t[dfe({env:t})],pathExt:e?WK.delimiter:void 0})}catch{}finally{s&&process.chdir(i)}return o&&(o=WK.resolve(n?r.options.cwd:"",o)),o}function Cfe(r){return zK(r)||zK(r,!0)}VK.exports=Cfe});var ZK=I((uZe,PS)=>{"use strict";var xS=/([()\][%!^"`<>&|;, *?])/g;function mfe(r){return r=r.replace(xS,"^$1"),r}function Efe(r,e){return r=`${r}`,r=r.replace(/(\\*)"/g,'$1$1\\"'),r=r.replace(/(\\*)$/,"$1$1"),r=`"${r}"`,r=r.replace(xS,"^$1"),e&&(r=r.replace(xS,"^$1")),r}PS.exports.command=mfe;PS.exports.argument=Efe});var $K=I((gZe,_K)=>{"use strict";_K.exports=/^#!(.*)/});var tU=I((fZe,eU)=>{"use strict";var Ife=$K();eU.exports=(r="")=>{let e=r.match(Ife);if(!e)return null;let[t,i]=e[0].replace(/#! ?/,"").split(" "),n=t.split("/").pop();return n==="env"?i:i?`${n} ${i}`:n}});var iU=I((hZe,rU)=>{"use strict";var kS=J("fs"),yfe=tU();function wfe(r){let t=Buffer.alloc(150),i;try{i=kS.openSync(r,"r"),kS.readSync(i,t,0,150,0),kS.closeSync(i)}catch{}return yfe(t.toString())}rU.exports=wfe});var aU=I((pZe,oU)=>{"use strict";var Bfe=J("path"),nU=XK(),sU=ZK(),Qfe=iU(),bfe=process.platform==="win32",Sfe=/\.(?:com|exe)$/i,vfe=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function xfe(r){r.file=nU(r);let e=r.file&&Qfe(r.file);return e?(r.args.unshift(r.file),r.command=e,nU(r)):r.file}function Pfe(r){if(!bfe)return r;let e=xfe(r),t=!Sfe.test(e);if(r.options.forceShell||t){let i=vfe.test(e);r.command=Bfe.normalize(r.command),r.command=sU.command(r.command),r.args=r.args.map(s=>sU.argument(s,i));let n=[r.command].concat(r.args).join(" ");r.args=["/d","/s","/c",`"${n}"`],r.command=process.env.comspec||"cmd.exe",r.options.windowsVerbatimArguments=!0}return r}function kfe(r,e,t){e&&!Array.isArray(e)&&(t=e,e=null),e=e?e.slice(0):[],t=Object.assign({},t);let i={command:r,args:e,options:t,file:void 0,original:{command:r,args:e}};return t.shell?i:Pfe(i)}oU.exports=kfe});var cU=I((dZe,lU)=>{"use strict";var DS=process.platform==="win32";function RS(r,e){return Object.assign(new Error(`${e} ${r.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${r.command}`,path:r.command,spawnargs:r.args})}function Dfe(r,e){if(!DS)return;let t=r.emit;r.emit=function(i,n){if(i==="exit"){let s=AU(n,e,"spawn");if(s)return t.call(r,"error",s)}return t.apply(r,arguments)}}function AU(r,e){return DS&&r===1&&!e.file?RS(e.original,"spawn"):null}function Rfe(r,e){return DS&&r===1&&!e.file?RS(e.original,"spawnSync"):null}lU.exports={hookChildProcess:Dfe,verifyENOENT:AU,verifyENOENTSync:Rfe,notFoundError:RS}});var NS=I((CZe,Dg)=>{"use strict";var uU=J("child_process"),FS=aU(),TS=cU();function gU(r,e,t){let i=FS(r,e,t),n=uU.spawn(i.command,i.args,i.options);return TS.hookChildProcess(n,i),n}function Ffe(r,e,t){let i=FS(r,e,t),n=uU.spawnSync(i.command,i.args,i.options);return n.error=n.error||TS.verifyENOENTSync(n.status,i),n}Dg.exports=gU;Dg.exports.spawn=gU;Dg.exports.sync=Ffe;Dg.exports._parse=FS;Dg.exports._enoent=TS});var hU=I((mZe,fU)=>{"use strict";function Tfe(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function $l(r,e,t,i){this.message=r,this.expected=e,this.found=t,this.location=i,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,$l)}Tfe($l,Error);$l.buildMessage=function(r,e){var t={literal:function(c){return'"'+n(c.text)+'"'},class:function(c){var u="",g;for(g=0;g0){for(g=1,h=1;g>",re=Ue(">>",!1),de=">&",Ze=Ue(">&",!1),vt=">",mt=Ue(">",!1),Lr="<<<",ti=Ue("<<<",!1),ui="<&",gr=Ue("<&",!1),gi="<",ri=Ue("<",!1),Ms=function(C){return{type:"argument",segments:[].concat(...C)}},fr=function(C){return C},Ei="$'",rs=Ue("$'",!1),ua="'",CA=Ue("'",!1),gg=function(C){return[{type:"text",text:C}]},is='""',mA=Ue('""',!1),ga=function(){return{type:"text",text:""}},wp='"',EA=Ue('"',!1),IA=function(C){return C},yr=function(C){return{type:"arithmetic",arithmetic:C,quoted:!0}},Tl=function(C){return{type:"shell",shell:C,quoted:!0}},fg=function(C){return{type:"variable",...C,quoted:!0}},Io=function(C){return{type:"text",text:C}},hg=function(C){return{type:"arithmetic",arithmetic:C,quoted:!1}},Bp=function(C){return{type:"shell",shell:C,quoted:!1}},Qp=function(C){return{type:"variable",...C,quoted:!1}},Sr=function(C){return{type:"glob",pattern:C}},Ri=/^[^']/,yo=Ve(["'"],!0,!1),Tn=function(C){return C.join("")},ae=/^[^$"]/,yt=Ve(["$",'"'],!0,!1),Nl=`\\ -`,Nn=Ue(`\\ -`,!1),ns=function(){return""},ss="\\",ut=Ue("\\",!1),wo=/^[\\$"`]/,At=Ve(["\\","$",'"',"`"],!1,!1),ln=function(C){return C},b="\\a",Tt=Ue("\\a",!1),pg=function(){return"a"},Ll="\\b",bp=Ue("\\b",!1),Sp=function(){return"\b"},vp=/^[Ee]/,xp=Ve(["E","e"],!1,!1),Pp=function(){return"\x1B"},j="\\f",Et=Ue("\\f",!1),yA=function(){return"\f"},zi="\\n",Ol=Ue("\\n",!1),ze=function(){return` -`},fa="\\r",dg=Ue("\\r",!1),OE=function(){return"\r"},kp="\\t",ME=Ue("\\t",!1),sr=function(){return" "},Ln="\\v",Ml=Ue("\\v",!1),Dp=function(){return"\v"},Ks=/^[\\'"?]/,ha=Ve(["\\","'",'"',"?"],!1,!1),cn=function(C){return String.fromCharCode(parseInt(C,16))},Te="\\x",Cg=Ue("\\x",!1),Kl="\\u",Us=Ue("\\u",!1),Ul="\\U",wA=Ue("\\U",!1),mg=function(C){return String.fromCodePoint(parseInt(C,16))},Eg=/^[0-7]/,pa=Ve([["0","7"]],!1,!1),da=/^[0-9a-fA-f]/,tt=Ve([["0","9"],["a","f"],["A","f"]],!1,!1),Bo=nt(),BA="{}",Rp=Ue("{}",!1),Ca=function(){return"{}"},Hl="-",jl=Ue("-",!1),QA="+",ma=Ue("+",!1),Fp=".",KE=Ue(".",!1),Gl=function(C,Q,R){return{type:"number",value:(C==="-"?-1:1)*parseFloat(Q.join("")+"."+R.join(""))}},UE=function(C,Q){return{type:"number",value:(C==="-"?-1:1)*parseInt(Q.join(""))}},Tp=function(C){return{type:"variable",...C}},Yl=function(C){return{type:"variable",name:C}},Or=function(C){return C},HE="*",Hs=Ue("*",!1),js="/",Ig=Ue("/",!1),bA=function(C,Q,R){return{type:Q==="*"?"multiplication":"division",right:R}},D=function(C,Q){return Q.reduce((R,U)=>({left:R,...U}),C)},Y=function(C,Q,R){return{type:Q==="+"?"addition":"subtraction",right:R}},pe="$((",Le=Ue("$((",!1),ke="))",Je=Ue("))",!1),pt=function(C){return C},Xt="$(",Ea=Ue("$(",!1),D1=function(C){return C},Gs="${",yg=Ue("${",!1),Jb=":-",R1=Ue(":-",!1),F1=function(C,Q){return{name:C,defaultValue:Q}},Wb=":-}",T1=Ue(":-}",!1),N1=function(C){return{name:C,defaultValue:[]}},zb=":+",L1=Ue(":+",!1),O1=function(C,Q){return{name:C,alternativeValue:Q}},Vb=":+}",M1=Ue(":+}",!1),K1=function(C){return{name:C,alternativeValue:[]}},Xb=function(C){return{name:C}},U1="$",H1=Ue("$",!1),j1=function(C){return e.isGlobPattern(C)},G1=function(C){return C},Zb=/^[a-zA-Z0-9_]/,_b=Ve([["a","z"],["A","Z"],["0","9"],"_"],!1,!1),$b=function(){return Ie()},ql=/^[$@*?#a-zA-Z0-9_\-]/,jE=Ve(["$","@","*","?","#",["a","z"],["A","Z"],["0","9"],"_","-"],!1,!1),eS=/^[()}<>$|&; \t"']/,tS=Ve(["(",")","}","<",">","$","|","&",";"," "," ",'"',"'"],!1,!1),rS=/^[<>&; \t"']/,GE=Ve(["<",">","&",";"," "," ",'"',"'"],!1,!1),Jl=/^[ \t]/,wg=Ve([" "," "],!1,!1),f=0,E=0,w=[{line:1,column:1}],k=0,L=[],N=0,ee;if("startRule"in e){if(!(e.startRule in i))throw new Error(`Can't start parsing from rule "`+e.startRule+'".');n=i[e.startRule]}function Ie(){return r.substring(E,f)}function Oe(){return ii(E,f)}function it(C,Q){throw Q=Q!==void 0?Q:ii(E,f),On([Ii(C)],r.substring(E,f),Q)}function at(C,Q){throw Q=Q!==void 0?Q:ii(E,f),yi(C,Q)}function Ue(C,Q){return{type:"literal",text:C,ignoreCase:Q}}function Ve(C,Q,R){return{type:"class",parts:C,inverted:Q,ignoreCase:R}}function nt(){return{type:"any"}}function wt(){return{type:"end"}}function Ii(C){return{type:"other",description:C}}function un(C){var Q=w[C],R;if(Q)return Q;for(R=C-1;!w[R];)R--;for(Q=w[R],Q={line:Q.line,column:Q.column};Rk&&(k=f,L=[]),L.push(C))}function yi(C,Q){return new $l(C,null,null,Q)}function On(C,Q,R){return new $l($l.buildMessage(C,Q),C,Q,R)}function Ia(){var C,Q,R;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();return Q!==t?(R=vr(),R===t&&(R=null),R!==t?(E=C,Q=s(R),C=Q):(f=C,C=t)):(f=C,C=t),C}function vr(){var C,Q,R,U,le;if(C=f,Q=iS(),Q!==t){for(R=[],U=Me();U!==t;)R.push(U),U=Me();R!==t?(U=Y1(),U!==t?(le=mge(),le===t&&(le=null),le!==t?(E=C,Q=o(Q,U,le),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t)}else f=C,C=t;if(C===t)if(C=f,Q=iS(),Q!==t){for(R=[],U=Me();U!==t;)R.push(U),U=Me();R!==t?(U=Y1(),U===t&&(U=null),U!==t?(E=C,Q=a(Q,U),C=Q):(f=C,C=t)):(f=C,C=t)}else f=C,C=t;return C}function mge(){var C,Q,R,U,le;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t)if(R=vr(),R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();U!==t?(E=C,Q=l(R),C=Q):(f=C,C=t)}else f=C,C=t;else f=C,C=t;return C}function Y1(){var C;return r.charCodeAt(f)===59?(C=c,f++):(C=t,N===0&&Be(u)),C===t&&(r.charCodeAt(f)===38?(C=g,f++):(C=t,N===0&&Be(h))),C}function iS(){var C,Q,R;return C=f,Q=q1(),Q!==t?(R=Ege(),R===t&&(R=null),R!==t?(E=C,Q=p(Q,R),C=Q):(f=C,C=t)):(f=C,C=t),C}function Ege(){var C,Q,R,U,le,Qe,ft;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t)if(R=Ige(),R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();if(U!==t)if(le=iS(),le!==t){for(Qe=[],ft=Me();ft!==t;)Qe.push(ft),ft=Me();Qe!==t?(E=C,Q=d(R,le),C=Q):(f=C,C=t)}else f=C,C=t;else f=C,C=t}else f=C,C=t;else f=C,C=t;return C}function Ige(){var C;return r.substr(f,2)===m?(C=m,f+=2):(C=t,N===0&&Be(y)),C===t&&(r.substr(f,2)===B?(C=B,f+=2):(C=t,N===0&&Be(S))),C}function q1(){var C,Q,R;return C=f,Q=Bge(),Q!==t?(R=yge(),R===t&&(R=null),R!==t?(E=C,Q=P(Q,R),C=Q):(f=C,C=t)):(f=C,C=t),C}function yge(){var C,Q,R,U,le,Qe,ft;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t)if(R=wge(),R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();if(U!==t)if(le=q1(),le!==t){for(Qe=[],ft=Me();ft!==t;)Qe.push(ft),ft=Me();Qe!==t?(E=C,Q=F(R,le),C=Q):(f=C,C=t)}else f=C,C=t;else f=C,C=t}else f=C,C=t;else f=C,C=t;return C}function wge(){var C;return r.substr(f,2)===H?(C=H,f+=2):(C=t,N===0&&Be(q)),C===t&&(r.charCodeAt(f)===124?(C=_,f++):(C=t,N===0&&Be(X))),C}function YE(){var C,Q,R,U,le,Qe;if(C=f,Q=iK(),Q!==t)if(r.charCodeAt(f)===61?(R=W,f++):(R=t,N===0&&Be(Z)),R!==t)if(U=z1(),U!==t){for(le=[],Qe=Me();Qe!==t;)le.push(Qe),Qe=Me();le!==t?(E=C,Q=A(Q,U),C=Q):(f=C,C=t)}else f=C,C=t;else f=C,C=t;else f=C,C=t;if(C===t)if(C=f,Q=iK(),Q!==t)if(r.charCodeAt(f)===61?(R=W,f++):(R=t,N===0&&Be(Z)),R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();U!==t?(E=C,Q=ne(Q),C=Q):(f=C,C=t)}else f=C,C=t;else f=C,C=t;return C}function Bge(){var C,Q,R,U,le,Qe,ft,It,Gr,fi,os;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t)if(r.charCodeAt(f)===40?(R=ue,f++):(R=t,N===0&&Be(te)),R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();if(U!==t)if(le=vr(),le!==t){for(Qe=[],ft=Me();ft!==t;)Qe.push(ft),ft=Me();if(Qe!==t)if(r.charCodeAt(f)===41?(ft=O,f++):(ft=t,N===0&&Be(T)),ft!==t){for(It=[],Gr=Me();Gr!==t;)It.push(Gr),Gr=Me();if(It!==t){for(Gr=[],fi=Np();fi!==t;)Gr.push(fi),fi=Np();if(Gr!==t){for(fi=[],os=Me();os!==t;)fi.push(os),os=Me();fi!==t?(E=C,Q=ce(le,Gr),C=Q):(f=C,C=t)}else f=C,C=t}else f=C,C=t}else f=C,C=t;else f=C,C=t}else f=C,C=t;else f=C,C=t}else f=C,C=t;else f=C,C=t;if(C===t){for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t)if(r.charCodeAt(f)===123?(R=he,f++):(R=t,N===0&&Be(Pe)),R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();if(U!==t)if(le=vr(),le!==t){for(Qe=[],ft=Me();ft!==t;)Qe.push(ft),ft=Me();if(Qe!==t)if(r.charCodeAt(f)===125?(ft=De,f++):(ft=t,N===0&&Be(Re)),ft!==t){for(It=[],Gr=Me();Gr!==t;)It.push(Gr),Gr=Me();if(It!==t){for(Gr=[],fi=Np();fi!==t;)Gr.push(fi),fi=Np();if(Gr!==t){for(fi=[],os=Me();os!==t;)fi.push(os),os=Me();fi!==t?(E=C,Q=se(le,Gr),C=Q):(f=C,C=t)}else f=C,C=t}else f=C,C=t}else f=C,C=t;else f=C,C=t}else f=C,C=t;else f=C,C=t}else f=C,C=t;else f=C,C=t;if(C===t){for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t){for(R=[],U=YE();U!==t;)R.push(U),U=YE();if(R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();if(U!==t){if(le=[],Qe=W1(),Qe!==t)for(;Qe!==t;)le.push(Qe),Qe=W1();else le=t;if(le!==t){for(Qe=[],ft=Me();ft!==t;)Qe.push(ft),ft=Me();Qe!==t?(E=C,Q=Ae(R,le),C=Q):(f=C,C=t)}else f=C,C=t}else f=C,C=t}else f=C,C=t}else f=C,C=t;if(C===t){for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t){if(R=[],U=YE(),U!==t)for(;U!==t;)R.push(U),U=YE();else R=t;if(R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();U!==t?(E=C,Q=ye(R),C=Q):(f=C,C=t)}else f=C,C=t}else f=C,C=t}}}return C}function J1(){var C,Q,R,U,le;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t){if(R=[],U=qE(),U!==t)for(;U!==t;)R.push(U),U=qE();else R=t;if(R!==t){for(U=[],le=Me();le!==t;)U.push(le),le=Me();U!==t?(E=C,Q=ge(R),C=Q):(f=C,C=t)}else f=C,C=t}else f=C,C=t;return C}function W1(){var C,Q,R;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();if(Q!==t?(R=Np(),R!==t?(E=C,Q=oe(R),C=Q):(f=C,C=t)):(f=C,C=t),C===t){for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();Q!==t?(R=qE(),R!==t?(E=C,Q=oe(R),C=Q):(f=C,C=t)):(f=C,C=t)}return C}function Np(){var C,Q,R,U,le;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();return Q!==t?(Ye.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(ie)),R===t&&(R=null),R!==t?(U=Qge(),U!==t?(le=qE(),le!==t?(E=C,Q=G(R,U,le),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C}function Qge(){var C;return r.substr(f,2)===fe?(C=fe,f+=2):(C=t,N===0&&Be(re)),C===t&&(r.substr(f,2)===de?(C=de,f+=2):(C=t,N===0&&Be(Ze)),C===t&&(r.charCodeAt(f)===62?(C=vt,f++):(C=t,N===0&&Be(mt)),C===t&&(r.substr(f,3)===Lr?(C=Lr,f+=3):(C=t,N===0&&Be(ti)),C===t&&(r.substr(f,2)===ui?(C=ui,f+=2):(C=t,N===0&&Be(gr)),C===t&&(r.charCodeAt(f)===60?(C=gi,f++):(C=t,N===0&&Be(ri))))))),C}function qE(){var C,Q,R;for(C=f,Q=[],R=Me();R!==t;)Q.push(R),R=Me();return Q!==t?(R=z1(),R!==t?(E=C,Q=oe(R),C=Q):(f=C,C=t)):(f=C,C=t),C}function z1(){var C,Q,R;if(C=f,Q=[],R=V1(),R!==t)for(;R!==t;)Q.push(R),R=V1();else Q=t;return Q!==t&&(E=C,Q=Ms(Q)),C=Q,C}function V1(){var C,Q;return C=f,Q=bge(),Q!==t&&(E=C,Q=fr(Q)),C=Q,C===t&&(C=f,Q=Sge(),Q!==t&&(E=C,Q=fr(Q)),C=Q,C===t&&(C=f,Q=vge(),Q!==t&&(E=C,Q=fr(Q)),C=Q,C===t&&(C=f,Q=xge(),Q!==t&&(E=C,Q=fr(Q)),C=Q))),C}function bge(){var C,Q,R,U;return C=f,r.substr(f,2)===Ei?(Q=Ei,f+=2):(Q=t,N===0&&Be(rs)),Q!==t?(R=Dge(),R!==t?(r.charCodeAt(f)===39?(U=ua,f++):(U=t,N===0&&Be(CA)),U!==t?(E=C,Q=gg(R),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C}function Sge(){var C,Q,R,U;return C=f,r.charCodeAt(f)===39?(Q=ua,f++):(Q=t,N===0&&Be(CA)),Q!==t?(R=Pge(),R!==t?(r.charCodeAt(f)===39?(U=ua,f++):(U=t,N===0&&Be(CA)),U!==t?(E=C,Q=gg(R),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C}function vge(){var C,Q,R,U;if(C=f,r.substr(f,2)===is?(Q=is,f+=2):(Q=t,N===0&&Be(mA)),Q!==t&&(E=C,Q=ga()),C=Q,C===t)if(C=f,r.charCodeAt(f)===34?(Q=wp,f++):(Q=t,N===0&&Be(EA)),Q!==t){for(R=[],U=X1();U!==t;)R.push(U),U=X1();R!==t?(r.charCodeAt(f)===34?(U=wp,f++):(U=t,N===0&&Be(EA)),U!==t?(E=C,Q=IA(R),C=Q):(f=C,C=t)):(f=C,C=t)}else f=C,C=t;return C}function xge(){var C,Q,R;if(C=f,Q=[],R=Z1(),R!==t)for(;R!==t;)Q.push(R),R=Z1();else Q=t;return Q!==t&&(E=C,Q=IA(Q)),C=Q,C}function X1(){var C,Q;return C=f,Q=tK(),Q!==t&&(E=C,Q=yr(Q)),C=Q,C===t&&(C=f,Q=rK(),Q!==t&&(E=C,Q=Tl(Q)),C=Q,C===t&&(C=f,Q=aS(),Q!==t&&(E=C,Q=fg(Q)),C=Q,C===t&&(C=f,Q=kge(),Q!==t&&(E=C,Q=Io(Q)),C=Q))),C}function Z1(){var C,Q;return C=f,Q=tK(),Q!==t&&(E=C,Q=hg(Q)),C=Q,C===t&&(C=f,Q=rK(),Q!==t&&(E=C,Q=Bp(Q)),C=Q,C===t&&(C=f,Q=aS(),Q!==t&&(E=C,Q=Qp(Q)),C=Q,C===t&&(C=f,Q=Tge(),Q!==t&&(E=C,Q=Sr(Q)),C=Q,C===t&&(C=f,Q=Fge(),Q!==t&&(E=C,Q=Io(Q)),C=Q)))),C}function Pge(){var C,Q,R;for(C=f,Q=[],Ri.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(yo));R!==t;)Q.push(R),Ri.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(yo));return Q!==t&&(E=C,Q=Tn(Q)),C=Q,C}function kge(){var C,Q,R;if(C=f,Q=[],R=_1(),R===t&&(ae.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(yt))),R!==t)for(;R!==t;)Q.push(R),R=_1(),R===t&&(ae.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(yt)));else Q=t;return Q!==t&&(E=C,Q=Tn(Q)),C=Q,C}function _1(){var C,Q,R;return C=f,r.substr(f,2)===Nl?(Q=Nl,f+=2):(Q=t,N===0&&Be(Nn)),Q!==t&&(E=C,Q=ns()),C=Q,C===t&&(C=f,r.charCodeAt(f)===92?(Q=ss,f++):(Q=t,N===0&&Be(ut)),Q!==t?(wo.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(At)),R!==t?(E=C,Q=ln(R),C=Q):(f=C,C=t)):(f=C,C=t)),C}function Dge(){var C,Q,R;for(C=f,Q=[],R=$1(),R===t&&(Ri.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(yo)));R!==t;)Q.push(R),R=$1(),R===t&&(Ri.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(yo)));return Q!==t&&(E=C,Q=Tn(Q)),C=Q,C}function $1(){var C,Q,R;return C=f,r.substr(f,2)===b?(Q=b,f+=2):(Q=t,N===0&&Be(Tt)),Q!==t&&(E=C,Q=pg()),C=Q,C===t&&(C=f,r.substr(f,2)===Ll?(Q=Ll,f+=2):(Q=t,N===0&&Be(bp)),Q!==t&&(E=C,Q=Sp()),C=Q,C===t&&(C=f,r.charCodeAt(f)===92?(Q=ss,f++):(Q=t,N===0&&Be(ut)),Q!==t?(vp.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(xp)),R!==t?(E=C,Q=Pp(),C=Q):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===j?(Q=j,f+=2):(Q=t,N===0&&Be(Et)),Q!==t&&(E=C,Q=yA()),C=Q,C===t&&(C=f,r.substr(f,2)===zi?(Q=zi,f+=2):(Q=t,N===0&&Be(Ol)),Q!==t&&(E=C,Q=ze()),C=Q,C===t&&(C=f,r.substr(f,2)===fa?(Q=fa,f+=2):(Q=t,N===0&&Be(dg)),Q!==t&&(E=C,Q=OE()),C=Q,C===t&&(C=f,r.substr(f,2)===kp?(Q=kp,f+=2):(Q=t,N===0&&Be(ME)),Q!==t&&(E=C,Q=sr()),C=Q,C===t&&(C=f,r.substr(f,2)===Ln?(Q=Ln,f+=2):(Q=t,N===0&&Be(Ml)),Q!==t&&(E=C,Q=Dp()),C=Q,C===t&&(C=f,r.charCodeAt(f)===92?(Q=ss,f++):(Q=t,N===0&&Be(ut)),Q!==t?(Ks.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(ha)),R!==t?(E=C,Q=ln(R),C=Q):(f=C,C=t)):(f=C,C=t),C===t&&(C=Rge()))))))))),C}function Rge(){var C,Q,R,U,le,Qe,ft,It,Gr,fi,os,AS;return C=f,r.charCodeAt(f)===92?(Q=ss,f++):(Q=t,N===0&&Be(ut)),Q!==t?(R=nS(),R!==t?(E=C,Q=cn(R),C=Q):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===Te?(Q=Te,f+=2):(Q=t,N===0&&Be(Cg)),Q!==t?(R=f,U=f,le=nS(),le!==t?(Qe=Mn(),Qe!==t?(le=[le,Qe],U=le):(f=U,U=t)):(f=U,U=t),U===t&&(U=nS()),U!==t?R=r.substring(R,f):R=U,R!==t?(E=C,Q=cn(R),C=Q):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===Kl?(Q=Kl,f+=2):(Q=t,N===0&&Be(Us)),Q!==t?(R=f,U=f,le=Mn(),le!==t?(Qe=Mn(),Qe!==t?(ft=Mn(),ft!==t?(It=Mn(),It!==t?(le=[le,Qe,ft,It],U=le):(f=U,U=t)):(f=U,U=t)):(f=U,U=t)):(f=U,U=t),U!==t?R=r.substring(R,f):R=U,R!==t?(E=C,Q=cn(R),C=Q):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===Ul?(Q=Ul,f+=2):(Q=t,N===0&&Be(wA)),Q!==t?(R=f,U=f,le=Mn(),le!==t?(Qe=Mn(),Qe!==t?(ft=Mn(),ft!==t?(It=Mn(),It!==t?(Gr=Mn(),Gr!==t?(fi=Mn(),fi!==t?(os=Mn(),os!==t?(AS=Mn(),AS!==t?(le=[le,Qe,ft,It,Gr,fi,os,AS],U=le):(f=U,U=t)):(f=U,U=t)):(f=U,U=t)):(f=U,U=t)):(f=U,U=t)):(f=U,U=t)):(f=U,U=t)):(f=U,U=t),U!==t?R=r.substring(R,f):R=U,R!==t?(E=C,Q=mg(R),C=Q):(f=C,C=t)):(f=C,C=t)))),C}function nS(){var C;return Eg.test(r.charAt(f))?(C=r.charAt(f),f++):(C=t,N===0&&Be(pa)),C}function Mn(){var C;return da.test(r.charAt(f))?(C=r.charAt(f),f++):(C=t,N===0&&Be(tt)),C}function Fge(){var C,Q,R,U,le;if(C=f,Q=[],R=f,r.charCodeAt(f)===92?(U=ss,f++):(U=t,N===0&&Be(ut)),U!==t?(r.length>f?(le=r.charAt(f),f++):(le=t,N===0&&Be(Bo)),le!==t?(E=R,U=ln(le),R=U):(f=R,R=t)):(f=R,R=t),R===t&&(R=f,r.substr(f,2)===BA?(U=BA,f+=2):(U=t,N===0&&Be(Rp)),U!==t&&(E=R,U=Ca()),R=U,R===t&&(R=f,U=f,N++,le=nK(),N--,le===t?U=void 0:(f=U,U=t),U!==t?(r.length>f?(le=r.charAt(f),f++):(le=t,N===0&&Be(Bo)),le!==t?(E=R,U=ln(le),R=U):(f=R,R=t)):(f=R,R=t))),R!==t)for(;R!==t;)Q.push(R),R=f,r.charCodeAt(f)===92?(U=ss,f++):(U=t,N===0&&Be(ut)),U!==t?(r.length>f?(le=r.charAt(f),f++):(le=t,N===0&&Be(Bo)),le!==t?(E=R,U=ln(le),R=U):(f=R,R=t)):(f=R,R=t),R===t&&(R=f,r.substr(f,2)===BA?(U=BA,f+=2):(U=t,N===0&&Be(Rp)),U!==t&&(E=R,U=Ca()),R=U,R===t&&(R=f,U=f,N++,le=nK(),N--,le===t?U=void 0:(f=U,U=t),U!==t?(r.length>f?(le=r.charAt(f),f++):(le=t,N===0&&Be(Bo)),le!==t?(E=R,U=ln(le),R=U):(f=R,R=t)):(f=R,R=t)));else Q=t;return Q!==t&&(E=C,Q=Tn(Q)),C=Q,C}function sS(){var C,Q,R,U,le,Qe;if(C=f,r.charCodeAt(f)===45?(Q=Hl,f++):(Q=t,N===0&&Be(jl)),Q===t&&(r.charCodeAt(f)===43?(Q=QA,f++):(Q=t,N===0&&Be(ma))),Q===t&&(Q=null),Q!==t){if(R=[],Ye.test(r.charAt(f))?(U=r.charAt(f),f++):(U=t,N===0&&Be(ie)),U!==t)for(;U!==t;)R.push(U),Ye.test(r.charAt(f))?(U=r.charAt(f),f++):(U=t,N===0&&Be(ie));else R=t;if(R!==t)if(r.charCodeAt(f)===46?(U=Fp,f++):(U=t,N===0&&Be(KE)),U!==t){if(le=[],Ye.test(r.charAt(f))?(Qe=r.charAt(f),f++):(Qe=t,N===0&&Be(ie)),Qe!==t)for(;Qe!==t;)le.push(Qe),Ye.test(r.charAt(f))?(Qe=r.charAt(f),f++):(Qe=t,N===0&&Be(ie));else le=t;le!==t?(E=C,Q=Gl(Q,R,le),C=Q):(f=C,C=t)}else f=C,C=t;else f=C,C=t}else f=C,C=t;if(C===t){if(C=f,r.charCodeAt(f)===45?(Q=Hl,f++):(Q=t,N===0&&Be(jl)),Q===t&&(r.charCodeAt(f)===43?(Q=QA,f++):(Q=t,N===0&&Be(ma))),Q===t&&(Q=null),Q!==t){if(R=[],Ye.test(r.charAt(f))?(U=r.charAt(f),f++):(U=t,N===0&&Be(ie)),U!==t)for(;U!==t;)R.push(U),Ye.test(r.charAt(f))?(U=r.charAt(f),f++):(U=t,N===0&&Be(ie));else R=t;R!==t?(E=C,Q=UE(Q,R),C=Q):(f=C,C=t)}else f=C,C=t;if(C===t&&(C=f,Q=aS(),Q!==t&&(E=C,Q=Tp(Q)),C=Q,C===t&&(C=f,Q=Wl(),Q!==t&&(E=C,Q=Yl(Q)),C=Q,C===t)))if(C=f,r.charCodeAt(f)===40?(Q=ue,f++):(Q=t,N===0&&Be(te)),Q!==t){for(R=[],U=Me();U!==t;)R.push(U),U=Me();if(R!==t)if(U=eK(),U!==t){for(le=[],Qe=Me();Qe!==t;)le.push(Qe),Qe=Me();le!==t?(r.charCodeAt(f)===41?(Qe=O,f++):(Qe=t,N===0&&Be(T)),Qe!==t?(E=C,Q=Or(U),C=Q):(f=C,C=t)):(f=C,C=t)}else f=C,C=t;else f=C,C=t}else f=C,C=t}return C}function oS(){var C,Q,R,U,le,Qe,ft,It;if(C=f,Q=sS(),Q!==t){for(R=[],U=f,le=[],Qe=Me();Qe!==t;)le.push(Qe),Qe=Me();if(le!==t)if(r.charCodeAt(f)===42?(Qe=HE,f++):(Qe=t,N===0&&Be(Hs)),Qe===t&&(r.charCodeAt(f)===47?(Qe=js,f++):(Qe=t,N===0&&Be(Ig))),Qe!==t){for(ft=[],It=Me();It!==t;)ft.push(It),It=Me();ft!==t?(It=sS(),It!==t?(E=U,le=bA(Q,Qe,It),U=le):(f=U,U=t)):(f=U,U=t)}else f=U,U=t;else f=U,U=t;for(;U!==t;){for(R.push(U),U=f,le=[],Qe=Me();Qe!==t;)le.push(Qe),Qe=Me();if(le!==t)if(r.charCodeAt(f)===42?(Qe=HE,f++):(Qe=t,N===0&&Be(Hs)),Qe===t&&(r.charCodeAt(f)===47?(Qe=js,f++):(Qe=t,N===0&&Be(Ig))),Qe!==t){for(ft=[],It=Me();It!==t;)ft.push(It),It=Me();ft!==t?(It=sS(),It!==t?(E=U,le=bA(Q,Qe,It),U=le):(f=U,U=t)):(f=U,U=t)}else f=U,U=t;else f=U,U=t}R!==t?(E=C,Q=D(Q,R),C=Q):(f=C,C=t)}else f=C,C=t;return C}function eK(){var C,Q,R,U,le,Qe,ft,It;if(C=f,Q=oS(),Q!==t){for(R=[],U=f,le=[],Qe=Me();Qe!==t;)le.push(Qe),Qe=Me();if(le!==t)if(r.charCodeAt(f)===43?(Qe=QA,f++):(Qe=t,N===0&&Be(ma)),Qe===t&&(r.charCodeAt(f)===45?(Qe=Hl,f++):(Qe=t,N===0&&Be(jl))),Qe!==t){for(ft=[],It=Me();It!==t;)ft.push(It),It=Me();ft!==t?(It=oS(),It!==t?(E=U,le=Y(Q,Qe,It),U=le):(f=U,U=t)):(f=U,U=t)}else f=U,U=t;else f=U,U=t;for(;U!==t;){for(R.push(U),U=f,le=[],Qe=Me();Qe!==t;)le.push(Qe),Qe=Me();if(le!==t)if(r.charCodeAt(f)===43?(Qe=QA,f++):(Qe=t,N===0&&Be(ma)),Qe===t&&(r.charCodeAt(f)===45?(Qe=Hl,f++):(Qe=t,N===0&&Be(jl))),Qe!==t){for(ft=[],It=Me();It!==t;)ft.push(It),It=Me();ft!==t?(It=oS(),It!==t?(E=U,le=Y(Q,Qe,It),U=le):(f=U,U=t)):(f=U,U=t)}else f=U,U=t;else f=U,U=t}R!==t?(E=C,Q=D(Q,R),C=Q):(f=C,C=t)}else f=C,C=t;return C}function tK(){var C,Q,R,U,le,Qe;if(C=f,r.substr(f,3)===pe?(Q=pe,f+=3):(Q=t,N===0&&Be(Le)),Q!==t){for(R=[],U=Me();U!==t;)R.push(U),U=Me();if(R!==t)if(U=eK(),U!==t){for(le=[],Qe=Me();Qe!==t;)le.push(Qe),Qe=Me();le!==t?(r.substr(f,2)===ke?(Qe=ke,f+=2):(Qe=t,N===0&&Be(Je)),Qe!==t?(E=C,Q=pt(U),C=Q):(f=C,C=t)):(f=C,C=t)}else f=C,C=t;else f=C,C=t}else f=C,C=t;return C}function rK(){var C,Q,R,U;return C=f,r.substr(f,2)===Xt?(Q=Xt,f+=2):(Q=t,N===0&&Be(Ea)),Q!==t?(R=vr(),R!==t?(r.charCodeAt(f)===41?(U=O,f++):(U=t,N===0&&Be(T)),U!==t?(E=C,Q=D1(R),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C}function aS(){var C,Q,R,U,le,Qe;return C=f,r.substr(f,2)===Gs?(Q=Gs,f+=2):(Q=t,N===0&&Be(yg)),Q!==t?(R=Wl(),R!==t?(r.substr(f,2)===Jb?(U=Jb,f+=2):(U=t,N===0&&Be(R1)),U!==t?(le=J1(),le!==t?(r.charCodeAt(f)===125?(Qe=De,f++):(Qe=t,N===0&&Be(Re)),Qe!==t?(E=C,Q=F1(R,le),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===Gs?(Q=Gs,f+=2):(Q=t,N===0&&Be(yg)),Q!==t?(R=Wl(),R!==t?(r.substr(f,3)===Wb?(U=Wb,f+=3):(U=t,N===0&&Be(T1)),U!==t?(E=C,Q=N1(R),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===Gs?(Q=Gs,f+=2):(Q=t,N===0&&Be(yg)),Q!==t?(R=Wl(),R!==t?(r.substr(f,2)===zb?(U=zb,f+=2):(U=t,N===0&&Be(L1)),U!==t?(le=J1(),le!==t?(r.charCodeAt(f)===125?(Qe=De,f++):(Qe=t,N===0&&Be(Re)),Qe!==t?(E=C,Q=O1(R,le),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===Gs?(Q=Gs,f+=2):(Q=t,N===0&&Be(yg)),Q!==t?(R=Wl(),R!==t?(r.substr(f,3)===Vb?(U=Vb,f+=3):(U=t,N===0&&Be(M1)),U!==t?(E=C,Q=K1(R),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.substr(f,2)===Gs?(Q=Gs,f+=2):(Q=t,N===0&&Be(yg)),Q!==t?(R=Wl(),R!==t?(r.charCodeAt(f)===125?(U=De,f++):(U=t,N===0&&Be(Re)),U!==t?(E=C,Q=Xb(R),C=Q):(f=C,C=t)):(f=C,C=t)):(f=C,C=t),C===t&&(C=f,r.charCodeAt(f)===36?(Q=U1,f++):(Q=t,N===0&&Be(H1)),Q!==t?(R=Wl(),R!==t?(E=C,Q=Xb(R),C=Q):(f=C,C=t)):(f=C,C=t)))))),C}function Tge(){var C,Q,R;return C=f,Q=Nge(),Q!==t?(E=f,R=j1(Q),R?R=void 0:R=t,R!==t?(E=C,Q=G1(Q),C=Q):(f=C,C=t)):(f=C,C=t),C}function Nge(){var C,Q,R,U,le;if(C=f,Q=[],R=f,U=f,N++,le=sK(),N--,le===t?U=void 0:(f=U,U=t),U!==t?(r.length>f?(le=r.charAt(f),f++):(le=t,N===0&&Be(Bo)),le!==t?(E=R,U=ln(le),R=U):(f=R,R=t)):(f=R,R=t),R!==t)for(;R!==t;)Q.push(R),R=f,U=f,N++,le=sK(),N--,le===t?U=void 0:(f=U,U=t),U!==t?(r.length>f?(le=r.charAt(f),f++):(le=t,N===0&&Be(Bo)),le!==t?(E=R,U=ln(le),R=U):(f=R,R=t)):(f=R,R=t);else Q=t;return Q!==t&&(E=C,Q=Tn(Q)),C=Q,C}function iK(){var C,Q,R;if(C=f,Q=[],Zb.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(_b)),R!==t)for(;R!==t;)Q.push(R),Zb.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(_b));else Q=t;return Q!==t&&(E=C,Q=$b()),C=Q,C}function Wl(){var C,Q,R;if(C=f,Q=[],ql.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(jE)),R!==t)for(;R!==t;)Q.push(R),ql.test(r.charAt(f))?(R=r.charAt(f),f++):(R=t,N===0&&Be(jE));else Q=t;return Q!==t&&(E=C,Q=$b()),C=Q,C}function nK(){var C;return eS.test(r.charAt(f))?(C=r.charAt(f),f++):(C=t,N===0&&Be(tS)),C}function sK(){var C;return rS.test(r.charAt(f))?(C=r.charAt(f),f++):(C=t,N===0&&Be(GE)),C}function Me(){var C,Q;if(C=[],Jl.test(r.charAt(f))?(Q=r.charAt(f),f++):(Q=t,N===0&&Be(wg)),Q!==t)for(;Q!==t;)C.push(Q),Jl.test(r.charAt(f))?(Q=r.charAt(f),f++):(Q=t,N===0&&Be(wg));else C=t;return C}if(ee=n(),ee!==t&&f===r.length)return ee;throw ee!==t&&f{"use strict";function Mfe(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function tc(r,e,t,i){this.message=r,this.expected=e,this.found=t,this.location=i,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,tc)}Mfe(tc,Error);tc.buildMessage=function(r,e){var t={literal:function(c){return'"'+n(c.text)+'"'},class:function(c){var u="",g;for(g=0;g0){for(g=1,h=1;gH&&(H=S,q=[]),q.push(ie))}function Re(ie,G){return new tc(ie,null,null,G)}function se(ie,G,fe){return new tc(tc.buildMessage(ie,G),ie,G,fe)}function Ae(){var ie,G,fe,re;return ie=S,G=ye(),G!==t?(r.charCodeAt(S)===47?(fe=s,S++):(fe=t,_===0&&De(o)),fe!==t?(re=ye(),re!==t?(P=ie,G=a(G,re),ie=G):(S=ie,ie=t)):(S=ie,ie=t)):(S=ie,ie=t),ie===t&&(ie=S,G=ye(),G!==t&&(P=ie,G=l(G)),ie=G),ie}function ye(){var ie,G,fe,re;return ie=S,G=ge(),G!==t?(r.charCodeAt(S)===64?(fe=c,S++):(fe=t,_===0&&De(u)),fe!==t?(re=Ye(),re!==t?(P=ie,G=g(G,re),ie=G):(S=ie,ie=t)):(S=ie,ie=t)):(S=ie,ie=t),ie===t&&(ie=S,G=ge(),G!==t&&(P=ie,G=h(G)),ie=G),ie}function ge(){var ie,G,fe,re,de;return ie=S,r.charCodeAt(S)===64?(G=c,S++):(G=t,_===0&&De(u)),G!==t?(fe=oe(),fe!==t?(r.charCodeAt(S)===47?(re=s,S++):(re=t,_===0&&De(o)),re!==t?(de=oe(),de!==t?(P=ie,G=p(),ie=G):(S=ie,ie=t)):(S=ie,ie=t)):(S=ie,ie=t)):(S=ie,ie=t),ie===t&&(ie=S,G=oe(),G!==t&&(P=ie,G=p()),ie=G),ie}function oe(){var ie,G,fe;if(ie=S,G=[],d.test(r.charAt(S))?(fe=r.charAt(S),S++):(fe=t,_===0&&De(m)),fe!==t)for(;fe!==t;)G.push(fe),d.test(r.charAt(S))?(fe=r.charAt(S),S++):(fe=t,_===0&&De(m));else G=t;return G!==t&&(P=ie,G=p()),ie=G,ie}function Ye(){var ie,G,fe;if(ie=S,G=[],y.test(r.charAt(S))?(fe=r.charAt(S),S++):(fe=t,_===0&&De(B)),fe!==t)for(;fe!==t;)G.push(fe),y.test(r.charAt(S))?(fe=r.charAt(S),S++):(fe=t,_===0&&De(B));else G=t;return G!==t&&(P=ie,G=p()),ie=G,ie}if(X=n(),X!==t&&S===r.length)return X;throw X!==t&&S{"use strict";function yU(r){return typeof r>"u"||r===null}function Ufe(r){return typeof r=="object"&&r!==null}function Hfe(r){return Array.isArray(r)?r:yU(r)?[]:[r]}function jfe(r,e){var t,i,n,s;if(e)for(s=Object.keys(e),t=0,i=s.length;t{"use strict";function Xp(r,e){Error.call(this),this.name="YAMLException",this.reason=r,this.mark=e,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}Xp.prototype=Object.create(Error.prototype);Xp.prototype.constructor=Xp;Xp.prototype.toString=function(e){var t=this.name+": ";return t+=this.reason||"(unknown reason)",!e&&this.mark&&(t+=" "+this.mark.toString()),t};wU.exports=Xp});var bU=I((LZe,QU)=>{"use strict";var BU=ic();function HS(r,e,t,i,n){this.name=r,this.buffer=e,this.position=t,this.line=i,this.column=n}HS.prototype.getSnippet=function(e,t){var i,n,s,o,a;if(!this.buffer)return null;for(e=e||4,t=t||75,i="",n=this.position;n>0&&`\0\r -\x85\u2028\u2029`.indexOf(this.buffer.charAt(n-1))===-1;)if(n-=1,this.position-n>t/2-1){i=" ... ",n+=5;break}for(s="",o=this.position;ot/2-1){s=" ... ",o-=5;break}return a=this.buffer.slice(n,o),BU.repeat(" ",e)+i+a+s+` -`+BU.repeat(" ",e+this.position-n+i.length)+"^"};HS.prototype.toString=function(e){var t,i="";return this.name&&(i+='in "'+this.name+'" '),i+="at line "+(this.line+1)+", column "+(this.column+1),e||(t=this.getSnippet(),t&&(i+=`: -`+t)),i};QU.exports=HS});var ni=I((OZe,vU)=>{"use strict";var SU=Tg(),qfe=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],Jfe=["scalar","sequence","mapping"];function Wfe(r){var e={};return r!==null&&Object.keys(r).forEach(function(t){r[t].forEach(function(i){e[String(i)]=t})}),e}function zfe(r,e){if(e=e||{},Object.keys(e).forEach(function(t){if(qfe.indexOf(t)===-1)throw new SU('Unknown option "'+t+'" is met in definition of "'+r+'" YAML type.')}),this.tag=r,this.kind=e.kind||null,this.resolve=e.resolve||function(){return!0},this.construct=e.construct||function(t){return t},this.instanceOf=e.instanceOf||null,this.predicate=e.predicate||null,this.represent=e.represent||null,this.defaultStyle=e.defaultStyle||null,this.styleAliases=Wfe(e.styleAliases||null),Jfe.indexOf(this.kind)===-1)throw new SU('Unknown kind "'+this.kind+'" is specified for "'+r+'" YAML type.')}vU.exports=zfe});var nc=I((MZe,PU)=>{"use strict";var xU=ic(),pI=Tg(),Vfe=ni();function jS(r,e,t){var i=[];return r.include.forEach(function(n){t=jS(n,e,t)}),r[e].forEach(function(n){t.forEach(function(s,o){s.tag===n.tag&&s.kind===n.kind&&i.push(o)}),t.push(n)}),t.filter(function(n,s){return i.indexOf(s)===-1})}function Xfe(){var r={scalar:{},sequence:{},mapping:{},fallback:{}},e,t;function i(n){r[n.kind][n.tag]=r.fallback[n.tag]=n}for(e=0,t=arguments.length;e{"use strict";var Zfe=ni();kU.exports=new Zfe("tag:yaml.org,2002:str",{kind:"scalar",construct:function(r){return r!==null?r:""}})});var FU=I((UZe,RU)=>{"use strict";var _fe=ni();RU.exports=new _fe("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(r){return r!==null?r:[]}})});var NU=I((HZe,TU)=>{"use strict";var $fe=ni();TU.exports=new $fe("tag:yaml.org,2002:map",{kind:"mapping",construct:function(r){return r!==null?r:{}}})});var dI=I((jZe,LU)=>{"use strict";var ehe=nc();LU.exports=new ehe({explicit:[DU(),FU(),NU()]})});var MU=I((GZe,OU)=>{"use strict";var the=ni();function rhe(r){if(r===null)return!0;var e=r.length;return e===1&&r==="~"||e===4&&(r==="null"||r==="Null"||r==="NULL")}function ihe(){return null}function nhe(r){return r===null}OU.exports=new the("tag:yaml.org,2002:null",{kind:"scalar",resolve:rhe,construct:ihe,predicate:nhe,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})});var UU=I((YZe,KU)=>{"use strict";var she=ni();function ohe(r){if(r===null)return!1;var e=r.length;return e===4&&(r==="true"||r==="True"||r==="TRUE")||e===5&&(r==="false"||r==="False"||r==="FALSE")}function ahe(r){return r==="true"||r==="True"||r==="TRUE"}function Ahe(r){return Object.prototype.toString.call(r)==="[object Boolean]"}KU.exports=new she("tag:yaml.org,2002:bool",{kind:"scalar",resolve:ohe,construct:ahe,predicate:Ahe,represent:{lowercase:function(r){return r?"true":"false"},uppercase:function(r){return r?"TRUE":"FALSE"},camelcase:function(r){return r?"True":"False"}},defaultStyle:"lowercase"})});var jU=I((qZe,HU)=>{"use strict";var lhe=ic(),che=ni();function uhe(r){return 48<=r&&r<=57||65<=r&&r<=70||97<=r&&r<=102}function ghe(r){return 48<=r&&r<=55}function fhe(r){return 48<=r&&r<=57}function hhe(r){if(r===null)return!1;var e=r.length,t=0,i=!1,n;if(!e)return!1;if(n=r[t],(n==="-"||n==="+")&&(n=r[++t]),n==="0"){if(t+1===e)return!0;if(n=r[++t],n==="b"){for(t++;t=0?"0b"+r.toString(2):"-0b"+r.toString(2).slice(1)},octal:function(r){return r>=0?"0"+r.toString(8):"-0"+r.toString(8).slice(1)},decimal:function(r){return r.toString(10)},hexadecimal:function(r){return r>=0?"0x"+r.toString(16).toUpperCase():"-0x"+r.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})});var qU=I((JZe,YU)=>{"use strict";var GU=ic(),Che=ni(),mhe=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function Ehe(r){return!(r===null||!mhe.test(r)||r[r.length-1]==="_")}function Ihe(r){var e,t,i,n;return e=r.replace(/_/g,"").toLowerCase(),t=e[0]==="-"?-1:1,n=[],"+-".indexOf(e[0])>=0&&(e=e.slice(1)),e===".inf"?t===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:e===".nan"?NaN:e.indexOf(":")>=0?(e.split(":").forEach(function(s){n.unshift(parseFloat(s,10))}),e=0,i=1,n.forEach(function(s){e+=s*i,i*=60}),t*e):t*parseFloat(e,10)}var yhe=/^[-+]?[0-9]+e/;function whe(r,e){var t;if(isNaN(r))switch(e){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===r)switch(e){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===r)switch(e){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(GU.isNegativeZero(r))return"-0.0";return t=r.toString(10),yhe.test(t)?t.replace("e",".e"):t}function Bhe(r){return Object.prototype.toString.call(r)==="[object Number]"&&(r%1!==0||GU.isNegativeZero(r))}YU.exports=new Che("tag:yaml.org,2002:float",{kind:"scalar",resolve:Ehe,construct:Ihe,predicate:Bhe,represent:whe,defaultStyle:"lowercase"})});var GS=I((WZe,JU)=>{"use strict";var Qhe=nc();JU.exports=new Qhe({include:[dI()],implicit:[MU(),UU(),jU(),qU()]})});var YS=I((zZe,WU)=>{"use strict";var bhe=nc();WU.exports=new bhe({include:[GS()]})});var ZU=I((VZe,XU)=>{"use strict";var She=ni(),zU=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),VU=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function vhe(r){return r===null?!1:zU.exec(r)!==null||VU.exec(r)!==null}function xhe(r){var e,t,i,n,s,o,a,l=0,c=null,u,g,h;if(e=zU.exec(r),e===null&&(e=VU.exec(r)),e===null)throw new Error("Date resolve error");if(t=+e[1],i=+e[2]-1,n=+e[3],!e[4])return new Date(Date.UTC(t,i,n));if(s=+e[4],o=+e[5],a=+e[6],e[7]){for(l=e[7].slice(0,3);l.length<3;)l+="0";l=+l}return e[9]&&(u=+e[10],g=+(e[11]||0),c=(u*60+g)*6e4,e[9]==="-"&&(c=-c)),h=new Date(Date.UTC(t,i,n,s,o,a,l)),c&&h.setTime(h.getTime()-c),h}function Phe(r){return r.toISOString()}XU.exports=new She("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:vhe,construct:xhe,instanceOf:Date,represent:Phe})});var $U=I((XZe,_U)=>{"use strict";var khe=ni();function Dhe(r){return r==="<<"||r===null}_U.exports=new khe("tag:yaml.org,2002:merge",{kind:"scalar",resolve:Dhe})});var r2=I((ZZe,t2)=>{"use strict";var sc;try{e2=J,sc=e2("buffer").Buffer}catch{}var e2,Rhe=ni(),qS=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= -\r`;function Fhe(r){if(r===null)return!1;var e,t,i=0,n=r.length,s=qS;for(t=0;t64)){if(e<0)return!1;i+=6}return i%8===0}function The(r){var e,t,i=r.replace(/[\r\n=]/g,""),n=i.length,s=qS,o=0,a=[];for(e=0;e>16&255),a.push(o>>8&255),a.push(o&255)),o=o<<6|s.indexOf(i.charAt(e));return t=n%4*6,t===0?(a.push(o>>16&255),a.push(o>>8&255),a.push(o&255)):t===18?(a.push(o>>10&255),a.push(o>>2&255)):t===12&&a.push(o>>4&255),sc?sc.from?sc.from(a):new sc(a):a}function Nhe(r){var e="",t=0,i,n,s=r.length,o=qS;for(i=0;i>18&63],e+=o[t>>12&63],e+=o[t>>6&63],e+=o[t&63]),t=(t<<8)+r[i];return n=s%3,n===0?(e+=o[t>>18&63],e+=o[t>>12&63],e+=o[t>>6&63],e+=o[t&63]):n===2?(e+=o[t>>10&63],e+=o[t>>4&63],e+=o[t<<2&63],e+=o[64]):n===1&&(e+=o[t>>2&63],e+=o[t<<4&63],e+=o[64],e+=o[64]),e}function Lhe(r){return sc&&sc.isBuffer(r)}t2.exports=new Rhe("tag:yaml.org,2002:binary",{kind:"scalar",resolve:Fhe,construct:The,predicate:Lhe,represent:Nhe})});var n2=I(($Ze,i2)=>{"use strict";var Ohe=ni(),Mhe=Object.prototype.hasOwnProperty,Khe=Object.prototype.toString;function Uhe(r){if(r===null)return!0;var e=[],t,i,n,s,o,a=r;for(t=0,i=a.length;t{"use strict";var jhe=ni(),Ghe=Object.prototype.toString;function Yhe(r){if(r===null)return!0;var e,t,i,n,s,o=r;for(s=new Array(o.length),e=0,t=o.length;e{"use strict";var Jhe=ni(),Whe=Object.prototype.hasOwnProperty;function zhe(r){if(r===null)return!0;var e,t=r;for(e in t)if(Whe.call(t,e)&&t[e]!==null)return!1;return!0}function Vhe(r){return r!==null?r:{}}a2.exports=new Jhe("tag:yaml.org,2002:set",{kind:"mapping",resolve:zhe,construct:Vhe})});var Lg=I((r_e,l2)=>{"use strict";var Xhe=nc();l2.exports=new Xhe({include:[YS()],implicit:[ZU(),$U()],explicit:[r2(),n2(),o2(),A2()]})});var u2=I((i_e,c2)=>{"use strict";var Zhe=ni();function _he(){return!0}function $he(){}function epe(){return""}function tpe(r){return typeof r>"u"}c2.exports=new Zhe("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:_he,construct:$he,predicate:tpe,represent:epe})});var f2=I((n_e,g2)=>{"use strict";var rpe=ni();function ipe(r){if(r===null||r.length===0)return!1;var e=r,t=/\/([gim]*)$/.exec(r),i="";return!(e[0]==="/"&&(t&&(i=t[1]),i.length>3||e[e.length-i.length-1]!=="/"))}function npe(r){var e=r,t=/\/([gim]*)$/.exec(r),i="";return e[0]==="/"&&(t&&(i=t[1]),e=e.slice(1,e.length-i.length-1)),new RegExp(e,i)}function spe(r){var e="/"+r.source+"/";return r.global&&(e+="g"),r.multiline&&(e+="m"),r.ignoreCase&&(e+="i"),e}function ope(r){return Object.prototype.toString.call(r)==="[object RegExp]"}g2.exports=new rpe("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:ipe,construct:npe,predicate:ope,represent:spe})});var d2=I((s_e,p2)=>{"use strict";var CI;try{h2=J,CI=h2("esprima")}catch{typeof window<"u"&&(CI=window.esprima)}var h2,ape=ni();function Ape(r){if(r===null)return!1;try{var e="("+r+")",t=CI.parse(e,{range:!0});return!(t.type!=="Program"||t.body.length!==1||t.body[0].type!=="ExpressionStatement"||t.body[0].expression.type!=="ArrowFunctionExpression"&&t.body[0].expression.type!=="FunctionExpression")}catch{return!1}}function lpe(r){var e="("+r+")",t=CI.parse(e,{range:!0}),i=[],n;if(t.type!=="Program"||t.body.length!==1||t.body[0].type!=="ExpressionStatement"||t.body[0].expression.type!=="ArrowFunctionExpression"&&t.body[0].expression.type!=="FunctionExpression")throw new Error("Failed to resolve function");return t.body[0].expression.params.forEach(function(s){i.push(s.name)}),n=t.body[0].expression.body.range,t.body[0].expression.body.type==="BlockStatement"?new Function(i,e.slice(n[0]+1,n[1]-1)):new Function(i,"return "+e.slice(n[0],n[1]))}function cpe(r){return r.toString()}function upe(r){return Object.prototype.toString.call(r)==="[object Function]"}p2.exports=new ape("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:Ape,construct:lpe,predicate:upe,represent:cpe})});var Zp=I((a_e,m2)=>{"use strict";var C2=nc();m2.exports=C2.DEFAULT=new C2({include:[Lg()],explicit:[u2(),f2(),d2()]})});var O2=I((A_e,_p)=>{"use strict";var Qa=ic(),b2=Tg(),gpe=bU(),S2=Lg(),fpe=Zp(),kA=Object.prototype.hasOwnProperty,mI=1,v2=2,x2=3,EI=4,JS=1,hpe=2,E2=3,ppe=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,dpe=/[\x85\u2028\u2029]/,Cpe=/[,\[\]\{\}]/,P2=/^(?:!|!!|![a-z\-]+!)$/i,k2=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function I2(r){return Object.prototype.toString.call(r)}function vo(r){return r===10||r===13}function ac(r){return r===9||r===32}function hn(r){return r===9||r===32||r===10||r===13}function Og(r){return r===44||r===91||r===93||r===123||r===125}function mpe(r){var e;return 48<=r&&r<=57?r-48:(e=r|32,97<=e&&e<=102?e-97+10:-1)}function Epe(r){return r===120?2:r===117?4:r===85?8:0}function Ipe(r){return 48<=r&&r<=57?r-48:-1}function y2(r){return r===48?"\0":r===97?"\x07":r===98?"\b":r===116||r===9?" ":r===110?` -`:r===118?"\v":r===102?"\f":r===114?"\r":r===101?"\x1B":r===32?" ":r===34?'"':r===47?"/":r===92?"\\":r===78?"\x85":r===95?"\xA0":r===76?"\u2028":r===80?"\u2029":""}function ype(r){return r<=65535?String.fromCharCode(r):String.fromCharCode((r-65536>>10)+55296,(r-65536&1023)+56320)}var D2=new Array(256),R2=new Array(256);for(oc=0;oc<256;oc++)D2[oc]=y2(oc)?1:0,R2[oc]=y2(oc);var oc;function wpe(r,e){this.input=r,this.filename=e.filename||null,this.schema=e.schema||fpe,this.onWarning=e.onWarning||null,this.legacy=e.legacy||!1,this.json=e.json||!1,this.listener=e.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=r.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function F2(r,e){return new b2(e,new gpe(r.filename,r.input,r.position,r.line,r.position-r.lineStart))}function gt(r,e){throw F2(r,e)}function II(r,e){r.onWarning&&r.onWarning.call(null,F2(r,e))}var w2={YAML:function(e,t,i){var n,s,o;e.version!==null&>(e,"duplication of %YAML directive"),i.length!==1&>(e,"YAML directive accepts exactly one argument"),n=/^([0-9]+)\.([0-9]+)$/.exec(i[0]),n===null&>(e,"ill-formed argument of the YAML directive"),s=parseInt(n[1],10),o=parseInt(n[2],10),s!==1&>(e,"unacceptable YAML version of the document"),e.version=i[0],e.checkLineBreaks=o<2,o!==1&&o!==2&&II(e,"unsupported YAML version of the document")},TAG:function(e,t,i){var n,s;i.length!==2&>(e,"TAG directive accepts exactly two arguments"),n=i[0],s=i[1],P2.test(n)||gt(e,"ill-formed tag handle (first argument) of the TAG directive"),kA.call(e.tagMap,n)&>(e,'there is a previously declared suffix for "'+n+'" tag handle'),k2.test(s)||gt(e,"ill-formed tag prefix (second argument) of the TAG directive"),e.tagMap[n]=s}};function PA(r,e,t,i){var n,s,o,a;if(e1&&(r.result+=Qa.repeat(` -`,e-1))}function Bpe(r,e,t){var i,n,s,o,a,l,c,u,g=r.kind,h=r.result,p;if(p=r.input.charCodeAt(r.position),hn(p)||Og(p)||p===35||p===38||p===42||p===33||p===124||p===62||p===39||p===34||p===37||p===64||p===96||(p===63||p===45)&&(n=r.input.charCodeAt(r.position+1),hn(n)||t&&Og(n)))return!1;for(r.kind="scalar",r.result="",s=o=r.position,a=!1;p!==0;){if(p===58){if(n=r.input.charCodeAt(r.position+1),hn(n)||t&&Og(n))break}else if(p===35){if(i=r.input.charCodeAt(r.position-1),hn(i))break}else{if(r.position===r.lineStart&&yI(r)||t&&Og(p))break;if(vo(p))if(l=r.line,c=r.lineStart,u=r.lineIndent,Jr(r,!1,-1),r.lineIndent>=e){a=!0,p=r.input.charCodeAt(r.position);continue}else{r.position=o,r.line=l,r.lineStart=c,r.lineIndent=u;break}}a&&(PA(r,s,o,!1),zS(r,r.line-l),s=o=r.position,a=!1),ac(p)||(o=r.position+1),p=r.input.charCodeAt(++r.position)}return PA(r,s,o,!1),r.result?!0:(r.kind=g,r.result=h,!1)}function Qpe(r,e){var t,i,n;if(t=r.input.charCodeAt(r.position),t!==39)return!1;for(r.kind="scalar",r.result="",r.position++,i=n=r.position;(t=r.input.charCodeAt(r.position))!==0;)if(t===39)if(PA(r,i,r.position,!0),t=r.input.charCodeAt(++r.position),t===39)i=r.position,r.position++,n=r.position;else return!0;else vo(t)?(PA(r,i,n,!0),zS(r,Jr(r,!1,e)),i=n=r.position):r.position===r.lineStart&&yI(r)?gt(r,"unexpected end of the document within a single quoted scalar"):(r.position++,n=r.position);gt(r,"unexpected end of the stream within a single quoted scalar")}function bpe(r,e){var t,i,n,s,o,a;if(a=r.input.charCodeAt(r.position),a!==34)return!1;for(r.kind="scalar",r.result="",r.position++,t=i=r.position;(a=r.input.charCodeAt(r.position))!==0;){if(a===34)return PA(r,t,r.position,!0),r.position++,!0;if(a===92){if(PA(r,t,r.position,!0),a=r.input.charCodeAt(++r.position),vo(a))Jr(r,!1,e);else if(a<256&&D2[a])r.result+=R2[a],r.position++;else if((o=Epe(a))>0){for(n=o,s=0;n>0;n--)a=r.input.charCodeAt(++r.position),(o=mpe(a))>=0?s=(s<<4)+o:gt(r,"expected hexadecimal character");r.result+=ype(s),r.position++}else gt(r,"unknown escape sequence");t=i=r.position}else vo(a)?(PA(r,t,i,!0),zS(r,Jr(r,!1,e)),t=i=r.position):r.position===r.lineStart&&yI(r)?gt(r,"unexpected end of the document within a double quoted scalar"):(r.position++,i=r.position)}gt(r,"unexpected end of the stream within a double quoted scalar")}function Spe(r,e){var t=!0,i,n=r.tag,s,o=r.anchor,a,l,c,u,g,h={},p,d,m,y;if(y=r.input.charCodeAt(r.position),y===91)l=93,g=!1,s=[];else if(y===123)l=125,g=!0,s={};else return!1;for(r.anchor!==null&&(r.anchorMap[r.anchor]=s),y=r.input.charCodeAt(++r.position);y!==0;){if(Jr(r,!0,e),y=r.input.charCodeAt(r.position),y===l)return r.position++,r.tag=n,r.anchor=o,r.kind=g?"mapping":"sequence",r.result=s,!0;t||gt(r,"missed comma between flow collection entries"),d=p=m=null,c=u=!1,y===63&&(a=r.input.charCodeAt(r.position+1),hn(a)&&(c=u=!0,r.position++,Jr(r,!0,e))),i=r.line,Kg(r,e,mI,!1,!0),d=r.tag,p=r.result,Jr(r,!0,e),y=r.input.charCodeAt(r.position),(u||r.line===i)&&y===58&&(c=!0,y=r.input.charCodeAt(++r.position),Jr(r,!0,e),Kg(r,e,mI,!1,!0),m=r.result),g?Mg(r,s,h,d,p,m):c?s.push(Mg(r,null,h,d,p,m)):s.push(p),Jr(r,!0,e),y=r.input.charCodeAt(r.position),y===44?(t=!0,y=r.input.charCodeAt(++r.position)):t=!1}gt(r,"unexpected end of the stream within a flow collection")}function vpe(r,e){var t,i,n=JS,s=!1,o=!1,a=e,l=0,c=!1,u,g;if(g=r.input.charCodeAt(r.position),g===124)i=!1;else if(g===62)i=!0;else return!1;for(r.kind="scalar",r.result="";g!==0;)if(g=r.input.charCodeAt(++r.position),g===43||g===45)JS===n?n=g===43?E2:hpe:gt(r,"repeat of a chomping mode identifier");else if((u=Ipe(g))>=0)u===0?gt(r,"bad explicit indentation width of a block scalar; it cannot be less than one"):o?gt(r,"repeat of an indentation width identifier"):(a=e+u-1,o=!0);else break;if(ac(g)){do g=r.input.charCodeAt(++r.position);while(ac(g));if(g===35)do g=r.input.charCodeAt(++r.position);while(!vo(g)&&g!==0)}for(;g!==0;){for(WS(r),r.lineIndent=0,g=r.input.charCodeAt(r.position);(!o||r.lineIndenta&&(a=r.lineIndent),vo(g)){l++;continue}if(r.lineIndente)&&l!==0)gt(r,"bad indentation of a sequence entry");else if(r.lineIndente)&&(Kg(r,e,EI,!0,n)&&(d?h=r.result:p=r.result),d||(Mg(r,c,u,g,h,p,s,o),g=h=p=null),Jr(r,!0,-1),y=r.input.charCodeAt(r.position)),r.lineIndent>e&&y!==0)gt(r,"bad indentation of a mapping entry");else if(r.lineIndente?l=1:r.lineIndent===e?l=0:r.lineIndente?l=1:r.lineIndent===e?l=0:r.lineIndent tag; it should be "scalar", not "'+r.kind+'"'),g=0,h=r.implicitTypes.length;g tag; it should be "'+p.kind+'", not "'+r.kind+'"'),p.resolve(r.result)?(r.result=p.construct(r.result),r.anchor!==null&&(r.anchorMap[r.anchor]=r.result)):gt(r,"cannot resolve a node with !<"+r.tag+"> explicit tag")):gt(r,"unknown tag !<"+r.tag+">");return r.listener!==null&&r.listener("close",r),r.tag!==null||r.anchor!==null||u}function Rpe(r){var e=r.position,t,i,n,s=!1,o;for(r.version=null,r.checkLineBreaks=r.legacy,r.tagMap={},r.anchorMap={};(o=r.input.charCodeAt(r.position))!==0&&(Jr(r,!0,-1),o=r.input.charCodeAt(r.position),!(r.lineIndent>0||o!==37));){for(s=!0,o=r.input.charCodeAt(++r.position),t=r.position;o!==0&&!hn(o);)o=r.input.charCodeAt(++r.position);for(i=r.input.slice(t,r.position),n=[],i.length<1&>(r,"directive name must not be less than one character in length");o!==0;){for(;ac(o);)o=r.input.charCodeAt(++r.position);if(o===35){do o=r.input.charCodeAt(++r.position);while(o!==0&&!vo(o));break}if(vo(o))break;for(t=r.position;o!==0&&!hn(o);)o=r.input.charCodeAt(++r.position);n.push(r.input.slice(t,r.position))}o!==0&&WS(r),kA.call(w2,i)?w2[i](r,i,n):II(r,'unknown document directive "'+i+'"')}if(Jr(r,!0,-1),r.lineIndent===0&&r.input.charCodeAt(r.position)===45&&r.input.charCodeAt(r.position+1)===45&&r.input.charCodeAt(r.position+2)===45?(r.position+=3,Jr(r,!0,-1)):s&>(r,"directives end mark is expected"),Kg(r,r.lineIndent-1,EI,!1,!0),Jr(r,!0,-1),r.checkLineBreaks&&dpe.test(r.input.slice(e,r.position))&&II(r,"non-ASCII line breaks are interpreted as content"),r.documents.push(r.result),r.position===r.lineStart&&yI(r)){r.input.charCodeAt(r.position)===46&&(r.position+=3,Jr(r,!0,-1));return}if(r.position"u"&&(t=e,e=null);var i=T2(r,t);if(typeof e!="function")return i;for(var n=0,s=i.length;n"u"&&(t=e,e=null),N2(r,e,Qa.extend({schema:S2},t))}function Tpe(r,e){return L2(r,Qa.extend({schema:S2},e))}_p.exports.loadAll=N2;_p.exports.load=L2;_p.exports.safeLoadAll=Fpe;_p.exports.safeLoad=Tpe});var oH=I((l_e,_S)=>{"use strict";var ed=ic(),td=Tg(),Npe=Zp(),Lpe=Lg(),q2=Object.prototype.toString,J2=Object.prototype.hasOwnProperty,Ope=9,$p=10,Mpe=13,Kpe=32,Upe=33,Hpe=34,W2=35,jpe=37,Gpe=38,Ype=39,qpe=42,z2=44,Jpe=45,V2=58,Wpe=61,zpe=62,Vpe=63,Xpe=64,X2=91,Z2=93,Zpe=96,_2=123,_pe=124,$2=125,Ti={};Ti[0]="\\0";Ti[7]="\\a";Ti[8]="\\b";Ti[9]="\\t";Ti[10]="\\n";Ti[11]="\\v";Ti[12]="\\f";Ti[13]="\\r";Ti[27]="\\e";Ti[34]='\\"';Ti[92]="\\\\";Ti[133]="\\N";Ti[160]="\\_";Ti[8232]="\\L";Ti[8233]="\\P";var $pe=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"];function ede(r,e){var t,i,n,s,o,a,l;if(e===null)return{};for(t={},i=Object.keys(e),n=0,s=i.length;n0?r.charCodeAt(s-1):null,h=h&&U2(o,a)}else{for(s=0;si&&r[g+1]!==" ",g=s);else if(!Ug(o))return wI;a=s>0?r.charCodeAt(s-1):null,h=h&&U2(o,a)}c=c||u&&s-g-1>i&&r[g+1]!==" "}return!l&&!c?h&&!n(r)?tH:rH:t>9&&eH(r)?wI:c?nH:iH}function ode(r,e,t,i){r.dump=function(){if(e.length===0)return"''";if(!r.noCompatMode&&$pe.indexOf(e)!==-1)return"'"+e+"'";var n=r.indent*Math.max(1,t),s=r.lineWidth===-1?-1:Math.max(Math.min(r.lineWidth,40),r.lineWidth-n),o=i||r.flowLevel>-1&&t>=r.flowLevel;function a(l){return rde(r,l)}switch(sde(e,o,r.indent,s,a)){case tH:return e;case rH:return"'"+e.replace(/'/g,"''")+"'";case iH:return"|"+H2(e,r.indent)+j2(K2(e,n));case nH:return">"+H2(e,r.indent)+j2(K2(ade(e,s),n));case wI:return'"'+Ade(e,s)+'"';default:throw new td("impossible error: invalid scalar style")}}()}function H2(r,e){var t=eH(r)?String(e):"",i=r[r.length-1]===` -`,n=i&&(r[r.length-2]===` -`||r===` -`),s=n?"+":i?"":"-";return t+s+` -`}function j2(r){return r[r.length-1]===` -`?r.slice(0,-1):r}function ade(r,e){for(var t=/(\n+)([^\n]*)/g,i=function(){var c=r.indexOf(` -`);return c=c!==-1?c:r.length,t.lastIndex=c,G2(r.slice(0,c),e)}(),n=r[0]===` -`||r[0]===" ",s,o;o=t.exec(r);){var a=o[1],l=o[2];s=l[0]===" ",i+=a+(!n&&!s&&l!==""?` -`:"")+G2(l,e),n=s}return i}function G2(r,e){if(r===""||r[0]===" ")return r;for(var t=/ [^ ]/g,i,n=0,s,o=0,a=0,l="";i=t.exec(r);)a=i.index,a-n>e&&(s=o>n?o:a,l+=` -`+r.slice(n,s),n=s+1),o=a;return l+=` -`,r.length-n>e&&o>n?l+=r.slice(n,o)+` -`+r.slice(o+1):l+=r.slice(n),l.slice(1)}function Ade(r){for(var e="",t,i,n,s=0;s=55296&&t<=56319&&(i=r.charCodeAt(s+1),i>=56320&&i<=57343)){e+=M2((t-55296)*1024+i-56320+65536),s++;continue}n=Ti[t],e+=!n&&Ug(t)?r[s]:n||M2(t)}return e}function lde(r,e,t){var i="",n=r.tag,s,o;for(s=0,o=t.length;s1024&&(u+="? "),u+=r.dump+(r.condenseFlow?'"':"")+":"+(r.condenseFlow?"":" "),Ac(r,e,c,!1,!1)&&(u+=r.dump,i+=u));r.tag=n,r.dump="{"+i+"}"}function gde(r,e,t,i){var n="",s=r.tag,o=Object.keys(t),a,l,c,u,g,h;if(r.sortKeys===!0)o.sort();else if(typeof r.sortKeys=="function")o.sort(r.sortKeys);else if(r.sortKeys)throw new td("sortKeys must be a boolean or a function");for(a=0,l=o.length;a1024,g&&(r.dump&&$p===r.dump.charCodeAt(0)?h+="?":h+="? "),h+=r.dump,g&&(h+=VS(r,e)),Ac(r,e+1,u,!0,g)&&(r.dump&&$p===r.dump.charCodeAt(0)?h+=":":h+=": ",h+=r.dump,n+=h));r.tag=s,r.dump=n||"{}"}function Y2(r,e,t){var i,n,s,o,a,l;for(n=t?r.explicitTypes:r.implicitTypes,s=0,o=n.length;s tag resolver accepts not "'+l+'" style');r.dump=i}return!0}return!1}function Ac(r,e,t,i,n,s){r.tag=null,r.dump=t,Y2(r,t,!1)||Y2(r,t,!0);var o=q2.call(r.dump);i&&(i=r.flowLevel<0||r.flowLevel>e);var a=o==="[object Object]"||o==="[object Array]",l,c;if(a&&(l=r.duplicates.indexOf(t),c=l!==-1),(r.tag!==null&&r.tag!=="?"||c||r.indent!==2&&e>0)&&(n=!1),c&&r.usedDuplicates[l])r.dump="*ref_"+l;else{if(a&&c&&!r.usedDuplicates[l]&&(r.usedDuplicates[l]=!0),o==="[object Object]")i&&Object.keys(r.dump).length!==0?(gde(r,e,r.dump,n),c&&(r.dump="&ref_"+l+r.dump)):(ude(r,e,r.dump),c&&(r.dump="&ref_"+l+" "+r.dump));else if(o==="[object Array]"){var u=r.noArrayIndent&&e>0?e-1:e;i&&r.dump.length!==0?(cde(r,u,r.dump,n),c&&(r.dump="&ref_"+l+r.dump)):(lde(r,u,r.dump),c&&(r.dump="&ref_"+l+" "+r.dump))}else if(o==="[object String]")r.tag!=="?"&&ode(r,r.dump,e,s);else{if(r.skipInvalid)return!1;throw new td("unacceptable kind of an object to dump "+o)}r.tag!==null&&r.tag!=="?"&&(r.dump="!<"+r.tag+"> "+r.dump)}return!0}function fde(r,e){var t=[],i=[],n,s;for(XS(r,t,i),n=0,s=i.length;n{"use strict";var BI=O2(),aH=oH();function QI(r){return function(){throw new Error("Function "+r+" is deprecated and cannot be used.")}}Rr.exports.Type=ni();Rr.exports.Schema=nc();Rr.exports.FAILSAFE_SCHEMA=dI();Rr.exports.JSON_SCHEMA=GS();Rr.exports.CORE_SCHEMA=YS();Rr.exports.DEFAULT_SAFE_SCHEMA=Lg();Rr.exports.DEFAULT_FULL_SCHEMA=Zp();Rr.exports.load=BI.load;Rr.exports.loadAll=BI.loadAll;Rr.exports.safeLoad=BI.safeLoad;Rr.exports.safeLoadAll=BI.safeLoadAll;Rr.exports.dump=aH.dump;Rr.exports.safeDump=aH.safeDump;Rr.exports.YAMLException=Tg();Rr.exports.MINIMAL_SCHEMA=dI();Rr.exports.SAFE_SCHEMA=Lg();Rr.exports.DEFAULT_SCHEMA=Zp();Rr.exports.scan=QI("scan");Rr.exports.parse=QI("parse");Rr.exports.compose=QI("compose");Rr.exports.addConstructor=QI("addConstructor")});var cH=I((u_e,lH)=>{"use strict";var pde=AH();lH.exports=pde});var gH=I((g_e,uH)=>{"use strict";function dde(r,e){function t(){this.constructor=r}t.prototype=e.prototype,r.prototype=new t}function lc(r,e,t,i){this.message=r,this.expected=e,this.found=t,this.location=i,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,lc)}dde(lc,Error);lc.buildMessage=function(r,e){var t={literal:function(c){return'"'+n(c.text)+'"'},class:function(c){var u="",g;for(g=0;g0){for(g=1,h=1;g({[Le]:pe})))},H=function(D){return D},q=function(D){return D},_=Ks("correct indentation"),X=" ",W=sr(" ",!1),Z=function(D){return D.length===bA*Ig},A=function(D){return D.length===(bA+1)*Ig},ne=function(){return bA++,!0},ue=function(){return bA--,!0},te=function(){return dg()},O=Ks("pseudostring"),T=/^[^\r\n\t ?:,\][{}#&*!|>'"%@`\-]/,ce=Ln(["\r",` -`," "," ","?",":",",","]","[","{","}","#","&","*","!","|",">","'",'"',"%","@","`","-"],!0,!1),he=/^[^\r\n\t ,\][{}:#"']/,Pe=Ln(["\r",` -`," "," ",",","]","[","{","}",":","#",'"',"'"],!0,!1),De=function(){return dg().replace(/^ *| *$/g,"")},Re="--",se=sr("--",!1),Ae=/^[a-zA-Z\/0-9]/,ye=Ln([["a","z"],["A","Z"],"/",["0","9"]],!1,!1),ge=/^[^\r\n\t :,]/,oe=Ln(["\r",` -`," "," ",":",","],!0,!1),Ye="null",ie=sr("null",!1),G=function(){return null},fe="true",re=sr("true",!1),de=function(){return!0},Ze="false",vt=sr("false",!1),mt=function(){return!1},Lr=Ks("string"),ti='"',ui=sr('"',!1),gr=function(){return""},gi=function(D){return D},ri=function(D){return D.join("")},Ms=/^[^"\\\0-\x1F\x7F]/,fr=Ln(['"',"\\",["\0",""],"\x7F"],!0,!1),Ei='\\"',rs=sr('\\"',!1),ua=function(){return'"'},CA="\\\\",gg=sr("\\\\",!1),is=function(){return"\\"},mA="\\/",ga=sr("\\/",!1),wp=function(){return"/"},EA="\\b",IA=sr("\\b",!1),yr=function(){return"\b"},Tl="\\f",fg=sr("\\f",!1),Io=function(){return"\f"},hg="\\n",Bp=sr("\\n",!1),Qp=function(){return` -`},Sr="\\r",Ri=sr("\\r",!1),yo=function(){return"\r"},Tn="\\t",ae=sr("\\t",!1),yt=function(){return" "},Nl="\\u",Nn=sr("\\u",!1),ns=function(D,Y,pe,Le){return String.fromCharCode(parseInt(`0x${D}${Y}${pe}${Le}`))},ss=/^[0-9a-fA-F]/,ut=Ln([["0","9"],["a","f"],["A","F"]],!1,!1),wo=Ks("blank space"),At=/^[ \t]/,ln=Ln([" "," "],!1,!1),b=Ks("white space"),Tt=/^[ \t\n\r]/,pg=Ln([" "," ",` -`,"\r"],!1,!1),Ll=`\r -`,bp=sr(`\r -`,!1),Sp=` -`,vp=sr(` -`,!1),xp="\r",Pp=sr("\r",!1),j=0,Et=0,yA=[{line:1,column:1}],zi=0,Ol=[],ze=0,fa;if("startRule"in e){if(!(e.startRule in i))throw new Error(`Can't start parsing from rule "`+e.startRule+'".');n=i[e.startRule]}function dg(){return r.substring(Et,j)}function OE(){return cn(Et,j)}function kp(D,Y){throw Y=Y!==void 0?Y:cn(Et,j),Kl([Ks(D)],r.substring(Et,j),Y)}function ME(D,Y){throw Y=Y!==void 0?Y:cn(Et,j),Cg(D,Y)}function sr(D,Y){return{type:"literal",text:D,ignoreCase:Y}}function Ln(D,Y,pe){return{type:"class",parts:D,inverted:Y,ignoreCase:pe}}function Ml(){return{type:"any"}}function Dp(){return{type:"end"}}function Ks(D){return{type:"other",description:D}}function ha(D){var Y=yA[D],pe;if(Y)return Y;for(pe=D-1;!yA[pe];)pe--;for(Y=yA[pe],Y={line:Y.line,column:Y.column};pezi&&(zi=j,Ol=[]),Ol.push(D))}function Cg(D,Y){return new lc(D,null,null,Y)}function Kl(D,Y,pe){return new lc(lc.buildMessage(D,Y),D,Y,pe)}function Us(){var D;return D=mg(),D}function Ul(){var D,Y,pe;for(D=j,Y=[],pe=wA();pe!==t;)Y.push(pe),pe=wA();return Y!==t&&(Et=D,Y=s(Y)),D=Y,D}function wA(){var D,Y,pe,Le,ke;return D=j,Y=da(),Y!==t?(r.charCodeAt(j)===45?(pe=o,j++):(pe=t,ze===0&&Te(a)),pe!==t?(Le=Or(),Le!==t?(ke=pa(),ke!==t?(Et=D,Y=l(ke),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t),D}function mg(){var D,Y,pe;for(D=j,Y=[],pe=Eg();pe!==t;)Y.push(pe),pe=Eg();return Y!==t&&(Et=D,Y=c(Y)),D=Y,D}function Eg(){var D,Y,pe,Le,ke,Je,pt,Xt,Ea;if(D=j,Y=Or(),Y===t&&(Y=null),Y!==t){if(pe=j,r.charCodeAt(j)===35?(Le=u,j++):(Le=t,ze===0&&Te(g)),Le!==t){if(ke=[],Je=j,pt=j,ze++,Xt=js(),ze--,Xt===t?pt=void 0:(j=pt,pt=t),pt!==t?(r.length>j?(Xt=r.charAt(j),j++):(Xt=t,ze===0&&Te(h)),Xt!==t?(pt=[pt,Xt],Je=pt):(j=Je,Je=t)):(j=Je,Je=t),Je!==t)for(;Je!==t;)ke.push(Je),Je=j,pt=j,ze++,Xt=js(),ze--,Xt===t?pt=void 0:(j=pt,pt=t),pt!==t?(r.length>j?(Xt=r.charAt(j),j++):(Xt=t,ze===0&&Te(h)),Xt!==t?(pt=[pt,Xt],Je=pt):(j=Je,Je=t)):(j=Je,Je=t);else ke=t;ke!==t?(Le=[Le,ke],pe=Le):(j=pe,pe=t)}else j=pe,pe=t;if(pe===t&&(pe=null),pe!==t){if(Le=[],ke=Hs(),ke!==t)for(;ke!==t;)Le.push(ke),ke=Hs();else Le=t;Le!==t?(Et=D,Y=p(),D=Y):(j=D,D=t)}else j=D,D=t}else j=D,D=t;if(D===t&&(D=j,Y=da(),Y!==t?(pe=Rp(),pe!==t?(Le=Or(),Le===t&&(Le=null),Le!==t?(r.charCodeAt(j)===58?(ke=d,j++):(ke=t,ze===0&&Te(m)),ke!==t?(Je=Or(),Je===t&&(Je=null),Je!==t?(pt=pa(),pt!==t?(Et=D,Y=y(pe,pt),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t),D===t&&(D=j,Y=da(),Y!==t?(pe=Ca(),pe!==t?(Le=Or(),Le===t&&(Le=null),Le!==t?(r.charCodeAt(j)===58?(ke=d,j++):(ke=t,ze===0&&Te(m)),ke!==t?(Je=Or(),Je===t&&(Je=null),Je!==t?(pt=pa(),pt!==t?(Et=D,Y=y(pe,pt),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t),D===t))){if(D=j,Y=da(),Y!==t)if(pe=Ca(),pe!==t)if(Le=Or(),Le!==t)if(ke=jl(),ke!==t){if(Je=[],pt=Hs(),pt!==t)for(;pt!==t;)Je.push(pt),pt=Hs();else Je=t;Je!==t?(Et=D,Y=y(pe,ke),D=Y):(j=D,D=t)}else j=D,D=t;else j=D,D=t;else j=D,D=t;else j=D,D=t;if(D===t)if(D=j,Y=da(),Y!==t)if(pe=Ca(),pe!==t){if(Le=[],ke=j,Je=Or(),Je===t&&(Je=null),Je!==t?(r.charCodeAt(j)===44?(pt=B,j++):(pt=t,ze===0&&Te(S)),pt!==t?(Xt=Or(),Xt===t&&(Xt=null),Xt!==t?(Ea=Ca(),Ea!==t?(Et=ke,Je=P(pe,Ea),ke=Je):(j=ke,ke=t)):(j=ke,ke=t)):(j=ke,ke=t)):(j=ke,ke=t),ke!==t)for(;ke!==t;)Le.push(ke),ke=j,Je=Or(),Je===t&&(Je=null),Je!==t?(r.charCodeAt(j)===44?(pt=B,j++):(pt=t,ze===0&&Te(S)),pt!==t?(Xt=Or(),Xt===t&&(Xt=null),Xt!==t?(Ea=Ca(),Ea!==t?(Et=ke,Je=P(pe,Ea),ke=Je):(j=ke,ke=t)):(j=ke,ke=t)):(j=ke,ke=t)):(j=ke,ke=t);else Le=t;Le!==t?(ke=Or(),ke===t&&(ke=null),ke!==t?(r.charCodeAt(j)===58?(Je=d,j++):(Je=t,ze===0&&Te(m)),Je!==t?(pt=Or(),pt===t&&(pt=null),pt!==t?(Xt=pa(),Xt!==t?(Et=D,Y=F(pe,Le,Xt),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)}else j=D,D=t;else j=D,D=t}return D}function pa(){var D,Y,pe,Le,ke,Je,pt;if(D=j,Y=j,ze++,pe=j,Le=js(),Le!==t?(ke=tt(),ke!==t?(r.charCodeAt(j)===45?(Je=o,j++):(Je=t,ze===0&&Te(a)),Je!==t?(pt=Or(),pt!==t?(Le=[Le,ke,Je,pt],pe=Le):(j=pe,pe=t)):(j=pe,pe=t)):(j=pe,pe=t)):(j=pe,pe=t),ze--,pe!==t?(j=Y,Y=void 0):Y=t,Y!==t?(pe=Hs(),pe!==t?(Le=Bo(),Le!==t?(ke=Ul(),ke!==t?(Je=BA(),Je!==t?(Et=D,Y=H(ke),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t),D===t&&(D=j,Y=js(),Y!==t?(pe=Bo(),pe!==t?(Le=mg(),Le!==t?(ke=BA(),ke!==t?(Et=D,Y=H(Le),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t),D===t))if(D=j,Y=Hl(),Y!==t){if(pe=[],Le=Hs(),Le!==t)for(;Le!==t;)pe.push(Le),Le=Hs();else pe=t;pe!==t?(Et=D,Y=q(Y),D=Y):(j=D,D=t)}else j=D,D=t;return D}function da(){var D,Y,pe;for(ze++,D=j,Y=[],r.charCodeAt(j)===32?(pe=X,j++):(pe=t,ze===0&&Te(W));pe!==t;)Y.push(pe),r.charCodeAt(j)===32?(pe=X,j++):(pe=t,ze===0&&Te(W));return Y!==t?(Et=j,pe=Z(Y),pe?pe=void 0:pe=t,pe!==t?(Y=[Y,pe],D=Y):(j=D,D=t)):(j=D,D=t),ze--,D===t&&(Y=t,ze===0&&Te(_)),D}function tt(){var D,Y,pe;for(D=j,Y=[],r.charCodeAt(j)===32?(pe=X,j++):(pe=t,ze===0&&Te(W));pe!==t;)Y.push(pe),r.charCodeAt(j)===32?(pe=X,j++):(pe=t,ze===0&&Te(W));return Y!==t?(Et=j,pe=A(Y),pe?pe=void 0:pe=t,pe!==t?(Y=[Y,pe],D=Y):(j=D,D=t)):(j=D,D=t),D}function Bo(){var D;return Et=j,D=ne(),D?D=void 0:D=t,D}function BA(){var D;return Et=j,D=ue(),D?D=void 0:D=t,D}function Rp(){var D;return D=Gl(),D===t&&(D=QA()),D}function Ca(){var D,Y,pe;if(D=Gl(),D===t){if(D=j,Y=[],pe=ma(),pe!==t)for(;pe!==t;)Y.push(pe),pe=ma();else Y=t;Y!==t&&(Et=D,Y=te()),D=Y}return D}function Hl(){var D;return D=Fp(),D===t&&(D=KE(),D===t&&(D=Gl(),D===t&&(D=QA()))),D}function jl(){var D;return D=Fp(),D===t&&(D=Gl(),D===t&&(D=ma())),D}function QA(){var D,Y,pe,Le,ke,Je;if(ze++,D=j,T.test(r.charAt(j))?(Y=r.charAt(j),j++):(Y=t,ze===0&&Te(ce)),Y!==t){for(pe=[],Le=j,ke=Or(),ke===t&&(ke=null),ke!==t?(he.test(r.charAt(j))?(Je=r.charAt(j),j++):(Je=t,ze===0&&Te(Pe)),Je!==t?(ke=[ke,Je],Le=ke):(j=Le,Le=t)):(j=Le,Le=t);Le!==t;)pe.push(Le),Le=j,ke=Or(),ke===t&&(ke=null),ke!==t?(he.test(r.charAt(j))?(Je=r.charAt(j),j++):(Je=t,ze===0&&Te(Pe)),Je!==t?(ke=[ke,Je],Le=ke):(j=Le,Le=t)):(j=Le,Le=t);pe!==t?(Et=D,Y=De(),D=Y):(j=D,D=t)}else j=D,D=t;return ze--,D===t&&(Y=t,ze===0&&Te(O)),D}function ma(){var D,Y,pe,Le,ke;if(D=j,r.substr(j,2)===Re?(Y=Re,j+=2):(Y=t,ze===0&&Te(se)),Y===t&&(Y=null),Y!==t)if(Ae.test(r.charAt(j))?(pe=r.charAt(j),j++):(pe=t,ze===0&&Te(ye)),pe!==t){for(Le=[],ge.test(r.charAt(j))?(ke=r.charAt(j),j++):(ke=t,ze===0&&Te(oe));ke!==t;)Le.push(ke),ge.test(r.charAt(j))?(ke=r.charAt(j),j++):(ke=t,ze===0&&Te(oe));Le!==t?(Et=D,Y=De(),D=Y):(j=D,D=t)}else j=D,D=t;else j=D,D=t;return D}function Fp(){var D,Y;return D=j,r.substr(j,4)===Ye?(Y=Ye,j+=4):(Y=t,ze===0&&Te(ie)),Y!==t&&(Et=D,Y=G()),D=Y,D}function KE(){var D,Y;return D=j,r.substr(j,4)===fe?(Y=fe,j+=4):(Y=t,ze===0&&Te(re)),Y!==t&&(Et=D,Y=de()),D=Y,D===t&&(D=j,r.substr(j,5)===Ze?(Y=Ze,j+=5):(Y=t,ze===0&&Te(vt)),Y!==t&&(Et=D,Y=mt()),D=Y),D}function Gl(){var D,Y,pe,Le;return ze++,D=j,r.charCodeAt(j)===34?(Y=ti,j++):(Y=t,ze===0&&Te(ui)),Y!==t?(r.charCodeAt(j)===34?(pe=ti,j++):(pe=t,ze===0&&Te(ui)),pe!==t?(Et=D,Y=gr(),D=Y):(j=D,D=t)):(j=D,D=t),D===t&&(D=j,r.charCodeAt(j)===34?(Y=ti,j++):(Y=t,ze===0&&Te(ui)),Y!==t?(pe=UE(),pe!==t?(r.charCodeAt(j)===34?(Le=ti,j++):(Le=t,ze===0&&Te(ui)),Le!==t?(Et=D,Y=gi(pe),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)),ze--,D===t&&(Y=t,ze===0&&Te(Lr)),D}function UE(){var D,Y,pe;if(D=j,Y=[],pe=Tp(),pe!==t)for(;pe!==t;)Y.push(pe),pe=Tp();else Y=t;return Y!==t&&(Et=D,Y=ri(Y)),D=Y,D}function Tp(){var D,Y,pe,Le,ke,Je;return Ms.test(r.charAt(j))?(D=r.charAt(j),j++):(D=t,ze===0&&Te(fr)),D===t&&(D=j,r.substr(j,2)===Ei?(Y=Ei,j+=2):(Y=t,ze===0&&Te(rs)),Y!==t&&(Et=D,Y=ua()),D=Y,D===t&&(D=j,r.substr(j,2)===CA?(Y=CA,j+=2):(Y=t,ze===0&&Te(gg)),Y!==t&&(Et=D,Y=is()),D=Y,D===t&&(D=j,r.substr(j,2)===mA?(Y=mA,j+=2):(Y=t,ze===0&&Te(ga)),Y!==t&&(Et=D,Y=wp()),D=Y,D===t&&(D=j,r.substr(j,2)===EA?(Y=EA,j+=2):(Y=t,ze===0&&Te(IA)),Y!==t&&(Et=D,Y=yr()),D=Y,D===t&&(D=j,r.substr(j,2)===Tl?(Y=Tl,j+=2):(Y=t,ze===0&&Te(fg)),Y!==t&&(Et=D,Y=Io()),D=Y,D===t&&(D=j,r.substr(j,2)===hg?(Y=hg,j+=2):(Y=t,ze===0&&Te(Bp)),Y!==t&&(Et=D,Y=Qp()),D=Y,D===t&&(D=j,r.substr(j,2)===Sr?(Y=Sr,j+=2):(Y=t,ze===0&&Te(Ri)),Y!==t&&(Et=D,Y=yo()),D=Y,D===t&&(D=j,r.substr(j,2)===Tn?(Y=Tn,j+=2):(Y=t,ze===0&&Te(ae)),Y!==t&&(Et=D,Y=yt()),D=Y,D===t&&(D=j,r.substr(j,2)===Nl?(Y=Nl,j+=2):(Y=t,ze===0&&Te(Nn)),Y!==t?(pe=Yl(),pe!==t?(Le=Yl(),Le!==t?(ke=Yl(),ke!==t?(Je=Yl(),Je!==t?(Et=D,Y=ns(pe,Le,ke,Je),D=Y):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)):(j=D,D=t)))))))))),D}function Yl(){var D;return ss.test(r.charAt(j))?(D=r.charAt(j),j++):(D=t,ze===0&&Te(ut)),D}function Or(){var D,Y;if(ze++,D=[],At.test(r.charAt(j))?(Y=r.charAt(j),j++):(Y=t,ze===0&&Te(ln)),Y!==t)for(;Y!==t;)D.push(Y),At.test(r.charAt(j))?(Y=r.charAt(j),j++):(Y=t,ze===0&&Te(ln));else D=t;return ze--,D===t&&(Y=t,ze===0&&Te(wo)),D}function HE(){var D,Y;if(ze++,D=[],Tt.test(r.charAt(j))?(Y=r.charAt(j),j++):(Y=t,ze===0&&Te(pg)),Y!==t)for(;Y!==t;)D.push(Y),Tt.test(r.charAt(j))?(Y=r.charAt(j),j++):(Y=t,ze===0&&Te(pg));else D=t;return ze--,D===t&&(Y=t,ze===0&&Te(b)),D}function Hs(){var D,Y,pe,Le,ke,Je;if(D=j,Y=js(),Y!==t){for(pe=[],Le=j,ke=Or(),ke===t&&(ke=null),ke!==t?(Je=js(),Je!==t?(ke=[ke,Je],Le=ke):(j=Le,Le=t)):(j=Le,Le=t);Le!==t;)pe.push(Le),Le=j,ke=Or(),ke===t&&(ke=null),ke!==t?(Je=js(),Je!==t?(ke=[ke,Je],Le=ke):(j=Le,Le=t)):(j=Le,Le=t);pe!==t?(Y=[Y,pe],D=Y):(j=D,D=t)}else j=D,D=t;return D}function js(){var D;return r.substr(j,2)===Ll?(D=Ll,j+=2):(D=t,ze===0&&Te(bp)),D===t&&(r.charCodeAt(j)===10?(D=Sp,j++):(D=t,ze===0&&Te(vp)),D===t&&(r.charCodeAt(j)===13?(D=xp,j++):(D=t,ze===0&&Te(Pp)))),D}let Ig=2,bA=0;if(fa=n(),fa!==t&&j===r.length)return fa;throw fa!==t&&j{"use strict";var wde=r=>{let e=!1,t=!1,i=!1;for(let n=0;n{if(!(typeof r=="string"||Array.isArray(r)))throw new TypeError("Expected the input to be `string | string[]`");e=Object.assign({pascalCase:!1},e);let t=n=>e.pascalCase?n.charAt(0).toUpperCase()+n.slice(1):n;return Array.isArray(r)?r=r.map(n=>n.trim()).filter(n=>n.length).join("-"):r=r.trim(),r.length===0?"":r.length===1?e.pascalCase?r.toUpperCase():r.toLowerCase():(r!==r.toLowerCase()&&(r=wde(r)),r=r.replace(/^[_.\- ]+/,"").toLowerCase().replace(/[_.\- ]+(\w|$)/g,(n,s)=>s.toUpperCase()).replace(/\d+(\w|$)/g,n=>n.toUpperCase()),t(r))};ev.exports=CH;ev.exports.default=CH});var EH=I((m_e,Bde)=>{Bde.exports=[{name:"AppVeyor",constant:"APPVEYOR",env:"APPVEYOR",pr:"APPVEYOR_PULL_REQUEST_NUMBER"},{name:"Azure Pipelines",constant:"AZURE_PIPELINES",env:"SYSTEM_TEAMFOUNDATIONCOLLECTIONURI",pr:"SYSTEM_PULLREQUEST_PULLREQUESTID"},{name:"Appcircle",constant:"APPCIRCLE",env:"AC_APPCIRCLE"},{name:"Bamboo",constant:"BAMBOO",env:"bamboo_planKey"},{name:"Bitbucket Pipelines",constant:"BITBUCKET",env:"BITBUCKET_COMMIT",pr:"BITBUCKET_PR_ID"},{name:"Bitrise",constant:"BITRISE",env:"BITRISE_IO",pr:"BITRISE_PULL_REQUEST"},{name:"Buddy",constant:"BUDDY",env:"BUDDY_WORKSPACE_ID",pr:"BUDDY_EXECUTION_PULL_REQUEST_ID"},{name:"Buildkite",constant:"BUILDKITE",env:"BUILDKITE",pr:{env:"BUILDKITE_PULL_REQUEST",ne:"false"}},{name:"CircleCI",constant:"CIRCLE",env:"CIRCLECI",pr:"CIRCLE_PULL_REQUEST"},{name:"Cirrus CI",constant:"CIRRUS",env:"CIRRUS_CI",pr:"CIRRUS_PR"},{name:"AWS CodeBuild",constant:"CODEBUILD",env:"CODEBUILD_BUILD_ARN"},{name:"Codefresh",constant:"CODEFRESH",env:"CF_BUILD_ID",pr:{any:["CF_PULL_REQUEST_NUMBER","CF_PULL_REQUEST_ID"]}},{name:"Codeship",constant:"CODESHIP",env:{CI_NAME:"codeship"}},{name:"Drone",constant:"DRONE",env:"DRONE",pr:{DRONE_BUILD_EVENT:"pull_request"}},{name:"dsari",constant:"DSARI",env:"DSARI"},{name:"GitHub Actions",constant:"GITHUB_ACTIONS",env:"GITHUB_ACTIONS",pr:{GITHUB_EVENT_NAME:"pull_request"}},{name:"GitLab CI",constant:"GITLAB",env:"GITLAB_CI",pr:"CI_MERGE_REQUEST_ID"},{name:"GoCD",constant:"GOCD",env:"GO_PIPELINE_LABEL"},{name:"LayerCI",constant:"LAYERCI",env:"LAYERCI",pr:"LAYERCI_PULL_REQUEST"},{name:"Hudson",constant:"HUDSON",env:"HUDSON_URL"},{name:"Jenkins",constant:"JENKINS",env:["JENKINS_URL","BUILD_ID"],pr:{any:["ghprbPullId","CHANGE_ID"]}},{name:"Magnum CI",constant:"MAGNUM",env:"MAGNUM"},{name:"Netlify CI",constant:"NETLIFY",env:"NETLIFY",pr:{env:"PULL_REQUEST",ne:"false"}},{name:"Nevercode",constant:"NEVERCODE",env:"NEVERCODE",pr:{env:"NEVERCODE_PULL_REQUEST",ne:"false"}},{name:"Render",constant:"RENDER",env:"RENDER",pr:{IS_PULL_REQUEST:"true"}},{name:"Sail CI",constant:"SAIL",env:"SAILCI",pr:"SAIL_PULL_REQUEST_NUMBER"},{name:"Semaphore",constant:"SEMAPHORE",env:"SEMAPHORE",pr:"PULL_REQUEST_NUMBER"},{name:"Screwdriver",constant:"SCREWDRIVER",env:"SCREWDRIVER",pr:{env:"SD_PULL_REQUEST",ne:"false"}},{name:"Shippable",constant:"SHIPPABLE",env:"SHIPPABLE",pr:{IS_PULL_REQUEST:"true"}},{name:"Solano CI",constant:"SOLANO",env:"TDDIUM",pr:"TDDIUM_PR_ID"},{name:"Strider CD",constant:"STRIDER",env:"STRIDER"},{name:"TaskCluster",constant:"TASKCLUSTER",env:["TASK_ID","RUN_ID"]},{name:"TeamCity",constant:"TEAMCITY",env:"TEAMCITY_VERSION"},{name:"Travis CI",constant:"TRAVIS",env:"TRAVIS",pr:{env:"TRAVIS_PULL_REQUEST",ne:"false"}},{name:"Vercel",constant:"VERCEL",env:"NOW_BUILDER"},{name:"Visual Studio App Center",constant:"APPCENTER",env:"APPCENTER_BUILD_ID"}]});var cc=I(Un=>{"use strict";var yH=EH(),xo=process.env;Object.defineProperty(Un,"_vendors",{value:yH.map(function(r){return r.constant})});Un.name=null;Un.isPR=null;yH.forEach(function(r){let t=(Array.isArray(r.env)?r.env:[r.env]).every(function(i){return IH(i)});if(Un[r.constant]=t,t)switch(Un.name=r.name,typeof r.pr){case"string":Un.isPR=!!xo[r.pr];break;case"object":"env"in r.pr?Un.isPR=r.pr.env in xo&&xo[r.pr.env]!==r.pr.ne:"any"in r.pr?Un.isPR=r.pr.any.some(function(i){return!!xo[i]}):Un.isPR=IH(r.pr);break;default:Un.isPR=null}});Un.isCI=!!(xo.CI||xo.CONTINUOUS_INTEGRATION||xo.BUILD_NUMBER||xo.RUN_ID||Un.name);function IH(r){return typeof r=="string"?!!xo[r]:Object.keys(r).every(function(e){return xo[e]===r[e]})}});var pn={};ct(pn,{KeyRelationship:()=>uc,applyCascade:()=>ad,base64RegExp:()=>SH,colorStringAlphaRegExp:()=>bH,colorStringRegExp:()=>QH,computeKey:()=>DA,getPrintable:()=>Wr,hasExactLength:()=>DH,hasForbiddenKeys:()=>tCe,hasKeyRelationship:()=>av,hasMaxLength:()=>Mde,hasMinLength:()=>Ode,hasMutuallyExclusiveKeys:()=>rCe,hasRequiredKeys:()=>eCe,hasUniqueItems:()=>Kde,isArray:()=>Pde,isAtLeast:()=>jde,isAtMost:()=>Gde,isBase64:()=>_de,isBoolean:()=>Sde,isDate:()=>xde,isDict:()=>Dde,isEnum:()=>Zi,isHexColor:()=>Zde,isISO8601:()=>Xde,isInExclusiveRange:()=>qde,isInInclusiveRange:()=>Yde,isInstanceOf:()=>Fde,isInteger:()=>Jde,isJSON:()=>$de,isLiteral:()=>Qde,isLowerCase:()=>Wde,isNegative:()=>Ude,isNullable:()=>Lde,isNumber:()=>vde,isObject:()=>Rde,isOneOf:()=>Tde,isOptional:()=>Nde,isPositive:()=>Hde,isString:()=>od,isTuple:()=>kde,isUUID4:()=>Vde,isUnknown:()=>kH,isUpperCase:()=>zde,iso8601RegExp:()=>ov,makeCoercionFn:()=>gc,makeSetter:()=>PH,makeTrait:()=>xH,makeValidator:()=>Bt,matchesRegExp:()=>Ad,plural:()=>kI,pushError:()=>ht,simpleKeyRegExp:()=>BH,uuid4RegExp:()=>vH});function Bt({test:r}){return xH(r)()}function Wr(r){return r===null?"null":r===void 0?"undefined":r===""?"an empty string":JSON.stringify(r)}function DA(r,e){var t,i,n;return typeof e=="number"?`${(t=r==null?void 0:r.p)!==null&&t!==void 0?t:"."}[${e}]`:BH.test(e)?`${(i=r==null?void 0:r.p)!==null&&i!==void 0?i:""}.${e}`:`${(n=r==null?void 0:r.p)!==null&&n!==void 0?n:"."}[${JSON.stringify(e)}]`}function gc(r,e){return t=>{let i=r[e];return r[e]=t,gc(r,e).bind(null,i)}}function PH(r,e){return t=>{r[e]=t}}function kI(r,e,t){return r===1?e:t}function ht({errors:r,p:e}={},t){return r==null||r.push(`${e!=null?e:"."}: ${t}`),!1}function Qde(r){return Bt({test:(e,t)=>e!==r?ht(t,`Expected a literal (got ${Wr(r)})`):!0})}function Zi(r){let e=Array.isArray(r)?r:Object.values(r),t=new Set(e);return Bt({test:(i,n)=>t.has(i)?!0:ht(n,`Expected a valid enumeration value (got ${Wr(i)})`)})}var BH,QH,bH,SH,vH,ov,xH,kH,od,bde,Sde,vde,xde,Pde,kde,Dde,Rde,Fde,Tde,ad,Nde,Lde,Ode,Mde,DH,Kde,Ude,Hde,jde,Gde,Yde,qde,Jde,Ad,Wde,zde,Vde,Xde,Zde,_de,$de,eCe,tCe,rCe,uc,iCe,av,As=Hge(()=>{BH=/^[a-zA-Z_][a-zA-Z0-9_]*$/,QH=/^#[0-9a-f]{6}$/i,bH=/^#[0-9a-f]{6}([0-9a-f]{2})?$/i,SH=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,vH=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i,ov=/^(?:[1-9]\d{3}(-?)(?:(?:0[1-9]|1[0-2])\1(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])\1(?:29|30)|(?:0[13578]|1[02])(?:\1)31|00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[0-5]))|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\2)29|-?366))T(?:[01]\d|2[0-3])(:?)[0-5]\d(?:\3[0-5]\d)?(?:Z|[+-][01]\d(?:\3[0-5]\d)?)$/,xH=r=>()=>r;kH=()=>Bt({test:(r,e)=>!0});od=()=>Bt({test:(r,e)=>typeof r!="string"?ht(e,`Expected a string (got ${Wr(r)})`):!0});bde=new Map([["true",!0],["True",!0],["1",!0],[1,!0],["false",!1],["False",!1],["0",!1],[0,!1]]),Sde=()=>Bt({test:(r,e)=>{var t;if(typeof r!="boolean"){if(typeof(e==null?void 0:e.coercions)<"u"){if(typeof(e==null?void 0:e.coercion)>"u")return ht(e,"Unbound coercion result");let i=bde.get(r);if(typeof i<"u")return e.coercions.push([(t=e.p)!==null&&t!==void 0?t:".",e.coercion.bind(null,i)]),!0}return ht(e,`Expected a boolean (got ${Wr(r)})`)}return!0}}),vde=()=>Bt({test:(r,e)=>{var t;if(typeof r!="number"){if(typeof(e==null?void 0:e.coercions)<"u"){if(typeof(e==null?void 0:e.coercion)>"u")return ht(e,"Unbound coercion result");let i;if(typeof r=="string"){let n;try{n=JSON.parse(r)}catch{}if(typeof n=="number")if(JSON.stringify(n)===r)i=n;else return ht(e,`Received a number that can't be safely represented by the runtime (${r})`)}if(typeof i<"u")return e.coercions.push([(t=e.p)!==null&&t!==void 0?t:".",e.coercion.bind(null,i)]),!0}return ht(e,`Expected a number (got ${Wr(r)})`)}return!0}}),xde=()=>Bt({test:(r,e)=>{var t;if(!(r instanceof Date)){if(typeof(e==null?void 0:e.coercions)<"u"){if(typeof(e==null?void 0:e.coercion)>"u")return ht(e,"Unbound coercion result");let i;if(typeof r=="string"&&ov.test(r))i=new Date(r);else{let n;if(typeof r=="string"){let s;try{s=JSON.parse(r)}catch{}typeof s=="number"&&(n=s)}else typeof r=="number"&&(n=r);if(typeof n<"u")if(Number.isSafeInteger(n)||!Number.isSafeInteger(n*1e3))i=new Date(n*1e3);else return ht(e,`Received a timestamp that can't be safely represented by the runtime (${r})`)}if(typeof i<"u")return e.coercions.push([(t=e.p)!==null&&t!==void 0?t:".",e.coercion.bind(null,i)]),!0}return ht(e,`Expected a date (got ${Wr(r)})`)}return!0}}),Pde=(r,{delimiter:e}={})=>Bt({test:(t,i)=>{var n;if(typeof t=="string"&&typeof e<"u"&&typeof(i==null?void 0:i.coercions)<"u"){if(typeof(i==null?void 0:i.coercion)>"u")return ht(i,"Unbound coercion result");t=t.split(e),i.coercions.push([(n=i.p)!==null&&n!==void 0?n:".",i.coercion.bind(null,t)])}if(!Array.isArray(t))return ht(i,`Expected an array (got ${Wr(t)})`);let s=!0;for(let o=0,a=t.length;o{let t=DH(r.length);return Bt({test:(i,n)=>{var s;if(typeof i=="string"&&typeof e<"u"&&typeof(n==null?void 0:n.coercions)<"u"){if(typeof(n==null?void 0:n.coercion)>"u")return ht(n,"Unbound coercion result");i=i.split(e),n.coercions.push([(s=n.p)!==null&&s!==void 0?s:".",n.coercion.bind(null,i)])}if(!Array.isArray(i))return ht(n,`Expected a tuple (got ${Wr(i)})`);let o=t(i,Object.assign({},n));for(let a=0,l=i.length;aBt({test:(t,i)=>{if(typeof t!="object"||t===null)return ht(i,`Expected an object (got ${Wr(t)})`);let n=Object.keys(t),s=!0;for(let o=0,a=n.length;o{let t=Object.keys(r);return Bt({test:(i,n)=>{if(typeof i!="object"||i===null)return ht(n,`Expected an object (got ${Wr(i)})`);let s=new Set([...t,...Object.keys(i)]),o={},a=!0;for(let l of s){if(l==="constructor"||l==="__proto__")a=ht(Object.assign(Object.assign({},n),{p:DA(n,l)}),"Unsafe property name");else{let c=Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0,u=Object.prototype.hasOwnProperty.call(i,l)?i[l]:void 0;typeof c<"u"?a=c(u,Object.assign(Object.assign({},n),{p:DA(n,l),coercion:gc(i,l)}))&&a:e===null?a=ht(Object.assign(Object.assign({},n),{p:DA(n,l)}),`Extraneous property (got ${Wr(u)})`):Object.defineProperty(o,l,{enumerable:!0,get:()=>u,set:PH(i,l)})}if(!a&&(n==null?void 0:n.errors)==null)break}return e!==null&&(a||(n==null?void 0:n.errors)!=null)&&(a=e(o,n)&&a),a}})},Fde=r=>Bt({test:(e,t)=>e instanceof r?!0:ht(t,`Expected an instance of ${r.name} (got ${Wr(e)})`)}),Tde=(r,{exclusive:e=!1}={})=>Bt({test:(t,i)=>{var n,s,o;let a=[],l=typeof(i==null?void 0:i.errors)<"u"?[]:void 0;for(let c=0,u=r.length;c1?ht(i,`Expected to match exactly a single predicate (matched ${a.join(", ")})`):(o=i==null?void 0:i.errors)===null||o===void 0||o.push(...l),!1}}),ad=(r,e)=>Bt({test:(t,i)=>{var n,s;let o={value:t},a=typeof(i==null?void 0:i.coercions)<"u"?gc(o,"value"):void 0,l=typeof(i==null?void 0:i.coercions)<"u"?[]:void 0;if(!r(t,Object.assign(Object.assign({},i),{coercion:a,coercions:l})))return!1;let c=[];if(typeof l<"u")for(let[,u]of l)c.push(u());try{if(typeof(i==null?void 0:i.coercions)<"u"){if(o.value!==t){if(typeof(i==null?void 0:i.coercion)>"u")return ht(i,"Unbound coercion result");i.coercions.push([(n=i.p)!==null&&n!==void 0?n:".",i.coercion.bind(null,o.value)])}(s=i==null?void 0:i.coercions)===null||s===void 0||s.push(...l)}return e.every(u=>u(o.value,i))}finally{for(let u of c)u()}}}),Nde=r=>Bt({test:(e,t)=>typeof e>"u"?!0:r(e,t)}),Lde=r=>Bt({test:(e,t)=>e===null?!0:r(e,t)}),Ode=r=>Bt({test:(e,t)=>e.length>=r?!0:ht(t,`Expected to have a length of at least ${r} elements (got ${e.length})`)}),Mde=r=>Bt({test:(e,t)=>e.length<=r?!0:ht(t,`Expected to have a length of at most ${r} elements (got ${e.length})`)}),DH=r=>Bt({test:(e,t)=>e.length!==r?ht(t,`Expected to have a length of exactly ${r} elements (got ${e.length})`):!0}),Kde=({map:r}={})=>Bt({test:(e,t)=>{let i=new Set,n=new Set;for(let s=0,o=e.length;sBt({test:(r,e)=>r<=0?!0:ht(e,`Expected to be negative (got ${r})`)}),Hde=()=>Bt({test:(r,e)=>r>=0?!0:ht(e,`Expected to be positive (got ${r})`)}),jde=r=>Bt({test:(e,t)=>e>=r?!0:ht(t,`Expected to be at least ${r} (got ${e})`)}),Gde=r=>Bt({test:(e,t)=>e<=r?!0:ht(t,`Expected to be at most ${r} (got ${e})`)}),Yde=(r,e)=>Bt({test:(t,i)=>t>=r&&t<=e?!0:ht(i,`Expected to be in the [${r}; ${e}] range (got ${t})`)}),qde=(r,e)=>Bt({test:(t,i)=>t>=r&&tBt({test:(e,t)=>e!==Math.round(e)?ht(t,`Expected to be an integer (got ${e})`):Number.isSafeInteger(e)?!0:ht(t,`Expected to be a safe integer (got ${e})`)}),Ad=r=>Bt({test:(e,t)=>r.test(e)?!0:ht(t,`Expected to match the pattern ${r.toString()} (got ${Wr(e)})`)}),Wde=()=>Bt({test:(r,e)=>r!==r.toLowerCase()?ht(e,`Expected to be all-lowercase (got ${r})`):!0}),zde=()=>Bt({test:(r,e)=>r!==r.toUpperCase()?ht(e,`Expected to be all-uppercase (got ${r})`):!0}),Vde=()=>Bt({test:(r,e)=>vH.test(r)?!0:ht(e,`Expected to be a valid UUID v4 (got ${Wr(r)})`)}),Xde=()=>Bt({test:(r,e)=>ov.test(r)?!1:ht(e,`Expected to be a valid ISO 8601 date string (got ${Wr(r)})`)}),Zde=({alpha:r=!1})=>Bt({test:(e,t)=>(r?QH.test(e):bH.test(e))?!0:ht(t,`Expected to be a valid hexadecimal color string (got ${Wr(e)})`)}),_de=()=>Bt({test:(r,e)=>SH.test(r)?!0:ht(e,`Expected to be a valid base 64 string (got ${Wr(r)})`)}),$de=(r=kH())=>Bt({test:(e,t)=>{let i;try{i=JSON.parse(e)}catch{return ht(t,`Expected to be a valid JSON string (got ${Wr(e)})`)}return r(i,t)}}),eCe=r=>{let e=new Set(r);return Bt({test:(t,i)=>{let n=new Set(Object.keys(t)),s=[];for(let o of e)n.has(o)||s.push(o);return s.length>0?ht(i,`Missing required ${kI(s.length,"property","properties")} ${s.map(o=>`"${o}"`).join(", ")}`):!0}})},tCe=r=>{let e=new Set(r);return Bt({test:(t,i)=>{let n=new Set(Object.keys(t)),s=[];for(let o of e)n.has(o)&&s.push(o);return s.length>0?ht(i,`Forbidden ${kI(s.length,"property","properties")} ${s.map(o=>`"${o}"`).join(", ")}`):!0}})},rCe=r=>{let e=new Set(r);return Bt({test:(t,i)=>{let n=new Set(Object.keys(t)),s=[];for(let o of e)n.has(o)&&s.push(o);return s.length>1?ht(i,`Mutually exclusive properties ${s.map(o=>`"${o}"`).join(", ")}`):!0}})};(function(r){r.Forbids="Forbids",r.Requires="Requires"})(uc||(uc={}));iCe={[uc.Forbids]:{expect:!1,message:"forbids using"},[uc.Requires]:{expect:!0,message:"requires using"}},av=(r,e,t,{ignore:i=[]}={})=>{let n=new Set(i),s=new Set(t),o=iCe[e];return Bt({test:(a,l)=>{let c=new Set(Object.keys(a));if(!c.has(r)||n.has(a[r]))return!0;let u=[];for(let g of s)(c.has(g)&&!n.has(a[g]))!==o.expect&&u.push(g);return u.length>=1?ht(l,`Property "${r}" ${o.message} ${kI(u.length,"property","properties")} ${u.map(g=>`"${g}"`).join(", ")}`):!0}})}});var zH=I((m$e,WH)=>{"use strict";WH.exports=(r,...e)=>new Promise(t=>{t(r(...e))})});var Jg=I((E$e,pv)=>{"use strict";var ICe=zH(),VH=r=>{if(r<1)throw new TypeError("Expected `concurrency` to be a number from 1 and up");let e=[],t=0,i=()=>{t--,e.length>0&&e.shift()()},n=(a,l,...c)=>{t++;let u=ICe(a,...c);l(u),u.then(i,i)},s=(a,l,...c)=>{tnew Promise(c=>s(a,c,...l));return Object.defineProperties(o,{activeCount:{get:()=>t},pendingCount:{get:()=>e.length}}),o};pv.exports=VH;pv.exports.default=VH});var fd=I((y$e,XH)=>{var yCe="2.0.0",wCe=Number.MAX_SAFE_INTEGER||9007199254740991,BCe=16;XH.exports={SEMVER_SPEC_VERSION:yCe,MAX_LENGTH:256,MAX_SAFE_INTEGER:wCe,MAX_SAFE_COMPONENT_LENGTH:BCe}});var hd=I((w$e,ZH)=>{var QCe=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};ZH.exports=QCe});var fc=I((FA,_H)=>{var{MAX_SAFE_COMPONENT_LENGTH:dv}=fd(),bCe=hd();FA=_H.exports={};var SCe=FA.re=[],$e=FA.src=[],et=FA.t={},vCe=0,Qt=(r,e,t)=>{let i=vCe++;bCe(i,e),et[r]=i,$e[i]=e,SCe[i]=new RegExp(e,t?"g":void 0)};Qt("NUMERICIDENTIFIER","0|[1-9]\\d*");Qt("NUMERICIDENTIFIERLOOSE","[0-9]+");Qt("NONNUMERICIDENTIFIER","\\d*[a-zA-Z-][a-zA-Z0-9-]*");Qt("MAINVERSION",`(${$e[et.NUMERICIDENTIFIER]})\\.(${$e[et.NUMERICIDENTIFIER]})\\.(${$e[et.NUMERICIDENTIFIER]})`);Qt("MAINVERSIONLOOSE",`(${$e[et.NUMERICIDENTIFIERLOOSE]})\\.(${$e[et.NUMERICIDENTIFIERLOOSE]})\\.(${$e[et.NUMERICIDENTIFIERLOOSE]})`);Qt("PRERELEASEIDENTIFIER",`(?:${$e[et.NUMERICIDENTIFIER]}|${$e[et.NONNUMERICIDENTIFIER]})`);Qt("PRERELEASEIDENTIFIERLOOSE",`(?:${$e[et.NUMERICIDENTIFIERLOOSE]}|${$e[et.NONNUMERICIDENTIFIER]})`);Qt("PRERELEASE",`(?:-(${$e[et.PRERELEASEIDENTIFIER]}(?:\\.${$e[et.PRERELEASEIDENTIFIER]})*))`);Qt("PRERELEASELOOSE",`(?:-?(${$e[et.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${$e[et.PRERELEASEIDENTIFIERLOOSE]})*))`);Qt("BUILDIDENTIFIER","[0-9A-Za-z-]+");Qt("BUILD",`(?:\\+(${$e[et.BUILDIDENTIFIER]}(?:\\.${$e[et.BUILDIDENTIFIER]})*))`);Qt("FULLPLAIN",`v?${$e[et.MAINVERSION]}${$e[et.PRERELEASE]}?${$e[et.BUILD]}?`);Qt("FULL",`^${$e[et.FULLPLAIN]}$`);Qt("LOOSEPLAIN",`[v=\\s]*${$e[et.MAINVERSIONLOOSE]}${$e[et.PRERELEASELOOSE]}?${$e[et.BUILD]}?`);Qt("LOOSE",`^${$e[et.LOOSEPLAIN]}$`);Qt("GTLT","((?:<|>)?=?)");Qt("XRANGEIDENTIFIERLOOSE",`${$e[et.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Qt("XRANGEIDENTIFIER",`${$e[et.NUMERICIDENTIFIER]}|x|X|\\*`);Qt("XRANGEPLAIN",`[v=\\s]*(${$e[et.XRANGEIDENTIFIER]})(?:\\.(${$e[et.XRANGEIDENTIFIER]})(?:\\.(${$e[et.XRANGEIDENTIFIER]})(?:${$e[et.PRERELEASE]})?${$e[et.BUILD]}?)?)?`);Qt("XRANGEPLAINLOOSE",`[v=\\s]*(${$e[et.XRANGEIDENTIFIERLOOSE]})(?:\\.(${$e[et.XRANGEIDENTIFIERLOOSE]})(?:\\.(${$e[et.XRANGEIDENTIFIERLOOSE]})(?:${$e[et.PRERELEASELOOSE]})?${$e[et.BUILD]}?)?)?`);Qt("XRANGE",`^${$e[et.GTLT]}\\s*${$e[et.XRANGEPLAIN]}$`);Qt("XRANGELOOSE",`^${$e[et.GTLT]}\\s*${$e[et.XRANGEPLAINLOOSE]}$`);Qt("COERCE",`(^|[^\\d])(\\d{1,${dv}})(?:\\.(\\d{1,${dv}}))?(?:\\.(\\d{1,${dv}}))?(?:$|[^\\d])`);Qt("COERCERTL",$e[et.COERCE],!0);Qt("LONETILDE","(?:~>?)");Qt("TILDETRIM",`(\\s*)${$e[et.LONETILDE]}\\s+`,!0);FA.tildeTrimReplace="$1~";Qt("TILDE",`^${$e[et.LONETILDE]}${$e[et.XRANGEPLAIN]}$`);Qt("TILDELOOSE",`^${$e[et.LONETILDE]}${$e[et.XRANGEPLAINLOOSE]}$`);Qt("LONECARET","(?:\\^)");Qt("CARETTRIM",`(\\s*)${$e[et.LONECARET]}\\s+`,!0);FA.caretTrimReplace="$1^";Qt("CARET",`^${$e[et.LONECARET]}${$e[et.XRANGEPLAIN]}$`);Qt("CARETLOOSE",`^${$e[et.LONECARET]}${$e[et.XRANGEPLAINLOOSE]}$`);Qt("COMPARATORLOOSE",`^${$e[et.GTLT]}\\s*(${$e[et.LOOSEPLAIN]})$|^$`);Qt("COMPARATOR",`^${$e[et.GTLT]}\\s*(${$e[et.FULLPLAIN]})$|^$`);Qt("COMPARATORTRIM",`(\\s*)${$e[et.GTLT]}\\s*(${$e[et.LOOSEPLAIN]}|${$e[et.XRANGEPLAIN]})`,!0);FA.comparatorTrimReplace="$1$2$3";Qt("HYPHENRANGE",`^\\s*(${$e[et.XRANGEPLAIN]})\\s+-\\s+(${$e[et.XRANGEPLAIN]})\\s*$`);Qt("HYPHENRANGELOOSE",`^\\s*(${$e[et.XRANGEPLAINLOOSE]})\\s+-\\s+(${$e[et.XRANGEPLAINLOOSE]})\\s*$`);Qt("STAR","(<|>)?=?\\s*\\*");Qt("GTE0","^\\s*>=\\s*0.0.0\\s*$");Qt("GTE0PRE","^\\s*>=\\s*0.0.0-0\\s*$")});var pd=I((B$e,$H)=>{var xCe=["includePrerelease","loose","rtl"],PCe=r=>r?typeof r!="object"?{loose:!0}:xCe.filter(e=>r[e]).reduce((e,t)=>(e[t]=!0,e),{}):{};$H.exports=PCe});var LI=I((Q$e,rj)=>{var ej=/^[0-9]+$/,tj=(r,e)=>{let t=ej.test(r),i=ej.test(e);return t&&i&&(r=+r,e=+e),r===e?0:t&&!i?-1:i&&!t?1:rtj(e,r);rj.exports={compareIdentifiers:tj,rcompareIdentifiers:kCe}});var Li=I((b$e,oj)=>{var OI=hd(),{MAX_LENGTH:ij,MAX_SAFE_INTEGER:MI}=fd(),{re:nj,t:sj}=fc(),DCe=pd(),{compareIdentifiers:dd}=LI(),Gn=class{constructor(e,t){if(t=DCe(t),e instanceof Gn){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid Version: ${e}`);if(e.length>ij)throw new TypeError(`version is longer than ${ij} characters`);OI("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let i=e.trim().match(t.loose?nj[sj.LOOSE]:nj[sj.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>MI||this.major<0)throw new TypeError("Invalid major version");if(this.minor>MI||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>MI||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(n=>{if(/^[0-9]+$/.test(n)){let s=+n;if(s>=0&&s=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);i===-1&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:throw new Error(`invalid increment argument: ${e}`)}return this.format(),this.raw=this.version,this}};oj.exports=Gn});var hc=I((S$e,cj)=>{var{MAX_LENGTH:RCe}=fd(),{re:aj,t:Aj}=fc(),lj=Li(),FCe=pd(),TCe=(r,e)=>{if(e=FCe(e),r instanceof lj)return r;if(typeof r!="string"||r.length>RCe||!(e.loose?aj[Aj.LOOSE]:aj[Aj.FULL]).test(r))return null;try{return new lj(r,e)}catch{return null}};cj.exports=TCe});var gj=I((v$e,uj)=>{var NCe=hc(),LCe=(r,e)=>{let t=NCe(r,e);return t?t.version:null};uj.exports=LCe});var hj=I((x$e,fj)=>{var OCe=hc(),MCe=(r,e)=>{let t=OCe(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};fj.exports=MCe});var dj=I((P$e,pj)=>{var KCe=Li(),UCe=(r,e,t,i)=>{typeof t=="string"&&(i=t,t=void 0);try{return new KCe(r,t).inc(e,i).version}catch{return null}};pj.exports=UCe});var ls=I((k$e,mj)=>{var Cj=Li(),HCe=(r,e,t)=>new Cj(r,t).compare(new Cj(e,t));mj.exports=HCe});var KI=I((D$e,Ej)=>{var jCe=ls(),GCe=(r,e,t)=>jCe(r,e,t)===0;Ej.exports=GCe});var wj=I((R$e,yj)=>{var Ij=hc(),YCe=KI(),qCe=(r,e)=>{if(YCe(r,e))return null;{let t=Ij(r),i=Ij(e),n=t.prerelease.length||i.prerelease.length,s=n?"pre":"",o=n?"prerelease":"";for(let a in t)if((a==="major"||a==="minor"||a==="patch")&&t[a]!==i[a])return s+a;return o}};yj.exports=qCe});var Qj=I((F$e,Bj)=>{var JCe=Li(),WCe=(r,e)=>new JCe(r,e).major;Bj.exports=WCe});var Sj=I((T$e,bj)=>{var zCe=Li(),VCe=(r,e)=>new zCe(r,e).minor;bj.exports=VCe});var xj=I((N$e,vj)=>{var XCe=Li(),ZCe=(r,e)=>new XCe(r,e).patch;vj.exports=ZCe});var kj=I((L$e,Pj)=>{var _Ce=hc(),$Ce=(r,e)=>{let t=_Ce(r,e);return t&&t.prerelease.length?t.prerelease:null};Pj.exports=$Ce});var Rj=I((O$e,Dj)=>{var eme=ls(),tme=(r,e,t)=>eme(e,r,t);Dj.exports=tme});var Tj=I((M$e,Fj)=>{var rme=ls(),ime=(r,e)=>rme(r,e,!0);Fj.exports=ime});var UI=I((K$e,Lj)=>{var Nj=Li(),nme=(r,e,t)=>{let i=new Nj(r,t),n=new Nj(e,t);return i.compare(n)||i.compareBuild(n)};Lj.exports=nme});var Mj=I((U$e,Oj)=>{var sme=UI(),ome=(r,e)=>r.sort((t,i)=>sme(t,i,e));Oj.exports=ome});var Uj=I((H$e,Kj)=>{var ame=UI(),Ame=(r,e)=>r.sort((t,i)=>ame(i,t,e));Kj.exports=Ame});var Cd=I((j$e,Hj)=>{var lme=ls(),cme=(r,e,t)=>lme(r,e,t)>0;Hj.exports=cme});var HI=I((G$e,jj)=>{var ume=ls(),gme=(r,e,t)=>ume(r,e,t)<0;jj.exports=gme});var Cv=I((Y$e,Gj)=>{var fme=ls(),hme=(r,e,t)=>fme(r,e,t)!==0;Gj.exports=hme});var jI=I((q$e,Yj)=>{var pme=ls(),dme=(r,e,t)=>pme(r,e,t)>=0;Yj.exports=dme});var GI=I((J$e,qj)=>{var Cme=ls(),mme=(r,e,t)=>Cme(r,e,t)<=0;qj.exports=mme});var mv=I((W$e,Jj)=>{var Eme=KI(),Ime=Cv(),yme=Cd(),wme=jI(),Bme=HI(),Qme=GI(),bme=(r,e,t,i)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Eme(r,t,i);case"!=":return Ime(r,t,i);case">":return yme(r,t,i);case">=":return wme(r,t,i);case"<":return Bme(r,t,i);case"<=":return Qme(r,t,i);default:throw new TypeError(`Invalid operator: ${e}`)}};Jj.exports=bme});var zj=I((z$e,Wj)=>{var Sme=Li(),vme=hc(),{re:YI,t:qI}=fc(),xme=(r,e)=>{if(r instanceof Sme)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(YI[qI.COERCE]);else{let i;for(;(i=YI[qI.COERCERTL].exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||i.index+i[0].length!==t.index+t[0].length)&&(t=i),YI[qI.COERCERTL].lastIndex=i.index+i[1].length+i[2].length;YI[qI.COERCERTL].lastIndex=-1}return t===null?null:vme(`${t[2]}.${t[3]||"0"}.${t[4]||"0"}`,e)};Wj.exports=xme});var Xj=I((V$e,Vj)=>{"use strict";Vj.exports=function(r){r.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var JI=I((X$e,Zj)=>{"use strict";Zj.exports=Mt;Mt.Node=pc;Mt.create=Mt;function Mt(r){var e=this;if(e instanceof Mt||(e=new Mt),e.tail=null,e.head=null,e.length=0,r&&typeof r.forEach=="function")r.forEach(function(n){e.push(n)});else if(arguments.length>0)for(var t=0,i=arguments.length;t1)t=e;else if(this.head)i=this.head.next,t=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=0;i!==null;n++)t=r(t,i.value,n),i=i.next;return t};Mt.prototype.reduceReverse=function(r,e){var t,i=this.tail;if(arguments.length>1)t=e;else if(this.tail)i=this.tail.prev,t=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(var n=this.length-1;i!==null;n--)t=r(t,i.value,n),i=i.prev;return t};Mt.prototype.toArray=function(){for(var r=new Array(this.length),e=0,t=this.head;t!==null;e++)r[e]=t.value,t=t.next;return r};Mt.prototype.toArrayReverse=function(){for(var r=new Array(this.length),e=0,t=this.tail;t!==null;e++)r[e]=t.value,t=t.prev;return r};Mt.prototype.slice=function(r,e){e=e||this.length,e<0&&(e+=this.length),r=r||0,r<0&&(r+=this.length);var t=new Mt;if(ethis.length&&(e=this.length);for(var i=0,n=this.head;n!==null&&ithis.length&&(e=this.length);for(var i=this.length,n=this.tail;n!==null&&i>e;i--)n=n.prev;for(;n!==null&&i>r;i--,n=n.prev)t.push(n.value);return t};Mt.prototype.splice=function(r,e,...t){r>this.length&&(r=this.length-1),r<0&&(r=this.length+r);for(var i=0,n=this.head;n!==null&&i{"use strict";var Rme=JI(),dc=Symbol("max"),xa=Symbol("length"),Wg=Symbol("lengthCalculator"),Ed=Symbol("allowStale"),Cc=Symbol("maxAge"),va=Symbol("dispose"),_j=Symbol("noDisposeOnSet"),pi=Symbol("lruList"),Xs=Symbol("cache"),eG=Symbol("updateAgeOnGet"),Ev=()=>1,yv=class{constructor(e){if(typeof e=="number"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!="number"||e.max<0))throw new TypeError("max must be a non-negative number");let t=this[dc]=e.max||1/0,i=e.length||Ev;if(this[Wg]=typeof i!="function"?Ev:i,this[Ed]=e.stale||!1,e.maxAge&&typeof e.maxAge!="number")throw new TypeError("maxAge must be a number");this[Cc]=e.maxAge||0,this[va]=e.dispose,this[_j]=e.noDisposeOnSet||!1,this[eG]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!="number"||e<0)throw new TypeError("max must be a non-negative number");this[dc]=e||1/0,md(this)}get max(){return this[dc]}set allowStale(e){this[Ed]=!!e}get allowStale(){return this[Ed]}set maxAge(e){if(typeof e!="number")throw new TypeError("maxAge must be a non-negative number");this[Cc]=e,md(this)}get maxAge(){return this[Cc]}set lengthCalculator(e){typeof e!="function"&&(e=Ev),e!==this[Wg]&&(this[Wg]=e,this[xa]=0,this[pi].forEach(t=>{t.length=this[Wg](t.value,t.key),this[xa]+=t.length})),md(this)}get lengthCalculator(){return this[Wg]}get length(){return this[xa]}get itemCount(){return this[pi].length}rforEach(e,t){t=t||this;for(let i=this[pi].tail;i!==null;){let n=i.prev;$j(this,e,i,t),i=n}}forEach(e,t){t=t||this;for(let i=this[pi].head;i!==null;){let n=i.next;$j(this,e,i,t),i=n}}keys(){return this[pi].toArray().map(e=>e.key)}values(){return this[pi].toArray().map(e=>e.value)}reset(){this[va]&&this[pi]&&this[pi].length&&this[pi].forEach(e=>this[va](e.key,e.value)),this[Xs]=new Map,this[pi]=new Rme,this[xa]=0}dump(){return this[pi].map(e=>WI(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[pi]}set(e,t,i){if(i=i||this[Cc],i&&typeof i!="number")throw new TypeError("maxAge must be a number");let n=i?Date.now():0,s=this[Wg](t,e);if(this[Xs].has(e)){if(s>this[dc])return zg(this,this[Xs].get(e)),!1;let l=this[Xs].get(e).value;return this[va]&&(this[_j]||this[va](e,l.value)),l.now=n,l.maxAge=i,l.value=t,this[xa]+=s-l.length,l.length=s,this.get(e),md(this),!0}let o=new wv(e,t,s,n,i);return o.length>this[dc]?(this[va]&&this[va](e,t),!1):(this[xa]+=o.length,this[pi].unshift(o),this[Xs].set(e,this[pi].head),md(this),!0)}has(e){if(!this[Xs].has(e))return!1;let t=this[Xs].get(e).value;return!WI(this,t)}get(e){return Iv(this,e,!0)}peek(e){return Iv(this,e,!1)}pop(){let e=this[pi].tail;return e?(zg(this,e),e.value):null}del(e){zg(this,this[Xs].get(e))}load(e){this.reset();let t=Date.now();for(let i=e.length-1;i>=0;i--){let n=e[i],s=n.e||0;if(s===0)this.set(n.k,n.v);else{let o=s-t;o>0&&this.set(n.k,n.v,o)}}}prune(){this[Xs].forEach((e,t)=>Iv(this,t,!1))}},Iv=(r,e,t)=>{let i=r[Xs].get(e);if(i){let n=i.value;if(WI(r,n)){if(zg(r,i),!r[Ed])return}else t&&(r[eG]&&(i.value.now=Date.now()),r[pi].unshiftNode(i));return n.value}},WI=(r,e)=>{if(!e||!e.maxAge&&!r[Cc])return!1;let t=Date.now()-e.now;return e.maxAge?t>e.maxAge:r[Cc]&&t>r[Cc]},md=r=>{if(r[xa]>r[dc])for(let e=r[pi].tail;r[xa]>r[dc]&&e!==null;){let t=e.prev;zg(r,e),e=t}},zg=(r,e)=>{if(e){let t=e.value;r[va]&&r[va](t.key,t.value),r[xa]-=t.length,r[Xs].delete(t.key),r[pi].removeNode(e)}},wv=class{constructor(e,t,i,n,s){this.key=e,this.value=t,this.length=i,this.now=n,this.maxAge=s||0}},$j=(r,e,t,i)=>{let n=t.value;WI(r,n)&&(zg(r,t),r[Ed]||(n=void 0)),n&&e.call(i,n.value,n.key,r)};tG.exports=yv});var cs=I((_$e,oG)=>{var mc=class{constructor(e,t){if(t=Tme(t),e instanceof mc)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new mc(e.raw,t);if(e instanceof Bv)return this.raw=e.value,this.set=[[e]],this.format(),this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map(i=>this.parseRange(i.trim())).filter(i=>i.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${e}`);if(this.set.length>1){let i=this.set[0];if(this.set=this.set.filter(n=>!nG(n[0])),this.set.length===0)this.set=[i];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&Kme(n[0])){this.set=[n];break}}}this.format()}format(){return this.range=this.set.map(e=>e.join(" ").trim()).join("||").trim(),this.range}toString(){return this.range}parseRange(e){e=e.trim();let i=`parseRange:${Object.keys(this.options).join(",")}:${e}`,n=iG.get(i);if(n)return n;let s=this.options.loose,o=s?Oi[bi.HYPHENRANGELOOSE]:Oi[bi.HYPHENRANGE];e=e.replace(o,Vme(this.options.includePrerelease)),Kr("hyphen replace",e),e=e.replace(Oi[bi.COMPARATORTRIM],Lme),Kr("comparator trim",e,Oi[bi.COMPARATORTRIM]),e=e.replace(Oi[bi.TILDETRIM],Ome),e=e.replace(Oi[bi.CARETTRIM],Mme),e=e.split(/\s+/).join(" ");let a=s?Oi[bi.COMPARATORLOOSE]:Oi[bi.COMPARATOR],l=e.split(" ").map(h=>Ume(h,this.options)).join(" ").split(/\s+/).map(h=>zme(h,this.options)).filter(this.options.loose?h=>!!h.match(a):()=>!0).map(h=>new Bv(h,this.options)),c=l.length,u=new Map;for(let h of l){if(nG(h))return[h];u.set(h.value,h)}u.size>1&&u.has("")&&u.delete("");let g=[...u.values()];return iG.set(i,g),g}intersects(e,t){if(!(e instanceof mc))throw new TypeError("a Range is required");return this.set.some(i=>sG(i,t)&&e.set.some(n=>sG(n,t)&&i.every(s=>n.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Nme(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",Kme=r=>r.value==="",sG=(r,e)=>{let t=!0,i=r.slice(),n=i.pop();for(;t&&i.length;)t=i.every(s=>n.intersects(s,e)),n=i.pop();return t},Ume=(r,e)=>(Kr("comp",r,e),r=Gme(r,e),Kr("caret",r),r=Hme(r,e),Kr("tildes",r),r=qme(r,e),Kr("xrange",r),r=Wme(r,e),Kr("stars",r),r),$i=r=>!r||r.toLowerCase()==="x"||r==="*",Hme=(r,e)=>r.trim().split(/\s+/).map(t=>jme(t,e)).join(" "),jme=(r,e)=>{let t=e.loose?Oi[bi.TILDELOOSE]:Oi[bi.TILDE];return r.replace(t,(i,n,s,o,a)=>{Kr("tilde",r,i,n,s,o,a);let l;return $i(n)?l="":$i(s)?l=`>=${n}.0.0 <${+n+1}.0.0-0`:$i(o)?l=`>=${n}.${s}.0 <${n}.${+s+1}.0-0`:a?(Kr("replaceTilde pr",a),l=`>=${n}.${s}.${o}-${a} <${n}.${+s+1}.0-0`):l=`>=${n}.${s}.${o} <${n}.${+s+1}.0-0`,Kr("tilde return",l),l})},Gme=(r,e)=>r.trim().split(/\s+/).map(t=>Yme(t,e)).join(" "),Yme=(r,e)=>{Kr("caret",r,e);let t=e.loose?Oi[bi.CARETLOOSE]:Oi[bi.CARET],i=e.includePrerelease?"-0":"";return r.replace(t,(n,s,o,a,l)=>{Kr("caret",r,n,s,o,a,l);let c;return $i(s)?c="":$i(o)?c=`>=${s}.0.0${i} <${+s+1}.0.0-0`:$i(a)?s==="0"?c=`>=${s}.${o}.0${i} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.0${i} <${+s+1}.0.0-0`:l?(Kr("replaceCaret pr",l),s==="0"?o==="0"?c=`>=${s}.${o}.${a}-${l} <${s}.${o}.${+a+1}-0`:c=`>=${s}.${o}.${a}-${l} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.${a}-${l} <${+s+1}.0.0-0`):(Kr("no pr"),s==="0"?o==="0"?c=`>=${s}.${o}.${a}${i} <${s}.${o}.${+a+1}-0`:c=`>=${s}.${o}.${a}${i} <${s}.${+o+1}.0-0`:c=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),Kr("caret return",c),c})},qme=(r,e)=>(Kr("replaceXRanges",r,e),r.split(/\s+/).map(t=>Jme(t,e)).join(" ")),Jme=(r,e)=>{r=r.trim();let t=e.loose?Oi[bi.XRANGELOOSE]:Oi[bi.XRANGE];return r.replace(t,(i,n,s,o,a,l)=>{Kr("xRange",r,i,n,s,o,a,l);let c=$i(s),u=c||$i(o),g=u||$i(a),h=g;return n==="="&&h&&(n=""),l=e.includePrerelease?"-0":"",c?n===">"||n==="<"?i="<0.0.0-0":i="*":n&&h?(u&&(o=0),a=0,n===">"?(n=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):n==="<="&&(n="<",u?s=+s+1:o=+o+1),n==="<"&&(l="-0"),i=`${n+s}.${o}.${a}${l}`):u?i=`>=${s}.0.0${l} <${+s+1}.0.0-0`:g&&(i=`>=${s}.${o}.0${l} <${s}.${+o+1}.0-0`),Kr("xRange return",i),i})},Wme=(r,e)=>(Kr("replaceStars",r,e),r.trim().replace(Oi[bi.STAR],"")),zme=(r,e)=>(Kr("replaceGTE0",r,e),r.trim().replace(Oi[e.includePrerelease?bi.GTE0PRE:bi.GTE0],"")),Vme=r=>(e,t,i,n,s,o,a,l,c,u,g,h,p)=>($i(i)?t="":$i(n)?t=`>=${i}.0.0${r?"-0":""}`:$i(s)?t=`>=${i}.${n}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,$i(c)?l="":$i(u)?l=`<${+c+1}.0.0-0`:$i(g)?l=`<${c}.${+u+1}.0-0`:h?l=`<=${c}.${u}.${g}-${h}`:r?l=`<${c}.${u}.${+g+1}-0`:l=`<=${l}`,`${t} ${l}`.trim()),Xme=(r,e,t)=>{for(let i=0;i0){let n=r[i].semver;if(n.major===e.major&&n.minor===e.minor&&n.patch===e.patch)return!0}return!1}return!0}});var Id=I(($$e,uG)=>{var yd=Symbol("SemVer ANY"),Vg=class{static get ANY(){return yd}constructor(e,t){if(t=Zme(t),e instanceof Vg){if(e.loose===!!t.loose)return e;e=e.value}bv("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===yd?this.value="":this.value=this.operator+this.semver.version,bv("comp",this)}parse(e){let t=this.options.loose?aG[AG.COMPARATORLOOSE]:aG[AG.COMPARATOR],i=e.match(t);if(!i)throw new TypeError(`Invalid comparator: ${e}`);this.operator=i[1]!==void 0?i[1]:"",this.operator==="="&&(this.operator=""),i[2]?this.semver=new lG(i[2],this.options.loose):this.semver=yd}toString(){return this.value}test(e){if(bv("Comparator.test",e,this.options.loose),this.semver===yd||e===yd)return!0;if(typeof e=="string")try{e=new lG(e,this.options)}catch{return!1}return Qv(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof Vg))throw new TypeError("a Comparator is required");if((!t||typeof t!="object")&&(t={loose:!!t,includePrerelease:!1}),this.operator==="")return this.value===""?!0:new cG(e.value,t).test(this.value);if(e.operator==="")return e.value===""?!0:new cG(this.value,t).test(e.semver);let i=(this.operator===">="||this.operator===">")&&(e.operator===">="||e.operator===">"),n=(this.operator==="<="||this.operator==="<")&&(e.operator==="<="||e.operator==="<"),s=this.semver.version===e.semver.version,o=(this.operator===">="||this.operator==="<=")&&(e.operator===">="||e.operator==="<="),a=Qv(this.semver,"<",e.semver,t)&&(this.operator===">="||this.operator===">")&&(e.operator==="<="||e.operator==="<"),l=Qv(this.semver,">",e.semver,t)&&(this.operator==="<="||this.operator==="<")&&(e.operator===">="||e.operator===">");return i||n||s&&o||a||l}};uG.exports=Vg;var Zme=pd(),{re:aG,t:AG}=fc(),Qv=mv(),bv=hd(),lG=Li(),cG=cs()});var wd=I((eet,gG)=>{var _me=cs(),$me=(r,e,t)=>{try{e=new _me(e,t)}catch{return!1}return e.test(r)};gG.exports=$me});var hG=I((tet,fG)=>{var eEe=cs(),tEe=(r,e)=>new eEe(r,e).set.map(t=>t.map(i=>i.value).join(" ").trim().split(" "));fG.exports=tEe});var dG=I((ret,pG)=>{var rEe=Li(),iEe=cs(),nEe=(r,e,t)=>{let i=null,n=null,s=null;try{s=new iEe(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!i||n.compare(o)===-1)&&(i=o,n=new rEe(i,t))}),i};pG.exports=nEe});var mG=I((iet,CG)=>{var sEe=Li(),oEe=cs(),aEe=(r,e,t)=>{let i=null,n=null,s=null;try{s=new oEe(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!i||n.compare(o)===1)&&(i=o,n=new sEe(i,t))}),i};CG.exports=aEe});var yG=I((net,IG)=>{var Sv=Li(),AEe=cs(),EG=Cd(),lEe=(r,e)=>{r=new AEe(r,e);let t=new Sv("0.0.0");if(r.test(t)||(t=new Sv("0.0.0-0"),r.test(t)))return t;t=null;for(let i=0;i{let a=new Sv(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||EG(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||EG(t,s))&&(t=s)}return t&&r.test(t)?t:null};IG.exports=lEe});var BG=I((set,wG)=>{var cEe=cs(),uEe=(r,e)=>{try{return new cEe(r,e).range||"*"}catch{return null}};wG.exports=uEe});var zI=I((oet,vG)=>{var gEe=Li(),SG=Id(),{ANY:fEe}=SG,hEe=cs(),pEe=wd(),QG=Cd(),bG=HI(),dEe=GI(),CEe=jI(),mEe=(r,e,t,i)=>{r=new gEe(r,i),e=new hEe(e,i);let n,s,o,a,l;switch(t){case">":n=QG,s=dEe,o=bG,a=">",l=">=";break;case"<":n=bG,s=CEe,o=QG,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(pEe(r,e,i))return!1;for(let c=0;c{p.semver===fEe&&(p=new SG(">=0.0.0")),g=g||p,h=h||p,n(p.semver,g.semver,i)?g=p:o(p.semver,h.semver,i)&&(h=p)}),g.operator===a||g.operator===l||(!h.operator||h.operator===a)&&s(r,h.semver))return!1;if(h.operator===l&&o(r,h.semver))return!1}return!0};vG.exports=mEe});var PG=I((aet,xG)=>{var EEe=zI(),IEe=(r,e,t)=>EEe(r,e,">",t);xG.exports=IEe});var DG=I((Aet,kG)=>{var yEe=zI(),wEe=(r,e,t)=>yEe(r,e,"<",t);kG.exports=wEe});var TG=I((cet,FG)=>{var RG=cs(),BEe=(r,e,t)=>(r=new RG(r,t),e=new RG(e,t),r.intersects(e));FG.exports=BEe});var LG=I((uet,NG)=>{var QEe=wd(),bEe=ls();NG.exports=(r,e,t)=>{let i=[],n=null,s=null,o=r.sort((u,g)=>bEe(u,g,t));for(let u of o)QEe(u,e,t)?(s=u,n||(n=u)):(s&&i.push([n,s]),s=null,n=null);n&&i.push([n,null]);let a=[];for(let[u,g]of i)u===g?a.push(u):!g&&u===o[0]?a.push("*"):g?u===o[0]?a.push(`<=${g}`):a.push(`${u} - ${g}`):a.push(`>=${u}`);let l=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return l.length{var OG=cs(),VI=Id(),{ANY:vv}=VI,Bd=wd(),xv=ls(),SEe=(r,e,t={})=>{if(r===e)return!0;r=new OG(r,t),e=new OG(e,t);let i=!1;e:for(let n of r.set){for(let s of e.set){let o=vEe(n,s,t);if(i=i||o!==null,o)continue e}if(i)return!1}return!0},vEe=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===vv){if(e.length===1&&e[0].semver===vv)return!0;t.includePrerelease?r=[new VI(">=0.0.0-0")]:r=[new VI(">=0.0.0")]}if(e.length===1&&e[0].semver===vv){if(t.includePrerelease)return!0;e=[new VI(">=0.0.0")]}let i=new Set,n,s;for(let p of r)p.operator===">"||p.operator===">="?n=MG(n,p,t):p.operator==="<"||p.operator==="<="?s=KG(s,p,t):i.add(p.semver);if(i.size>1)return null;let o;if(n&&s){if(o=xv(n.semver,s.semver,t),o>0)return null;if(o===0&&(n.operator!==">="||s.operator!=="<="))return null}for(let p of i){if(n&&!Bd(p,String(n),t)||s&&!Bd(p,String(s),t))return null;for(let d of e)if(!Bd(p,String(d),t))return!1;return!0}let a,l,c,u,g=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,h=n&&!t.includePrerelease&&n.semver.prerelease.length?n.semver:!1;g&&g.prerelease.length===1&&s.operator==="<"&&g.prerelease[0]===0&&(g=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",c=c||p.operator==="<"||p.operator==="<=",n){if(h&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===h.major&&p.semver.minor===h.minor&&p.semver.patch===h.patch&&(h=!1),p.operator===">"||p.operator===">="){if(a=MG(n,p,t),a===p&&a!==n)return!1}else if(n.operator===">="&&!Bd(n.semver,String(p),t))return!1}if(s){if(g&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===g.major&&p.semver.minor===g.minor&&p.semver.patch===g.patch&&(g=!1),p.operator==="<"||p.operator==="<="){if(l=KG(s,p,t),l===p&&l!==s)return!1}else if(s.operator==="<="&&!Bd(s.semver,String(p),t))return!1}if(!p.operator&&(s||n)&&o!==0)return!1}return!(n&&c&&!s&&o!==0||s&&u&&!n&&o!==0||h||g)},MG=(r,e,t)=>{if(!r)return e;let i=xv(r.semver,e.semver,t);return i>0?r:i<0||e.operator===">"&&r.operator===">="?e:r},KG=(r,e,t)=>{if(!r)return e;let i=xv(r.semver,e.semver,t);return i<0?r:i>0||e.operator==="<"&&r.operator==="<="?e:r};UG.exports=SEe});var zr=I((fet,jG)=>{var Pv=fc();jG.exports={re:Pv.re,src:Pv.src,tokens:Pv.t,SEMVER_SPEC_VERSION:fd().SEMVER_SPEC_VERSION,SemVer:Li(),compareIdentifiers:LI().compareIdentifiers,rcompareIdentifiers:LI().rcompareIdentifiers,parse:hc(),valid:gj(),clean:hj(),inc:dj(),diff:wj(),major:Qj(),minor:Sj(),patch:xj(),prerelease:kj(),compare:ls(),rcompare:Rj(),compareLoose:Tj(),compareBuild:UI(),sort:Mj(),rsort:Uj(),gt:Cd(),lt:HI(),eq:KI(),neq:Cv(),gte:jI(),lte:GI(),cmp:mv(),coerce:zj(),Comparator:Id(),Range:cs(),satisfies:wd(),toComparators:hG(),maxSatisfying:dG(),minSatisfying:mG(),minVersion:yG(),validRange:BG(),outside:zI(),gtr:PG(),ltr:DG(),intersects:TG(),simplifyRange:LG(),subset:HG()}});var kv=I(XI=>{"use strict";Object.defineProperty(XI,"__esModule",{value:!0});XI.VERSION=void 0;XI.VERSION="9.1.0"});var Kt=I((exports,module)=>{"use strict";var __spreadArray=exports&&exports.__spreadArray||function(r,e,t){if(t||arguments.length===2)for(var i=0,n=e.length,s;i{(function(r,e){typeof define=="function"&&define.amd?define([],e):typeof ZI=="object"&&ZI.exports?ZI.exports=e():r.regexpToAst=e()})(typeof self<"u"?self:GG,function(){function r(){}r.prototype.saveState=function(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}},r.prototype.restoreState=function(d){this.idx=d.idx,this.input=d.input,this.groupIdx=d.groupIdx},r.prototype.pattern=function(d){this.idx=0,this.input=d,this.groupIdx=0,this.consumeChar("/");var m=this.disjunction();this.consumeChar("/");for(var y={type:"Flags",loc:{begin:this.idx,end:d.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};this.isRegExpFlag();)switch(this.popChar()){case"g":o(y,"global");break;case"i":o(y,"ignoreCase");break;case"m":o(y,"multiLine");break;case"u":o(y,"unicode");break;case"y":o(y,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:y,value:m,loc:this.loc(0)}},r.prototype.disjunction=function(){var d=[],m=this.idx;for(d.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),d.push(this.alternative());return{type:"Disjunction",value:d,loc:this.loc(m)}},r.prototype.alternative=function(){for(var d=[],m=this.idx;this.isTerm();)d.push(this.term());return{type:"Alternative",value:d,loc:this.loc(m)}},r.prototype.term=function(){return this.isAssertion()?this.assertion():this.atom()},r.prototype.assertion=function(){var d=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(d)};case"$":return{type:"EndAnchor",loc:this.loc(d)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(d)};case"B":return{type:"NonWordBoundary",loc:this.loc(d)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");var m;switch(this.popChar()){case"=":m="Lookahead";break;case"!":m="NegativeLookahead";break}a(m);var y=this.disjunction();return this.consumeChar(")"),{type:m,value:y,loc:this.loc(d)}}l()},r.prototype.quantifier=function(d){var m,y=this.idx;switch(this.popChar()){case"*":m={atLeast:0,atMost:1/0};break;case"+":m={atLeast:1,atMost:1/0};break;case"?":m={atLeast:0,atMost:1};break;case"{":var B=this.integerIncludingZero();switch(this.popChar()){case"}":m={atLeast:B,atMost:B};break;case",":var S;this.isDigit()?(S=this.integerIncludingZero(),m={atLeast:B,atMost:S}):m={atLeast:B,atMost:1/0},this.consumeChar("}");break}if(d===!0&&m===void 0)return;a(m);break}if(!(d===!0&&m===void 0))return a(m),this.peekChar(0)==="?"?(this.consumeChar("?"),m.greedy=!1):m.greedy=!0,m.type="Quantifier",m.loc=this.loc(y),m},r.prototype.atom=function(){var d,m=this.idx;switch(this.peekChar()){case".":d=this.dotAll();break;case"\\":d=this.atomEscape();break;case"[":d=this.characterClass();break;case"(":d=this.group();break}return d===void 0&&this.isPatternCharacter()&&(d=this.patternCharacter()),a(d),d.loc=this.loc(m),this.isQuantifier()&&(d.quantifier=this.quantifier()),d},r.prototype.dotAll=function(){return this.consumeChar("."),{type:"Set",complement:!0,value:[n(` -`),n("\r"),n("\u2028"),n("\u2029")]}},r.prototype.atomEscape=function(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}},r.prototype.decimalEscapeAtom=function(){var d=this.positiveInteger();return{type:"GroupBackReference",value:d}},r.prototype.characterClassEscape=function(){var d,m=!1;switch(this.popChar()){case"d":d=u;break;case"D":d=u,m=!0;break;case"s":d=h;break;case"S":d=h,m=!0;break;case"w":d=g;break;case"W":d=g,m=!0;break}return a(d),{type:"Set",value:d,complement:m}},r.prototype.controlEscapeAtom=function(){var d;switch(this.popChar()){case"f":d=n("\f");break;case"n":d=n(` -`);break;case"r":d=n("\r");break;case"t":d=n(" ");break;case"v":d=n("\v");break}return a(d),{type:"Character",value:d}},r.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var d=this.popChar();if(/[a-zA-Z]/.test(d)===!1)throw Error("Invalid ");var m=d.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:m}},r.prototype.nulCharacterAtom=function(){return this.consumeChar("0"),{type:"Character",value:n("\0")}},r.prototype.hexEscapeSequenceAtom=function(){return this.consumeChar("x"),this.parseHexDigits(2)},r.prototype.regExpUnicodeEscapeSequenceAtom=function(){return this.consumeChar("u"),this.parseHexDigits(4)},r.prototype.identityEscapeAtom=function(){var d=this.popChar();return{type:"Character",value:n(d)}},r.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case` -`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var d=this.popChar();return{type:"Character",value:n(d)}}},r.prototype.characterClass=function(){var d=[],m=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),m=!0);this.isClassAtom();){var y=this.classAtom(),B=y.type==="Character";if(B&&this.isRangeDash()){this.consumeChar("-");var S=this.classAtom(),P=S.type==="Character";if(P){if(S.value=this.input.length)throw Error("Unexpected end of input");this.idx++},r.prototype.loc=function(d){return{begin:d,end:this.idx}};var e=/[0-9a-fA-F]/,t=/[0-9]/,i=/[1-9]/;function n(d){return d.charCodeAt(0)}function s(d,m){d.length!==void 0?d.forEach(function(y){m.push(y)}):m.push(d)}function o(d,m){if(d[m]===!0)throw"duplicate flag "+m;d[m]=!0}function a(d){if(d===void 0)throw Error("Internal Error - Should never get here!")}function l(){throw Error("Internal Error - Should never get here!")}var c,u=[];for(c=n("0");c<=n("9");c++)u.push(c);var g=[n("_")].concat(u);for(c=n("a");c<=n("z");c++)g.push(c);for(c=n("A");c<=n("Z");c++)g.push(c);var h=[n(" "),n("\f"),n(` -`),n("\r"),n(" "),n("\v"),n(" "),n("\xA0"),n("\u1680"),n("\u2000"),n("\u2001"),n("\u2002"),n("\u2003"),n("\u2004"),n("\u2005"),n("\u2006"),n("\u2007"),n("\u2008"),n("\u2009"),n("\u200A"),n("\u2028"),n("\u2029"),n("\u202F"),n("\u205F"),n("\u3000"),n("\uFEFF")];function p(){}return p.prototype.visitChildren=function(d){for(var m in d){var y=d[m];d.hasOwnProperty(m)&&(y.type!==void 0?this.visit(y):Array.isArray(y)&&y.forEach(function(B){this.visit(B)},this))}},p.prototype.visit=function(d){switch(d.type){case"Pattern":this.visitPattern(d);break;case"Flags":this.visitFlags(d);break;case"Disjunction":this.visitDisjunction(d);break;case"Alternative":this.visitAlternative(d);break;case"StartAnchor":this.visitStartAnchor(d);break;case"EndAnchor":this.visitEndAnchor(d);break;case"WordBoundary":this.visitWordBoundary(d);break;case"NonWordBoundary":this.visitNonWordBoundary(d);break;case"Lookahead":this.visitLookahead(d);break;case"NegativeLookahead":this.visitNegativeLookahead(d);break;case"Character":this.visitCharacter(d);break;case"Set":this.visitSet(d);break;case"Group":this.visitGroup(d);break;case"GroupBackReference":this.visitGroupBackReference(d);break;case"Quantifier":this.visitQuantifier(d);break}this.visitChildren(d)},p.prototype.visitPattern=function(d){},p.prototype.visitFlags=function(d){},p.prototype.visitDisjunction=function(d){},p.prototype.visitAlternative=function(d){},p.prototype.visitStartAnchor=function(d){},p.prototype.visitEndAnchor=function(d){},p.prototype.visitWordBoundary=function(d){},p.prototype.visitNonWordBoundary=function(d){},p.prototype.visitLookahead=function(d){},p.prototype.visitNegativeLookahead=function(d){},p.prototype.visitCharacter=function(d){},p.prototype.visitSet=function(d){},p.prototype.visitGroup=function(d){},p.prototype.visitGroupBackReference=function(d){},p.prototype.visitQuantifier=function(d){},{RegExpParser:r,BaseRegExpVisitor:p,VERSION:"0.5.0"}})});var ey=I(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});Xg.clearRegExpParserCache=Xg.getRegExpAst=void 0;var xEe=_I(),$I={},PEe=new xEe.RegExpParser;function kEe(r){var e=r.toString();if($I.hasOwnProperty(e))return $I[e];var t=PEe.pattern(e);return $I[e]=t,t}Xg.getRegExpAst=kEe;function DEe(){$I={}}Xg.clearRegExpParserCache=DEe});var zG=I(mn=>{"use strict";var REe=mn&&mn.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(mn,"__esModule",{value:!0});mn.canMatchCharCode=mn.firstCharOptimizedIndices=mn.getOptimizedStartCodesIndices=mn.failedOptimizationPrefixMsg=void 0;var qG=_I(),us=Kt(),JG=ey(),Pa=Rv(),WG="Complement Sets are not supported for first char optimization";mn.failedOptimizationPrefixMsg=`Unable to use "first char" lexer optimizations: -`;function FEe(r,e){e===void 0&&(e=!1);try{var t=(0,JG.getRegExpAst)(r),i=ry(t.value,{},t.flags.ignoreCase);return i}catch(s){if(s.message===WG)e&&(0,us.PRINT_WARNING)(""+mn.failedOptimizationPrefixMsg+(" Unable to optimize: < "+r.toString()+` > -`)+` Complement Sets cannot be automatically optimized. - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{var n="";e&&(n=` - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),(0,us.PRINT_ERROR)(mn.failedOptimizationPrefixMsg+` -`+(" Failed parsing: < "+r.toString()+` > -`)+(" Using the regexp-to-ast library version: "+qG.VERSION+` -`)+" Please open an issue at: https://github.com/bd82/regexp-to-ast/issues"+n)}}return[]}mn.getOptimizedStartCodesIndices=FEe;function ry(r,e,t){switch(r.type){case"Disjunction":for(var i=0;i=Pa.minOptimizationVal)for(var h=u.from>=Pa.minOptimizationVal?u.from:Pa.minOptimizationVal,p=u.to,d=(0,Pa.charCodeToOptimizedIndex)(h),m=(0,Pa.charCodeToOptimizedIndex)(p),y=d;y<=m;y++)e[y]=y}}});break;case"Group":ry(o.value,e,t);break;default:throw Error("Non Exhaustive Match")}var a=o.quantifier!==void 0&&o.quantifier.atLeast===0;if(o.type==="Group"&&Dv(o)===!1||o.type!=="Group"&&a===!1)break}break;default:throw Error("non exhaustive match!")}return(0,us.values)(e)}mn.firstCharOptimizedIndices=ry;function ty(r,e,t){var i=(0,Pa.charCodeToOptimizedIndex)(r);e[i]=i,t===!0&&TEe(r,e)}function TEe(r,e){var t=String.fromCharCode(r),i=t.toUpperCase();if(i!==t){var n=(0,Pa.charCodeToOptimizedIndex)(i.charCodeAt(0));e[n]=n}else{var s=t.toLowerCase();if(s!==t){var n=(0,Pa.charCodeToOptimizedIndex)(s.charCodeAt(0));e[n]=n}}}function YG(r,e){return(0,us.find)(r.value,function(t){if(typeof t=="number")return(0,us.contains)(e,t);var i=t;return(0,us.find)(e,function(n){return i.from<=n&&n<=i.to})!==void 0})}function Dv(r){return r.quantifier&&r.quantifier.atLeast===0?!0:r.value?(0,us.isArray)(r.value)?(0,us.every)(r.value,Dv):Dv(r.value):!1}var NEe=function(r){REe(e,r);function e(t){var i=r.call(this)||this;return i.targetCharCodes=t,i.found=!1,i}return e.prototype.visitChildren=function(t){if(this.found!==!0){switch(t.type){case"Lookahead":this.visitLookahead(t);return;case"NegativeLookahead":this.visitNegativeLookahead(t);return}r.prototype.visitChildren.call(this,t)}},e.prototype.visitCharacter=function(t){(0,us.contains)(this.targetCharCodes,t.value)&&(this.found=!0)},e.prototype.visitSet=function(t){t.complement?YG(t,this.targetCharCodes)===void 0&&(this.found=!0):YG(t,this.targetCharCodes)!==void 0&&(this.found=!0)},e}(qG.BaseRegExpVisitor);function LEe(r,e){if(e instanceof RegExp){var t=(0,JG.getRegExpAst)(e),i=new NEe(r);return i.visit(t),i.found}else return(0,us.find)(e,function(n){return(0,us.contains)(r,n.charCodeAt(0))})!==void 0}mn.canMatchCharCode=LEe});var Rv=I(We=>{"use strict";var VG=We&&We.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(We,"__esModule",{value:!0});We.charCodeToOptimizedIndex=We.minOptimizationVal=We.buildLineBreakIssueMessage=We.LineTerminatorOptimizedTester=We.isShortPattern=We.isCustomPattern=We.cloneEmptyGroups=We.performWarningRuntimeChecks=We.performRuntimeChecks=We.addStickyFlag=We.addStartOfInput=We.findUnreachablePatterns=We.findModesThatDoNotExist=We.findInvalidGroupType=We.findDuplicatePatterns=We.findUnsupportedFlags=We.findStartOfInputAnchor=We.findEmptyMatchRegExps=We.findEndOfInputAnchor=We.findInvalidPatterns=We.findMissingPatterns=We.validatePatterns=We.analyzeTokenTypes=We.enableSticky=We.disableSticky=We.SUPPORT_STICKY=We.MODES=We.DEFAULT_MODE=void 0;var XG=_I(),tr=Qd(),Se=Kt(),Zg=zG(),ZG=ey(),ko="PATTERN";We.DEFAULT_MODE="defaultMode";We.MODES="modes";We.SUPPORT_STICKY=typeof new RegExp("(?:)").sticky=="boolean";function OEe(){We.SUPPORT_STICKY=!1}We.disableSticky=OEe;function MEe(){We.SUPPORT_STICKY=!0}We.enableSticky=MEe;function KEe(r,e){e=(0,Se.defaults)(e,{useSticky:We.SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` -`],tracer:function(S,P){return P()}});var t=e.tracer;t("initCharCodeToOptimizedIndexMap",function(){VEe()});var i;t("Reject Lexer.NA",function(){i=(0,Se.reject)(r,function(S){return S[ko]===tr.Lexer.NA})});var n=!1,s;t("Transform Patterns",function(){n=!1,s=(0,Se.map)(i,function(S){var P=S[ko];if((0,Se.isRegExp)(P)){var F=P.source;return F.length===1&&F!=="^"&&F!=="$"&&F!=="."&&!P.ignoreCase?F:F.length===2&&F[0]==="\\"&&!(0,Se.contains)(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],F[1])?F[1]:e.useSticky?Nv(P):Tv(P)}else{if((0,Se.isFunction)(P))return n=!0,{exec:P};if((0,Se.has)(P,"exec"))return n=!0,P;if(typeof P=="string"){if(P.length===1)return P;var H=P.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),q=new RegExp(H);return e.useSticky?Nv(q):Tv(q)}else throw Error("non exhaustive match")}})});var o,a,l,c,u;t("misc mapping",function(){o=(0,Se.map)(i,function(S){return S.tokenTypeIdx}),a=(0,Se.map)(i,function(S){var P=S.GROUP;if(P!==tr.Lexer.SKIPPED){if((0,Se.isString)(P))return P;if((0,Se.isUndefined)(P))return!1;throw Error("non exhaustive match")}}),l=(0,Se.map)(i,function(S){var P=S.LONGER_ALT;if(P){var F=(0,Se.isArray)(P)?(0,Se.map)(P,function(H){return(0,Se.indexOf)(i,H)}):[(0,Se.indexOf)(i,P)];return F}}),c=(0,Se.map)(i,function(S){return S.PUSH_MODE}),u=(0,Se.map)(i,function(S){return(0,Se.has)(S,"POP_MODE")})});var g;t("Line Terminator Handling",function(){var S=uY(e.lineTerminatorCharacters);g=(0,Se.map)(i,function(P){return!1}),e.positionTracking!=="onlyOffset"&&(g=(0,Se.map)(i,function(P){if((0,Se.has)(P,"LINE_BREAKS"))return P.LINE_BREAKS;if(lY(P,S)===!1)return(0,Zg.canMatchCharCode)(S,P.PATTERN)}))});var h,p,d,m;t("Misc Mapping #2",function(){h=(0,Se.map)(i,Ov),p=(0,Se.map)(s,AY),d=(0,Se.reduce)(i,function(S,P){var F=P.GROUP;return(0,Se.isString)(F)&&F!==tr.Lexer.SKIPPED&&(S[F]=[]),S},{}),m=(0,Se.map)(s,function(S,P){return{pattern:s[P],longerAlt:l[P],canLineTerminator:g[P],isCustom:h[P],short:p[P],group:a[P],push:c[P],pop:u[P],tokenTypeIdx:o[P],tokenType:i[P]}})});var y=!0,B=[];return e.safeMode||t("First Char Optimization",function(){B=(0,Se.reduce)(i,function(S,P,F){if(typeof P.PATTERN=="string"){var H=P.PATTERN.charCodeAt(0),q=Lv(H);Fv(S,q,m[F])}else if((0,Se.isArray)(P.START_CHARS_HINT)){var _;(0,Se.forEach)(P.START_CHARS_HINT,function(W){var Z=typeof W=="string"?W.charCodeAt(0):W,A=Lv(Z);_!==A&&(_=A,Fv(S,A,m[F]))})}else if((0,Se.isRegExp)(P.PATTERN))if(P.PATTERN.unicode)y=!1,e.ensureOptimizations&&(0,Se.PRINT_ERROR)(""+Zg.failedOptimizationPrefixMsg+(" Unable to analyze < "+P.PATTERN.toString()+` > pattern. -`)+` The regexp unicode flag is not currently supported by the regexp-to-ast library. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{var X=(0,Zg.getOptimizedStartCodesIndices)(P.PATTERN,e.ensureOptimizations);(0,Se.isEmpty)(X)&&(y=!1),(0,Se.forEach)(X,function(W){Fv(S,W,m[F])})}else e.ensureOptimizations&&(0,Se.PRINT_ERROR)(""+Zg.failedOptimizationPrefixMsg+(" TokenType: <"+P.name+`> is using a custom token pattern without providing parameter. -`)+` This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),y=!1;return S},[])}),t("ArrayPacking",function(){B=(0,Se.packArray)(B)}),{emptyGroups:d,patternIdxToConfig:m,charCodeToPatternIdxToConfig:B,hasCustom:n,canBeOptimized:y}}We.analyzeTokenTypes=KEe;function UEe(r,e){var t=[],i=_G(r);t=t.concat(i.errors);var n=$G(i.valid),s=n.valid;return t=t.concat(n.errors),t=t.concat(HEe(s)),t=t.concat(sY(s)),t=t.concat(oY(s,e)),t=t.concat(aY(s)),t}We.validatePatterns=UEe;function HEe(r){var e=[],t=(0,Se.filter)(r,function(i){return(0,Se.isRegExp)(i[ko])});return e=e.concat(eY(t)),e=e.concat(rY(t)),e=e.concat(iY(t)),e=e.concat(nY(t)),e=e.concat(tY(t)),e}function _G(r){var e=(0,Se.filter)(r,function(n){return!(0,Se.has)(n,ko)}),t=(0,Se.map)(e,function(n){return{message:"Token Type: ->"+n.name+"<- missing static 'PATTERN' property",type:tr.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[n]}}),i=(0,Se.difference)(r,e);return{errors:t,valid:i}}We.findMissingPatterns=_G;function $G(r){var e=(0,Se.filter)(r,function(n){var s=n[ko];return!(0,Se.isRegExp)(s)&&!(0,Se.isFunction)(s)&&!(0,Se.has)(s,"exec")&&!(0,Se.isString)(s)}),t=(0,Se.map)(e,function(n){return{message:"Token Type: ->"+n.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:tr.LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[n]}}),i=(0,Se.difference)(r,e);return{errors:t,valid:i}}We.findInvalidPatterns=$G;var jEe=/[^\\][\$]/;function eY(r){var e=function(n){VG(s,n);function s(){var o=n!==null&&n.apply(this,arguments)||this;return o.found=!1,o}return s.prototype.visitEndAnchor=function(o){this.found=!0},s}(XG.BaseRegExpVisitor),t=(0,Se.filter)(r,function(n){var s=n[ko];try{var o=(0,ZG.getRegExpAst)(s),a=new e;return a.visit(o),a.found}catch{return jEe.test(s.source)}}),i=(0,Se.map)(t,function(n){return{message:`Unexpected RegExp Anchor Error: - Token Type: ->`+n.name+`<- static 'PATTERN' cannot contain end of input anchor '$' - See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:tr.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[n]}});return i}We.findEndOfInputAnchor=eY;function tY(r){var e=(0,Se.filter)(r,function(i){var n=i[ko];return n.test("")}),t=(0,Se.map)(e,function(i){return{message:"Token Type: ->"+i.name+"<- static 'PATTERN' must not match an empty string",type:tr.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[i]}});return t}We.findEmptyMatchRegExps=tY;var GEe=/[^\\[][\^]|^\^/;function rY(r){var e=function(n){VG(s,n);function s(){var o=n!==null&&n.apply(this,arguments)||this;return o.found=!1,o}return s.prototype.visitStartAnchor=function(o){this.found=!0},s}(XG.BaseRegExpVisitor),t=(0,Se.filter)(r,function(n){var s=n[ko];try{var o=(0,ZG.getRegExpAst)(s),a=new e;return a.visit(o),a.found}catch{return GEe.test(s.source)}}),i=(0,Se.map)(t,function(n){return{message:`Unexpected RegExp Anchor Error: - Token Type: ->`+n.name+`<- static 'PATTERN' cannot contain start of input anchor '^' - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:tr.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[n]}});return i}We.findStartOfInputAnchor=rY;function iY(r){var e=(0,Se.filter)(r,function(i){var n=i[ko];return n instanceof RegExp&&(n.multiline||n.global)}),t=(0,Se.map)(e,function(i){return{message:"Token Type: ->"+i.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:tr.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[i]}});return t}We.findUnsupportedFlags=iY;function nY(r){var e=[],t=(0,Se.map)(r,function(s){return(0,Se.reduce)(r,function(o,a){return s.PATTERN.source===a.PATTERN.source&&!(0,Se.contains)(e,a)&&a.PATTERN!==tr.Lexer.NA&&(e.push(a),o.push(a)),o},[])});t=(0,Se.compact)(t);var i=(0,Se.filter)(t,function(s){return s.length>1}),n=(0,Se.map)(i,function(s){var o=(0,Se.map)(s,function(l){return l.name}),a=(0,Se.first)(s).PATTERN;return{message:"The same RegExp pattern ->"+a+"<-"+("has been used in all of the following Token Types: "+o.join(", ")+" <-"),type:tr.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:s}});return n}We.findDuplicatePatterns=nY;function sY(r){var e=(0,Se.filter)(r,function(i){if(!(0,Se.has)(i,"GROUP"))return!1;var n=i.GROUP;return n!==tr.Lexer.SKIPPED&&n!==tr.Lexer.NA&&!(0,Se.isString)(n)}),t=(0,Se.map)(e,function(i){return{message:"Token Type: ->"+i.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:tr.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[i]}});return t}We.findInvalidGroupType=sY;function oY(r,e){var t=(0,Se.filter)(r,function(n){return n.PUSH_MODE!==void 0&&!(0,Se.contains)(e,n.PUSH_MODE)}),i=(0,Se.map)(t,function(n){var s="Token Type: ->"+n.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+n.PUSH_MODE+"<-which does not exist";return{message:s,type:tr.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[n]}});return i}We.findModesThatDoNotExist=oY;function aY(r){var e=[],t=(0,Se.reduce)(r,function(i,n,s){var o=n.PATTERN;return o===tr.Lexer.NA||((0,Se.isString)(o)?i.push({str:o,idx:s,tokenType:n}):(0,Se.isRegExp)(o)&&qEe(o)&&i.push({str:o.source,idx:s,tokenType:n})),i},[]);return(0,Se.forEach)(r,function(i,n){(0,Se.forEach)(t,function(s){var o=s.str,a=s.idx,l=s.tokenType;if(n"+i.name+"<-")+`in the lexer's definition. -See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:c,type:tr.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[i,l]})}})}),e}We.findUnreachablePatterns=aY;function YEe(r,e){if((0,Se.isRegExp)(e)){var t=e.exec(r);return t!==null&&t.index===0}else{if((0,Se.isFunction)(e))return e(r,0,[],{});if((0,Se.has)(e,"exec"))return e.exec(r,0,[],{});if(typeof e=="string")return e===r;throw Error("non exhaustive match")}}function qEe(r){var e=[".","\\","[","]","|","^","$","(",")","?","*","+","{"];return(0,Se.find)(e,function(t){return r.source.indexOf(t)!==-1})===void 0}function Tv(r){var e=r.ignoreCase?"i":"";return new RegExp("^(?:"+r.source+")",e)}We.addStartOfInput=Tv;function Nv(r){var e=r.ignoreCase?"iy":"y";return new RegExp(""+r.source,e)}We.addStickyFlag=Nv;function JEe(r,e,t){var i=[];return(0,Se.has)(r,We.DEFAULT_MODE)||i.push({message:"A MultiMode Lexer cannot be initialized without a <"+We.DEFAULT_MODE+`> property in its definition -`,type:tr.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),(0,Se.has)(r,We.MODES)||i.push({message:"A MultiMode Lexer cannot be initialized without a <"+We.MODES+`> property in its definition -`,type:tr.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),(0,Se.has)(r,We.MODES)&&(0,Se.has)(r,We.DEFAULT_MODE)&&!(0,Se.has)(r.modes,r.defaultMode)&&i.push({message:"A MultiMode Lexer cannot be initialized with a "+We.DEFAULT_MODE+": <"+r.defaultMode+`>which does not exist -`,type:tr.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),(0,Se.has)(r,We.MODES)&&(0,Se.forEach)(r.modes,function(n,s){(0,Se.forEach)(n,function(o,a){(0,Se.isUndefined)(o)&&i.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:"+("<"+s+"> at index: <"+a+`> -`),type:tr.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})})}),i}We.performRuntimeChecks=JEe;function WEe(r,e,t){var i=[],n=!1,s=(0,Se.compact)((0,Se.flatten)((0,Se.mapValues)(r.modes,function(l){return l}))),o=(0,Se.reject)(s,function(l){return l[ko]===tr.Lexer.NA}),a=uY(t);return e&&(0,Se.forEach)(o,function(l){var c=lY(l,a);if(c!==!1){var u=cY(l,c),g={message:u,type:c.issue,tokenType:l};i.push(g)}else(0,Se.has)(l,"LINE_BREAKS")?l.LINE_BREAKS===!0&&(n=!0):(0,Zg.canMatchCharCode)(a,l.PATTERN)&&(n=!0)}),e&&!n&&i.push({message:`Warning: No LINE_BREAKS Found. - This Lexer has been defined to track line and column information, - But none of the Token Types can be identified as matching a line terminator. - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS - for details.`,type:tr.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),i}We.performWarningRuntimeChecks=WEe;function zEe(r){var e={},t=(0,Se.keys)(r);return(0,Se.forEach)(t,function(i){var n=r[i];if((0,Se.isArray)(n))e[i]=[];else throw Error("non exhaustive match")}),e}We.cloneEmptyGroups=zEe;function Ov(r){var e=r.PATTERN;if((0,Se.isRegExp)(e))return!1;if((0,Se.isFunction)(e))return!0;if((0,Se.has)(e,"exec"))return!0;if((0,Se.isString)(e))return!1;throw Error("non exhaustive match")}We.isCustomPattern=Ov;function AY(r){return(0,Se.isString)(r)&&r.length===1?r.charCodeAt(0):!1}We.isShortPattern=AY;We.LineTerminatorOptimizedTester={test:function(r){for(var e=r.length,t=this.lastIndex;t Token Type -`)+(" Root cause: "+e.errMsg+`. -`)+" For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(e.issue===tr.LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. -`+(" The problem is in the <"+r.name+`> Token Type -`)+" For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}We.buildLineBreakIssueMessage=cY;function uY(r){var e=(0,Se.map)(r,function(t){return(0,Se.isString)(t)&&t.length>0?t.charCodeAt(0):t});return e}function Fv(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}We.minOptimizationVal=256;var iy=[];function Lv(r){return r255?255+~~(r/255):r}}});var _g=I(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.isTokenType=Rt.hasExtendingTokensTypesMapProperty=Rt.hasExtendingTokensTypesProperty=Rt.hasCategoriesProperty=Rt.hasShortKeyProperty=Rt.singleAssignCategoriesToksMap=Rt.assignCategoriesMapProp=Rt.assignCategoriesTokensProp=Rt.assignTokenDefaultProps=Rt.expandCategories=Rt.augmentTokenTypes=Rt.tokenIdxToClass=Rt.tokenShortNameIdx=Rt.tokenStructuredMatcherNoCategories=Rt.tokenStructuredMatcher=void 0;var Vr=Kt();function XEe(r,e){var t=r.tokenTypeIdx;return t===e.tokenTypeIdx?!0:e.isParent===!0&&e.categoryMatchesMap[t]===!0}Rt.tokenStructuredMatcher=XEe;function ZEe(r,e){return r.tokenTypeIdx===e.tokenTypeIdx}Rt.tokenStructuredMatcherNoCategories=ZEe;Rt.tokenShortNameIdx=1;Rt.tokenIdxToClass={};function _Ee(r){var e=gY(r);fY(e),pY(e),hY(e),(0,Vr.forEach)(e,function(t){t.isParent=t.categoryMatches.length>0})}Rt.augmentTokenTypes=_Ee;function gY(r){for(var e=(0,Vr.cloneArr)(r),t=r,i=!0;i;){t=(0,Vr.compact)((0,Vr.flatten)((0,Vr.map)(t,function(s){return s.CATEGORIES})));var n=(0,Vr.difference)(t,e);e=e.concat(n),(0,Vr.isEmpty)(n)?i=!1:t=n}return e}Rt.expandCategories=gY;function fY(r){(0,Vr.forEach)(r,function(e){dY(e)||(Rt.tokenIdxToClass[Rt.tokenShortNameIdx]=e,e.tokenTypeIdx=Rt.tokenShortNameIdx++),Mv(e)&&!(0,Vr.isArray)(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),Mv(e)||(e.CATEGORIES=[]),CY(e)||(e.categoryMatches=[]),mY(e)||(e.categoryMatchesMap={})})}Rt.assignTokenDefaultProps=fY;function hY(r){(0,Vr.forEach)(r,function(e){e.categoryMatches=[],(0,Vr.forEach)(e.categoryMatchesMap,function(t,i){e.categoryMatches.push(Rt.tokenIdxToClass[i].tokenTypeIdx)})})}Rt.assignCategoriesTokensProp=hY;function pY(r){(0,Vr.forEach)(r,function(e){Kv([],e)})}Rt.assignCategoriesMapProp=pY;function Kv(r,e){(0,Vr.forEach)(r,function(t){e.categoryMatchesMap[t.tokenTypeIdx]=!0}),(0,Vr.forEach)(e.CATEGORIES,function(t){var i=r.concat(e);(0,Vr.contains)(i,t)||Kv(i,t)})}Rt.singleAssignCategoriesToksMap=Kv;function dY(r){return(0,Vr.has)(r,"tokenTypeIdx")}Rt.hasShortKeyProperty=dY;function Mv(r){return(0,Vr.has)(r,"CATEGORIES")}Rt.hasCategoriesProperty=Mv;function CY(r){return(0,Vr.has)(r,"categoryMatches")}Rt.hasExtendingTokensTypesProperty=CY;function mY(r){return(0,Vr.has)(r,"categoryMatchesMap")}Rt.hasExtendingTokensTypesMapProperty=mY;function $Ee(r){return(0,Vr.has)(r,"tokenTypeIdx")}Rt.isTokenType=$Ee});var Uv=I(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});ny.defaultLexerErrorProvider=void 0;ny.defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(r){return"Unable to pop Lexer Mode after encountering Token ->"+r.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(r,e,t,i,n){return"unexpected character: ->"+r.charAt(e)+"<- at offset: "+e+","+(" skipped "+t+" characters.")}}});var Qd=I(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.Lexer=Ec.LexerDefinitionErrorType=void 0;var Zs=Rv(),rr=Kt(),eIe=_g(),tIe=Uv(),rIe=ey(),iIe;(function(r){r[r.MISSING_PATTERN=0]="MISSING_PATTERN",r[r.INVALID_PATTERN=1]="INVALID_PATTERN",r[r.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",r[r.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",r[r.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",r[r.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",r[r.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",r[r.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",r[r.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",r[r.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",r[r.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",r[r.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",r[r.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",r[r.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",r[r.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",r[r.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",r[r.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"})(iIe=Ec.LexerDefinitionErrorType||(Ec.LexerDefinitionErrorType={}));var bd={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` -`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:tIe.defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1};Object.freeze(bd);var nIe=function(){function r(e,t){var i=this;if(t===void 0&&(t=bd),this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},typeof t=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. -a boolean 2nd argument is no longer supported`);this.config=(0,rr.merge)(bd,t);var n=this.config.traceInitPerf;n===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof n=="number"&&(this.traceInitMaxIdent=n,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",function(){var s,o=!0;i.TRACE_INIT("Lexer Config handling",function(){if(i.config.lineTerminatorsPattern===bd.lineTerminatorsPattern)i.config.lineTerminatorsPattern=Zs.LineTerminatorOptimizedTester;else if(i.config.lineTerminatorCharacters===bd.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(t.safeMode&&t.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');i.trackStartLines=/full|onlyStart/i.test(i.config.positionTracking),i.trackEndLines=/full/i.test(i.config.positionTracking),(0,rr.isArray)(e)?(s={modes:{}},s.modes[Zs.DEFAULT_MODE]=(0,rr.cloneArr)(e),s[Zs.DEFAULT_MODE]=Zs.DEFAULT_MODE):(o=!1,s=(0,rr.cloneObj)(e))}),i.config.skipValidations===!1&&(i.TRACE_INIT("performRuntimeChecks",function(){i.lexerDefinitionErrors=i.lexerDefinitionErrors.concat((0,Zs.performRuntimeChecks)(s,i.trackStartLines,i.config.lineTerminatorCharacters))}),i.TRACE_INIT("performWarningRuntimeChecks",function(){i.lexerDefinitionWarning=i.lexerDefinitionWarning.concat((0,Zs.performWarningRuntimeChecks)(s,i.trackStartLines,i.config.lineTerminatorCharacters))})),s.modes=s.modes?s.modes:{},(0,rr.forEach)(s.modes,function(u,g){s.modes[g]=(0,rr.reject)(u,function(h){return(0,rr.isUndefined)(h)})});var a=(0,rr.keys)(s.modes);if((0,rr.forEach)(s.modes,function(u,g){i.TRACE_INIT("Mode: <"+g+"> processing",function(){if(i.modes.push(g),i.config.skipValidations===!1&&i.TRACE_INIT("validatePatterns",function(){i.lexerDefinitionErrors=i.lexerDefinitionErrors.concat((0,Zs.validatePatterns)(u,a))}),(0,rr.isEmpty)(i.lexerDefinitionErrors)){(0,eIe.augmentTokenTypes)(u);var h;i.TRACE_INIT("analyzeTokenTypes",function(){h=(0,Zs.analyzeTokenTypes)(u,{lineTerminatorCharacters:i.config.lineTerminatorCharacters,positionTracking:t.positionTracking,ensureOptimizations:t.ensureOptimizations,safeMode:t.safeMode,tracer:i.TRACE_INIT.bind(i)})}),i.patternIdxToConfig[g]=h.patternIdxToConfig,i.charCodeToPatternIdxToConfig[g]=h.charCodeToPatternIdxToConfig,i.emptyGroups=(0,rr.merge)(i.emptyGroups,h.emptyGroups),i.hasCustom=h.hasCustom||i.hasCustom,i.canModeBeOptimized[g]=h.canBeOptimized}})}),i.defaultMode=s.defaultMode,!(0,rr.isEmpty)(i.lexerDefinitionErrors)&&!i.config.deferDefinitionErrorsHandling){var l=(0,rr.map)(i.lexerDefinitionErrors,function(u){return u.message}),c=l.join(`----------------------- -`);throw new Error(`Errors detected in definition of Lexer: -`+c)}(0,rr.forEach)(i.lexerDefinitionWarning,function(u){(0,rr.PRINT_WARNING)(u.message)}),i.TRACE_INIT("Choosing sub-methods implementations",function(){if(Zs.SUPPORT_STICKY?(i.chopInput=rr.IDENTITY,i.match=i.matchWithTest):(i.updateLastIndex=rr.NOOP,i.match=i.matchWithExec),o&&(i.handleModes=rr.NOOP),i.trackStartLines===!1&&(i.computeNewColumn=rr.IDENTITY),i.trackEndLines===!1&&(i.updateTokenEndLineColumnLocation=rr.NOOP),/full/i.test(i.config.positionTracking))i.createTokenInstance=i.createFullToken;else if(/onlyStart/i.test(i.config.positionTracking))i.createTokenInstance=i.createStartOnlyToken;else if(/onlyOffset/i.test(i.config.positionTracking))i.createTokenInstance=i.createOffsetOnlyToken;else throw Error('Invalid config option: "'+i.config.positionTracking+'"');i.hasCustom?(i.addToken=i.addTokenUsingPush,i.handlePayload=i.handlePayloadWithCustom):(i.addToken=i.addTokenUsingMemberAccess,i.handlePayload=i.handlePayloadNoCustom)}),i.TRACE_INIT("Failed Optimization Warnings",function(){var u=(0,rr.reduce)(i.canModeBeOptimized,function(g,h,p){return h===!1&&g.push(p),g},[]);if(t.ensureOptimizations&&!(0,rr.isEmpty)(u))throw Error("Lexer Modes: < "+u.join(", ")+` > cannot be optimized. - Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. - Or inspect the console log for details on how to resolve these issues.`)}),i.TRACE_INIT("clearRegExpParserCache",function(){(0,rIe.clearRegExpParserCache)()}),i.TRACE_INIT("toFastProperties",function(){(0,rr.toFastProperties)(i)})})}return r.prototype.tokenize=function(e,t){if(t===void 0&&(t=this.defaultMode),!(0,rr.isEmpty)(this.lexerDefinitionErrors)){var i=(0,rr.map)(this.lexerDefinitionErrors,function(o){return o.message}),n=i.join(`----------------------- -`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: -`+n)}var s=this.tokenizeInternal(e,t);return s},r.prototype.tokenizeInternal=function(e,t){var i=this,n,s,o,a,l,c,u,g,h,p,d,m,y,B,S,P,F=e,H=F.length,q=0,_=0,X=this.hasCustom?0:Math.floor(e.length/10),W=new Array(X),Z=[],A=this.trackStartLines?1:void 0,ne=this.trackStartLines?1:void 0,ue=(0,Zs.cloneEmptyGroups)(this.emptyGroups),te=this.trackStartLines,O=this.config.lineTerminatorsPattern,T=0,ce=[],he=[],Pe=[],De=[];Object.freeze(De);var Re=void 0;function se(){return ce}function Ae(fr){var Ei=(0,Zs.charCodeToOptimizedIndex)(fr),rs=he[Ei];return rs===void 0?De:rs}var ye=function(fr){if(Pe.length===1&&fr.tokenType.PUSH_MODE===void 0){var Ei=i.config.errorMessageProvider.buildUnableToPopLexerModeMessage(fr);Z.push({offset:fr.startOffset,line:fr.startLine!==void 0?fr.startLine:void 0,column:fr.startColumn!==void 0?fr.startColumn:void 0,length:fr.image.length,message:Ei})}else{Pe.pop();var rs=(0,rr.last)(Pe);ce=i.patternIdxToConfig[rs],he=i.charCodeToPatternIdxToConfig[rs],T=ce.length;var ua=i.canModeBeOptimized[rs]&&i.config.safeMode===!1;he&&ua?Re=Ae:Re=se}};function ge(fr){Pe.push(fr),he=this.charCodeToPatternIdxToConfig[fr],ce=this.patternIdxToConfig[fr],T=ce.length,T=ce.length;var Ei=this.canModeBeOptimized[fr]&&this.config.safeMode===!1;he&&Ei?Re=Ae:Re=se}ge.call(this,t);for(var oe;qc.length){c=a,u=g,oe=Ze;break}}}break}}if(c!==null){if(h=c.length,p=oe.group,p!==void 0&&(d=oe.tokenTypeIdx,m=this.createTokenInstance(c,q,d,oe.tokenType,A,ne,h),this.handlePayload(m,u),p===!1?_=this.addToken(W,_,m):ue[p].push(m)),e=this.chopInput(e,h),q=q+h,ne=this.computeNewColumn(ne,h),te===!0&&oe.canLineTerminator===!0){var mt=0,Lr=void 0,ti=void 0;O.lastIndex=0;do Lr=O.test(c),Lr===!0&&(ti=O.lastIndex-1,mt++);while(Lr===!0);mt!==0&&(A=A+mt,ne=h-ti,this.updateTokenEndLineColumnLocation(m,p,ti,mt,A,ne,h))}this.handleModes(oe,ye,ge,m)}else{for(var ui=q,gr=A,gi=ne,ri=!1;!ri&&q <"+e+">");var n=(0,rr.timer)(t),s=n.time,o=n.value,a=s>10?console.warn:console.log;return this.traceInitIndent time: "+s+"ms"),this.traceInitIndent--,o}else return t()},r.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",r.NA=/NOT_APPLICABLE/,r}();Ec.Lexer=nIe});var TA=I(Si=>{"use strict";Object.defineProperty(Si,"__esModule",{value:!0});Si.tokenMatcher=Si.createTokenInstance=Si.EOF=Si.createToken=Si.hasTokenLabel=Si.tokenName=Si.tokenLabel=void 0;var _s=Kt(),sIe=Qd(),Hv=_g();function oIe(r){return vY(r)?r.LABEL:r.name}Si.tokenLabel=oIe;function aIe(r){return r.name}Si.tokenName=aIe;function vY(r){return(0,_s.isString)(r.LABEL)&&r.LABEL!==""}Si.hasTokenLabel=vY;var AIe="parent",EY="categories",IY="label",yY="group",wY="push_mode",BY="pop_mode",QY="longer_alt",bY="line_breaks",SY="start_chars_hint";function xY(r){return lIe(r)}Si.createToken=xY;function lIe(r){var e=r.pattern,t={};if(t.name=r.name,(0,_s.isUndefined)(e)||(t.PATTERN=e),(0,_s.has)(r,AIe))throw`The parent property is no longer supported. -See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return(0,_s.has)(r,EY)&&(t.CATEGORIES=r[EY]),(0,Hv.augmentTokenTypes)([t]),(0,_s.has)(r,IY)&&(t.LABEL=r[IY]),(0,_s.has)(r,yY)&&(t.GROUP=r[yY]),(0,_s.has)(r,BY)&&(t.POP_MODE=r[BY]),(0,_s.has)(r,wY)&&(t.PUSH_MODE=r[wY]),(0,_s.has)(r,QY)&&(t.LONGER_ALT=r[QY]),(0,_s.has)(r,bY)&&(t.LINE_BREAKS=r[bY]),(0,_s.has)(r,SY)&&(t.START_CHARS_HINT=r[SY]),t}Si.EOF=xY({name:"EOF",pattern:sIe.Lexer.NA});(0,Hv.augmentTokenTypes)([Si.EOF]);function cIe(r,e,t,i,n,s,o,a){return{image:e,startOffset:t,endOffset:i,startLine:n,endLine:s,startColumn:o,endColumn:a,tokenTypeIdx:r.tokenTypeIdx,tokenType:r}}Si.createTokenInstance=cIe;function uIe(r,e){return(0,Hv.tokenStructuredMatcher)(r,e)}Si.tokenMatcher=uIe});var En=I(qt=>{"use strict";var ka=qt&&qt.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(qt,"__esModule",{value:!0});qt.serializeProduction=qt.serializeGrammar=qt.Terminal=qt.Alternation=qt.RepetitionWithSeparator=qt.Repetition=qt.RepetitionMandatoryWithSeparator=qt.RepetitionMandatory=qt.Option=qt.Alternative=qt.Rule=qt.NonTerminal=qt.AbstractProduction=void 0;var or=Kt(),gIe=TA(),Do=function(){function r(e){this._definition=e}return Object.defineProperty(r.prototype,"definition",{get:function(){return this._definition},set:function(e){this._definition=e},enumerable:!1,configurable:!0}),r.prototype.accept=function(e){e.visit(this),(0,or.forEach)(this.definition,function(t){t.accept(e)})},r}();qt.AbstractProduction=Do;var PY=function(r){ka(e,r);function e(t){var i=r.call(this,[])||this;return i.idx=1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return Object.defineProperty(e.prototype,"definition",{get:function(){return this.referencedRule!==void 0?this.referencedRule.definition:[]},set:function(t){},enumerable:!1,configurable:!0}),e.prototype.accept=function(t){t.visit(this)},e}(Do);qt.NonTerminal=PY;var kY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.orgText="",(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return e}(Do);qt.Rule=kY;var DY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.ignoreAmbiguities=!1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return e}(Do);qt.Alternative=DY;var RY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.idx=1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return e}(Do);qt.Option=RY;var FY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.idx=1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return e}(Do);qt.RepetitionMandatory=FY;var TY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.idx=1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return e}(Do);qt.RepetitionMandatoryWithSeparator=TY;var NY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.idx=1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return e}(Do);qt.Repetition=NY;var LY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.idx=1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return e}(Do);qt.RepetitionWithSeparator=LY;var OY=function(r){ka(e,r);function e(t){var i=r.call(this,t.definition)||this;return i.idx=1,i.ignoreAmbiguities=!1,i.hasPredicates=!1,(0,or.assign)(i,(0,or.pick)(t,function(n){return n!==void 0})),i}return Object.defineProperty(e.prototype,"definition",{get:function(){return this._definition},set:function(t){this._definition=t},enumerable:!1,configurable:!0}),e}(Do);qt.Alternation=OY;var sy=function(){function r(e){this.idx=1,(0,or.assign)(this,(0,or.pick)(e,function(t){return t!==void 0}))}return r.prototype.accept=function(e){e.visit(this)},r}();qt.Terminal=sy;function fIe(r){return(0,or.map)(r,Sd)}qt.serializeGrammar=fIe;function Sd(r){function e(s){return(0,or.map)(s,Sd)}if(r instanceof PY){var t={type:"NonTerminal",name:r.nonTerminalName,idx:r.idx};return(0,or.isString)(r.label)&&(t.label=r.label),t}else{if(r instanceof DY)return{type:"Alternative",definition:e(r.definition)};if(r instanceof RY)return{type:"Option",idx:r.idx,definition:e(r.definition)};if(r instanceof FY)return{type:"RepetitionMandatory",idx:r.idx,definition:e(r.definition)};if(r instanceof TY)return{type:"RepetitionMandatoryWithSeparator",idx:r.idx,separator:Sd(new sy({terminalType:r.separator})),definition:e(r.definition)};if(r instanceof LY)return{type:"RepetitionWithSeparator",idx:r.idx,separator:Sd(new sy({terminalType:r.separator})),definition:e(r.definition)};if(r instanceof NY)return{type:"Repetition",idx:r.idx,definition:e(r.definition)};if(r instanceof OY)return{type:"Alternation",idx:r.idx,definition:e(r.definition)};if(r instanceof sy){var i={type:"Terminal",name:r.terminalType.name,label:(0,gIe.tokenLabel)(r.terminalType),idx:r.idx};(0,or.isString)(r.label)&&(i.terminalLabel=r.label);var n=r.terminalType.PATTERN;return r.terminalType.PATTERN&&(i.pattern=(0,or.isRegExp)(n)?n.source:n),i}else{if(r instanceof kY)return{type:"Rule",name:r.name,orgText:r.orgText,definition:e(r.definition)};throw Error("non exhaustive match")}}}qt.serializeProduction=Sd});var ay=I(oy=>{"use strict";Object.defineProperty(oy,"__esModule",{value:!0});oy.RestWalker=void 0;var jv=Kt(),In=En(),hIe=function(){function r(){}return r.prototype.walk=function(e,t){var i=this;t===void 0&&(t=[]),(0,jv.forEach)(e.definition,function(n,s){var o=(0,jv.drop)(e.definition,s+1);if(n instanceof In.NonTerminal)i.walkProdRef(n,o,t);else if(n instanceof In.Terminal)i.walkTerminal(n,o,t);else if(n instanceof In.Alternative)i.walkFlat(n,o,t);else if(n instanceof In.Option)i.walkOption(n,o,t);else if(n instanceof In.RepetitionMandatory)i.walkAtLeastOne(n,o,t);else if(n instanceof In.RepetitionMandatoryWithSeparator)i.walkAtLeastOneSep(n,o,t);else if(n instanceof In.RepetitionWithSeparator)i.walkManySep(n,o,t);else if(n instanceof In.Repetition)i.walkMany(n,o,t);else if(n instanceof In.Alternation)i.walkOr(n,o,t);else throw Error("non exhaustive match")})},r.prototype.walkTerminal=function(e,t,i){},r.prototype.walkProdRef=function(e,t,i){},r.prototype.walkFlat=function(e,t,i){var n=t.concat(i);this.walk(e,n)},r.prototype.walkOption=function(e,t,i){var n=t.concat(i);this.walk(e,n)},r.prototype.walkAtLeastOne=function(e,t,i){var n=[new In.Option({definition:e.definition})].concat(t,i);this.walk(e,n)},r.prototype.walkAtLeastOneSep=function(e,t,i){var n=MY(e,t,i);this.walk(e,n)},r.prototype.walkMany=function(e,t,i){var n=[new In.Option({definition:e.definition})].concat(t,i);this.walk(e,n)},r.prototype.walkManySep=function(e,t,i){var n=MY(e,t,i);this.walk(e,n)},r.prototype.walkOr=function(e,t,i){var n=this,s=t.concat(i);(0,jv.forEach)(e.definition,function(o){var a=new In.Alternative({definition:[o]});n.walk(a,s)})},r}();oy.RestWalker=hIe;function MY(r,e,t){var i=[new In.Option({definition:[new In.Terminal({terminalType:r.separator})].concat(r.definition)})],n=i.concat(e,t);return n}});var $g=I(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});Ay.GAstVisitor=void 0;var Ro=En(),pIe=function(){function r(){}return r.prototype.visit=function(e){var t=e;switch(t.constructor){case Ro.NonTerminal:return this.visitNonTerminal(t);case Ro.Alternative:return this.visitAlternative(t);case Ro.Option:return this.visitOption(t);case Ro.RepetitionMandatory:return this.visitRepetitionMandatory(t);case Ro.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(t);case Ro.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(t);case Ro.Repetition:return this.visitRepetition(t);case Ro.Alternation:return this.visitAlternation(t);case Ro.Terminal:return this.visitTerminal(t);case Ro.Rule:return this.visitRule(t);default:throw Error("non exhaustive match")}},r.prototype.visitNonTerminal=function(e){},r.prototype.visitAlternative=function(e){},r.prototype.visitOption=function(e){},r.prototype.visitRepetition=function(e){},r.prototype.visitRepetitionMandatory=function(e){},r.prototype.visitRepetitionMandatoryWithSeparator=function(e){},r.prototype.visitRepetitionWithSeparator=function(e){},r.prototype.visitAlternation=function(e){},r.prototype.visitTerminal=function(e){},r.prototype.visitRule=function(e){},r}();Ay.GAstVisitor=pIe});var xd=I(Mi=>{"use strict";var dIe=Mi&&Mi.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(Mi,"__esModule",{value:!0});Mi.collectMethods=Mi.DslMethodsCollectorVisitor=Mi.getProductionDslName=Mi.isBranchingProd=Mi.isOptionalProd=Mi.isSequenceProd=void 0;var vd=Kt(),Br=En(),CIe=$g();function mIe(r){return r instanceof Br.Alternative||r instanceof Br.Option||r instanceof Br.Repetition||r instanceof Br.RepetitionMandatory||r instanceof Br.RepetitionMandatoryWithSeparator||r instanceof Br.RepetitionWithSeparator||r instanceof Br.Terminal||r instanceof Br.Rule}Mi.isSequenceProd=mIe;function Gv(r,e){e===void 0&&(e=[]);var t=r instanceof Br.Option||r instanceof Br.Repetition||r instanceof Br.RepetitionWithSeparator;return t?!0:r instanceof Br.Alternation?(0,vd.some)(r.definition,function(i){return Gv(i,e)}):r instanceof Br.NonTerminal&&(0,vd.contains)(e,r)?!1:r instanceof Br.AbstractProduction?(r instanceof Br.NonTerminal&&e.push(r),(0,vd.every)(r.definition,function(i){return Gv(i,e)})):!1}Mi.isOptionalProd=Gv;function EIe(r){return r instanceof Br.Alternation}Mi.isBranchingProd=EIe;function IIe(r){if(r instanceof Br.NonTerminal)return"SUBRULE";if(r instanceof Br.Option)return"OPTION";if(r instanceof Br.Alternation)return"OR";if(r instanceof Br.RepetitionMandatory)return"AT_LEAST_ONE";if(r instanceof Br.RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(r instanceof Br.RepetitionWithSeparator)return"MANY_SEP";if(r instanceof Br.Repetition)return"MANY";if(r instanceof Br.Terminal)return"CONSUME";throw Error("non exhaustive match")}Mi.getProductionDslName=IIe;var KY=function(r){dIe(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.separator="-",t.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},t}return e.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},e.prototype.visitTerminal=function(t){var i=t.terminalType.name+this.separator+"Terminal";(0,vd.has)(this.dslMethods,i)||(this.dslMethods[i]=[]),this.dslMethods[i].push(t)},e.prototype.visitNonTerminal=function(t){var i=t.nonTerminalName+this.separator+"Terminal";(0,vd.has)(this.dslMethods,i)||(this.dslMethods[i]=[]),this.dslMethods[i].push(t)},e.prototype.visitOption=function(t){this.dslMethods.option.push(t)},e.prototype.visitRepetitionWithSeparator=function(t){this.dslMethods.repetitionWithSeparator.push(t)},e.prototype.visitRepetitionMandatory=function(t){this.dslMethods.repetitionMandatory.push(t)},e.prototype.visitRepetitionMandatoryWithSeparator=function(t){this.dslMethods.repetitionMandatoryWithSeparator.push(t)},e.prototype.visitRepetition=function(t){this.dslMethods.repetition.push(t)},e.prototype.visitAlternation=function(t){this.dslMethods.alternation.push(t)},e}(CIe.GAstVisitor);Mi.DslMethodsCollectorVisitor=KY;var ly=new KY;function yIe(r){ly.reset(),r.accept(ly);var e=ly.dslMethods;return ly.reset(),e}Mi.collectMethods=yIe});var qv=I(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.firstForTerminal=Fo.firstForBranching=Fo.firstForSequence=Fo.first=void 0;var cy=Kt(),UY=En(),Yv=xd();function uy(r){if(r instanceof UY.NonTerminal)return uy(r.referencedRule);if(r instanceof UY.Terminal)return GY(r);if((0,Yv.isSequenceProd)(r))return HY(r);if((0,Yv.isBranchingProd)(r))return jY(r);throw Error("non exhaustive match")}Fo.first=uy;function HY(r){for(var e=[],t=r.definition,i=0,n=t.length>i,s,o=!0;n&&o;)s=t[i],o=(0,Yv.isOptionalProd)(s),e=e.concat(uy(s)),i=i+1,n=t.length>i;return(0,cy.uniq)(e)}Fo.firstForSequence=HY;function jY(r){var e=(0,cy.map)(r.definition,function(t){return uy(t)});return(0,cy.uniq)((0,cy.flatten)(e))}Fo.firstForBranching=jY;function GY(r){return[r.terminalType]}Fo.firstForTerminal=GY});var Jv=I(gy=>{"use strict";Object.defineProperty(gy,"__esModule",{value:!0});gy.IN=void 0;gy.IN="_~IN~_"});var zY=I(gs=>{"use strict";var wIe=gs&&gs.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(gs,"__esModule",{value:!0});gs.buildInProdFollowPrefix=gs.buildBetweenProdsFollowPrefix=gs.computeAllProdsFollows=gs.ResyncFollowsWalker=void 0;var BIe=ay(),QIe=qv(),YY=Kt(),qY=Jv(),bIe=En(),JY=function(r){wIe(e,r);function e(t){var i=r.call(this)||this;return i.topProd=t,i.follows={},i}return e.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},e.prototype.walkTerminal=function(t,i,n){},e.prototype.walkProdRef=function(t,i,n){var s=WY(t.referencedRule,t.idx)+this.topProd.name,o=i.concat(n),a=new bIe.Alternative({definition:o}),l=(0,QIe.first)(a);this.follows[s]=l},e}(BIe.RestWalker);gs.ResyncFollowsWalker=JY;function SIe(r){var e={};return(0,YY.forEach)(r,function(t){var i=new JY(t).startWalking();(0,YY.assign)(e,i)}),e}gs.computeAllProdsFollows=SIe;function WY(r,e){return r.name+e+qY.IN}gs.buildBetweenProdsFollowPrefix=WY;function vIe(r){var e=r.terminalType.name;return e+r.idx+qY.IN}gs.buildInProdFollowPrefix=vIe});var Pd=I(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.defaultGrammarValidatorErrorProvider=Da.defaultGrammarResolverErrorProvider=Da.defaultParserErrorProvider=void 0;var ef=TA(),xIe=Kt(),$s=Kt(),Wv=En(),VY=xd();Da.defaultParserErrorProvider={buildMismatchTokenMessage:function(r){var e=r.expected,t=r.actual,i=r.previous,n=r.ruleName,s=(0,ef.hasTokenLabel)(e),o=s?"--> "+(0,ef.tokenLabel)(e)+" <--":"token of type --> "+e.name+" <--",a="Expecting "+o+" but found --> '"+t.image+"' <--";return a},buildNotAllInputParsedMessage:function(r){var e=r.firstRedundant,t=r.ruleName;return"Redundant input, expecting EOF but found: "+e.image},buildNoViableAltMessage:function(r){var e=r.expectedPathsPerAlt,t=r.actual,i=r.previous,n=r.customUserDescription,s=r.ruleName,o="Expecting: ",a=(0,$s.first)(t).image,l=` -but found: '`+a+"'";if(n)return o+n+l;var c=(0,$s.reduce)(e,function(p,d){return p.concat(d)},[]),u=(0,$s.map)(c,function(p){return"["+(0,$s.map)(p,function(d){return(0,ef.tokenLabel)(d)}).join(", ")+"]"}),g=(0,$s.map)(u,function(p,d){return" "+(d+1)+". "+p}),h=`one of these possible Token sequences: -`+g.join(` -`);return o+h+l},buildEarlyExitMessage:function(r){var e=r.expectedIterationPaths,t=r.actual,i=r.customUserDescription,n=r.ruleName,s="Expecting: ",o=(0,$s.first)(t).image,a=` -but found: '`+o+"'";if(i)return s+i+a;var l=(0,$s.map)(e,function(u){return"["+(0,$s.map)(u,function(g){return(0,ef.tokenLabel)(g)}).join(",")+"]"}),c=`expecting at least one iteration which starts with one of these possible Token sequences:: - `+("<"+l.join(" ,")+">");return s+c+a}};Object.freeze(Da.defaultParserErrorProvider);Da.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(r,e){var t="Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- -inside top level rule: ->`+r.name+"<-";return t}};Da.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(r,e){function t(u){return u instanceof Wv.Terminal?u.terminalType.name:u instanceof Wv.NonTerminal?u.nonTerminalName:""}var i=r.name,n=(0,$s.first)(e),s=n.idx,o=(0,VY.getProductionDslName)(n),a=t(n),l=s>0,c="->"+o+(l?s:"")+"<- "+(a?"with argument: ->"+a+"<-":"")+` - appears more than once (`+e.length+" times) in the top level rule: ->"+i+`<-. - For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES - `;return c=c.replace(/[ \t]+/g," "),c=c.replace(/\s\s+/g,` -`),c},buildNamespaceConflictError:function(r){var e=`Namespace conflict found in grammar. -`+("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+r.name+`>. -`)+`To resolve this make sure each Terminal and Non-Terminal names are unique -This is easy to accomplish by using the convention that Terminal names start with an uppercase letter -and Non-Terminal names start with a lower case letter.`;return e},buildAlternationPrefixAmbiguityError:function(r){var e=(0,$s.map)(r.prefixPath,function(n){return(0,ef.tokenLabel)(n)}).join(", "),t=r.alternation.idx===0?"":r.alternation.idx,i="Ambiguous alternatives: <"+r.ambiguityIndices.join(" ,")+`> due to common lookahead prefix -`+("in inside <"+r.topLevelRule.name+`> Rule, -`)+("<"+e+`> may appears as a prefix path in all these alternatives. -`)+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX -For Further details.`;return i},buildAlternationAmbiguityError:function(r){var e=(0,$s.map)(r.prefixPath,function(n){return(0,ef.tokenLabel)(n)}).join(", "),t=r.alternation.idx===0?"":r.alternation.idx,i="Ambiguous Alternatives Detected: <"+r.ambiguityIndices.join(" ,")+"> in "+(" inside <"+r.topLevelRule.name+`> Rule, -`)+("<"+e+`> may appears as a prefix path in all these alternatives. -`);return i=i+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES -For Further details.`,i},buildEmptyRepetitionError:function(r){var e=(0,VY.getProductionDslName)(r.repetition);r.repetition.idx!==0&&(e+=r.repetition.idx);var t="The repetition <"+e+"> within Rule <"+r.topLevelRule.name+`> can never consume any tokens. -This could lead to an infinite loop.`;return t},buildTokenNameError:function(r){return"deprecated"},buildEmptyAlternationError:function(r){var e="Ambiguous empty alternative: <"+(r.emptyChoiceIdx+1)+">"+(" in inside <"+r.topLevelRule.name+`> Rule. -`)+"Only the last alternative may be an empty alternative.";return e},buildTooManyAlternativesError:function(r){var e=`An Alternation cannot have more than 256 alternatives: -`+(" inside <"+r.topLevelRule.name+`> Rule. - has `+(r.alternation.definition.length+1)+" alternatives.");return e},buildLeftRecursionError:function(r){var e=r.topLevelRule.name,t=xIe.map(r.leftRecursionPath,function(s){return s.name}),i=e+" --> "+t.concat([e]).join(" --> "),n=`Left Recursion found in grammar. -`+("rule: <"+e+`> can be invoked from itself (directly or indirectly) -`)+(`without consuming any Tokens. The grammar path that causes this is: - `+i+` -`)+` To fix this refactor your grammar to remove the left recursion. -see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`;return n},buildInvalidRuleNameError:function(r){return"deprecated"},buildDuplicateRuleNameError:function(r){var e;r.topLevelRule instanceof Wv.Rule?e=r.topLevelRule.name:e=r.topLevelRule;var t="Duplicate definition, rule: ->"+e+"<- is already defined in the grammar: ->"+r.grammarName+"<-";return t}}});var _Y=I(NA=>{"use strict";var PIe=NA&&NA.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(NA,"__esModule",{value:!0});NA.GastRefResolverVisitor=NA.resolveGrammar=void 0;var kIe=Yn(),XY=Kt(),DIe=$g();function RIe(r,e){var t=new ZY(r,e);return t.resolveRefs(),t.errors}NA.resolveGrammar=RIe;var ZY=function(r){PIe(e,r);function e(t,i){var n=r.call(this)||this;return n.nameToTopRule=t,n.errMsgProvider=i,n.errors=[],n}return e.prototype.resolveRefs=function(){var t=this;(0,XY.forEach)((0,XY.values)(this.nameToTopRule),function(i){t.currTopLevel=i,i.accept(t)})},e.prototype.visitNonTerminal=function(t){var i=this.nameToTopRule[t.nonTerminalName];if(i)t.referencedRule=i;else{var n=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,t);this.errors.push({message:n,type:kIe.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:t.nonTerminalName})}},e}(DIe.GAstVisitor);NA.GastRefResolverVisitor=ZY});var Dd=I(Fr=>{"use strict";var Ic=Fr&&Fr.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(Fr,"__esModule",{value:!0});Fr.nextPossibleTokensAfter=Fr.possiblePathsFrom=Fr.NextTerminalAfterAtLeastOneSepWalker=Fr.NextTerminalAfterAtLeastOneWalker=Fr.NextTerminalAfterManySepWalker=Fr.NextTerminalAfterManyWalker=Fr.AbstractNextTerminalAfterProductionWalker=Fr.NextAfterTokenWalker=Fr.AbstractNextPossibleTokensWalker=void 0;var $Y=ay(),Lt=Kt(),FIe=qv(),kt=En(),eq=function(r){Ic(e,r);function e(t,i){var n=r.call(this)||this;return n.topProd=t,n.path=i,n.possibleTokTypes=[],n.nextProductionName="",n.nextProductionOccurrence=0,n.found=!1,n.isAtEndOfPath=!1,n}return e.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=(0,Lt.cloneArr)(this.path.ruleStack).reverse(),this.occurrenceStack=(0,Lt.cloneArr)(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},e.prototype.walk=function(t,i){i===void 0&&(i=[]),this.found||r.prototype.walk.call(this,t,i)},e.prototype.walkProdRef=function(t,i,n){if(t.referencedRule.name===this.nextProductionName&&t.idx===this.nextProductionOccurrence){var s=i.concat(n);this.updateExpectedNext(),this.walk(t.referencedRule,s)}},e.prototype.updateExpectedNext=function(){(0,Lt.isEmpty)(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},e}($Y.RestWalker);Fr.AbstractNextPossibleTokensWalker=eq;var TIe=function(r){Ic(e,r);function e(t,i){var n=r.call(this,t,i)||this;return n.path=i,n.nextTerminalName="",n.nextTerminalOccurrence=0,n.nextTerminalName=n.path.lastTok.name,n.nextTerminalOccurrence=n.path.lastTokOccurrence,n}return e.prototype.walkTerminal=function(t,i,n){if(this.isAtEndOfPath&&t.terminalType.name===this.nextTerminalName&&t.idx===this.nextTerminalOccurrence&&!this.found){var s=i.concat(n),o=new kt.Alternative({definition:s});this.possibleTokTypes=(0,FIe.first)(o),this.found=!0}},e}(eq);Fr.NextAfterTokenWalker=TIe;var kd=function(r){Ic(e,r);function e(t,i){var n=r.call(this)||this;return n.topRule=t,n.occurrence=i,n.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},n}return e.prototype.startWalking=function(){return this.walk(this.topRule),this.result},e}($Y.RestWalker);Fr.AbstractNextTerminalAfterProductionWalker=kd;var NIe=function(r){Ic(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.walkMany=function(t,i,n){if(t.idx===this.occurrence){var s=(0,Lt.first)(i.concat(n));this.result.isEndOfRule=s===void 0,s instanceof kt.Terminal&&(this.result.token=s.terminalType,this.result.occurrence=s.idx)}else r.prototype.walkMany.call(this,t,i,n)},e}(kd);Fr.NextTerminalAfterManyWalker=NIe;var LIe=function(r){Ic(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.walkManySep=function(t,i,n){if(t.idx===this.occurrence){var s=(0,Lt.first)(i.concat(n));this.result.isEndOfRule=s===void 0,s instanceof kt.Terminal&&(this.result.token=s.terminalType,this.result.occurrence=s.idx)}else r.prototype.walkManySep.call(this,t,i,n)},e}(kd);Fr.NextTerminalAfterManySepWalker=LIe;var OIe=function(r){Ic(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.walkAtLeastOne=function(t,i,n){if(t.idx===this.occurrence){var s=(0,Lt.first)(i.concat(n));this.result.isEndOfRule=s===void 0,s instanceof kt.Terminal&&(this.result.token=s.terminalType,this.result.occurrence=s.idx)}else r.prototype.walkAtLeastOne.call(this,t,i,n)},e}(kd);Fr.NextTerminalAfterAtLeastOneWalker=OIe;var MIe=function(r){Ic(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e.prototype.walkAtLeastOneSep=function(t,i,n){if(t.idx===this.occurrence){var s=(0,Lt.first)(i.concat(n));this.result.isEndOfRule=s===void 0,s instanceof kt.Terminal&&(this.result.token=s.terminalType,this.result.occurrence=s.idx)}else r.prototype.walkAtLeastOneSep.call(this,t,i,n)},e}(kd);Fr.NextTerminalAfterAtLeastOneSepWalker=MIe;function tq(r,e,t){t===void 0&&(t=[]),t=(0,Lt.cloneArr)(t);var i=[],n=0;function s(c){return c.concat((0,Lt.drop)(r,n+1))}function o(c){var u=tq(s(c),e,t);return i.concat(u)}for(;t.length=0;ue--){var te=B.definition[ue],O={idx:d,def:te.definition.concat((0,Lt.drop)(p)),ruleStack:m,occurrenceStack:y};g.push(O),g.push(o)}else if(B instanceof kt.Alternative)g.push({idx:d,def:B.definition.concat((0,Lt.drop)(p)),ruleStack:m,occurrenceStack:y});else if(B instanceof kt.Rule)g.push(UIe(B,d,m,y));else throw Error("non exhaustive match")}}return u}Fr.nextPossibleTokensAfter=KIe;function UIe(r,e,t,i){var n=(0,Lt.cloneArr)(t);n.push(r.name);var s=(0,Lt.cloneArr)(i);return s.push(1),{idx:e,def:r.definition,ruleStack:n,occurrenceStack:s}}});var Rd=I(Wt=>{"use strict";var nq=Wt&&Wt.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(Wt,"__esModule",{value:!0});Wt.areTokenCategoriesNotUsed=Wt.isStrictPrefixOfPath=Wt.containsPath=Wt.getLookaheadPathsForOptionalProd=Wt.getLookaheadPathsForOr=Wt.lookAheadSequenceFromAlternatives=Wt.buildSingleAlternativeLookaheadFunction=Wt.buildAlternativesLookAheadFunc=Wt.buildLookaheadFuncForOptionalProd=Wt.buildLookaheadFuncForOr=Wt.getProdType=Wt.PROD_TYPE=void 0;var ir=Kt(),rq=Dd(),HIe=ay(),fy=_g(),LA=En(),jIe=$g(),si;(function(r){r[r.OPTION=0]="OPTION",r[r.REPETITION=1]="REPETITION",r[r.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",r[r.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",r[r.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",r[r.ALTERNATION=5]="ALTERNATION"})(si=Wt.PROD_TYPE||(Wt.PROD_TYPE={}));function GIe(r){if(r instanceof LA.Option)return si.OPTION;if(r instanceof LA.Repetition)return si.REPETITION;if(r instanceof LA.RepetitionMandatory)return si.REPETITION_MANDATORY;if(r instanceof LA.RepetitionMandatoryWithSeparator)return si.REPETITION_MANDATORY_WITH_SEPARATOR;if(r instanceof LA.RepetitionWithSeparator)return si.REPETITION_WITH_SEPARATOR;if(r instanceof LA.Alternation)return si.ALTERNATION;throw Error("non exhaustive match")}Wt.getProdType=GIe;function YIe(r,e,t,i,n,s){var o=oq(r,e,t),a=Xv(o)?fy.tokenStructuredMatcherNoCategories:fy.tokenStructuredMatcher;return s(o,i,a,n)}Wt.buildLookaheadFuncForOr=YIe;function qIe(r,e,t,i,n,s){var o=aq(r,e,n,t),a=Xv(o)?fy.tokenStructuredMatcherNoCategories:fy.tokenStructuredMatcher;return s(o[0],a,i)}Wt.buildLookaheadFuncForOptionalProd=qIe;function JIe(r,e,t,i){var n=r.length,s=(0,ir.every)(r,function(l){return(0,ir.every)(l,function(c){return c.length===1})});if(e)return function(l){for(var c=(0,ir.map)(l,function(P){return P.GATE}),u=0;u{"use strict";var Zv=Jt&&Jt.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(Jt,"__esModule",{value:!0});Jt.checkPrefixAlternativesAmbiguities=Jt.validateSomeNonEmptyLookaheadPath=Jt.validateTooManyAlts=Jt.RepetionCollector=Jt.validateAmbiguousAlternationAlternatives=Jt.validateEmptyOrAlternative=Jt.getFirstNoneTerminal=Jt.validateNoLeftRecursion=Jt.validateRuleIsOverridden=Jt.validateRuleDoesNotAlreadyExist=Jt.OccurrenceValidationCollector=Jt.identifyProductionForDuplicates=Jt.validateGrammar=void 0;var _t=Kt(),Qr=Kt(),To=Yn(),_v=xd(),tf=Rd(),ZIe=Dd(),eo=En(),$v=$g();function _Ie(r,e,t,i,n){var s=_t.map(r,function(p){return $Ie(p,i)}),o=_t.map(r,function(p){return ex(p,p,i)}),a=[],l=[],c=[];(0,Qr.every)(o,Qr.isEmpty)&&(a=(0,Qr.map)(r,function(p){return fq(p,i)}),l=(0,Qr.map)(r,function(p){return hq(p,e,i)}),c=Cq(r,e,i));var u=rye(r,t,i),g=(0,Qr.map)(r,function(p){return dq(p,i)}),h=(0,Qr.map)(r,function(p){return gq(p,r,n,i)});return _t.flatten(s.concat(c,o,a,l,u,g,h))}Jt.validateGrammar=_Ie;function $Ie(r,e){var t=new uq;r.accept(t);var i=t.allProductions,n=_t.groupBy(i,lq),s=_t.pick(n,function(a){return a.length>1}),o=_t.map(_t.values(s),function(a){var l=_t.first(a),c=e.buildDuplicateFoundError(r,a),u=(0,_v.getProductionDslName)(l),g={message:c,type:To.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:r.name,dslName:u,occurrence:l.idx},h=cq(l);return h&&(g.parameter=h),g});return o}function lq(r){return(0,_v.getProductionDslName)(r)+"_#_"+r.idx+"_#_"+cq(r)}Jt.identifyProductionForDuplicates=lq;function cq(r){return r instanceof eo.Terminal?r.terminalType.name:r instanceof eo.NonTerminal?r.nonTerminalName:""}var uq=function(r){Zv(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.allProductions=[],t}return e.prototype.visitNonTerminal=function(t){this.allProductions.push(t)},e.prototype.visitOption=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatory=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatoryWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetition=function(t){this.allProductions.push(t)},e.prototype.visitAlternation=function(t){this.allProductions.push(t)},e.prototype.visitTerminal=function(t){this.allProductions.push(t)},e}($v.GAstVisitor);Jt.OccurrenceValidationCollector=uq;function gq(r,e,t,i){var n=[],s=(0,Qr.reduce)(e,function(a,l){return l.name===r.name?a+1:a},0);if(s>1){var o=i.buildDuplicateRuleNameError({topLevelRule:r,grammarName:t});n.push({message:o,type:To.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:r.name})}return n}Jt.validateRuleDoesNotAlreadyExist=gq;function eye(r,e,t){var i=[],n;return _t.contains(e,r)||(n="Invalid rule override, rule: ->"+r+"<- cannot be overridden in the grammar: ->"+t+"<-as it is not defined in any of the super grammars ",i.push({message:n,type:To.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:r})),i}Jt.validateRuleIsOverridden=eye;function ex(r,e,t,i){i===void 0&&(i=[]);var n=[],s=Fd(e.definition);if(_t.isEmpty(s))return[];var o=r.name,a=_t.contains(s,r);a&&n.push({message:t.buildLeftRecursionError({topLevelRule:r,leftRecursionPath:i}),type:To.ParserDefinitionErrorType.LEFT_RECURSION,ruleName:o});var l=_t.difference(s,i.concat([r])),c=_t.map(l,function(u){var g=_t.cloneArr(i);return g.push(u),ex(r,u,t,g)});return n.concat(_t.flatten(c))}Jt.validateNoLeftRecursion=ex;function Fd(r){var e=[];if(_t.isEmpty(r))return e;var t=_t.first(r);if(t instanceof eo.NonTerminal)e.push(t.referencedRule);else if(t instanceof eo.Alternative||t instanceof eo.Option||t instanceof eo.RepetitionMandatory||t instanceof eo.RepetitionMandatoryWithSeparator||t instanceof eo.RepetitionWithSeparator||t instanceof eo.Repetition)e=e.concat(Fd(t.definition));else if(t instanceof eo.Alternation)e=_t.flatten(_t.map(t.definition,function(o){return Fd(o.definition)}));else if(!(t instanceof eo.Terminal))throw Error("non exhaustive match");var i=(0,_v.isOptionalProd)(t),n=r.length>1;if(i&&n){var s=_t.drop(r);return e.concat(Fd(s))}else return e}Jt.getFirstNoneTerminal=Fd;var tx=function(r){Zv(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.alternations=[],t}return e.prototype.visitAlternation=function(t){this.alternations.push(t)},e}($v.GAstVisitor);function fq(r,e){var t=new tx;r.accept(t);var i=t.alternations,n=_t.reduce(i,function(s,o){var a=_t.dropRight(o.definition),l=_t.map(a,function(c,u){var g=(0,ZIe.nextPossibleTokensAfter)([c],[],null,1);return _t.isEmpty(g)?{message:e.buildEmptyAlternationError({topLevelRule:r,alternation:o,emptyChoiceIdx:u}),type:To.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:r.name,occurrence:o.idx,alternative:u+1}:null});return s.concat(_t.compact(l))},[]);return n}Jt.validateEmptyOrAlternative=fq;function hq(r,e,t){var i=new tx;r.accept(i);var n=i.alternations;n=(0,Qr.reject)(n,function(o){return o.ignoreAmbiguities===!0});var s=_t.reduce(n,function(o,a){var l=a.idx,c=a.maxLookahead||e,u=(0,tf.getLookaheadPathsForOr)(l,r,c,a),g=tye(u,a,r,t),h=mq(u,a,r,t);return o.concat(g,h)},[]);return s}Jt.validateAmbiguousAlternationAlternatives=hq;var pq=function(r){Zv(e,r);function e(){var t=r!==null&&r.apply(this,arguments)||this;return t.allProductions=[],t}return e.prototype.visitRepetitionWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatory=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatoryWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetition=function(t){this.allProductions.push(t)},e}($v.GAstVisitor);Jt.RepetionCollector=pq;function dq(r,e){var t=new tx;r.accept(t);var i=t.alternations,n=_t.reduce(i,function(s,o){return o.definition.length>255&&s.push({message:e.buildTooManyAlternativesError({topLevelRule:r,alternation:o}),type:To.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:r.name,occurrence:o.idx}),s},[]);return n}Jt.validateTooManyAlts=dq;function Cq(r,e,t){var i=[];return(0,Qr.forEach)(r,function(n){var s=new pq;n.accept(s);var o=s.allProductions;(0,Qr.forEach)(o,function(a){var l=(0,tf.getProdType)(a),c=a.maxLookahead||e,u=a.idx,g=(0,tf.getLookaheadPathsForOptionalProd)(u,n,l,c),h=g[0];if((0,Qr.isEmpty)((0,Qr.flatten)(h))){var p=t.buildEmptyRepetitionError({topLevelRule:n,repetition:a});i.push({message:p,type:To.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:n.name})}})}),i}Jt.validateSomeNonEmptyLookaheadPath=Cq;function tye(r,e,t,i){var n=[],s=(0,Qr.reduce)(r,function(a,l,c){return e.definition[c].ignoreAmbiguities===!0||(0,Qr.forEach)(l,function(u){var g=[c];(0,Qr.forEach)(r,function(h,p){c!==p&&(0,tf.containsPath)(h,u)&&e.definition[p].ignoreAmbiguities!==!0&&g.push(p)}),g.length>1&&!(0,tf.containsPath)(n,u)&&(n.push(u),a.push({alts:g,path:u}))}),a},[]),o=_t.map(s,function(a){var l=(0,Qr.map)(a.alts,function(u){return u+1}),c=i.buildAlternationAmbiguityError({topLevelRule:t,alternation:e,ambiguityIndices:l,prefixPath:a.path});return{message:c,type:To.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:t.name,occurrence:e.idx,alternatives:[a.alts]}});return o}function mq(r,e,t,i){var n=[],s=(0,Qr.reduce)(r,function(o,a,l){var c=(0,Qr.map)(a,function(u){return{idx:l,path:u}});return o.concat(c)},[]);return(0,Qr.forEach)(s,function(o){var a=e.definition[o.idx];if(a.ignoreAmbiguities!==!0){var l=o.idx,c=o.path,u=(0,Qr.findAll)(s,function(h){return e.definition[h.idx].ignoreAmbiguities!==!0&&h.idx{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.validateGrammar=rf.resolveGrammar=void 0;var ix=Kt(),iye=_Y(),nye=rx(),Eq=Pd();function sye(r){r=(0,ix.defaults)(r,{errMsgProvider:Eq.defaultGrammarResolverErrorProvider});var e={};return(0,ix.forEach)(r.rules,function(t){e[t.name]=t}),(0,iye.resolveGrammar)(e,r.errMsgProvider)}rf.resolveGrammar=sye;function oye(r){return r=(0,ix.defaults)(r,{errMsgProvider:Eq.defaultGrammarValidatorErrorProvider}),(0,nye.validateGrammar)(r.rules,r.maxLookahead,r.tokenTypes,r.errMsgProvider,r.grammarName)}rf.validateGrammar=oye});var nf=I(yn=>{"use strict";var Td=yn&&yn.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(yn,"__esModule",{value:!0});yn.EarlyExitException=yn.NotAllInputParsedException=yn.NoViableAltException=yn.MismatchedTokenException=yn.isRecognitionException=void 0;var aye=Kt(),yq="MismatchedTokenException",wq="NoViableAltException",Bq="EarlyExitException",Qq="NotAllInputParsedException",bq=[yq,wq,Bq,Qq];Object.freeze(bq);function Aye(r){return(0,aye.contains)(bq,r.name)}yn.isRecognitionException=Aye;var hy=function(r){Td(e,r);function e(t,i){var n=this.constructor,s=r.call(this,t)||this;return s.token=i,s.resyncedTokens=[],Object.setPrototypeOf(s,n.prototype),Error.captureStackTrace&&Error.captureStackTrace(s,s.constructor),s}return e}(Error),lye=function(r){Td(e,r);function e(t,i,n){var s=r.call(this,t,i)||this;return s.previousToken=n,s.name=yq,s}return e}(hy);yn.MismatchedTokenException=lye;var cye=function(r){Td(e,r);function e(t,i,n){var s=r.call(this,t,i)||this;return s.previousToken=n,s.name=wq,s}return e}(hy);yn.NoViableAltException=cye;var uye=function(r){Td(e,r);function e(t,i){var n=r.call(this,t,i)||this;return n.name=Qq,n}return e}(hy);yn.NotAllInputParsedException=uye;var gye=function(r){Td(e,r);function e(t,i,n){var s=r.call(this,t,i)||this;return s.previousToken=n,s.name=Bq,s}return e}(hy);yn.EarlyExitException=gye});var sx=I(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});Ki.attemptInRepetitionRecovery=Ki.Recoverable=Ki.InRuleRecoveryException=Ki.IN_RULE_RECOVERY_EXCEPTION=Ki.EOF_FOLLOW_KEY=void 0;var py=TA(),fs=Kt(),fye=nf(),hye=Jv(),pye=Yn();Ki.EOF_FOLLOW_KEY={};Ki.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function nx(r){this.name=Ki.IN_RULE_RECOVERY_EXCEPTION,this.message=r}Ki.InRuleRecoveryException=nx;nx.prototype=Error.prototype;var dye=function(){function r(){}return r.prototype.initRecoverable=function(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=(0,fs.has)(e,"recoveryEnabled")?e.recoveryEnabled:pye.DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=Sq)},r.prototype.getTokenToInsert=function(e){var t=(0,py.createTokenInstance)(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return t.isInsertedInRecovery=!0,t},r.prototype.canTokenTypeBeInsertedInRecovery=function(e){return!0},r.prototype.tryInRepetitionRecovery=function(e,t,i,n){for(var s=this,o=this.findReSyncTokenType(),a=this.exportLexerState(),l=[],c=!1,u=this.LA(1),g=this.LA(1),h=function(){var p=s.LA(0),d=s.errorMessageProvider.buildMismatchTokenMessage({expected:n,actual:u,previous:p,ruleName:s.getCurrRuleFullName()}),m=new fye.MismatchedTokenException(d,u,s.LA(0));m.resyncedTokens=(0,fs.dropRight)(l),s.SAVE_ERROR(m)};!c;)if(this.tokenMatcher(g,n)){h();return}else if(i.call(this)){h(),e.apply(this,t);return}else this.tokenMatcher(g,o)?c=!0:(g=this.SKIP_TOKEN(),this.addToResyncTokens(g,l));this.importLexerState(a)},r.prototype.shouldInRepetitionRecoveryBeTried=function(e,t,i){return!(i===!1||e===void 0||t===void 0||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,t)))},r.prototype.getFollowsForInRuleRecovery=function(e,t){var i=this.getCurrentGrammarPath(e,t),n=this.getNextPossibleTokenTypes(i);return n},r.prototype.tryInRuleRecovery=function(e,t){if(this.canRecoverWithSingleTokenInsertion(e,t)){var i=this.getTokenToInsert(e);return i}if(this.canRecoverWithSingleTokenDeletion(e)){var n=this.SKIP_TOKEN();return this.consumeToken(),n}throw new nx("sad sad panda")},r.prototype.canPerformInRuleRecovery=function(e,t){return this.canRecoverWithSingleTokenInsertion(e,t)||this.canRecoverWithSingleTokenDeletion(e)},r.prototype.canRecoverWithSingleTokenInsertion=function(e,t){var i=this;if(!this.canTokenTypeBeInsertedInRecovery(e)||(0,fs.isEmpty)(t))return!1;var n=this.LA(1),s=(0,fs.find)(t,function(o){return i.tokenMatcher(n,o)})!==void 0;return s},r.prototype.canRecoverWithSingleTokenDeletion=function(e){var t=this.tokenMatcher(this.LA(2),e);return t},r.prototype.isInCurrentRuleReSyncSet=function(e){var t=this.getCurrFollowKey(),i=this.getFollowSetFromFollowKey(t);return(0,fs.contains)(i,e)},r.prototype.findReSyncTokenType=function(){for(var e=this.flattenFollowSet(),t=this.LA(1),i=2;;){var n=t.tokenType;if((0,fs.contains)(e,n))return n;t=this.LA(i),i++}},r.prototype.getCurrFollowKey=function(){if(this.RULE_STACK.length===1)return Ki.EOF_FOLLOW_KEY;var e=this.getLastExplicitRuleShortName(),t=this.getLastExplicitRuleOccurrenceIndex(),i=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:t,inRule:this.shortRuleNameToFullName(i)}},r.prototype.buildFullFollowKeyStack=function(){var e=this,t=this.RULE_STACK,i=this.RULE_OCCURRENCE_STACK;return(0,fs.map)(t,function(n,s){return s===0?Ki.EOF_FOLLOW_KEY:{ruleName:e.shortRuleNameToFullName(n),idxInCallingRule:i[s],inRule:e.shortRuleNameToFullName(t[s-1])}})},r.prototype.flattenFollowSet=function(){var e=this,t=(0,fs.map)(this.buildFullFollowKeyStack(),function(i){return e.getFollowSetFromFollowKey(i)});return(0,fs.flatten)(t)},r.prototype.getFollowSetFromFollowKey=function(e){if(e===Ki.EOF_FOLLOW_KEY)return[py.EOF];var t=e.ruleName+e.idxInCallingRule+hye.IN+e.inRule;return this.resyncFollows[t]},r.prototype.addToResyncTokens=function(e,t){return this.tokenMatcher(e,py.EOF)||t.push(e),t},r.prototype.reSyncTo=function(e){for(var t=[],i=this.LA(1);this.tokenMatcher(i,e)===!1;)i=this.SKIP_TOKEN(),this.addToResyncTokens(i,t);return(0,fs.dropRight)(t)},r.prototype.attemptInRepetitionRecovery=function(e,t,i,n,s,o,a){},r.prototype.getCurrentGrammarPath=function(e,t){var i=this.getHumanReadableRuleStack(),n=(0,fs.cloneArr)(this.RULE_OCCURRENCE_STACK),s={ruleStack:i,occurrenceStack:n,lastTok:e,lastTokOccurrence:t};return s},r.prototype.getHumanReadableRuleStack=function(){var e=this;return(0,fs.map)(this.RULE_STACK,function(t){return e.shortRuleNameToFullName(t)})},r}();Ki.Recoverable=dye;function Sq(r,e,t,i,n,s,o){var a=this.getKeyForAutomaticLookahead(i,n),l=this.firstAfterRepMap[a];if(l===void 0){var c=this.getCurrRuleFullName(),u=this.getGAstProductions()[c],g=new s(u,n);l=g.startWalking(),this.firstAfterRepMap[a]=l}var h=l.token,p=l.occurrence,d=l.isEndOfRule;this.RULE_STACK.length===1&&d&&h===void 0&&(h=py.EOF,p=1),this.shouldInRepetitionRecoveryBeTried(h,p,o)&&this.tryInRepetitionRecovery(r,e,t,h)}Ki.attemptInRepetitionRecovery=Sq});var dy=I(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.getKeyForAutomaticLookahead=Gt.AT_LEAST_ONE_SEP_IDX=Gt.MANY_SEP_IDX=Gt.AT_LEAST_ONE_IDX=Gt.MANY_IDX=Gt.OPTION_IDX=Gt.OR_IDX=Gt.BITS_FOR_ALT_IDX=Gt.BITS_FOR_RULE_IDX=Gt.BITS_FOR_OCCURRENCE_IDX=Gt.BITS_FOR_METHOD_TYPE=void 0;Gt.BITS_FOR_METHOD_TYPE=4;Gt.BITS_FOR_OCCURRENCE_IDX=8;Gt.BITS_FOR_RULE_IDX=12;Gt.BITS_FOR_ALT_IDX=8;Gt.OR_IDX=1<{"use strict";Object.defineProperty(Cy,"__esModule",{value:!0});Cy.LooksAhead=void 0;var Ra=Rd(),to=Kt(),vq=Yn(),Fa=dy(),yc=xd(),mye=function(){function r(){}return r.prototype.initLooksAhead=function(e){this.dynamicTokensEnabled=(0,to.has)(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:vq.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=(0,to.has)(e,"maxLookahead")?e.maxLookahead:vq.DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=(0,to.isES2015MapSupported)()?new Map:[],(0,to.isES2015MapSupported)()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},r.prototype.preComputeLookaheadFunctions=function(e){var t=this;(0,to.forEach)(e,function(i){t.TRACE_INIT(i.name+" Rule Lookahead",function(){var n=(0,yc.collectMethods)(i),s=n.alternation,o=n.repetition,a=n.option,l=n.repetitionMandatory,c=n.repetitionMandatoryWithSeparator,u=n.repetitionWithSeparator;(0,to.forEach)(s,function(g){var h=g.idx===0?"":g.idx;t.TRACE_INIT(""+(0,yc.getProductionDslName)(g)+h,function(){var p=(0,Ra.buildLookaheadFuncForOr)(g.idx,i,g.maxLookahead||t.maxLookahead,g.hasPredicates,t.dynamicTokensEnabled,t.lookAheadBuilderForAlternatives),d=(0,Fa.getKeyForAutomaticLookahead)(t.fullRuleNameToShort[i.name],Fa.OR_IDX,g.idx);t.setLaFuncCache(d,p)})}),(0,to.forEach)(o,function(g){t.computeLookaheadFunc(i,g.idx,Fa.MANY_IDX,Ra.PROD_TYPE.REPETITION,g.maxLookahead,(0,yc.getProductionDslName)(g))}),(0,to.forEach)(a,function(g){t.computeLookaheadFunc(i,g.idx,Fa.OPTION_IDX,Ra.PROD_TYPE.OPTION,g.maxLookahead,(0,yc.getProductionDslName)(g))}),(0,to.forEach)(l,function(g){t.computeLookaheadFunc(i,g.idx,Fa.AT_LEAST_ONE_IDX,Ra.PROD_TYPE.REPETITION_MANDATORY,g.maxLookahead,(0,yc.getProductionDslName)(g))}),(0,to.forEach)(c,function(g){t.computeLookaheadFunc(i,g.idx,Fa.AT_LEAST_ONE_SEP_IDX,Ra.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,g.maxLookahead,(0,yc.getProductionDslName)(g))}),(0,to.forEach)(u,function(g){t.computeLookaheadFunc(i,g.idx,Fa.MANY_SEP_IDX,Ra.PROD_TYPE.REPETITION_WITH_SEPARATOR,g.maxLookahead,(0,yc.getProductionDslName)(g))})})})},r.prototype.computeLookaheadFunc=function(e,t,i,n,s,o){var a=this;this.TRACE_INIT(""+o+(t===0?"":t),function(){var l=(0,Ra.buildLookaheadFuncForOptionalProd)(t,e,s||a.maxLookahead,a.dynamicTokensEnabled,n,a.lookAheadBuilderForOptional),c=(0,Fa.getKeyForAutomaticLookahead)(a.fullRuleNameToShort[e.name],i,t);a.setLaFuncCache(c,l)})},r.prototype.lookAheadBuilderForOptional=function(e,t,i){return(0,Ra.buildSingleAlternativeLookaheadFunction)(e,t,i)},r.prototype.lookAheadBuilderForAlternatives=function(e,t,i,n){return(0,Ra.buildAlternativesLookAheadFunc)(e,t,i,n)},r.prototype.getKeyForAutomaticLookahead=function(e,t){var i=this.getLastExplicitRuleShortName();return(0,Fa.getKeyForAutomaticLookahead)(i,e,t)},r.prototype.getLaFuncFromCache=function(e){},r.prototype.getLaFuncFromMap=function(e){return this.lookAheadFuncsCache.get(e)},r.prototype.getLaFuncFromObj=function(e){return this.lookAheadFuncsCache[e]},r.prototype.setLaFuncCache=function(e,t){},r.prototype.setLaFuncCacheUsingMap=function(e,t){this.lookAheadFuncsCache.set(e,t)},r.prototype.setLaFuncUsingObj=function(e,t){this.lookAheadFuncsCache[e]=t},r}();Cy.LooksAhead=mye});var Pq=I(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.addNoneTerminalToCst=No.addTerminalToCst=No.setNodeLocationFull=No.setNodeLocationOnlyOffset=void 0;function Eye(r,e){isNaN(r.startOffset)===!0?(r.startOffset=e.startOffset,r.endOffset=e.endOffset):r.endOffset{"use strict";Object.defineProperty(OA,"__esModule",{value:!0});OA.defineNameProp=OA.functionName=OA.classNameFromInstance=void 0;var Bye=Kt();function Qye(r){return Dq(r.constructor)}OA.classNameFromInstance=Qye;var kq="name";function Dq(r){var e=r.name;return e||"anonymous"}OA.functionName=Dq;function bye(r,e){var t=Object.getOwnPropertyDescriptor(r,kq);return(0,Bye.isUndefined)(t)||t.configurable?(Object.defineProperty(r,kq,{enumerable:!1,configurable:!0,writable:!1,value:e}),!0):!1}OA.defineNameProp=bye});var Lq=I(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.validateRedundantMethods=vi.validateMissingCstMethods=vi.validateVisitor=vi.CstVisitorDefinitionError=vi.createBaseVisitorConstructorWithDefaults=vi.createBaseSemanticVisitorConstructor=vi.defaultVisit=void 0;var hs=Kt(),Nd=ox();function Rq(r,e){for(var t=(0,hs.keys)(r),i=t.length,n=0;n: - `+(""+s.join(` - -`).replace(/\n/g,` - `)))}}};return t.prototype=i,t.prototype.constructor=t,t._RULE_NAMES=e,t}vi.createBaseSemanticVisitorConstructor=Sye;function vye(r,e,t){var i=function(){};(0,Nd.defineNameProp)(i,r+"BaseSemanticsWithDefaults");var n=Object.create(t.prototype);return(0,hs.forEach)(e,function(s){n[s]=Rq}),i.prototype=n,i.prototype.constructor=i,i}vi.createBaseVisitorConstructorWithDefaults=vye;var ax;(function(r){r[r.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",r[r.MISSING_METHOD=1]="MISSING_METHOD"})(ax=vi.CstVisitorDefinitionError||(vi.CstVisitorDefinitionError={}));function Fq(r,e){var t=Tq(r,e),i=Nq(r,e);return t.concat(i)}vi.validateVisitor=Fq;function Tq(r,e){var t=(0,hs.map)(e,function(i){if(!(0,hs.isFunction)(r[i]))return{msg:"Missing visitor method: <"+i+"> on "+(0,Nd.functionName)(r.constructor)+" CST Visitor.",type:ax.MISSING_METHOD,methodName:i}});return(0,hs.compact)(t)}vi.validateMissingCstMethods=Tq;var xye=["constructor","visit","validateVisitor"];function Nq(r,e){var t=[];for(var i in r)(0,hs.isFunction)(r[i])&&!(0,hs.contains)(xye,i)&&!(0,hs.contains)(e,i)&&t.push({msg:"Redundant visitor method: <"+i+"> on "+(0,Nd.functionName)(r.constructor)+` CST Visitor -There is no Grammar Rule corresponding to this method's name. -`,type:ax.REDUNDANT_METHOD,methodName:i});return t}vi.validateRedundantMethods=Nq});var Mq=I(my=>{"use strict";Object.defineProperty(my,"__esModule",{value:!0});my.TreeBuilder=void 0;var sf=Pq(),Xr=Kt(),Oq=Lq(),Pye=Yn(),kye=function(){function r(){}return r.prototype.initTreeBuilder=function(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=(0,Xr.has)(e,"nodeLocationTracking")?e.nodeLocationTracking:Pye.DEFAULT_PARSER_CONFIG.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=Xr.NOOP,this.cstFinallyStateUpdate=Xr.NOOP,this.cstPostTerminal=Xr.NOOP,this.cstPostNonTerminal=Xr.NOOP,this.cstPostRule=Xr.NOOP;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=sf.setNodeLocationFull,this.setNodeLocationFromNode=sf.setNodeLocationFull,this.cstPostRule=Xr.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=Xr.NOOP,this.setNodeLocationFromNode=Xr.NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=sf.setNodeLocationOnlyOffset,this.setNodeLocationFromNode=sf.setNodeLocationOnlyOffset,this.cstPostRule=Xr.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=Xr.NOOP,this.setNodeLocationFromNode=Xr.NOOP,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=Xr.NOOP,this.setNodeLocationFromNode=Xr.NOOP,this.cstPostRule=Xr.NOOP,this.setInitialNodeLocation=Xr.NOOP;else throw Error('Invalid config option: "'+e.nodeLocationTracking+'"')},r.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(e){e.location={startOffset:NaN,endOffset:NaN}},r.prototype.setInitialNodeLocationOnlyOffsetRegular=function(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},r.prototype.setInitialNodeLocationFullRecovery=function(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},r.prototype.setInitialNodeLocationFullRegular=function(e){var t=this.LA(1);e.location={startOffset:t.startOffset,startLine:t.startLine,startColumn:t.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},r.prototype.cstInvocationStateUpdate=function(e,t){var i={name:e,children:{}};this.setInitialNodeLocation(i),this.CST_STACK.push(i)},r.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()},r.prototype.cstPostRuleFull=function(e){var t=this.LA(0),i=e.location;i.startOffset<=t.startOffset?(i.endOffset=t.endOffset,i.endLine=t.endLine,i.endColumn=t.endColumn):(i.startOffset=NaN,i.startLine=NaN,i.startColumn=NaN)},r.prototype.cstPostRuleOnlyOffset=function(e){var t=this.LA(0),i=e.location;i.startOffset<=t.startOffset?i.endOffset=t.endOffset:i.startOffset=NaN},r.prototype.cstPostTerminal=function(e,t){var i=this.CST_STACK[this.CST_STACK.length-1];(0,sf.addTerminalToCst)(i,t,e),this.setNodeLocationFromToken(i.location,t)},r.prototype.cstPostNonTerminal=function(e,t){var i=this.CST_STACK[this.CST_STACK.length-1];(0,sf.addNoneTerminalToCst)(i,t,e),this.setNodeLocationFromNode(i.location,e.location)},r.prototype.getBaseCstVisitorConstructor=function(){if((0,Xr.isUndefined)(this.baseCstVisitorConstructor)){var e=(0,Oq.createBaseSemanticVisitorConstructor)(this.className,(0,Xr.keys)(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor},r.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if((0,Xr.isUndefined)(this.baseCstVisitorWithDefaultsConstructor)){var e=(0,Oq.createBaseVisitorConstructorWithDefaults)(this.className,(0,Xr.keys)(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor},r.prototype.getLastExplicitRuleShortName=function(){var e=this.RULE_STACK;return e[e.length-1]},r.prototype.getPreviousExplicitRuleShortName=function(){var e=this.RULE_STACK;return e[e.length-2]},r.prototype.getLastExplicitRuleOccurrenceIndex=function(){var e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]},r}();my.TreeBuilder=kye});var Uq=I(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});Ey.LexerAdapter=void 0;var Kq=Yn(),Dye=function(){function r(){}return r.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(r.prototype,"input",{get:function(){return this.tokVector},set:function(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length},enumerable:!1,configurable:!0}),r.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):Kq.END_OF_FILE},r.prototype.LA=function(e){var t=this.currIdx+e;return t<0||this.tokVectorLength<=t?Kq.END_OF_FILE:this.tokVector[t]},r.prototype.consumeToken=function(){this.currIdx++},r.prototype.exportLexerState=function(){return this.currIdx},r.prototype.importLexerState=function(e){this.currIdx=e},r.prototype.resetLexerState=function(){this.currIdx=-1},r.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},r.prototype.getLexerPosition=function(){return this.exportLexerState()},r}();Ey.LexerAdapter=Dye});var jq=I(Iy=>{"use strict";Object.defineProperty(Iy,"__esModule",{value:!0});Iy.RecognizerApi=void 0;var Hq=Kt(),Rye=nf(),Ax=Yn(),Fye=Pd(),Tye=rx(),Nye=En(),Lye=function(){function r(){}return r.prototype.ACTION=function(e){return e.call(this)},r.prototype.consume=function(e,t,i){return this.consumeInternal(t,e,i)},r.prototype.subrule=function(e,t,i){return this.subruleInternal(t,e,i)},r.prototype.option=function(e,t){return this.optionInternal(t,e)},r.prototype.or=function(e,t){return this.orInternal(t,e)},r.prototype.many=function(e,t){return this.manyInternal(e,t)},r.prototype.atLeastOne=function(e,t){return this.atLeastOneInternal(e,t)},r.prototype.CONSUME=function(e,t){return this.consumeInternal(e,0,t)},r.prototype.CONSUME1=function(e,t){return this.consumeInternal(e,1,t)},r.prototype.CONSUME2=function(e,t){return this.consumeInternal(e,2,t)},r.prototype.CONSUME3=function(e,t){return this.consumeInternal(e,3,t)},r.prototype.CONSUME4=function(e,t){return this.consumeInternal(e,4,t)},r.prototype.CONSUME5=function(e,t){return this.consumeInternal(e,5,t)},r.prototype.CONSUME6=function(e,t){return this.consumeInternal(e,6,t)},r.prototype.CONSUME7=function(e,t){return this.consumeInternal(e,7,t)},r.prototype.CONSUME8=function(e,t){return this.consumeInternal(e,8,t)},r.prototype.CONSUME9=function(e,t){return this.consumeInternal(e,9,t)},r.prototype.SUBRULE=function(e,t){return this.subruleInternal(e,0,t)},r.prototype.SUBRULE1=function(e,t){return this.subruleInternal(e,1,t)},r.prototype.SUBRULE2=function(e,t){return this.subruleInternal(e,2,t)},r.prototype.SUBRULE3=function(e,t){return this.subruleInternal(e,3,t)},r.prototype.SUBRULE4=function(e,t){return this.subruleInternal(e,4,t)},r.prototype.SUBRULE5=function(e,t){return this.subruleInternal(e,5,t)},r.prototype.SUBRULE6=function(e,t){return this.subruleInternal(e,6,t)},r.prototype.SUBRULE7=function(e,t){return this.subruleInternal(e,7,t)},r.prototype.SUBRULE8=function(e,t){return this.subruleInternal(e,8,t)},r.prototype.SUBRULE9=function(e,t){return this.subruleInternal(e,9,t)},r.prototype.OPTION=function(e){return this.optionInternal(e,0)},r.prototype.OPTION1=function(e){return this.optionInternal(e,1)},r.prototype.OPTION2=function(e){return this.optionInternal(e,2)},r.prototype.OPTION3=function(e){return this.optionInternal(e,3)},r.prototype.OPTION4=function(e){return this.optionInternal(e,4)},r.prototype.OPTION5=function(e){return this.optionInternal(e,5)},r.prototype.OPTION6=function(e){return this.optionInternal(e,6)},r.prototype.OPTION7=function(e){return this.optionInternal(e,7)},r.prototype.OPTION8=function(e){return this.optionInternal(e,8)},r.prototype.OPTION9=function(e){return this.optionInternal(e,9)},r.prototype.OR=function(e){return this.orInternal(e,0)},r.prototype.OR1=function(e){return this.orInternal(e,1)},r.prototype.OR2=function(e){return this.orInternal(e,2)},r.prototype.OR3=function(e){return this.orInternal(e,3)},r.prototype.OR4=function(e){return this.orInternal(e,4)},r.prototype.OR5=function(e){return this.orInternal(e,5)},r.prototype.OR6=function(e){return this.orInternal(e,6)},r.prototype.OR7=function(e){return this.orInternal(e,7)},r.prototype.OR8=function(e){return this.orInternal(e,8)},r.prototype.OR9=function(e){return this.orInternal(e,9)},r.prototype.MANY=function(e){this.manyInternal(0,e)},r.prototype.MANY1=function(e){this.manyInternal(1,e)},r.prototype.MANY2=function(e){this.manyInternal(2,e)},r.prototype.MANY3=function(e){this.manyInternal(3,e)},r.prototype.MANY4=function(e){this.manyInternal(4,e)},r.prototype.MANY5=function(e){this.manyInternal(5,e)},r.prototype.MANY6=function(e){this.manyInternal(6,e)},r.prototype.MANY7=function(e){this.manyInternal(7,e)},r.prototype.MANY8=function(e){this.manyInternal(8,e)},r.prototype.MANY9=function(e){this.manyInternal(9,e)},r.prototype.MANY_SEP=function(e){this.manySepFirstInternal(0,e)},r.prototype.MANY_SEP1=function(e){this.manySepFirstInternal(1,e)},r.prototype.MANY_SEP2=function(e){this.manySepFirstInternal(2,e)},r.prototype.MANY_SEP3=function(e){this.manySepFirstInternal(3,e)},r.prototype.MANY_SEP4=function(e){this.manySepFirstInternal(4,e)},r.prototype.MANY_SEP5=function(e){this.manySepFirstInternal(5,e)},r.prototype.MANY_SEP6=function(e){this.manySepFirstInternal(6,e)},r.prototype.MANY_SEP7=function(e){this.manySepFirstInternal(7,e)},r.prototype.MANY_SEP8=function(e){this.manySepFirstInternal(8,e)},r.prototype.MANY_SEP9=function(e){this.manySepFirstInternal(9,e)},r.prototype.AT_LEAST_ONE=function(e){this.atLeastOneInternal(0,e)},r.prototype.AT_LEAST_ONE1=function(e){return this.atLeastOneInternal(1,e)},r.prototype.AT_LEAST_ONE2=function(e){this.atLeastOneInternal(2,e)},r.prototype.AT_LEAST_ONE3=function(e){this.atLeastOneInternal(3,e)},r.prototype.AT_LEAST_ONE4=function(e){this.atLeastOneInternal(4,e)},r.prototype.AT_LEAST_ONE5=function(e){this.atLeastOneInternal(5,e)},r.prototype.AT_LEAST_ONE6=function(e){this.atLeastOneInternal(6,e)},r.prototype.AT_LEAST_ONE7=function(e){this.atLeastOneInternal(7,e)},r.prototype.AT_LEAST_ONE8=function(e){this.atLeastOneInternal(8,e)},r.prototype.AT_LEAST_ONE9=function(e){this.atLeastOneInternal(9,e)},r.prototype.AT_LEAST_ONE_SEP=function(e){this.atLeastOneSepFirstInternal(0,e)},r.prototype.AT_LEAST_ONE_SEP1=function(e){this.atLeastOneSepFirstInternal(1,e)},r.prototype.AT_LEAST_ONE_SEP2=function(e){this.atLeastOneSepFirstInternal(2,e)},r.prototype.AT_LEAST_ONE_SEP3=function(e){this.atLeastOneSepFirstInternal(3,e)},r.prototype.AT_LEAST_ONE_SEP4=function(e){this.atLeastOneSepFirstInternal(4,e)},r.prototype.AT_LEAST_ONE_SEP5=function(e){this.atLeastOneSepFirstInternal(5,e)},r.prototype.AT_LEAST_ONE_SEP6=function(e){this.atLeastOneSepFirstInternal(6,e)},r.prototype.AT_LEAST_ONE_SEP7=function(e){this.atLeastOneSepFirstInternal(7,e)},r.prototype.AT_LEAST_ONE_SEP8=function(e){this.atLeastOneSepFirstInternal(8,e)},r.prototype.AT_LEAST_ONE_SEP9=function(e){this.atLeastOneSepFirstInternal(9,e)},r.prototype.RULE=function(e,t,i){if(i===void 0&&(i=Ax.DEFAULT_RULE_CONFIG),(0,Hq.contains)(this.definedRulesNames,e)){var n=Fye.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),s={message:n,type:Ax.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(s)}this.definedRulesNames.push(e);var o=this.defineRule(e,t,i);return this[e]=o,o},r.prototype.OVERRIDE_RULE=function(e,t,i){i===void 0&&(i=Ax.DEFAULT_RULE_CONFIG);var n=[];n=n.concat((0,Tye.validateRuleIsOverridden)(e,this.definedRulesNames,this.className)),this.definitionErrors=this.definitionErrors.concat(n);var s=this.defineRule(e,t,i);return this[e]=s,s},r.prototype.BACKTRACK=function(e,t){return function(){this.isBackTrackingStack.push(1);var i=this.saveRecogState();try{return e.apply(this,t),!0}catch(n){if((0,Rye.isRecognitionException)(n))return!1;throw n}finally{this.reloadRecogState(i),this.isBackTrackingStack.pop()}}},r.prototype.getGAstProductions=function(){return this.gastProductionsCache},r.prototype.getSerializedGastProductions=function(){return(0,Nye.serializeGrammar)((0,Hq.values)(this.gastProductionsCache))},r}();Iy.RecognizerApi=Lye});var Jq=I(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});wy.RecognizerEngine=void 0;var Pr=Kt(),qn=dy(),yy=nf(),Gq=Rd(),of=Dd(),Yq=Yn(),Oye=sx(),qq=TA(),Ld=_g(),Mye=ox(),Kye=function(){function r(){}return r.prototype.initRecognizerEngine=function(e,t){if(this.className=(0,Mye.classNameFromInstance)(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=Ld.tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},(0,Pr.has)(t,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 - For Further details.`);if((0,Pr.isArray)(e)){if((0,Pr.isEmpty)(e))throw Error(`A Token Vocabulary cannot be empty. - Note that the first argument for the parser constructor - is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 - For Further details.`)}if((0,Pr.isArray)(e))this.tokensMap=(0,Pr.reduce)(e,function(o,a){return o[a.name]=a,o},{});else if((0,Pr.has)(e,"modes")&&(0,Pr.every)((0,Pr.flatten)((0,Pr.values)(e.modes)),Ld.isTokenType)){var i=(0,Pr.flatten)((0,Pr.values)(e.modes)),n=(0,Pr.uniq)(i);this.tokensMap=(0,Pr.reduce)(n,function(o,a){return o[a.name]=a,o},{})}else if((0,Pr.isObject)(e))this.tokensMap=(0,Pr.cloneObj)(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=qq.EOF;var s=(0,Pr.every)((0,Pr.values)(e),function(o){return(0,Pr.isEmpty)(o.categoryMatches)});this.tokenMatcher=s?Ld.tokenStructuredMatcherNoCategories:Ld.tokenStructuredMatcher,(0,Ld.augmentTokenTypes)((0,Pr.values)(this.tokensMap))},r.prototype.defineRule=function(e,t,i){if(this.selfAnalysisDone)throw Error("Grammar rule <"+e+`> may not be defined after the 'performSelfAnalysis' method has been called' -Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);var n=(0,Pr.has)(i,"resyncEnabled")?i.resyncEnabled:Yq.DEFAULT_RULE_CONFIG.resyncEnabled,s=(0,Pr.has)(i,"recoveryValueFunc")?i.recoveryValueFunc:Yq.DEFAULT_RULE_CONFIG.recoveryValueFunc,o=this.ruleShortNameIdx<t},r.prototype.orInternal=function(e,t){var i=this.getKeyForAutomaticLookahead(qn.OR_IDX,t),n=(0,Pr.isArray)(e)?e:e.DEF,s=this.getLaFuncFromCache(i),o=s.call(this,n);if(o!==void 0){var a=n[o];return a.ALT.call(this)}this.raiseNoAltException(t,e.ERR_MSG)},r.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){var e=this.LA(1),t=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new yy.NotAllInputParsedException(t,e))}},r.prototype.subruleInternal=function(e,t,i){var n;try{var s=i!==void 0?i.ARGS:void 0;return n=e.call(this,t,s),this.cstPostNonTerminal(n,i!==void 0&&i.LABEL!==void 0?i.LABEL:e.ruleName),n}catch(o){this.subruleInternalError(o,i,e.ruleName)}},r.prototype.subruleInternalError=function(e,t,i){throw(0,yy.isRecognitionException)(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,t!==void 0&&t.LABEL!==void 0?t.LABEL:i),delete e.partialCstResult),e},r.prototype.consumeInternal=function(e,t,i){var n;try{var s=this.LA(1);this.tokenMatcher(s,e)===!0?(this.consumeToken(),n=s):this.consumeInternalError(e,s,i)}catch(o){n=this.consumeInternalRecovery(e,t,o)}return this.cstPostTerminal(i!==void 0&&i.LABEL!==void 0?i.LABEL:e.name,n),n},r.prototype.consumeInternalError=function(e,t,i){var n,s=this.LA(0);throw i!==void 0&&i.ERR_MSG?n=i.ERR_MSG:n=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:t,previous:s,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new yy.MismatchedTokenException(n,t,s))},r.prototype.consumeInternalRecovery=function(e,t,i){if(this.recoveryEnabled&&i.name==="MismatchedTokenException"&&!this.isBackTracking()){var n=this.getFollowsForInRuleRecovery(e,t);try{return this.tryInRuleRecovery(e,n)}catch(s){throw s.name===Oye.IN_RULE_RECOVERY_EXCEPTION?i:s}}else throw i},r.prototype.saveRecogState=function(){var e=this.errors,t=(0,Pr.cloneArr)(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:t,CST_STACK:this.CST_STACK}},r.prototype.reloadRecogState=function(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK},r.prototype.ruleInvocationStateUpdate=function(e,t,i){this.RULE_OCCURRENCE_STACK.push(i),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(t,e)},r.prototype.isBackTracking=function(){return this.isBackTrackingStack.length!==0},r.prototype.getCurrRuleFullName=function(){var e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]},r.prototype.shortRuleNameToFullName=function(e){return this.shortRuleNameToFull[e]},r.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),qq.EOF)},r.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},r}();wy.RecognizerEngine=Kye});var zq=I(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});By.ErrorHandler=void 0;var lx=nf(),cx=Kt(),Wq=Rd(),Uye=Yn(),Hye=function(){function r(){}return r.prototype.initErrorHandler=function(e){this._errors=[],this.errorMessageProvider=(0,cx.has)(e,"errorMessageProvider")?e.errorMessageProvider:Uye.DEFAULT_PARSER_CONFIG.errorMessageProvider},r.prototype.SAVE_ERROR=function(e){if((0,lx.isRecognitionException)(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:(0,cx.cloneArr)(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(r.prototype,"errors",{get:function(){return(0,cx.cloneArr)(this._errors)},set:function(e){this._errors=e},enumerable:!1,configurable:!0}),r.prototype.raiseEarlyExitException=function(e,t,i){for(var n=this.getCurrRuleFullName(),s=this.getGAstProductions()[n],o=(0,Wq.getLookaheadPathsForOptionalProd)(e,s,t,this.maxLookahead),a=o[0],l=[],c=1;c<=this.maxLookahead;c++)l.push(this.LA(c));var u=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:a,actual:l,previous:this.LA(0),customUserDescription:i,ruleName:n});throw this.SAVE_ERROR(new lx.EarlyExitException(u,this.LA(1),this.LA(0)))},r.prototype.raiseNoAltException=function(e,t){for(var i=this.getCurrRuleFullName(),n=this.getGAstProductions()[i],s=(0,Wq.getLookaheadPathsForOr)(e,n,this.maxLookahead),o=[],a=1;a<=this.maxLookahead;a++)o.push(this.LA(a));var l=this.LA(0),c=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:s,actual:o,previous:l,customUserDescription:t,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new lx.NoViableAltException(c,this.LA(1),l))},r}();By.ErrorHandler=Hye});var Zq=I(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});Qy.ContentAssist=void 0;var Vq=Dd(),Xq=Kt(),jye=function(){function r(){}return r.prototype.initContentAssist=function(){},r.prototype.computeContentAssist=function(e,t){var i=this.gastProductionsCache[e];if((0,Xq.isUndefined)(i))throw Error("Rule ->"+e+"<- does not exist in this grammar.");return(0,Vq.nextPossibleTokensAfter)([i],t,this.tokenMatcher,this.maxLookahead)},r.prototype.getNextPossibleTokenTypes=function(e){var t=(0,Xq.first)(e.ruleStack),i=this.getGAstProductions(),n=i[t],s=new Vq.NextAfterTokenWalker(n,e).startWalking();return s},r}();Qy.ContentAssist=jye});var sJ=I(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});vy.GastRecorder=void 0;var wn=Kt(),Lo=En(),Gye=Qd(),tJ=_g(),rJ=TA(),Yye=Yn(),qye=dy(),Sy={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(Sy);var _q=!0,$q=Math.pow(2,qye.BITS_FOR_OCCURRENCE_IDX)-1,iJ=(0,rJ.createToken)({name:"RECORDING_PHASE_TOKEN",pattern:Gye.Lexer.NA});(0,tJ.augmentTokenTypes)([iJ]);var nJ=(0,rJ.createTokenInstance)(iJ,`This IToken indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(nJ);var Jye={name:`This CSTNode indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},Wye=function(){function r(){}return r.prototype.initGastRecorder=function(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1},r.prototype.enableRecording=function(){var e=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",function(){for(var t=function(n){var s=n>0?n:"";e["CONSUME"+s]=function(o,a){return this.consumeInternalRecord(o,n,a)},e["SUBRULE"+s]=function(o,a){return this.subruleInternalRecord(o,n,a)},e["OPTION"+s]=function(o){return this.optionInternalRecord(o,n)},e["OR"+s]=function(o){return this.orInternalRecord(o,n)},e["MANY"+s]=function(o){this.manyInternalRecord(n,o)},e["MANY_SEP"+s]=function(o){this.manySepFirstInternalRecord(n,o)},e["AT_LEAST_ONE"+s]=function(o){this.atLeastOneInternalRecord(n,o)},e["AT_LEAST_ONE_SEP"+s]=function(o){this.atLeastOneSepFirstInternalRecord(n,o)}},i=0;i<10;i++)t(i);e.consume=function(n,s,o){return this.consumeInternalRecord(s,n,o)},e.subrule=function(n,s,o){return this.subruleInternalRecord(s,n,o)},e.option=function(n,s){return this.optionInternalRecord(s,n)},e.or=function(n,s){return this.orInternalRecord(s,n)},e.many=function(n,s){this.manyInternalRecord(n,s)},e.atLeastOne=function(n,s){this.atLeastOneInternalRecord(n,s)},e.ACTION=e.ACTION_RECORD,e.BACKTRACK=e.BACKTRACK_RECORD,e.LA=e.LA_RECORD})},r.prototype.disableRecording=function(){var e=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",function(){for(var t=0;t<10;t++){var i=t>0?t:"";delete e["CONSUME"+i],delete e["SUBRULE"+i],delete e["OPTION"+i],delete e["OR"+i],delete e["MANY"+i],delete e["MANY_SEP"+i],delete e["AT_LEAST_ONE"+i],delete e["AT_LEAST_ONE_SEP"+i]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})},r.prototype.ACTION_RECORD=function(e){},r.prototype.BACKTRACK_RECORD=function(e,t){return function(){return!0}},r.prototype.LA_RECORD=function(e){return Yye.END_OF_FILE},r.prototype.topLevelRuleRecord=function(e,t){try{var i=new Lo.Rule({definition:[],name:e});return i.name=e,this.recordingProdStack.push(i),t.call(this),this.recordingProdStack.pop(),i}catch(n){if(n.KNOWN_RECORDER_ERROR!==!0)try{n.message=n.message+` - This error was thrown during the "grammar recording phase" For more info see: - https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw n}throw n}},r.prototype.optionInternalRecord=function(e,t){return Od.call(this,Lo.Option,e,t)},r.prototype.atLeastOneInternalRecord=function(e,t){Od.call(this,Lo.RepetitionMandatory,t,e)},r.prototype.atLeastOneSepFirstInternalRecord=function(e,t){Od.call(this,Lo.RepetitionMandatoryWithSeparator,t,e,_q)},r.prototype.manyInternalRecord=function(e,t){Od.call(this,Lo.Repetition,t,e)},r.prototype.manySepFirstInternalRecord=function(e,t){Od.call(this,Lo.RepetitionWithSeparator,t,e,_q)},r.prototype.orInternalRecord=function(e,t){return zye.call(this,e,t)},r.prototype.subruleInternalRecord=function(e,t,i){if(by(t),!e||(0,wn.has)(e,"ruleName")===!1){var n=new Error(" argument is invalid"+(" expecting a Parser method reference but got: <"+JSON.stringify(e)+">")+(` - inside top level rule: <`+this.recordingProdStack[0].name+">"));throw n.KNOWN_RECORDER_ERROR=!0,n}var s=(0,wn.peek)(this.recordingProdStack),o=e.ruleName,a=new Lo.NonTerminal({idx:t,nonTerminalName:o,label:i==null?void 0:i.LABEL,referencedRule:void 0});return s.definition.push(a),this.outputCst?Jye:Sy},r.prototype.consumeInternalRecord=function(e,t,i){if(by(t),!(0,tJ.hasShortKeyProperty)(e)){var n=new Error(" argument is invalid"+(" expecting a TokenType reference but got: <"+JSON.stringify(e)+">")+(` - inside top level rule: <`+this.recordingProdStack[0].name+">"));throw n.KNOWN_RECORDER_ERROR=!0,n}var s=(0,wn.peek)(this.recordingProdStack),o=new Lo.Terminal({idx:t,terminalType:e,label:i==null?void 0:i.LABEL});return s.definition.push(o),nJ},r}();vy.GastRecorder=Wye;function Od(r,e,t,i){i===void 0&&(i=!1),by(t);var n=(0,wn.peek)(this.recordingProdStack),s=(0,wn.isFunction)(e)?e:e.DEF,o=new r({definition:[],idx:t});return i&&(o.separator=e.SEP),(0,wn.has)(e,"MAX_LOOKAHEAD")&&(o.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(o),s.call(this),n.definition.push(o),this.recordingProdStack.pop(),Sy}function zye(r,e){var t=this;by(e);var i=(0,wn.peek)(this.recordingProdStack),n=(0,wn.isArray)(r)===!1,s=n===!1?r:r.DEF,o=new Lo.Alternation({definition:[],idx:e,ignoreAmbiguities:n&&r.IGNORE_AMBIGUITIES===!0});(0,wn.has)(r,"MAX_LOOKAHEAD")&&(o.maxLookahead=r.MAX_LOOKAHEAD);var a=(0,wn.some)(s,function(l){return(0,wn.isFunction)(l.GATE)});return o.hasPredicates=a,i.definition.push(o),(0,wn.forEach)(s,function(l){var c=new Lo.Alternative({definition:[]});o.definition.push(c),(0,wn.has)(l,"IGNORE_AMBIGUITIES")?c.ignoreAmbiguities=l.IGNORE_AMBIGUITIES:(0,wn.has)(l,"GATE")&&(c.ignoreAmbiguities=!0),t.recordingProdStack.push(c),l.ALT.call(t),t.recordingProdStack.pop()}),Sy}function eJ(r){return r===0?"":""+r}function by(r){if(r<0||r>$q){var e=new Error("Invalid DSL Method idx value: <"+r+`> - `+("Idx value must be a none negative value smaller than "+($q+1)));throw e.KNOWN_RECORDER_ERROR=!0,e}}});var aJ=I(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});xy.PerformanceTracer=void 0;var oJ=Kt(),Vye=Yn(),Xye=function(){function r(){}return r.prototype.initPerformanceTracer=function(e){if((0,oJ.has)(e,"traceInitPerf")){var t=e.traceInitPerf,i=typeof t=="number";this.traceInitMaxIdent=i?t:1/0,this.traceInitPerf=i?t>0:t}else this.traceInitMaxIdent=0,this.traceInitPerf=Vye.DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},r.prototype.TRACE_INIT=function(e,t){if(this.traceInitPerf===!0){this.traceInitIndent++;var i=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <"+e+">");var n=(0,oJ.timer)(t),s=n.time,o=n.value,a=s>10?console.warn:console.log;return this.traceInitIndent time: "+s+"ms"),this.traceInitIndent--,o}else return t()},r}();xy.PerformanceTracer=Xye});var AJ=I(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});Py.applyMixins=void 0;function Zye(r,e){e.forEach(function(t){var i=t.prototype;Object.getOwnPropertyNames(i).forEach(function(n){if(n!=="constructor"){var s=Object.getOwnPropertyDescriptor(i,n);s&&(s.get||s.set)?Object.defineProperty(r.prototype,n,s):r.prototype[n]=t.prototype[n]}})})}Py.applyMixins=Zye});var Yn=I(hr=>{"use strict";var uJ=hr&&hr.__extends||function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}();Object.defineProperty(hr,"__esModule",{value:!0});hr.EmbeddedActionsParser=hr.CstParser=hr.Parser=hr.EMPTY_ALT=hr.ParserDefinitionErrorType=hr.DEFAULT_RULE_CONFIG=hr.DEFAULT_PARSER_CONFIG=hr.END_OF_FILE=void 0;var en=Kt(),_ye=zY(),lJ=TA(),gJ=Pd(),cJ=Iq(),$ye=sx(),ewe=xq(),twe=Mq(),rwe=Uq(),iwe=jq(),nwe=Jq(),swe=zq(),owe=Zq(),awe=sJ(),Awe=aJ(),lwe=AJ();hr.END_OF_FILE=(0,lJ.createTokenInstance)(lJ.EOF,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(hr.END_OF_FILE);hr.DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:gJ.defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1});hr.DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0});var cwe;(function(r){r[r.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",r[r.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",r[r.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",r[r.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",r[r.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",r[r.LEFT_RECURSION=5]="LEFT_RECURSION",r[r.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",r[r.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",r[r.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",r[r.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",r[r.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",r[r.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",r[r.TOO_MANY_ALTS=12]="TOO_MANY_ALTS"})(cwe=hr.ParserDefinitionErrorType||(hr.ParserDefinitionErrorType={}));function uwe(r){return r===void 0&&(r=void 0),function(){return r}}hr.EMPTY_ALT=uwe;var ky=function(){function r(e,t){this.definitionErrors=[],this.selfAnalysisDone=!1;var i=this;if(i.initErrorHandler(t),i.initLexerAdapter(),i.initLooksAhead(t),i.initRecognizerEngine(e,t),i.initRecoverable(t),i.initTreeBuilder(t),i.initContentAssist(),i.initGastRecorder(t),i.initPerformanceTracer(t),(0,en.has)(t,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. - Please use the flag on the relevant DSL method instead. - See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES - For further details.`);this.skipValidations=(0,en.has)(t,"skipValidations")?t.skipValidations:hr.DEFAULT_PARSER_CONFIG.skipValidations}return r.performSelfAnalysis=function(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")},r.prototype.performSelfAnalysis=function(){var e=this;this.TRACE_INIT("performSelfAnalysis",function(){var t;e.selfAnalysisDone=!0;var i=e.className;e.TRACE_INIT("toFastProps",function(){(0,en.toFastProperties)(e)}),e.TRACE_INIT("Grammar Recording",function(){try{e.enableRecording(),(0,en.forEach)(e.definedRulesNames,function(s){var o=e[s],a=o.originalGrammarAction,l=void 0;e.TRACE_INIT(s+" Rule",function(){l=e.topLevelRuleRecord(s,a)}),e.gastProductionsCache[s]=l})}finally{e.disableRecording()}});var n=[];if(e.TRACE_INIT("Grammar Resolving",function(){n=(0,cJ.resolveGrammar)({rules:(0,en.values)(e.gastProductionsCache)}),e.definitionErrors=e.definitionErrors.concat(n)}),e.TRACE_INIT("Grammar Validations",function(){if((0,en.isEmpty)(n)&&e.skipValidations===!1){var s=(0,cJ.validateGrammar)({rules:(0,en.values)(e.gastProductionsCache),maxLookahead:e.maxLookahead,tokenTypes:(0,en.values)(e.tokensMap),errMsgProvider:gJ.defaultGrammarValidatorErrorProvider,grammarName:i});e.definitionErrors=e.definitionErrors.concat(s)}}),(0,en.isEmpty)(e.definitionErrors)&&(e.recoveryEnabled&&e.TRACE_INIT("computeAllProdsFollows",function(){var s=(0,_ye.computeAllProdsFollows)((0,en.values)(e.gastProductionsCache));e.resyncFollows=s}),e.TRACE_INIT("ComputeLookaheadFunctions",function(){e.preComputeLookaheadFunctions((0,en.values)(e.gastProductionsCache))})),!r.DEFER_DEFINITION_ERRORS_HANDLING&&!(0,en.isEmpty)(e.definitionErrors))throw t=(0,en.map)(e.definitionErrors,function(s){return s.message}),new Error(`Parser Definition Errors detected: - `+t.join(` -------------------------------- -`))})},r.DEFER_DEFINITION_ERRORS_HANDLING=!1,r}();hr.Parser=ky;(0,lwe.applyMixins)(ky,[$ye.Recoverable,ewe.LooksAhead,twe.TreeBuilder,rwe.LexerAdapter,nwe.RecognizerEngine,iwe.RecognizerApi,swe.ErrorHandler,owe.ContentAssist,awe.GastRecorder,Awe.PerformanceTracer]);var gwe=function(r){uJ(e,r);function e(t,i){i===void 0&&(i=hr.DEFAULT_PARSER_CONFIG);var n=this,s=(0,en.cloneObj)(i);return s.outputCst=!0,n=r.call(this,t,s)||this,n}return e}(ky);hr.CstParser=gwe;var fwe=function(r){uJ(e,r);function e(t,i){i===void 0&&(i=hr.DEFAULT_PARSER_CONFIG);var n=this,s=(0,en.cloneObj)(i);return s.outputCst=!1,n=r.call(this,t,s)||this,n}return e}(ky);hr.EmbeddedActionsParser=fwe});var hJ=I(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});Dy.createSyntaxDiagramsCode=void 0;var fJ=kv();function hwe(r,e){var t=e===void 0?{}:e,i=t.resourceBase,n=i===void 0?"https://unpkg.com/chevrotain@"+fJ.VERSION+"/diagrams/":i,s=t.css,o=s===void 0?"https://unpkg.com/chevrotain@"+fJ.VERSION+"/diagrams/diagrams.css":s,a=` - - - - - -`,l=` - -`,c=` -