From be0f48407ddd3f807f181fd4f445d923bf4e0bb8 Mon Sep 17 00:00:00 2001 From: Vasek - Tom C Date: Mon, 10 Aug 2026 14:59:25 +0200 Subject: [PATCH 1/2] feat(library): vendor the TypeScript SDK library and build its bundle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Module bindings import their runtime from ./core.js, a bundle that until now only existed inside the engine image — which is why this repo could generate a module's bindings but not the library they run against. Vendor the library and build the bundle here instead. The source is dagger/dagger's sdk/typescript at v1.0.0-beta.9, the engine these checks run against, minus what does not belong to the library itself: the Go runtime module (which stays upstream), the test and lint tooling, the upstream changelog, and its dagger.json — a stray module config here would be discovered as a workspace module. src/api/client.gen.ts is left out too; the packager already generates it. libraryBundle builds core.js and core.d.ts with the same commands and the same pinned bun image as toolchains/engine-dev/build/sdk.go, so a module built against this bundle behaves like one built against the engine's. Verified: it exports the runtime the generated bindings import (Context, BaseClient) and the decorators modules are written with (object, func, field, enumType, entrypoint, ...). The bundle is committed rather than built on demand: the SDK reads it at generate time, and building it there would put a bun toolchain in the critical path of every `dagger generate`. Signed-off-by: Tom Chauveau --- .dagger/modules/packager/main.dang | 44 + .gitattributes | 2 +- design/module-gen.md | 9 +- library/.gitignore | 4 + library/LICENSE | 191 + library/README.md | 88 + library/bundle/core.d.ts | 8717 ++ library/bundle/core.js | 108946 +++++++++++++++ library/package.json | 86 + library/rollup.dts.config.mjs | 10 + library/src/api/.gitattributes | 1 + library/src/common/context.ts | 62 + library/src/common/errors/DaggerSDKError.ts | 46 + .../errors/DockerImageRefValidationError.ts | 28 + .../EngineSessionConnectParamsParseError.ts | 30 + .../EngineSessionConnectionTimeoutError.ts | 30 + .../errors/EngineSessionErrorOptions.ts | 20 + library/src/common/errors/ExecError.ts | 57 + library/src/common/errors/FunctionNotFound.ts | 11 + .../src/common/errors/GraphQLRequestError.ts | 42 + .../errors/InitEngineSessionBinaryError.ts | 17 + .../src/common/errors/IntrospectionError.ts | 11 + .../common/errors/NotAwaitedRequestError.ts | 17 + .../errors/TooManyNestedObjectsError.ts | 27 + .../src/common/errors/UnknownDaggerError.ts | 17 + library/src/common/errors/errors-codes.ts | 68 + library/src/common/errors/index.ts | 14 + library/src/common/graphql/client.ts | 99 + library/src/common/graphql/compute_query.ts | 277 + library/src/common/graphql/connect.ts | 37 + library/src/common/graphql/connection.ts | 27 + library/src/common/utils.ts | 14 + library/src/connect.ts | 78 + library/src/connectOpts.ts | 31 + library/src/index.ts | 23 + library/src/module/decorators.ts | 72 + library/src/module/entrypoint/context.ts | 8 + library/src/module/entrypoint/entrypoint.ts | 107 + .../entrypoint/introspection_entrypoint.ts | 134 + library/src/module/entrypoint/invoke.ts | 109 + library/src/module/entrypoint/load.ts | 373 + library/src/module/entrypoint/register.ts | 325 + library/src/module/executor.ts | 255 + .../src/module/introspector/case_convertor.ts | 18 + .../introspector/dagger_module/argument.ts | 169 + .../introspector/dagger_module/constructor.ts | 53 + .../introspector/dagger_module/decorator.ts | 29 + .../module/introspector/dagger_module/enum.ts | 82 + .../introspector/dagger_module/enumBase.ts | 18 + .../introspector/dagger_module/enumClass.ts | 91 + .../introspector/dagger_module/function.ts | 159 + .../introspector/dagger_module/index.ts | 14 + .../introspector/dagger_module/interface.ts | 79 + .../dagger_module/interfaceFunction.ts | 133 + .../introspector/dagger_module/locatable.ts | 15 + .../introspector/dagger_module/module.ts | 410 + .../introspector/dagger_module/object.ts | 154 + .../introspector/dagger_module/objectBase.ts | 36 + .../introspector/dagger_module/property.ts | 130 + .../introspector/dagger_module/reference.ts | 60 + .../introspector/dagger_module/typeObject.ts | 111 + .../dagger_module/typeObjectProperty.ts | 94 + library/src/module/introspector/index.ts | 35 + .../module/introspector/introspection_json.ts | 689 + library/src/module/introspector/typedef.ts | 69 + .../src/module/introspector/typedef_json.ts | 160 + .../introspector/typescript_module/ast.ts | 737 + .../typescript_module/declarations.ts | 26 + .../introspector/typescript_module/index.ts | 3 + .../typescript_module/location.ts | 5 + .../typescript_module/typedef_utils.ts | 41 + .../src/module/introspector/utils/files.ts | 38 + library/src/module/registry.ts | 276 + library/src/provisioning/.gitattributes | 1 + library/src/provisioning/bin.ts | 620 + library/src/provisioning/default.ts | 2 + library/src/provisioning/engineconn.ts | 34 + library/src/provisioning/index.ts | 22 + library/src/telemetry/index.ts | 3 + library/src/telemetry/init.ts | 105 + library/src/telemetry/live_processor.ts | 15 + library/src/telemetry/telemetry.ts | 48 + library/src/telemetry/tracer.ts | 64 + library/tsconfig.json | 25 + library/yarn.lock | 3007 + 85 files changed, 128439 insertions(+), 5 deletions(-) create mode 100644 library/.gitignore create mode 100644 library/LICENSE create mode 100644 library/README.md create mode 100644 library/bundle/core.d.ts create mode 100644 library/bundle/core.js create mode 100644 library/package.json create mode 100644 library/rollup.dts.config.mjs create mode 100644 library/src/api/.gitattributes create mode 100644 library/src/common/context.ts create mode 100644 library/src/common/errors/DaggerSDKError.ts create mode 100644 library/src/common/errors/DockerImageRefValidationError.ts create mode 100644 library/src/common/errors/EngineSessionConnectParamsParseError.ts create mode 100644 library/src/common/errors/EngineSessionConnectionTimeoutError.ts create mode 100644 library/src/common/errors/EngineSessionErrorOptions.ts create mode 100644 library/src/common/errors/ExecError.ts create mode 100644 library/src/common/errors/FunctionNotFound.ts create mode 100644 library/src/common/errors/GraphQLRequestError.ts create mode 100644 library/src/common/errors/InitEngineSessionBinaryError.ts create mode 100644 library/src/common/errors/IntrospectionError.ts create mode 100644 library/src/common/errors/NotAwaitedRequestError.ts create mode 100644 library/src/common/errors/TooManyNestedObjectsError.ts create mode 100644 library/src/common/errors/UnknownDaggerError.ts create mode 100644 library/src/common/errors/errors-codes.ts create mode 100644 library/src/common/errors/index.ts create mode 100644 library/src/common/graphql/client.ts create mode 100644 library/src/common/graphql/compute_query.ts create mode 100644 library/src/common/graphql/connect.ts create mode 100644 library/src/common/graphql/connection.ts create mode 100644 library/src/common/utils.ts create mode 100644 library/src/connect.ts create mode 100644 library/src/connectOpts.ts create mode 100644 library/src/index.ts create mode 100644 library/src/module/decorators.ts create mode 100644 library/src/module/entrypoint/context.ts create mode 100644 library/src/module/entrypoint/entrypoint.ts create mode 100644 library/src/module/entrypoint/introspection_entrypoint.ts create mode 100644 library/src/module/entrypoint/invoke.ts create mode 100644 library/src/module/entrypoint/load.ts create mode 100644 library/src/module/entrypoint/register.ts create mode 100644 library/src/module/executor.ts create mode 100644 library/src/module/introspector/case_convertor.ts create mode 100644 library/src/module/introspector/dagger_module/argument.ts create mode 100644 library/src/module/introspector/dagger_module/constructor.ts create mode 100644 library/src/module/introspector/dagger_module/decorator.ts create mode 100644 library/src/module/introspector/dagger_module/enum.ts create mode 100644 library/src/module/introspector/dagger_module/enumBase.ts create mode 100644 library/src/module/introspector/dagger_module/enumClass.ts create mode 100644 library/src/module/introspector/dagger_module/function.ts create mode 100644 library/src/module/introspector/dagger_module/index.ts create mode 100644 library/src/module/introspector/dagger_module/interface.ts create mode 100644 library/src/module/introspector/dagger_module/interfaceFunction.ts create mode 100644 library/src/module/introspector/dagger_module/locatable.ts create mode 100644 library/src/module/introspector/dagger_module/module.ts create mode 100644 library/src/module/introspector/dagger_module/object.ts create mode 100644 library/src/module/introspector/dagger_module/objectBase.ts create mode 100644 library/src/module/introspector/dagger_module/property.ts create mode 100644 library/src/module/introspector/dagger_module/reference.ts create mode 100644 library/src/module/introspector/dagger_module/typeObject.ts create mode 100644 library/src/module/introspector/dagger_module/typeObjectProperty.ts create mode 100644 library/src/module/introspector/index.ts create mode 100644 library/src/module/introspector/introspection_json.ts create mode 100644 library/src/module/introspector/typedef.ts create mode 100644 library/src/module/introspector/typedef_json.ts create mode 100644 library/src/module/introspector/typescript_module/ast.ts create mode 100644 library/src/module/introspector/typescript_module/declarations.ts create mode 100644 library/src/module/introspector/typescript_module/index.ts create mode 100644 library/src/module/introspector/typescript_module/location.ts create mode 100644 library/src/module/introspector/typescript_module/typedef_utils.ts create mode 100644 library/src/module/introspector/utils/files.ts create mode 100644 library/src/module/registry.ts create mode 100644 library/src/provisioning/.gitattributes create mode 100644 library/src/provisioning/bin.ts create mode 100644 library/src/provisioning/default.ts create mode 100644 library/src/provisioning/engineconn.ts create mode 100644 library/src/provisioning/index.ts create mode 100644 library/src/telemetry/index.ts create mode 100644 library/src/telemetry/init.ts create mode 100644 library/src/telemetry/live_processor.ts create mode 100644 library/src/telemetry/telemetry.ts create mode 100644 library/src/telemetry/tracer.ts create mode 100644 library/tsconfig.json create mode 100644 library/yarn.lock diff --git a/.dagger/modules/packager/main.dang b/.dagger/modules/packager/main.dang index e9d9123..8db062b 100644 --- a/.dagger/modules/packager/main.dang +++ b/.dagger/modules/packager/main.dang @@ -39,6 +39,50 @@ type Packager { .changes } + """ + Build the bundled library the generated module bindings import as ./core.js. + + Same recipe and same pinned image as the engine's own build + (toolchains/engine-dev/build/sdk.go), so a module built against this bundle + behaves like one built against the engine's: a single node-targeted JS bundle + with the TypeScript compiler left external, plus the rolled-up type + declarations for it. + """ + libraryBundle(ws: Workspace!): Changeset! @generate { + let built = bun + .withDirectory("/src", ws.directory("/" + libraryPath)) + .withWorkdir("/src") + .withExec(["bun", "install", "--frozen-lockfile"]) + .withExec(["bun", "build", "./src/index.ts", "--external=typescript", "--target=node", "--outfile", "/out/core.js"]) + .withExec(["tsc", "--emitDeclarationOnly"]) + .withExec(["bun", "x", "rollup", "-c", "rollup.dts.config.mjs", "-o", "/out/core.d.ts"]) + .directory("/out") + + polyfill.workspace(ws).fork + .withDirectory(libraryPath + "/" + bundlePath, built) + .changes + } + + """ + Directory holding the built bundle, relative to libraryPath. Committed: the + SDK module reads it at generate time, and building it there would put a bun + toolchain in every user's `dagger generate`. + """ + let bundlePath: String! = "bundle" + + """ + Bun toolchain the bundle is built with, pinned to the version and digest the + engine builds its own with. NodeJS comes along because the declaration build + shells out to tsc. + """ + let bun: Container! { + container + .from("oven/bun:1.3.0-alpine@sha256:37e6b1cbe053939bccf6ae4507977ed957eaa6e7f275670b72ad6348e0d2c11f") + .withoutEntrypoint + .withExec(["apk", "add", "nodejs"]) + .withExec(["bun", "install", "-g", "typescript"]) + } + """ Container with the codegen helper compiled and on PATH at /usr/local/bin/codegen. Read from the workspace rather than this module's own diff --git a/.gitattributes b/.gitattributes index c18deac..1eb75f8 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -/library/src/api/client.gen.ts linguist-generated +/library/bundle/** linguist-generated diff --git a/design/module-gen.md b/design/module-gen.md index 96e0956..297d13c 100644 --- a/design/module-gen.md +++ b/design/module-gen.md @@ -300,9 +300,10 @@ maintaining it. Its golden test is "reproduce the vendored file byte-for-byte". committed bundle, so a stale artifact fails CI instead of silently shipping. - **Marked generated.** `.gitattributes` `linguist-generated` for the bundle directory, mirroring what codegen does in user modules. -- **Cost of carry.** ~3.7 MB of text per bundle refresh in git history - (`core.js` 3.5 MB, `core.d.ts` 240 KB), plus the introspector. Acceptable, but - it argues for refreshing on engine bumps rather than casually. +- **Cost of carry.** ~4.6 MB per bundle refresh in git history — measured on + `v1.0.0-beta.9`: `core.js` 4.3 MB, `core.d.ts` 329 KB, plus the 466 KB of + library bindings and (later) the introspector. Acceptable, but it argues for + refreshing on engine bumps rather than casually. ## 5. Target architecture @@ -401,7 +402,7 @@ scoping, same `changes.{{isEmpty}}` concurrency trick, same fold onto One private field resolves the bundle, and it is now trivial: ``` -let tsBundle: Directory! { currentModule.source.directory("bundle") } +let tsBundle: Directory! { currentModule.source.directory("library/bundle") } ``` Everything downstream takes it as an argument rather than reaching for it, so if diff --git a/library/.gitignore b/library/.gitignore new file mode 100644 index 0000000..83af6aa --- /dev/null +++ b/library/.gitignore @@ -0,0 +1,4 @@ +node_modules +dist/ +**/*.diff.json +.yarn \ No newline at end of file diff --git a/library/LICENSE b/library/LICENSE new file mode 100644 index 0000000..17b2ba2 --- /dev/null +++ b/library/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2022 Dagger, 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. diff --git a/library/README.md b/library/README.md new file mode 100644 index 0000000..bb98adb --- /dev/null +++ b/library/README.md @@ -0,0 +1,88 @@ +# Dagger TypeScript SDK + +A client package for running [Dagger](https://dagger.io/) pipelines. + +## What is the Dagger TypeScript SDK? + +The Dagger TypeScript SDK contains everything you need to develop CI/CD pipelines in TypeScript or Javascript, and run them on any OCI-compatible container runtime. + +## Install + +```shell +npm install @dagger.io/dagger --save-dev +``` + +## Local development + +You may want to work on the TypeScript SDK and test it directly on a local node project. + +### 1. Create a new Node project + +:warning: Skip this step if you already have a node project + +```shell +mkdir my-test-ts-project + +# Init project (you may use yarn or pnpm) +npm init -y + +# Add typescript +npm install typescript ts-node --save-dev + +# Init typescript project +npx tsc --init +``` + +### 2. Update project settings + +Dagger exports its SDK using type module so you will need to also update +your `package.json` to the same type. + +Add or update the field `type` in your `package.json` from your project root directory: + +```shell +npm pkg set type=module +``` + +You must also update your `tsconfig.json` to use `NodeNext` as `module`. + +```json +"module": "NodeNext" +``` + +### 3. Symlink Dagger local module + +Go to the Dagger TypeScript SDK directory and do the following : + +```shell +cd path/to/dagger/sdk/typescript # go into the package directory +npm link # creates global link +``` + +Go back to the root directory of your local project to link the TypeScript SDK. + +```shell +cd path/to/my_app # go into your project directory. +npm link @dagger.io/dagger # link install the package +``` + +:bulb: Any changes to `path/to/dagger/sdk/typescript` will be reflected in `path/to/my_app/node_modules/@dagger.io/dagger`. + +### 4. Make your contribution + +While making SDK code modification you should `watch` the input files: + +```shell +cd path/to/dagger/sdk/typescript # go into the package directory +yarn watch # Recompile the code when input files are modified +``` + +You can now import the local Dagger TypeScript SDK as if you were using the official one. + +```ts +import { connect } from "@dagger.io/dagger" +``` + +## Documentation + +Please [visit our documentation](https://docs.dagger.io/sdk/nodejs/835948/install) for a full list of commands and examples. diff --git a/library/bundle/core.d.ts b/library/bundle/core.d.ts new file mode 100644 index 0000000..e1cd1c0 --- /dev/null +++ b/library/bundle/core.d.ts @@ -0,0 +1,8717 @@ +import * as graphql_request from 'graphql-request'; +import { GraphQLClient, ClientError } from 'graphql-request'; +export { GraphQLClient } from 'graphql-request'; +import * as opentelemetry from '@opentelemetry/api'; +import { GraphQLErrorExtensions } from 'graphql'; +import { Writable } from 'node:stream'; + +/** + * Tracer encapsulates the OpenTelemetry Tracer. + */ +declare class Tracer { + private tracer; + constructor(name: string); + startSpan(name: string, attributes?: opentelemetry.Attributes): opentelemetry.Span; + /** + * Execute the functions with a custom span with the given name using startActiveSpan. + * The function executed will use the parent context of the function (it can be another span + * or the main function). + * + * @param name The name of the span + * @param fn The functions to execute + * + * startActiveSpan returns the result of the executed functions. + * + * The span is automatically ended when the function is done. + * The span is automatically marked as an error if the function throws an error. + * + * + * @example + * ``` + * return getTracer().startActiveSpan(name, async () => { + * return this.containerEcho("test").stdout() + * }) + * ``` + */ + startActiveSpan(name: string, fn: (span: opentelemetry.Span) => Promise, attributes?: opentelemetry.Attributes): Promise; +} + +/** + * Return a tracer to use with Dagger. + * + * The tracer is automatically initialized if not already done. + * As a conveniance function, you can use `withTracingSpan` that automatically close + * the span at the end of the function. + * + * You can add a custom name to the tracer based on your application. + */ +declare function getTracer(name?: string): Tracer; + +/** + * Wraps the GraphQL client to allow lazy initialization and setting + * the GQL client of the global Dagger client instance (`dag`). + */ +declare class Connection { + private _gqlClient?; + constructor(_gqlClient?: GraphQLClient | undefined); + resetClient(): void; + setGQLClient(gqlClient: GraphQLClient): void; + getGQLClient(): GraphQLClient; +} + +type QueryTree = { + operation: string; + args?: Record; + inlineType?: string; +}; + +declare class Context { + private _queryTree; + private _connection; + constructor(_queryTree?: QueryTree[], _connection?: Connection); + getGQLClient(): GraphQLClient; + copy(): Context; + select(operation: string, args?: Record): Context; + /** + * Select via node(id:) with an inline fragment on the given type. + * Produces: node(id: "...") { ... on TypeName { children } } + */ + selectNode(id: string, typeName: string): Context; + execute(): Promise; +} +/** + * Common base class for every generated API class (Client, Container, and + * dependency-contributed types). + * + * It lives here in the SDK runtime rather than in the generated client.gen.ts + * so that per-dependency generated files (e.g. hello.gen.ts) can `extends + * BaseClient` without importing a value from client.gen.ts — client.gen.ts + * `export *`s those dep files, so a value import would create an ESM cycle. + * client.gen.ts re-exports BaseClient to keep `import { BaseClient } from + * "./client.gen.js"` working for existing consumers. + */ +declare class BaseClient { + protected _ctx: Context; + /** + * @hidden + */ + constructor(_ctx?: Context); +} + +/** + * Declare a number as float in the Dagger API. + */ +type float = number; + +type AddressDirectoryOpts = { + exclude?: string[]; + include?: string[]; + gitignore?: boolean; + noCache?: boolean; +}; +type AddressFileOpts = { + exclude?: string[]; + include?: string[]; + gitignore?: boolean; + noCache?: boolean; +}; +type BuildArg = { + /** + * The build argument name. + */ + name: string; + /** + * The build argument value. + */ + value: string; +}; +/** + * Sharing mode of the cache volume. + */ +declare enum CacheSharingMode { + /** + * Shares the cache volume amongst many build pipelines, but will serialize the writes + */ + Locked = "LOCKED", + /** + * Keeps a cache volume for a single build pipeline + */ + Private = "PRIVATE", + /** + * Shares the cache volume amongst many build pipelines + */ + Shared = "SHARED" +} +/** + * Utility function to convert a CacheSharingMode value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function CacheSharingModeValueToName(value: CacheSharingMode): string; +/** + * Utility function to convert a CacheSharingMode name to its value so + * it can be properly used inside the module runtime. + */ +declare function CacheSharingModeNameToValue(name: string): CacheSharingMode; +type ChangesetWithChangesetOpts = { + /** + * What to do on a merge conflict + */ + onConflict?: ChangesetMergeConflict; +}; +type ChangesetWithChangesetsOpts = { + /** + * What to do on a merge conflict + */ + onConflict?: ChangesetsMergeConflict; +}; +/** + * Strategy to use when merging changesets with conflicting changes. + */ +declare enum ChangesetMergeConflict { + /** + * Attempt the merge and fail if git merge fails due to conflicts + */ + Fail = "FAIL", + /** + * Fail before attempting merge if file-level conflicts are detected + */ + FailEarly = "FAIL_EARLY", + /** + * Let git create conflict markers in files. For modify/delete conflicts, keeps the modified version. Fails on binary conflicts. + */ + LeaveConflictMarkers = "LEAVE_CONFLICT_MARKERS", + /** + * The conflict is resolved by applying the version of the calling changeset + */ + PreferOurs = "PREFER_OURS", + /** + * The conflict is resolved by applying the version of the other changeset + */ + PreferTheirs = "PREFER_THEIRS" +} +/** + * Utility function to convert a ChangesetMergeConflict value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ChangesetMergeConflictValueToName(value: ChangesetMergeConflict): string; +/** + * Utility function to convert a ChangesetMergeConflict name to its value so + * it can be properly used inside the module runtime. + */ +declare function ChangesetMergeConflictNameToValue(name: string): ChangesetMergeConflict; +/** + * Strategy to use when merging multiple changesets with git octopus merge. + */ +declare enum ChangesetsMergeConflict { + /** + * Attempt the octopus merge and fail if git merge fails due to conflicts + */ + Fail = "FAIL", + /** + * Fail before attempting merge if file-level conflicts are detected between any changesets + */ + FailEarly = "FAIL_EARLY" +} +/** + * Utility function to convert a ChangesetsMergeConflict value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ChangesetsMergeConflictValueToName(value: ChangesetsMergeConflict): string; +/** + * Utility function to convert a ChangesetsMergeConflict name to its value so + * it can be properly used inside the module runtime. + */ +declare function ChangesetsMergeConflictNameToValue(name: string): ChangesetsMergeConflict; +type CheckGroupRunOpts = { + /** + * If true, stop running checks as soon as any check fails. + */ + failFast?: boolean; +}; +type ContainerAsServiceOpts = { + /** + * Command to run instead of the container's default command (e.g., ["go", "run", "main.go"]). + * + * If empty, the container's default command is used. + */ + args?: string[]; + /** + * If the container has an entrypoint, prepend it to the args. + */ + useEntrypoint?: boolean; + /** + * Provides Dagger access to the executed command. + */ + experimentalPrivilegedNesting?: boolean; + /** + * Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + insecureRootCapabilities?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the args according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; + /** + * If set, skip the automatic init process injected into containers by default. + * + * This should only be used if the user requires that their exec process be the pid 1 process in the container. Otherwise it may result in unexpected behavior. + */ + noInit?: boolean; +}; +type ContainerAsTarballOpts = { + /** + * Identifiers for other platform specific containers. + * + * Used for multi-platform images. + */ + platformVariants?: Container[]; + /** + * Force each layer of the image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + */ + forcedCompression?: ImageLayerCompression; + /** + * Use the specified media types for the image's layers. + * + * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support. + */ + mediaTypes?: ImageMediaTypes; +}; +type ContainerDirectoryOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerExistsOpts = { + /** + * If specified, also validate the type of file (e.g. "REGULAR_TYPE", "DIRECTORY_TYPE", or "SYMLINK_TYPE"). + */ + expectedType?: ExistsType; + /** + * If specified, do not follow symlinks. + */ + doNotFollowSymlinks?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerExportOpts = { + /** + * Identifiers for other platform specific containers. + * + * Used for multi-platform image. + */ + platformVariants?: Container[]; + /** + * Force each layer of the exported image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + */ + forcedCompression?: ImageLayerCompression; + /** + * Use the specified media types for the exported image's layers. + * + * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support. + */ + mediaTypes?: ImageMediaTypes; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerExportImageOpts = { + /** + * Identifiers for other platform specific containers. + * + * Used for multi-platform image. + */ + platformVariants?: Container[]; + /** + * Force each layer of the exported image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + */ + forcedCompression?: ImageLayerCompression; + /** + * Use the specified media types for the exported image's layers. + * + * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support. + */ + mediaTypes?: ImageMediaTypes; +}; +type ContainerFileOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerFromOpts = { + /** + * Service to use as the registry endpoint for the image address. + * + * The service will be started only for this pull. + */ + registryService?: Service; + /** + * Protocol to use for registry communication. + * + * Defaults to "HTTPS". Use "HTTP" only for plain HTTP registries. + */ + protocol?: RegistryProtocol; + /** + * Allow HTTPS registry communication without verifying the server certificate. + */ + insecureSkipTLSVerify?: boolean; +}; +type ContainerImportOpts = { + /** + * Identifies the tag to import from the archive, if the archive bundles multiple tags. + */ + tag?: string; +}; +type ContainerLayerOpts = { + /** + * Force each layer of the image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + */ + forcedCompression?: ImageLayerCompression; + /** + * Media types to use for image layers. Defaults to OCI. + */ + mediaTypes?: ImageMediaTypes; +}; +type ContainerManifestOpts = { + /** + * Force each layer of the image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + */ + forcedCompression?: ImageLayerCompression; + /** + * Media types to use for image layers. Defaults to OCI. + */ + mediaTypes?: ImageMediaTypes; +}; +type ContainerPublishOpts = { + /** + * Identifiers for other platform specific containers. + * + * Used for multi-platform image. + */ + platformVariants?: Container[]; + /** + * Force each layer of the published image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + */ + forcedCompression?: ImageLayerCompression; + /** + * Use the specified media types for the published image's layers. + * + * Defaults to "OCI", which is compatible with most recent registries, but "Docker" may be needed for older registries without OCI support. + */ + mediaTypes?: ImageMediaTypes; + /** + * Service to use as the registry endpoint for the image address. + * + * The service will be started only for this push. + */ + registryService?: Service; + /** + * Protocol to use for registry communication. + * + * Defaults to "HTTPS". Use "HTTP" only for plain HTTP registries. + */ + protocol?: RegistryProtocol; + /** + * Allow HTTPS registry communication without verifying the server certificate. + */ + insecureSkipTLSVerify?: boolean; +}; +type ContainerStatOpts = { + /** + * If specified, do not follow symlinks. + */ + doNotFollowSymlinks?: boolean; +}; +type ContainerTerminalOpts = { + /** + * If set, override the container's default terminal command and invoke these command arguments instead. + */ + cmd?: string[]; + /** + * Provides Dagger access to the executed command. + */ + experimentalPrivilegedNesting?: boolean; + /** + * Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + insecureRootCapabilities?: boolean; +}; +type ContainerUpOpts = { + /** + * Bind each tunnel port to a random port on the host. + */ + random?: boolean; + /** + * List of frontend/backend port mappings to forward. + * + * Frontend is the port accepting traffic on the host, backend is the service port. + */ + ports?: PortForward[]; + /** + * Command to run instead of the container's default command (e.g., ["go", "run", "main.go"]). + * + * If empty, the container's default command is used. + */ + args?: string[]; + /** + * If the container has an entrypoint, prepend it to the args. + */ + useEntrypoint?: boolean; + /** + * Provides Dagger access to the executed command. + */ + experimentalPrivilegedNesting?: boolean; + /** + * Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + insecureRootCapabilities?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the args according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; + /** + * If set, skip the automatic init process injected into containers by default. + * + * This should only be used if the user requires that their exec process be the pid 1 process in the container. Otherwise it may result in unexpected behavior. + */ + noInit?: boolean; +}; +type ContainerWithDefaultTerminalCmdOpts = { + /** + * Provides Dagger access to the executed command. + */ + experimentalPrivilegedNesting?: boolean; + /** + * Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + insecureRootCapabilities?: boolean; +}; +type ContainerWithDirectoryOpts = { + /** + * Patterns to exclude in the written directory (e.g. ["node_modules/**", ".gitignore", ".git/"]). + */ + exclude?: string[]; + /** + * Patterns to include in the written directory (e.g. ["*.go", "go.mod", "go.sum"]). + */ + include?: string[]; + /** + * Apply .gitignore rules when writing the directory. + */ + gitignore?: boolean; + /** + * A user:group to set for the directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; + permissions?: number; +}; +type ContainerWithDockerHealthcheckOpts = { + /** + * When true, command must be a single element, which is run using the container's shell + */ + shell?: boolean; + /** + * Interval between running healthcheck. Example: "30s" + */ + interval?: string; + /** + * Healthcheck timeout. Example: "3s" + */ + timeout?: string; + /** + * StartPeriod allows for failures during this initial startup period which do not count towards maximum number of retries. Example: "0s" + */ + startPeriod?: string; + /** + * StartInterval configures the duration between checks during the startup phase. Example: "5s" + */ + startInterval?: string; + /** + * The maximum number of consecutive failures before the container is marked as unhealthy. Example: "3" + */ + retries?: number; +}; +type ContainerWithEntrypointOpts = { + /** + * Don't reset the default arguments when setting the entrypoint. By default it is reset, since entrypoint and default args are often tightly coupled. + */ + keepDefaultArgs?: boolean; +}; +type ContainerWithEnvVariableOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value according to the current environment variables defined in the container (e.g. "/opt/bin:$PATH"). + */ + expand?: boolean; +}; +type ContainerWithExecOpts = { + /** + * Apply the OCI entrypoint, if present, by prepending it to the args. Ignored by default. + */ + useEntrypoint?: boolean; + /** + * Content to write to the command's standard input. Example: "Hello world") + */ + stdin?: string; + /** + * Redirect the command's standard input from a file in the container. Example: "./stdin.txt" + */ + redirectStdin?: string; + /** + * Redirect the command's standard output to a file in the container. Example: "./stdout.txt" + */ + redirectStdout?: string; + /** + * Redirect the command's standard error to a file in the container. Example: "./stderr.txt" + */ + redirectStderr?: string; + /** + * Exit codes this command is allowed to exit with without error + */ + expect?: ReturnType; + /** + * Provides Dagger access to the executed command. + */ + experimentalPrivilegedNesting?: boolean; + /** + * Execute the command with all root capabilities. Like --privileged in Docker + * + * DANGER: this grants the command full access to the host system. Only use when 1) you trust the command being executed and 2) you specifically need this level of access. + */ + insecureRootCapabilities?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the args according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; + /** + * Skip the automatic init process injected into containers by default. + * + * Only use this if you specifically need the command to be pid 1 in the container. Otherwise it may result in unexpected behavior. If you're not sure, you don't need this. + */ + noInit?: boolean; +}; +type ContainerWithExposedPortOpts = { + /** + * Network protocol. Example: "tcp" + */ + protocol?: NetworkProtocol; + /** + * Port description. Example: "payment API endpoint" + */ + description?: string; + /** + * Skip the health check when run as a service. + */ + experimentalSkipHealthcheck?: boolean; +}; +type ContainerWithFileOpts = { + /** + * Permissions of the new file. Example: 0600 + */ + permissions?: number; + /** + * A user:group to set for the file. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerWithFilesOpts = { + /** + * Permission given to the copied files (e.g., 0600). + */ + permissions?: number; + /** + * A user:group to set for the files. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerWithMountedCacheOpts = { + /** + * Identifier of the directory to use as the cache volume's root. + */ + source?: Directory; + /** + * Sharing mode of the cache volume. + */ + sharing?: CacheSharingMode; + /** + * A user:group to set for the mounted cache directory. + * + * Note that this changes the ownership of the specified mount along with the initial filesystem provided by source (if any). It does not have any effect if/when the cache has already been created. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithMountedDirectoryOpts = { + /** + * A user:group to set for the mounted directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Mount the directory read-only. + */ + readOnly?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithMountedFileOpts = { + /** + * A user or user:group to set for the mounted file. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerWithMountedSecretOpts = { + /** + * A user:group to set for the mounted secret. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Permission given to the mounted secret (e.g., 0600). + * + * This option requires an owner to be set to be active. + */ + mode?: number; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithMountedTempOpts = { + /** + * Size of the temporary directory in bytes. + */ + size?: number; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithMountedVolumeOpts = { + /** + * Mount the volume read-only. + */ + readOnly?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithNewFileOpts = { + /** + * Permissions of the new file. Example: 0600 + */ + permissions?: number; + /** + * A user:group to set for the file. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerWithSymlinkOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerWithUnixSocketOpts = { + /** + * A user:group to set for the mounted socket. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Set the owner to the container's current user. + */ + inheritOwner?: boolean; + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithWorkdirOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithoutDirectoryOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithoutEntrypointOpts = { + /** + * Don't remove the default arguments when unsetting the entrypoint. + */ + keepDefaultArgs?: boolean; +}; +type ContainerWithoutExposedPortOpts = { + /** + * Port protocol to unexpose + */ + protocol?: NetworkProtocol; +}; +type ContainerWithoutFileOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerWithoutFilesOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of paths according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + expand?: boolean; +}; +type ContainerWithoutMountOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type ContainerWithoutUnixSocketOpts = { + /** + * Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + expand?: boolean; +}; +type CurrentModuleAsSdkOpts = { + /** + * The workspace to resolve SDK-role data against. Defaults to the current workspace. + */ + workspace?: Workspace; +}; +type CurrentModuleGeneratorsOpts = { + /** + * Only include generators matching the specified patterns + */ + include?: string[]; +}; +type CurrentModuleWorkdirOpts = { + /** + * Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + */ + exclude?: string[]; + /** + * Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + */ + include?: string[]; + /** + * Apply .gitignore filter rules inside the directory + */ + gitignore?: boolean; +}; +/** + * The type of change for a diff stat entry. + */ +declare enum DiffStatKind { + /** + * A file or directory was added. + */ + Added = "ADDED", + /** + * A file was modified. + */ + Modified = "MODIFIED", + /** + * A file or directory was removed. + */ + Removed = "REMOVED", + /** + * A file was renamed. + */ + Renamed = "RENAMED" +} +/** + * Utility function to convert a DiffStatKind value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function DiffStatKindValueToName(value: DiffStatKind): string; +/** + * Utility function to convert a DiffStatKind name to its value so + * it can be properly used inside the module runtime. + */ +declare function DiffStatKindNameToValue(name: string): DiffStatKind; +type DirectoryAsModuleOpts = { + /** + * An optional subpath of the directory which contains the module's configuration file. + * + * If not set, the module source code is loaded from the root of the directory. + */ + sourceRootPath?: string; +}; +type DirectoryAsModuleSourceOpts = { + /** + * An optional subpath of the directory which contains the module's configuration file. + * + * If not set, the module source code is loaded from the root of the directory. + */ + sourceRootPath?: string; +}; +type DirectoryAsWorkspaceOpts = { + /** + * Current working directory inside the workspace root. Defaults to the workspace root. + */ + cwd?: string; +}; +type DirectoryDockerBuildOpts = { + /** + * Path to the Dockerfile to use (e.g., "frontend.Dockerfile"). + */ + dockerfile?: string; + /** + * The platform to build. + */ + platform?: Platform; + /** + * Build arguments to use in the build. + */ + buildArgs?: BuildArg[]; + /** + * Target build stage to build. + */ + target?: string; + /** + * Secrets to pass to the build. + * + * They will be mounted at /run/secrets/[secret-name]. + */ + secrets?: Secret[]; + /** + * If set, skip the automatic init process injected into containers created by RUN statements. + * + * This should only be used if the user requires that their exec processes be the pid 1 process in the container. Otherwise it may result in unexpected behavior. + */ + noInit?: boolean; + /** + * A socket to use for SSH authentication during the build + * + * (e.g., for Dockerfile RUN --mount=type=ssh instructions). + * + * Typically obtained via host.unixSocket() pointing to the SSH_AUTH_SOCK. + */ + ssh?: Socket; +}; +type DirectoryEntriesOpts = { + /** + * Location of the directory to look at (e.g., "/src"). + */ + path?: string; +}; +type DirectoryExistsOpts = { + /** + * If specified, also validate the type of file (e.g. "REGULAR_TYPE", "DIRECTORY_TYPE", or "SYMLINK_TYPE"). + */ + expectedType?: ExistsType; + /** + * If specified, do not follow symlinks. + */ + doNotFollowSymlinks?: boolean; +}; +type DirectoryExportOpts = { + /** + * If true, then the host directory will be wiped clean before exporting so that it exactly matches the directory being exported; this means it will delete any files on the host that aren't in the exported dir. If false (the default), the contents of the directory will be merged with any existing contents of the host directory, leaving any existing files on the host that aren't in the exported directory alone. + */ + wipe?: boolean; +}; +type DirectoryFilterOpts = { + /** + * If set, paths matching one of these glob patterns is excluded from the new snapshot. Example: ["node_modules/", ".git*", ".env"] + */ + exclude?: string[]; + /** + * If set, only paths matching one of these glob patterns is included in the new snapshot. Example: (e.g., ["app/", "package.*"]). + */ + include?: string[]; + /** + * If set, apply .gitignore rules when filtering the directory. + */ + gitignore?: boolean; +}; +type DirectorySearchOpts = { + /** + * Directory or file paths to search + */ + paths?: string[]; + /** + * Glob patterns to match (e.g., "*.md") + */ + globs?: string[]; + /** + * The text to match. + */ + pattern: string; + /** + * Interpret the pattern as a literal string instead of a regular expression. + */ + literal?: boolean; + /** + * Enable searching across multiple lines. + */ + multiline?: boolean; + /** + * Allow the . pattern to match newlines in multiline mode. + */ + dotall?: boolean; + /** + * Enable case-insensitive matching. + */ + insensitive?: boolean; + /** + * Honor .gitignore, .ignore, and .rgignore files. + */ + skipIgnored?: boolean; + /** + * Skip hidden files (files starting with .). + */ + skipHidden?: boolean; + /** + * Only return matching files, not lines and content + */ + filesOnly?: boolean; + /** + * Limit the number of results to return + */ + limit?: number; +}; +type DirectoryStatOpts = { + /** + * If specified, do not follow symlinks. + */ + doNotFollowSymlinks?: boolean; +}; +type DirectoryTerminalOpts = { + /** + * If set, override the default container used for the terminal. + */ + container?: Container; + /** + * If set, override the container's default terminal command and invoke these command arguments instead. + */ + cmd?: string[]; + /** + * Provides Dagger access to the executed command. + */ + experimentalPrivilegedNesting?: boolean; + /** + * Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + insecureRootCapabilities?: boolean; +}; +type DirectoryWithDirectoryOpts = { + /** + * Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + */ + exclude?: string[]; + /** + * Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + */ + include?: string[]; + /** + * Apply .gitignore filter rules inside the directory + */ + gitignore?: boolean; + /** + * A user:group to set for the copied directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; + /** + * Permission given to the copied directory and contents (e.g., 0755). + */ + permissions?: number; +}; +type DirectoryWithFileOpts = { + /** + * Permission given to the copied file (e.g., 0600). + */ + permissions?: number; + /** + * A user:group to set for the copied directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; +}; +type DirectoryWithFilesOpts = { + /** + * Permission given to the copied files (e.g., 0600). + */ + permissions?: number; +}; +type DirectoryWithNewDirectoryOpts = { + /** + * Permission granted to the created directory (e.g., 0777). + */ + permissions?: number; +}; +type DirectoryWithNewFileOpts = { + /** + * Permissions of the new file. Example: 0600 + */ + permissions?: number; +}; +type EngineCacheEntrySetOpts = { + key?: string; +}; +type EngineCachePruneOpts = { + /** + * Use the engine-wide default pruning policy if true, otherwise prune the whole cache of any releasable entries. + */ + useDefaultPolicy?: boolean; + /** + * Override the maximum disk space to keep before pruning (e.g. "200GB" or "80%"). + */ + maxUsedSpace?: string; + /** + * Override the minimum disk space to retain during pruning (e.g. "500GB" or "10%"). + */ + reservedSpace?: string; + /** + * Override the minimum free disk space target during pruning (e.g. "20GB" or "20%"). + */ + minFreeSpace?: string; + /** + * Override the target disk space to keep after pruning (e.g. "200GB" or "50%"). + */ + targetSpace?: string; +}; +type EnvChecksOpts = { + /** + * Only include checks matching the specified patterns + */ + include?: string[]; + /** + * When true, only return annotated check functions; exclude generate-as-checks + */ + noGenerate?: boolean; +}; +type EnvServicesOpts = { + /** + * Only include services matching the specified patterns + */ + include?: string[]; +}; +type EnvFileGetOpts = { + /** + * Return the value exactly as written to the file. No quote removal or variable expansion + */ + raw?: boolean; +}; +type EnvFileVariablesOpts = { + /** + * Return values exactly as written to the file. No quote removal or variable expansion + */ + raw?: boolean; +}; +/** + * File type. + */ +declare enum ExistsType { + /** + * Tests path is a directory + */ + DirectoryType = "DIRECTORY_TYPE", + /** + * Tests path is a regular file + */ + RegularType = "REGULAR_TYPE", + /** + * Tests path is a symlink + */ + SymlinkType = "SYMLINK_TYPE" +} +/** + * Utility function to convert a ExistsType value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ExistsTypeValueToName(value: ExistsType): string; +/** + * Utility function to convert a ExistsType name to its value so + * it can be properly used inside the module runtime. + */ +declare function ExistsTypeNameToValue(name: string): ExistsType; +type FileAsEnvFileOpts = { + /** + * Replace "${VAR}" or "$VAR" with the value of other vars + * + * @deprecated Variable expansion is now enabled by default + */ + expand?: boolean; +}; +type FileContentsOpts = { + /** + * Start reading after this line + */ + offsetLines?: number; + /** + * Maximum number of lines to read + */ + limitLines?: number; +}; +type FileDigestOpts = { + /** + * If true, exclude metadata from the digest. + */ + excludeMetadata?: boolean; +}; +type FileExportOpts = { + /** + * If allowParentDirPath is true, the path argument can be a directory path, in which case the file will be created in that directory. + */ + allowParentDirPath?: boolean; +}; +type FileSearchOpts = { + /** + * Interpret the pattern as a literal string instead of a regular expression. + */ + literal?: boolean; + /** + * Enable searching across multiple lines. + */ + multiline?: boolean; + /** + * Allow the . pattern to match newlines in multiline mode. + */ + dotall?: boolean; + /** + * Enable case-insensitive matching. + */ + insensitive?: boolean; + /** + * Honor .gitignore, .ignore, and .rgignore files. + */ + skipIgnored?: boolean; + /** + * Skip hidden files (files starting with .). + */ + skipHidden?: boolean; + /** + * Only return matching files, not lines and content + */ + filesOnly?: boolean; + /** + * Limit the number of results to return + */ + limit?: number; + paths?: string[]; + globs?: string[]; +}; +type FileWithReplacedOpts = { + /** + * Replace all occurrences of the pattern. + */ + all?: boolean; + /** + * Replace the first match starting from the specified line. + */ + firstFrom?: number; +}; +/** + * File type. + */ +declare enum FileType { + /** + * directory file type + */ + Directory = "DIRECTORY", + /** + * directory file type + */ + DirectoryType = "DIRECTORY", + /** + * regular file type + */ + Regular = "REGULAR", + /** + * regular file type + */ + RegularType = "REGULAR", + /** + * symlink file type + */ + Symlink = "SYMLINK", + /** + * symlink file type + */ + SymlinkType = "SYMLINK", + /** + * unknown file type + */ + Unknown = "UNKNOWN" +} +/** + * Utility function to convert a FileType value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function FileTypeValueToName(value: FileType): string; +/** + * Utility function to convert a FileType name to its value so + * it can be properly used inside the module runtime. + */ +declare function FileTypeNameToValue(name: string): FileType; +type FunctionWithArgOpts = { + /** + * A doc string for the argument, if any + */ + description?: string; + /** + * A default value to use for this argument if not explicitly set by the caller, if any + */ + defaultValue?: JSON; + /** + * If the argument is a Directory or File type, default to load path from context directory, relative to root directory. + */ + defaultPath?: string; + /** + * Patterns to ignore when loading the contextual argument value. + */ + ignore?: string[]; + /** + * The source map for the argument definition. + */ + sourceMap?: SourceMap; + /** + * If deprecated, the reason or migration path. + */ + deprecated?: string; + defaultAddress?: string; +}; +type FunctionWithCachePolicyOpts = { + /** + * The TTL for the cache policy, if applicable. Provided as a duration string, e.g. "5m", "1h30s". + */ + timeToLive?: string; +}; +type FunctionWithDeprecatedOpts = { + /** + * Reason or migration path describing the deprecation. + */ + reason?: string; +}; +/** + * The behavior configured for function result caching. + */ +declare enum FunctionCachePolicy { + Default = "Default", + Never = "Never", + PerSession = "PerSession" +} +/** + * Utility function to convert a FunctionCachePolicy value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function FunctionCachePolicyValueToName(value: FunctionCachePolicy): string; +/** + * Utility function to convert a FunctionCachePolicy name to its value so + * it can be properly used inside the module runtime. + */ +declare function FunctionCachePolicyNameToValue(name: string): FunctionCachePolicy; +type GeneratorGroupChangesOpts = { + /** + * Strategy to apply on conflicts between generators + */ + onConflict?: ChangesetsMergeConflict; +}; +type GitRefAsWorkspaceOpts = { + /** + * Current working directory inside the workspace root. Defaults to the workspace root. + */ + cwd?: string; +}; +type GitRefTreeOpts = { + /** + * Set to true to discard .git directory. + */ + discardGitDir?: boolean; + /** + * The depth of the tree to fetch. + */ + depth?: number; + /** + * Set to true to populate tag refs in the local checkout .git. + */ + includeTags?: boolean; +}; +type GitRepositoryAsWorkspaceOpts = { + /** + * Current working directory inside the workspace root. Defaults to the workspace root. + */ + cwd?: string; +}; +type GitRepositoryBranchesOpts = { + /** + * Glob patterns (e.g., "refs/tags/v*"). + */ + patterns?: string[]; +}; +type GitRepositoryTagsOpts = { + /** + * Glob patterns (e.g., "refs/tags/v*"). + */ + patterns?: string[]; +}; +type HostDirectoryOpts = { + /** + * Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + */ + exclude?: string[]; + /** + * Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + */ + include?: string[]; + /** + * If true, the directory will always be reloaded from the host. + */ + noCache?: boolean; + /** + * Apply .gitignore filter rules inside the directory + */ + gitignore?: boolean; +}; +type HostFileOpts = { + /** + * If true, the file will always be reloaded from the host. + */ + noCache?: boolean; +}; +type HostFindUpOpts = { + noCache?: boolean; +}; +type HostServiceOpts = { + /** + * Upstream host to forward traffic to. + */ + host?: string; +}; +type HostTunnelOpts = { + /** + * Map each service port to the same port on the host, as if the service were running natively. + * + * Note: enabling may result in port conflicts. + */ + native?: boolean; + /** + * Configure explicit port forwarding rules for the tunnel. + * + * If a port's frontend is unspecified or 0, a random port will be chosen by the host. + * + * If no ports are given, all of the service's ports are forwarded. If native is true, each port maps to the same port on the host. If native is false, each port maps to a random port chosen by the host. + * + * If ports are given and native is true, the ports are additive. + */ + ports?: PortForward[]; +}; +/** + * A unique identifier for an object. + */ +type ID = string & { + __ID: never; +}; +/** + * Compression algorithm to use for image layers. + */ +declare enum ImageLayerCompression { + EstarGz = "EStarGZ", + Estargz = "EStarGZ", + Gzip = "Gzip", + Uncompressed = "Uncompressed", + Zstd = "Zstd" +} +/** + * Utility function to convert a ImageLayerCompression value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ImageLayerCompressionValueToName(value: ImageLayerCompression): string; +/** + * Utility function to convert a ImageLayerCompression name to its value so + * it can be properly used inside the module runtime. + */ +declare function ImageLayerCompressionNameToValue(name: string): ImageLayerCompression; +/** + * Mediatypes to use in published or exported image metadata. + */ +declare enum ImageMediaTypes { + Docker = "DockerMediaTypes", + DockerMediaTypes = "DockerMediaTypes", + Oci = "OCIMediaTypes", + OcimediaTypes = "OCIMediaTypes" +} +/** + * Utility function to convert a ImageMediaTypes value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ImageMediaTypesValueToName(value: ImageMediaTypes): string; +/** + * Utility function to convert a ImageMediaTypes name to its value so + * it can be properly used inside the module runtime. + */ +declare function ImageMediaTypesNameToValue(name: string): ImageMediaTypes; +/** + * An arbitrary JSON-encoded value. + */ +type JSON = string & { + __JSON: never; +}; +type JSONValueContentsOpts = { + /** + * Pretty-print + */ + pretty?: boolean; + /** + * Optional line prefix + */ + indent?: string; +}; +type LLMLoopOpts = { + /** + * Cap the number of steps. The loop fails if the cap is reached before the model ends its turn. + */ + maxSteps?: number; + /** + * Cap the model's output tokens on each step. Defaults to the model's maximum. + */ + maxTokens?: number; +}; +type LLMStepOpts = { + /** + * Cap the model's output tokens for this step. Defaults to the model's maximum. + */ + maxTokens?: number; +}; +type LLMWithModelOpts = { + /** + * The provider serving the model, e.g. "openai". Overrides the provider otherwise inferred from the model name — useful when the name matches no known pattern (e.g. a fine-tune), or matches the wrong one. + */ + provider?: string; +}; +type LLMWithResponseOpts = { + /** + * Uncached input tokens sent + */ + inputTokens?: number; + /** + * Tokens received from the model, including text and tool calls + */ + outputTokens?: number; + /** + * Cached input tokens read + */ + cachedTokenReads?: number; + /** + * Cached input tokens written + */ + cachedTokenWrites?: number; + /** + * Total tokens consumed by this response + */ + totalTokens?: number; +}; +type LLMContentBlockInput = { + /** + * The arguments to pass to the tool (for TOOL_CALL kind). + */ + arguments?: JSON; + /** + * The unique ID of a tool call (for TOOL_CALL or TOOL_RESULT kinds). + */ + callId?: string; + /** + * Whether the tool call resulted in an error (for TOOL_RESULT kind). + */ + errored?: boolean; + /** + * The kind of content block. + */ + kind: LLMContentBlockKind; + /** + * Provider-specific opaque data (e.g. Anthropic thinking signature). + */ + signature?: string; + /** + * Text content (for TEXT, THINKING, or TOOL_RESULT kinds). + */ + text?: string; + /** + * The name of the tool to call (for TOOL_CALL kind). + */ + toolName?: string; +}; +/** + * The kind of content in a message block. + */ +declare enum LLMContentBlockKind { + /** + * Plain text content. + */ + Text = "TEXT", + /** + * Model thinking/reasoning content (e.g. Anthropic extended thinking). + */ + Thinking = "THINKING", + /** + * A tool/function call from the model. + */ + ToolCall = "TOOL_CALL", + /** + * A tool/function result. + */ + ToolResult = "TOOL_RESULT" +} +/** + * Utility function to convert a LLMContentBlockKind value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function LLMContentBlockKindValueToName(value: LLMContentBlockKind): string; +/** + * Utility function to convert a LLMContentBlockKind name to its value so + * it can be properly used inside the module runtime. + */ +declare function LLMContentBlockKindNameToValue(name: string): LLMContentBlockKind; +/** + * The role that generated a message. + */ +declare enum LLMMessageRole { + /** + * A reply from the model. + */ + Assistant = "ASSISTANT", + /** + * A system prompt. + */ + System = "SYSTEM", + /** + * A user prompt or tool response. + */ + User = "USER" +} +/** + * Utility function to convert a LLMMessageRole value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function LLMMessageRoleValueToName(value: LLMMessageRole): string; +/** + * Utility function to convert a LLMMessageRole name to its value so + * it can be properly used inside the module runtime. + */ +declare function LLMMessageRoleNameToValue(name: string): LLMMessageRole; +type ModuleChecksOpts = { + /** + * Only include checks matching the specified patterns + */ + include?: string[]; + /** + * When true, only return annotated check functions; exclude generate-as-checks + */ + noGenerate?: boolean; +}; +type ModuleGeneratorsOpts = { + /** + * Only include generators matching the specified patterns + */ + include?: string[]; +}; +type ModuleServeOpts = { + /** + * Expose the dependencies of this module to the client + */ + includeDependencies?: boolean; + /** + * Install the module as the entrypoint, promoting its main-object methods onto the Query root + */ + entrypoint?: boolean; +}; +type ModuleServicesOpts = { + /** + * Only include services matching the specified patterns + */ + include?: string[]; +}; +/** + * Experimental features of a module + */ +declare enum ModuleSourceExperimentalFeature { + /** + * Self calls + */ + SelfCalls = "SELF_CALLS" +} +/** + * Utility function to convert a ModuleSourceExperimentalFeature value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ModuleSourceExperimentalFeatureValueToName(value: ModuleSourceExperimentalFeature): string; +/** + * Utility function to convert a ModuleSourceExperimentalFeature name to its value so + * it can be properly used inside the module runtime. + */ +declare function ModuleSourceExperimentalFeatureNameToValue(name: string): ModuleSourceExperimentalFeature; +/** + * The kind of module source. + */ +declare enum ModuleSourceKind { + Dir = "DIR_SOURCE", + DirSource = "DIR_SOURCE", + Git = "GIT_SOURCE", + GitSource = "GIT_SOURCE", + Local = "LOCAL_SOURCE", + LocalSource = "LOCAL_SOURCE" +} +/** + * Utility function to convert a ModuleSourceKind value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ModuleSourceKindValueToName(value: ModuleSourceKind): string; +/** + * Utility function to convert a ModuleSourceKind name to its value so + * it can be properly used inside the module runtime. + */ +declare function ModuleSourceKindNameToValue(name: string): ModuleSourceKind; +/** + * Transport layer network protocol associated to a port. + */ +declare enum NetworkProtocol { + Tcp = "TCP", + Udp = "UDP" +} +/** + * Utility function to convert a NetworkProtocol value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function NetworkProtocolValueToName(value: NetworkProtocol): string; +/** + * Utility function to convert a NetworkProtocol name to its value so + * it can be properly used inside the module runtime. + */ +declare function NetworkProtocolNameToValue(name: string): NetworkProtocol; +type PipelineLabel = { + /** + * Label name. + */ + name: string; + /** + * Label value. + */ + value: string; +}; +/** + * The platform config OS and architecture in a Container. + * + * The format is [os]/[platform]/[version] (e.g., "darwin/arm64/v7", "windows/amd64", "linux/arm64"). + */ +type Platform = string & { + __Platform: never; +}; +type PortForward = { + /** + * Destination port for traffic. + */ + backend: number; + /** + * Port to expose to clients. If unspecified, a default will be chosen. + */ + frontend?: number; + /** + * Transport layer protocol to use for traffic. + */ + protocol?: NetworkProtocol; +}; +type ClientCacheVolumeOpts = { + /** + * Identifier of the directory to use as the cache volume's root. + */ + source?: Directory; + /** + * Sharing mode of the cache volume. + */ + sharing?: CacheSharingMode; + /** + * A user:group to set for the cache volume root. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + owner?: string; +}; +type ClientContainerOpts = { + /** + * Platform to initialize the container with. Defaults to the native platform of the current engine + */ + platform?: Platform; +}; +type ClientCurrentTypeDefsOpts = { + /** + * Return the full referenced typedef closure instead of only top-level served typedefs. + */ + returnAllTypes?: boolean; + /** + * Strip core API functions from the Query type, leaving only module-sourced functions (constructors, entrypoint proxies, etc.). + * + * Core types (Container, Directory, etc.) are kept so return types and method chaining still work. + */ + hideCore?: boolean; +}; +type ClientEnvOpts = { + /** + * Give the environment the same privileges as the caller: core API including host access, current module, and dependencies + */ + privileged?: boolean; + /** + * Allow new outputs to be declared and saved in the environment + */ + writable?: boolean; +}; +type ClientEnvFileOpts = { + /** + * Replace "${VAR}" or "$VAR" with the value of other vars + * + * @deprecated Variable expansion is now enabled by default + */ + expand?: boolean; +}; +type ClientFileOpts = { + /** + * Permissions of the new file. Example: 0600 + */ + permissions?: number; +}; +type ClientGitOpts = { + /** + * DEPRECATED: Set to true to keep .git directory. + * + * @deprecated Set to true to keep .git directory. + */ + keepGitDir?: boolean; + /** + * Set SSH known hosts + */ + sshKnownHosts?: string; + /** + * Set SSH auth socket + */ + sshAuthSocket?: Socket; + /** + * Username used to populate the password during basic HTTP Authorization + */ + httpAuthUsername?: string; + /** + * Secret used to populate the password during basic HTTP Authorization + */ + httpAuthToken?: Secret; + /** + * Secret used to populate the Authorization HTTP header + */ + httpAuthHeader?: Secret; + /** + * A service which must be started before the repo is fetched. + */ + experimentalServiceHost?: Service; +}; +type ClientHttpOpts = { + /** + * File name to use for the file. Defaults to the last part of the URL. + */ + name?: string; + /** + * Permissions to set on the file. + */ + permissions?: number; + /** + * Expected digest of the downloaded content (e.g., "sha256:..."). + */ + checksum?: string; + /** + * Secret used to populate the Authorization HTTP header + */ + authHeader?: Secret; + /** + * A service which must be started before the URL is fetched. + */ + experimentalServiceHost?: Service; +}; +type ClientLLMOpts = { + /** + * The model to converse with, e.g. "claude-sonnet-4-5" or "gpt-5.4". Defaults to the configured default model. + */ + model?: string; + /** + * The provider serving the model, e.g. "openai". Overrides the provider otherwise inferred from the model name — useful when the name matches no known pattern (e.g. a fine-tune), or matches the wrong one. + */ + provider?: string; +}; +type ClientModuleSourceOpts = { + /** + * The pinned version of the module source + */ + refPin?: string; + /** + * If true, do not attempt to find a module config file in a parent directory of the provided path. Only relevant for local module sources. + */ + disableFindUp?: boolean; + /** + * If true, do not error out if the provided ref string is a local path and does not exist yet. Useful when initializing new modules in directories that don't exist yet. + */ + allowNotExists?: boolean; + /** + * If set, error out if the ref string is not of the provided requireKind. + */ + requireKind?: ModuleSourceKind; +}; +type ClientSecretOpts = { + /** + * If set, the given string will be used as the cache key for this secret. This means that any secrets with the same cache key will be considered equivalent in terms of cache lookups, even if they have different URIs or plaintext values. + * + * For example, two secrets with the same cache key provided as secret env vars to other wise equivalent containers will result in the container withExecs hitting the cache for each other. + * + * If not set, the cache key for the secret will be derived from its plaintext value as looked up when the secret is constructed. + */ + cacheKey?: string; +}; +type ClientSshfsVolumeOpts = { + /** + * known_hosts material used to verify the remote host key. Required unless insecureSkipHostKeyCheck is true. + */ + knownHosts?: Secret; + /** + * Optional cache equivalence key. If set, volumes with the same cacheKey may be considered equivalent for cache lookups, still subject to their resource dependencies. + */ + cacheKey?: string; + /** + * Disable SSH host key verification. This is insecure and must be explicitly opted into. + */ + insecureSkipHostKeyCheck?: boolean; + /** + * Service to use as the SSHFS network endpoint while verifying the original host key. + */ + experimentalServiceHost?: Service; +}; +/** + * Transport protocol to use for registry operations. + */ +declare enum RegistryProtocol { + Http = "HTTP", + Https = "HTTPS" +} +/** + * Utility function to convert a RegistryProtocol value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function RegistryProtocolValueToName(value: RegistryProtocol): string; +/** + * Utility function to convert a RegistryProtocol name to its value so + * it can be properly used inside the module runtime. + */ +declare function RegistryProtocolNameToValue(name: string): RegistryProtocol; +/** + * Expected return type of an execution + */ +declare enum ReturnType { + /** + * Any execution (exit codes 0-127 and 192-255) + */ + Any = "ANY", + /** + * A failed execution (exit codes 1-127 and 192-255) + */ + Failure = "FAILURE", + /** + * A successful execution (exit code 0) + */ + Success = "SUCCESS" +} +/** + * Utility function to convert a ReturnType value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function ReturnTypeValueToName(value: ReturnType): string; +/** + * Utility function to convert a ReturnType name to its value so + * it can be properly used inside the module runtime. + */ +declare function ReturnTypeNameToValue(name: string): ReturnType; +type ServiceEndpointOpts = { + /** + * The exposed port number for the endpoint + */ + port?: number; + /** + * Return a URL with the given scheme, eg. http for http:// + */ + scheme?: string; +}; +type ServiceStopOpts = { + /** + * Immediately kill the service without waiting for a graceful exit + */ + kill?: boolean; +}; +type ServiceTerminalOpts = { + cmd?: string[]; +}; +type ServiceUpOpts = { + /** + * List of frontend/backend port mappings to forward. + * + * Frontend is the port accepting traffic on the host, backend is the service port. + */ + ports?: PortForward[]; + /** + * Bind each tunnel port to a random port on the host. + */ + random?: boolean; +}; +type TypeDefWithEnumOpts = { + /** + * A doc string for the enum, if any + */ + description?: string; + /** + * The source map for the enum definition. + */ + sourceMap?: SourceMap; +}; +type TypeDefWithEnumMemberOpts = { + /** + * The value of the member in the enum + */ + value?: string; + /** + * A doc string for the member, if any + */ + description?: string; + /** + * The source map for the enum member definition. + */ + sourceMap?: SourceMap; + /** + * If deprecated, the reason or migration path. + */ + deprecated?: string; +}; +type TypeDefWithEnumValueOpts = { + /** + * A doc string for the value, if any + */ + description?: string; + /** + * The source map for the enum value definition. + */ + sourceMap?: SourceMap; + /** + * If deprecated, the reason or migration path. + */ + deprecated?: string; +}; +type TypeDefWithFieldOpts = { + /** + * A doc string for the field, if any + */ + description?: string; + /** + * The source map for the field definition. + */ + sourceMap?: SourceMap; + /** + * If deprecated, the reason or migration path. + */ + deprecated?: string; +}; +type TypeDefWithInterfaceOpts = { + description?: string; + sourceMap?: SourceMap; +}; +type TypeDefWithObjectOpts = { + description?: string; + sourceMap?: SourceMap; + deprecated?: string; +}; +type TypeDefWithScalarOpts = { + description?: string; +}; +/** + * Distinguishes the different kinds of TypeDefs. + */ +declare enum TypeDefKind { + /** + * A boolean value. + */ + Boolean = "BOOLEAN_KIND", + /** + * A boolean value. + */ + BooleanKind = "BOOLEAN_KIND", + /** + * A GraphQL enum type and its values + * + * Always paired with an EnumTypeDef. + */ + Enum = "ENUM_KIND", + /** + * A GraphQL enum type and its values + * + * Always paired with an EnumTypeDef. + */ + EnumKind = "ENUM_KIND", + /** + * A float value. + */ + Float = "FLOAT_KIND", + /** + * A float value. + */ + FloatKind = "FLOAT_KIND", + /** + * A graphql input type, used only when representing the core API via TypeDefs. + */ + Input = "INPUT_KIND", + /** + * A graphql input type, used only when representing the core API via TypeDefs. + */ + InputKind = "INPUT_KIND", + /** + * An integer value. + */ + Integer = "INTEGER_KIND", + /** + * An integer value. + */ + IntegerKind = "INTEGER_KIND", + /** + * Always paired with an InterfaceTypeDef. + * + * A named type of functions that can be matched+implemented by other objects+interfaces. + */ + Interface = "INTERFACE_KIND", + /** + * Always paired with an InterfaceTypeDef. + * + * A named type of functions that can be matched+implemented by other objects+interfaces. + */ + InterfaceKind = "INTERFACE_KIND", + /** + * Always paired with a ListTypeDef. + * + * A list of values all having the same type. + */ + List = "LIST_KIND", + /** + * Always paired with a ListTypeDef. + * + * A list of values all having the same type. + */ + ListKind = "LIST_KIND", + /** + * Always paired with an ObjectTypeDef. + * + * A named type defined in the GraphQL schema, with fields and functions. + */ + Object = "OBJECT_KIND", + /** + * Always paired with an ObjectTypeDef. + * + * A named type defined in the GraphQL schema, with fields and functions. + */ + ObjectKind = "OBJECT_KIND", + /** + * A scalar value of any basic kind. + */ + Scalar = "SCALAR_KIND", + /** + * A scalar value of any basic kind. + */ + ScalarKind = "SCALAR_KIND", + /** + * A string value. + */ + String = "STRING_KIND", + /** + * A string value. + */ + StringKind = "STRING_KIND", + /** + * A special kind used to signify that no value is returned. + * + * This is used for functions that have no return value. The outer TypeDef specifying this Kind is always Optional, as the Void is never actually represented. + */ + Void = "VOID_KIND", + /** + * A special kind used to signify that no value is returned. + * + * This is used for functions that have no return value. The outer TypeDef specifying this Kind is always Optional, as the Void is never actually represented. + */ + VoidKind = "VOID_KIND" +} +/** + * Utility function to convert a TypeDefKind value to its name so + * it can be uses as argument to call a exposed function. + */ +declare function TypeDefKindValueToName(value: TypeDefKind): string; +/** + * Utility function to convert a TypeDefKind name to its value so + * it can be properly used inside the module runtime. + */ +declare function TypeDefKindNameToValue(name: string): TypeDefKind; +/** + * The absence of a value. + * + * A Null Void is used as a placeholder for resolvers that do not return anything. + */ +type Void = string & { + __Void: never; +}; +type WorkspaceChecksOpts = { + /** + * Only include checks matching the specified patterns + */ + include?: string[]; + /** + * Skip checks matching the specified patterns + */ + skip?: string[]; + /** + * When true, only return annotated check functions; exclude generate-as-checks + */ + noGenerate?: boolean; + /** + * When true, only return generate-as-checks; exclude annotated check functions + */ + onlyGenerate?: boolean; +}; +type WorkspaceConfigReadOpts = { + /** + * Dotted key path (e.g. modules.greeter.source). Empty for full config. + */ + key?: string; +}; +type WorkspaceDirectoryOpts = { + /** + * Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + */ + exclude?: string[]; + /** + * Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + */ + include?: string[]; + /** + * Apply .gitignore filter rules inside the directory. + */ + gitignore?: boolean; +}; +type WorkspaceFindUpOpts = { + /** + * Path to start the search from. Relative paths resolve from the workspace cwd; absolute paths resolve from the workspace root. + */ + from?: string; +}; +type WorkspaceGeneratorsOpts = { + /** + * Only include generators matching the specified patterns + */ + include?: string[]; +}; +type WorkspaceSearchOpts = { + /** + * Directory or file paths to search + */ + paths?: string[]; + /** + * Glob patterns to match (e.g., "*.md") + */ + globs?: string[]; + /** + * The text to match. + */ + pattern: string; + /** + * Interpret the pattern as a literal string instead of a regular expression. + */ + literal?: boolean; + /** + * Enable searching across multiple lines. + */ + multiline?: boolean; + /** + * Allow the . pattern to match newlines in multiline mode. + */ + dotall?: boolean; + /** + * Enable case-insensitive matching. + */ + insensitive?: boolean; + /** + * Honor .gitignore, .ignore, and .rgignore files. + */ + skipIgnored?: boolean; + /** + * Skip hidden files (files starting with .). + */ + skipHidden?: boolean; + /** + * Only return matching files, not lines and content + */ + filesOnly?: boolean; + /** + * Limit the number of results to return + */ + limit?: number; +}; +type WorkspaceServicesOpts = { + /** + * Only include services matching the specified patterns + */ + include?: string[]; +}; +type WorkspaceWithConfigEnvOpts = { + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithConfigValueOpts = { + /** + * List value to set. Elements are stored verbatim, with no auto-detection. Mutually exclusive with value. + */ + values?: string[]; + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithInitClientOpts = { + /** + * SDK-specific init arguments. + */ + args?: JSON; + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithInitModuleOpts = { + /** + * Workspace-relative path for the new module. + */ + path?: string; + /** + * Source subpath within the new module. + */ + source?: string; + /** + * Additional include patterns for the module. + */ + include?: string[]; + /** + * SDK-specific init arguments. + */ + args?: JSON; + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithModuleOpts = { + /** + * Override name for the installed module entry. + */ + name?: string; + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithNewFileOpts = { + /** + * Permissions of the new file. + */ + permissions?: number; +}; +type WorkspaceWithSdkOpts = { + /** + * Override name for the installed SDK entry. + */ + name?: string; + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; + /** + * User-facing SDK name to persist under `[modules..as-sdk] name = ...`. + */ + asSdkName?: string; +}; +type WorkspaceWithoutConfigEnvOpts = { + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithoutConfigValueOpts = { + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithoutModuleOpts = { + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type WorkspaceWithoutSdkOpts = { + /** + * Write to the workspace config directory at the workspace cwd. + */ + here?: boolean; +}; +type __DirectiveArgsOpts = { + includeDeprecated?: boolean; +}; +type __FieldArgsOpts = { + includeDeprecated?: boolean; +}; +type __TypeEnumValuesOpts = { + includeDeprecated?: boolean; +}; +type __TypeFieldsOpts = { + includeDeprecated?: boolean; +}; +type __TypeInputFieldsOpts = { + includeDeprecated?: boolean; +}; +/** + * A standardized address to load containers, directories, secrets, and other object types. Address format depends on the type, and is validated at type selection. + */ +declare class Address extends BaseClient { + private readonly _id?; + private readonly _value?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _value?: string); + /** + * A unique identifier for this Address. + */ + id: () => Promise; + /** + * Load a container from the address. + */ + container: () => Container; + /** + * Load a directory from the address. + */ + directory: (opts?: AddressDirectoryOpts) => Directory; + /** + * Load a file from the address. + */ + file: (opts?: AddressFileOpts) => File; + /** + * Load a git ref (branch, tag or commit) from the address. + */ + gitRef: () => GitRef; + /** + * Load a git repository from the address. + */ + gitRepository: () => GitRepository; + /** + * Load a secret from the address. + */ + secret: () => Secret; + /** + * Load a service from the address. + */ + service: () => Service; + /** + * Load a local socket from the address. + */ + socket: () => Socket; + /** + * The address value + */ + value: () => Promise; + /** + * Load a volume from the address. + */ + volume: () => Volume; +} +declare class Binding extends BaseClient { + private readonly _id?; + private readonly _asString?; + private readonly _digest?; + private readonly _isNull?; + private readonly _name?; + private readonly _typeName?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _asString?: string, _digest?: string, _isNull?: boolean, _name?: string, _typeName?: string); + /** + * A unique identifier for this Binding. + */ + id: () => Promise; + /** + * Retrieve the binding value, as type Address + */ + asAddress: () => Address; + /** + * Retrieve the binding value, as type CacheVolume + */ + asCacheVolume: () => CacheVolume; + /** + * Retrieve the binding value, as type Changeset + */ + asChangeset: () => Changeset; + /** + * Retrieve the binding value, as type Check + */ + asCheck: () => Check; + /** + * Retrieve the binding value, as type CheckGroup + */ + asCheckGroup: () => CheckGroup; + /** + * Retrieve the binding value, as type Cloud + */ + asCloud: () => Cloud; + /** + * Retrieve the binding value, as type Container + */ + asContainer: () => Container; + /** + * Retrieve the binding value, as type CurrentModuleAsSDK + */ + asCurrentModuleAsSDK: () => CurrentModuleAsSDK; + /** + * Retrieve the binding value, as type CurrentModuleAsSDKClient + */ + asCurrentModuleAsSDKClient: () => CurrentModuleAsSDKClient; + /** + * Retrieve the binding value, as type CurrentModuleAsSDKModule + */ + asCurrentModuleAsSDKModule: () => CurrentModuleAsSDKModule; + /** + * Retrieve the binding value, as type DiffStat + */ + asDiffStat: () => DiffStat; + /** + * Retrieve the binding value, as type Directory + */ + asDirectory: () => Directory; + /** + * Retrieve the binding value, as type Env + */ + asEnv: () => Env; + /** + * Retrieve the binding value, as type EnvFile + */ + asEnvFile: () => EnvFile; + /** + * Retrieve the binding value, as type File + */ + asFile: () => File; + /** + * Retrieve the binding value, as type Generator + */ + asGenerator: () => Generator; + /** + * Retrieve the binding value, as type GeneratorGroup + */ + asGeneratorGroup: () => GeneratorGroup; + /** + * Retrieve the binding value, as type GitRef + */ + asGitRef: () => GitRef; + /** + * Retrieve the binding value, as type GitRepository + */ + asGitRepository: () => GitRepository; + /** + * Retrieve the binding value, as type HTTPState + */ + asHTTPState: () => HTTPState; + /** + * Retrieve the binding value, as type JSONValue + */ + asJSONValue: () => JSONValue; + /** + * Retrieve the binding value, as type LLMContentBlock + */ + asLLMContentBlock: () => LLMContentBlock; + /** + * Retrieve the binding value, as type LLMMessage + */ + asLLMMessage: () => LLMMessage; + /** + * Retrieve the binding value, as type Module + */ + asModule: () => Module_; + /** + * Retrieve the binding value, as type ModuleConfigClient + */ + asModuleConfigClient: () => ModuleConfigClient; + /** + * Retrieve the binding value, as type ModuleSource + */ + asModuleSource: () => ModuleSource; + /** + * Retrieve the binding value, as type Schema + */ + asSchema: () => Schema; + /** + * Retrieve the binding value, as type SearchResult + */ + asSearchResult: () => SearchResult; + /** + * Retrieve the binding value, as type SearchSubmatch + */ + asSearchSubmatch: () => SearchSubmatch; + /** + * Retrieve the binding value, as type Secret + */ + asSecret: () => Secret; + /** + * Retrieve the binding value, as type Service + */ + asService: () => Service; + /** + * Retrieve the binding value, as type Socket + */ + asSocket: () => Socket; + /** + * Retrieve the binding value, as type Stat + */ + asStat: () => Stat; + /** + * Returns the binding's string value + */ + asString: () => Promise; + /** + * Retrieve the binding value, as type Up + */ + asUp: () => Up; + /** + * Retrieve the binding value, as type UpGroup + */ + asUpGroup: () => UpGroup; + /** + * Retrieve the binding value, as type Volume + */ + asVolume: () => Volume; + /** + * Retrieve the binding value, as type Workspace + */ + asWorkspace: () => Workspace; + /** + * Retrieve the binding value, as type WorkspaceGit + */ + asWorkspaceGit: () => WorkspaceGit; + /** + * Retrieve the binding value, as type WorkspaceMigration + */ + asWorkspaceMigration: () => WorkspaceMigration; + /** + * Retrieve the binding value, as type WorkspaceMigrationStep + */ + asWorkspaceMigrationStep: () => WorkspaceMigrationStep; + /** + * Retrieve the binding value, as type WorkspaceModule + */ + asWorkspaceModule: () => WorkspaceModule; + /** + * Retrieve the binding value, as type WorkspaceModuleSetting + */ + asWorkspaceModuleSetting: () => WorkspaceModuleSetting; + /** + * Retrieve the binding value, as type WorkspaceSDK + */ + asWorkspaceSDK: () => WorkspaceSDK; + /** + * Returns the digest of the binding value + */ + digest: () => Promise; + /** + * Returns true if the binding is null + */ + isNull: () => Promise; + /** + * Returns the binding name + */ + name: () => Promise; + /** + * Returns the binding type + */ + typeName: () => Promise; +} +/** + * A directory whose contents persist across runs. + */ +declare class CacheVolume extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this CacheVolume. + */ + id: () => Promise; +} +/** + * A comparison between two directories representing changes that can be applied. + */ +declare class Changeset extends BaseClient { + private readonly _id?; + private readonly _export?; + private readonly _isEmpty?; + private readonly _sync?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _export?: string, _isEmpty?: boolean, _sync?: ID); + /** + * A unique identifier for this Changeset. + */ + id: () => Promise; + /** + * Files and directories that were added in the newer directory. + */ + addedPaths: () => Promise; + /** + * The newer/upper snapshot. + */ + after: () => Directory; + /** + * Return a Git-compatible patch of the changes + */ + asPatch: () => File; + /** + * The older/lower snapshot to compare against. + */ + before: () => Directory; + /** + * Structured per-path diff statistics (kind and line counts) for this changeset. + */ + diffStats: () => Promise; + /** + * Applies the diff represented by this changeset to a path on the host. + * @param path Location of the copied directory (e.g., "logs/"). + */ + export: (path: string) => Promise; + /** + * Returns true if the changeset is empty (i.e. there are no changes). + */ + isEmpty: () => Promise; + /** + * Return a snapshot containing only the created and modified files + */ + layer: () => Directory; + /** + * Files and directories that existed before and were updated in the newer directory. + */ + modifiedPaths: () => Promise; + /** + * Files and directories that were removed. Directories are indicated by a trailing slash, and their child paths are not included. + */ + removedPaths: () => Promise; + /** + * Force evaluation in the engine. + */ + sync: () => Promise; + /** + * Add changes to an existing changeset + * + * By default the operation will fail in case of conflicts, for instance a file modified in both changesets. The behavior can be adjusted using onConflict argument + * @param changes Changes to merge into the actual changeset + * @param opts.onConflict What to do on a merge conflict + */ + withChangeset: (changes: Changeset, opts?: ChangesetWithChangesetOpts) => Changeset; + /** + * Add changes from multiple changesets using git octopus merge strategy + * + * This is more efficient than chaining multiple withChangeset calls when merging many changesets. + * + * Only FAIL and FAIL_EARLY conflict strategies are supported (octopus merge cannot use -X ours/theirs). + * @param changes List of changesets to merge into the actual changeset + * @param opts.onConflict What to do on a merge conflict + */ + withChangesets: (changes: Changeset[], opts?: ChangesetWithChangesetsOpts) => Changeset; + /** + * Call the provided function with current Changeset. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Changeset) => Changeset) => Changeset; +} +declare class Check extends BaseClient { + private readonly _id?; + private readonly _checkType?; + private readonly _completed?; + private readonly _description?; + private readonly _name?; + private readonly _passed?; + private readonly _resultEmoji?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _checkType?: string, _completed?: boolean, _description?: string, _name?: string, _passed?: boolean, _resultEmoji?: string); + /** + * A unique identifier for this Check. + */ + id: () => Promise; + /** + * The type of check: 'check' for annotated checks, 'generate' for generate-as-checks + */ + checkType: () => Promise; + /** + * Whether the check completed + */ + completed: () => Promise; + /** + * The description of the check + */ + description: () => Promise; + /** + * If the check failed, this is the error + */ + error: () => Error$1; + /** + * Return the fully qualified name of the check + */ + name: () => Promise; + /** + * The original module in which the check has been defined + */ + originalModule: () => Module_; + /** + * Whether the check passed + */ + passed: () => Promise; + /** + * The path of the check within its module + */ + path: () => Promise; + /** + * An emoji representing the result of the check + */ + resultEmoji: () => Promise; + /** + * Execute the check + */ + run: () => Check; + /** + * Call the provided function with current Check. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Check) => Check) => Check; +} +declare class CheckGroup extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this CheckGroup. + */ + id: () => Promise; + /** + * Return a list of individual checks and their details + */ + list: () => Promise; + /** + * Generate a markdown report + */ + report: () => File; + /** + * Execute all selected checks + * @param opts.failFast If true, stop running checks as soon as any check fails. + */ + run: (opts?: CheckGroupRunOpts) => CheckGroup; + /** + * Call the provided function with current CheckGroup. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: CheckGroup) => CheckGroup) => CheckGroup; +} +/** + * An internal persistent filesync mirror. + */ +declare class ClientFilesyncMirror extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this ClientFilesyncMirror. + */ + id: () => Promise; +} +/** + * Dagger Cloud configuration and state + */ +declare class Cloud extends BaseClient { + private readonly _id?; + private readonly _traceURL?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _traceURL?: string); + /** + * A unique identifier for this Cloud. + */ + id: () => Promise; + /** + * The trace URL for the current session + */ + traceURL: () => Promise; +} +/** + * An OCI-compatible container, also known as a Docker container. + */ +declare class Container extends BaseClient { + private readonly _id?; + private readonly _combinedOutput?; + private readonly _envVariable?; + private readonly _exists?; + private readonly _exitCode?; + private readonly _export?; + private readonly _exportImage?; + private readonly _imageRef?; + private readonly _label?; + private readonly _platform?; + private readonly _publish?; + private readonly _stderr?; + private readonly _stdout?; + private readonly _sync?; + private readonly _up?; + private readonly _user?; + private readonly _workdir?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _combinedOutput?: string, _envVariable?: string, _exists?: boolean, _exitCode?: number, _export?: string, _exportImage?: Void, _imageRef?: string, _label?: string, _platform?: Platform, _publish?: string, _stderr?: string, _stdout?: string, _sync?: ID, _up?: Void, _user?: string, _workdir?: string); + /** + * A unique identifier for this Container. + */ + id: () => Promise; + /** + * Turn the container into a Service. + * + * Be sure to set any exposed ports before this conversion. + * @param opts.args Command to run instead of the container's default command (e.g., ["go", "run", "main.go"]). + * + * If empty, the container's default command is used. + * @param opts.useEntrypoint If the container has an entrypoint, prepend it to the args. + * @param opts.experimentalPrivilegedNesting Provides Dagger access to the executed command. + * @param opts.insecureRootCapabilities Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + * @param opts.expand Replace "${VAR}" or "$VAR" in the args according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + * @param opts.noInit If set, skip the automatic init process injected into containers by default. + * + * This should only be used if the user requires that their exec process be the pid 1 process in the container. Otherwise it may result in unexpected behavior. + */ + asService: (opts?: ContainerAsServiceOpts) => Service; + /** + * Package the container state as an OCI image, and return it as a tar archive + * @param opts.platformVariants Identifiers for other platform specific containers. + * + * Used for multi-platform images. + * @param opts.forcedCompression Force each layer of the image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + * @param opts.mediaTypes Use the specified media types for the image's layers. + * + * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support. + */ + asTarball: (opts?: ContainerAsTarballOpts) => File; + /** + * The combined buffered standard output and standard error stream of the last executed command + * + * Returns an error if no command was executed + */ + combinedOutput: () => Promise; + /** + * Return the container's default arguments. + */ + defaultArgs: () => Promise; + /** + * Retrieve a directory from the container's root filesystem + * + * Mounts are included. + * @param path The path of the directory to retrieve (e.g., "./src"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + directory: (path: string, opts?: ContainerDirectoryOpts) => Directory; + /** + * Retrieves this container's configured docker healthcheck. + */ + dockerHealthcheck: () => HealthcheckConfig; + /** + * Return the container's OCI entrypoint. + */ + entrypoint: () => Promise; + /** + * Retrieves the value of the specified persistent environment variable. + * @param name The name of the environment variable to retrieve (e.g., "PATH"). + */ + envVariable: (name: string) => Promise; + /** + * Retrieves the list of persistent environment variables configured on the container. + */ + envVariables: () => Promise; + /** + * check if a file or directory exists + * @param path Path to check (e.g., "/file.txt"). + * @param opts.expectedType If specified, also validate the type of file (e.g. "REGULAR_TYPE", "DIRECTORY_TYPE", or "SYMLINK_TYPE"). + * @param opts.doNotFollowSymlinks If specified, do not follow symlinks. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + exists: (path: string, opts?: ContainerExistsOpts) => Promise; + /** + * The exit code of the last executed command + * + * Returns an error if no command was executed + */ + exitCode: () => Promise; + /** + * EXPERIMENTAL API! Subject to change/removal at any time. + * + * Configures all available GPUs on the host to be accessible to this container. + * + * This currently works for Nvidia devices only. + */ + experimentalWithAllGPUs: () => Container; + /** + * EXPERIMENTAL API! Subject to change/removal at any time. + * + * Configures the provided list of devices to be accessible to this container. + * + * This currently works for Nvidia devices only. + * @param devices List of devices to be accessible to this container. + */ + experimentalWithGPU: (devices: string[]) => Container; + /** + * Writes the container as an OCI tarball to the destination file path on the host. + * + * It can also export platform variants. + * @param path Host's destination path (e.g., "./tarball"). + * + * Path can be relative to the engine's workdir or absolute. + * @param opts.platformVariants Identifiers for other platform specific containers. + * + * Used for multi-platform image. + * @param opts.forcedCompression Force each layer of the exported image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + * @param opts.mediaTypes Use the specified media types for the exported image's layers. + * + * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + export: (path: string, opts?: ContainerExportOpts) => Promise; + /** + * Exports the container as an image to the host's container image store. + * @param name Name of image to export to in the host's store + * @param opts.platformVariants Identifiers for other platform specific containers. + * + * Used for multi-platform image. + * @param opts.forcedCompression Force each layer of the exported image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + * @param opts.mediaTypes Use the specified media types for the exported image's layers. + * + * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support. + */ + exportImage: (name: string, opts?: ContainerExportImageOpts) => Promise; + /** + * Retrieves the list of exposed ports. + * + * This includes ports already exposed by the image, even if not explicitly added with dagger. + */ + exposedPorts: () => Promise; + /** + * Retrieves a file at the given path. + * + * Mounts are included. + * @param path The path of the file to retrieve (e.g., "./README.md"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + file: (path: string, opts?: ContainerFileOpts) => File; + /** + * Download a container image, and apply it to the container state. All previous state will be lost. + * @param address Address of the container image to download, in standard OCI ref format. Example:"registry.dagger.io/engine:latest" + * @param opts.registryService Service to use as the registry endpoint for the image address. + * + * The service will be started only for this pull. + * @param opts.protocol Protocol to use for registry communication. + * + * Defaults to "HTTPS". Use "HTTP" only for plain HTTP registries. + * @param opts.insecureSkipTLSVerify Allow HTTPS registry communication without verifying the server certificate. + */ + from: (address: string, opts?: ContainerFromOpts) => Container; + /** + * The unique image reference which can only be retrieved immediately after the 'Container.From' call. + */ + imageRef: () => Promise; + /** + * Reads the container from an OCI tarball. + * @param source File to read the container from. + * @param opts.tag Identifies the tag to import from the archive, if the archive bundles multiple tags. + */ + import_: (source: File, opts?: ContainerImportOpts) => Container; + /** + * Retrieves the value of the specified label. + * @param name The name of the label (e.g., "org.opencontainers.artifact.created"). + */ + label: (name: string) => Promise; + /** + * Retrieves the list of labels passed to container. + */ + labels: () => Promise; + /** + * Returns the image layer or configuration blob with the given digest as a File. + * @param id Digest of the layer or configuration blob (e.g. "sha256:abc123..."). + * @param opts.forcedCompression Force each layer of the image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + * @param opts.mediaTypes Media types to use for image layers. Defaults to OCI. + */ + layer: (id: string, opts?: ContainerLayerOpts) => File; + /** + * Computes and returns the manifest for this container as a File. + * @param opts.forcedCompression Force each layer of the image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + * @param opts.mediaTypes Media types to use for image layers. Defaults to OCI. + */ + manifest: (opts?: ContainerManifestOpts) => File; + /** + * Retrieves the list of paths where a directory is mounted. + */ + mounts: () => Promise; + /** + * The platform this container executes and publishes as. + */ + platform: () => Promise; + /** + * Package the container state as an OCI image, and publish it to a registry + * + * Returns the fully qualified address of the published image, with digest + * @param address The OCI address to publish to + * + * Same format as "docker push". Example: "registry.example.com/user/repo:tag" + * @param opts.platformVariants Identifiers for other platform specific containers. + * + * Used for multi-platform image. + * @param opts.forcedCompression Force each layer of the published image to use the specified compression algorithm. + * + * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip. + * @param opts.mediaTypes Use the specified media types for the published image's layers. + * + * Defaults to "OCI", which is compatible with most recent registries, but "Docker" may be needed for older registries without OCI support. + * @param opts.registryService Service to use as the registry endpoint for the image address. + * + * The service will be started only for this push. + * @param opts.protocol Protocol to use for registry communication. + * + * Defaults to "HTTPS". Use "HTTP" only for plain HTTP registries. + * @param opts.insecureSkipTLSVerify Allow HTTPS registry communication without verifying the server certificate. + */ + publish: (address: string, opts?: ContainerPublishOpts) => Promise; + /** + * Return a snapshot of the container's root filesystem. The snapshot can be modified then written back using withRootfs. Use that method for filesystem modifications. + */ + rootfs: () => Directory; + /** + * Return file status + * @param path Path to check (e.g., "/file.txt"). + * @param opts.doNotFollowSymlinks If specified, do not follow symlinks. + */ + stat: (path: string, opts?: ContainerStatOpts) => Stat; + /** + * The buffered standard error stream of the last executed command + * + * Returns an error if no command was executed + */ + stderr: () => Promise; + /** + * The buffered standard output stream of the last executed command + * + * Returns an error if no command was executed + */ + stdout: () => Promise; + /** + * Forces evaluation of the pipeline in the engine. + * + * It doesn't run the default command if no exec has been set. + */ + sync: () => Promise; + /** + * Opens an interactive terminal for this container using its configured default terminal command if not overridden by args (or sh as a fallback default). + * @param opts.cmd If set, override the container's default terminal command and invoke these command arguments instead. + * @param opts.experimentalPrivilegedNesting Provides Dagger access to the executed command. + * @param opts.insecureRootCapabilities Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + terminal: (opts?: ContainerTerminalOpts) => Container; + /** + * Starts a Service and creates a tunnel that forwards traffic from the caller's network to that service. + * + * Be sure to set any exposed ports before calling this api. + * @param opts.random Bind each tunnel port to a random port on the host. + * @param opts.ports List of frontend/backend port mappings to forward. + * + * Frontend is the port accepting traffic on the host, backend is the service port. + * @param opts.args Command to run instead of the container's default command (e.g., ["go", "run", "main.go"]). + * + * If empty, the container's default command is used. + * @param opts.useEntrypoint If the container has an entrypoint, prepend it to the args. + * @param opts.experimentalPrivilegedNesting Provides Dagger access to the executed command. + * @param opts.insecureRootCapabilities Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + * @param opts.expand Replace "${VAR}" or "$VAR" in the args according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + * @param opts.noInit If set, skip the automatic init process injected into containers by default. + * + * This should only be used if the user requires that their exec process be the pid 1 process in the container. Otherwise it may result in unexpected behavior. + */ + up: (opts?: ContainerUpOpts) => Promise; + /** + * Retrieves the user to be set for all commands. + */ + user: () => Promise; + /** + * Retrieves this container plus the given OCI annotation. + * @param name The name of the annotation. + * @param value The value of the annotation. + */ + withAnnotation: (name: string, value: string) => Container; + /** + * Configures default arguments for future commands. Like CMD in Dockerfile. + * @param args Arguments to prepend to future executions (e.g., ["-v", "--no-cache"]). + */ + withDefaultArgs: (args: string[]) => Container; + /** + * Set the default command to invoke for the container's terminal API. + * @param args The args of the command. + * @param opts.experimentalPrivilegedNesting Provides Dagger access to the executed command. + * @param opts.insecureRootCapabilities Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + withDefaultTerminalCmd: (args: string[], opts?: ContainerWithDefaultTerminalCmdOpts) => Container; + /** + * Return a new container snapshot, with a directory added to its filesystem + * @param path Location of the written directory (e.g., "/tmp/directory"). + * @param source Identifier of the directory to write + * @param opts.exclude Patterns to exclude in the written directory (e.g. ["node_modules/**", ".gitignore", ".git/"]). + * @param opts.include Patterns to include in the written directory (e.g. ["*.go", "go.mod", "go.sum"]). + * @param opts.gitignore Apply .gitignore rules when writing the directory. + * @param opts.owner A user:group to set for the directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withDirectory: (path: string, source: Directory, opts?: ContainerWithDirectoryOpts) => Container; + /** + * Retrieves this container with the specificed docker healtcheck command set. + * @param args Healthcheck command to execute. Example: ["go", "run", "main.go"]. + * @param opts.shell When true, command must be a single element, which is run using the container's shell + * @param opts.interval Interval between running healthcheck. Example: "30s" + * @param opts.timeout Healthcheck timeout. Example: "3s" + * @param opts.startPeriod StartPeriod allows for failures during this initial startup period which do not count towards maximum number of retries. Example: "0s" + * @param opts.startInterval StartInterval configures the duration between checks during the startup phase. Example: "5s" + * @param opts.retries The maximum number of consecutive failures before the container is marked as unhealthy. Example: "3" + */ + withDockerHealthcheck: (args: string[], opts?: ContainerWithDockerHealthcheckOpts) => Container; + /** + * Set an OCI-style entrypoint. It will be included in the container's OCI configuration. Note, withExec ignores the entrypoint by default. + * @param args Arguments of the entrypoint. Example: ["go", "run"]. + * @param opts.keepDefaultArgs Don't reset the default arguments when setting the entrypoint. By default it is reset, since entrypoint and default args are often tightly coupled. + */ + withEntrypoint: (args: string[], opts?: ContainerWithEntrypointOpts) => Container; + /** + * Export environment variables from an env-file to the container. + * @param source Identifier of the envfile + */ + withEnvFileVariables: (source: EnvFile) => Container; + /** + * Set a new environment variable in the container. + * @param name Name of the environment variable (e.g., "HOST"). + * @param value Value of the environment variable. (e.g., "localhost"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value according to the current environment variables defined in the container (e.g. "/opt/bin:$PATH"). + */ + withEnvVariable: (name: string, value: string, opts?: ContainerWithEnvVariableOpts) => Container; + /** + * Raise an error. + * @param err Message of the error to raise. If empty, the error will be ignored. + */ + withError: (err: string) => Container; + /** + * Execute a command in the container, and return a new snapshot of the container state after execution. + * @param args Command to execute. Must be valid exec() arguments, not a shell command. Example: ["go", "run", "main.go"]. + * + * To run a shell command, execute the shell and pass the shell command as argument. Example: ["sh", "-c", "ls -l | grep foo"] + * + * Defaults to the container's default arguments (see "defaultArgs" and "withDefaultArgs"). + * @param opts.useEntrypoint Apply the OCI entrypoint, if present, by prepending it to the args. Ignored by default. + * @param opts.stdin Content to write to the command's standard input. Example: "Hello world") + * @param opts.redirectStdin Redirect the command's standard input from a file in the container. Example: "./stdin.txt" + * @param opts.redirectStdout Redirect the command's standard output to a file in the container. Example: "./stdout.txt" + * @param opts.redirectStderr Redirect the command's standard error to a file in the container. Example: "./stderr.txt" + * @param opts.expect Exit codes this command is allowed to exit with without error + * @param opts.experimentalPrivilegedNesting Provides Dagger access to the executed command. + * @param opts.insecureRootCapabilities Execute the command with all root capabilities. Like --privileged in Docker + * + * DANGER: this grants the command full access to the host system. Only use when 1) you trust the command being executed and 2) you specifically need this level of access. + * @param opts.expand Replace "${VAR}" or "$VAR" in the args according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + * @param opts.noInit Skip the automatic init process injected into containers by default. + * + * Only use this if you specifically need the command to be pid 1 in the container. Otherwise it may result in unexpected behavior. If you're not sure, you don't need this. + */ + withExec: (args: string[], opts?: ContainerWithExecOpts) => Container; + /** + * Expose a network port. Like EXPOSE in Dockerfile (but with healthcheck support) + * + * Exposed ports serve two purposes: + * + * - For health checks and introspection, when running services + * + * - For setting the EXPOSE OCI field when publishing the container + * @param port Port number to expose. Example: 8080 + * @param opts.protocol Network protocol. Example: "tcp" + * @param opts.description Port description. Example: "payment API endpoint" + * @param opts.experimentalSkipHealthcheck Skip the health check when run as a service. + */ + withExposedPort: (port: number, opts?: ContainerWithExposedPortOpts) => Container; + /** + * Return a container snapshot with a file added + * @param path Path of the new file. Example: "/path/to/new-file.txt" + * @param source File to add + * @param opts.permissions Permissions of the new file. Example: 0600 + * @param opts.owner A user:group to set for the file. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + withFile: (path: string, source: File, opts?: ContainerWithFileOpts) => Container; + /** + * Retrieves this container plus the contents of the given files copied to the given path. + * @param path Location where copied files should be placed (e.g., "/src"). + * @param sources Identifiers of the files to copy. + * @param opts.permissions Permission given to the copied files (e.g., 0600). + * @param opts.owner A user:group to set for the files. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + withFiles: (path: string, sources: File[], opts?: ContainerWithFilesOpts) => Container; + /** + * Retrieves this container plus the given label. + * @param name The name of the label (e.g., "org.opencontainers.artifact.created"). + * @param value The value of the label (e.g., "2023-01-01T00:00:00Z"). + */ + withLabel: (name: string, value: string) => Container; + /** + * Retrieves this container plus a cache volume mounted at the given path. + * @param path Location of the cache directory (e.g., "/root/.npm"). + * @param cache Identifier of the cache volume to mount. + * @param opts.source Identifier of the directory to use as the cache volume's root. + * @param opts.sharing Sharing mode of the cache volume. + * @param opts.owner A user:group to set for the mounted cache directory. + * + * Note that this changes the ownership of the specified mount along with the initial filesystem provided by source (if any). It does not have any effect if/when the cache has already been created. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withMountedCache: (path: string, cache: CacheVolume, opts?: ContainerWithMountedCacheOpts) => Container; + /** + * Retrieves this container plus a directory mounted at the given path. + * @param path Location of the mounted directory (e.g., "/mnt/directory"). + * @param source Identifier of the mounted directory. + * @param opts.owner A user:group to set for the mounted directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.readOnly Mount the directory read-only. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withMountedDirectory: (path: string, source: Directory, opts?: ContainerWithMountedDirectoryOpts) => Container; + /** + * Retrieves this container plus a file mounted at the given path. + * @param path Location of the mounted file (e.g., "/tmp/file.txt"). + * @param source Identifier of the mounted file. + * @param opts.owner A user or user:group to set for the mounted file. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + withMountedFile: (path: string, source: File, opts?: ContainerWithMountedFileOpts) => Container; + /** + * Retrieves this container plus a secret mounted into a file at the given path. + * @param path Location of the secret file (e.g., "/tmp/secret.txt"). + * @param source Identifier of the secret to mount. + * @param opts.owner A user:group to set for the mounted secret. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.mode Permission given to the mounted secret (e.g., 0600). + * + * This option requires an owner to be set to be active. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withMountedSecret: (path: string, source: Secret, opts?: ContainerWithMountedSecretOpts) => Container; + /** + * Retrieves this container plus a temporary directory mounted at the given path. Any writes will be ephemeral to a single withExec call; they will not be persisted to subsequent withExecs. + * @param path Location of the temporary directory (e.g., "/tmp/temp_dir"). + * @param opts.size Size of the temporary directory in bytes. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withMountedTemp: (path: string, opts?: ContainerWithMountedTempOpts) => Container; + /** + * Retrieves this container plus a volume mounted at the given path. + * @param path Location of the volume mount (e.g., "/mnt/volume"). + * @param volume Identifier of the volume to mount. + * @param opts.readOnly Mount the volume read-only. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withMountedVolume: (path: string, volume: Volume, opts?: ContainerWithMountedVolumeOpts) => Container; + /** + * Return a new container snapshot, with a file added to its filesystem with text content + * @param path Path of the new file. May be relative or absolute. Example: "README.md" or "/etc/profile" + * @param contents Contents of the new file. Example: "Hello world!" + * @param opts.permissions Permissions of the new file. Example: 0600 + * @param opts.owner A user:group to set for the file. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + withNewFile: (path: string, contents: string, opts?: ContainerWithNewFileOpts) => Container; + /** + * Attach credentials for future publishing to a registry. Use in combination with publish + * @param address The image address that needs authentication. Same format as "docker push". Example: "registry.dagger.io/dagger:latest" + * @param username The username to authenticate with. Example: "alice" + * @param secret The API key, password or token to authenticate to this registry + */ + withRegistryAuth: (address: string, username: string, secret: Secret) => Container; + /** + * Change the container's root filesystem. The previous root filesystem will be lost. + * @param directory The new root filesystem. + */ + withRootfs: (directory: Directory) => Container; + /** + * Set a new environment variable, using a secret value + * @param name Name of the secret variable (e.g., "API_SECRET"). + * @param secret Identifier of the secret value. + */ + withSecretVariable: (name: string, secret: Secret) => Container; + /** + * Establish a runtime dependency from a container to a network service. + * + * The service will be started automatically when needed and detached when it is no longer needed, executing the default command if none is set. + * + * The service will be reachable from the container via the provided hostname alias. + * + * The service dependency will also convey to any files or directories produced by the container. + * @param alias Hostname that will resolve to the target service (only accessible from within this container) + * @param service The target service + */ + withServiceBinding: (alias: string, service: Service) => Container; + /** + * Return a snapshot with a symlink + * @param target Location of the file or directory to link to (e.g., "/existing/file"). + * @param linkName Location where the symbolic link will be created (e.g., "/new-file-link"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + withSymlink: (target: string, linkName: string, opts?: ContainerWithSymlinkOpts) => Container; + /** + * Retrieves this container plus a socket forwarded to the given Unix socket path. + * @param path Location of the forwarded Unix socket (e.g., "/tmp/socket"). + * @param source Identifier of the socket to forward. + * @param opts.owner A user:group to set for the mounted socket. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.inheritOwner Set the owner to the container's current user. + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withUnixSocket: (path: string, source: Socket, opts?: ContainerWithUnixSocketOpts) => Container; + /** + * Retrieves this container with a different command user. + * @param name The user to set (e.g., "root"). + */ + withUser: (name: string) => Container; + /** + * Set a new non-secret environment variable for future execs without invalidating exec cache when only its value changes. + * + * This is an expert-only escape hatch. If a volatile value affects observable exec results, stale cached results may be reused. + * @param name Name of the volatile variable (e.g., "CI_RUN_ID"). + * @param value Value of the volatile variable. + */ + withVolatileVariable: (name: string, value: string) => Container; + /** + * Change the container's working directory. Like WORKDIR in Dockerfile. + * @param path The path to set as the working directory (e.g., "/app"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withWorkdir: (path: string, opts?: ContainerWithWorkdirOpts) => Container; + /** + * Retrieves this container minus the given OCI annotation. + * @param name The name of the annotation. + */ + withoutAnnotation: (name: string) => Container; + /** + * Remove the container's default arguments. + */ + withoutDefaultArgs: () => Container; + /** + * Return a new container snapshot, with a directory removed from its filesystem + * @param path Location of the directory to remove (e.g., ".github/"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withoutDirectory: (path: string, opts?: ContainerWithoutDirectoryOpts) => Container; + /** + * Retrieves this container without a configured docker healtcheck command. + */ + withoutDockerHealthcheck: () => Container; + /** + * Reset the container's OCI entrypoint. + * @param opts.keepDefaultArgs Don't remove the default arguments when unsetting the entrypoint. + */ + withoutEntrypoint: (opts?: ContainerWithoutEntrypointOpts) => Container; + /** + * Retrieves this container minus the given environment variable. + * @param name The name of the environment variable (e.g., "HOST"). + */ + withoutEnvVariable: (name: string) => Container; + /** + * Unexpose a previously exposed port. + * @param port Port number to unexpose + * @param opts.protocol Port protocol to unexpose + */ + withoutExposedPort: (port: number, opts?: ContainerWithoutExposedPortOpts) => Container; + /** + * Retrieves this container with the file at the given path removed. + * @param path Location of the file to remove (e.g., "/file.txt"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + withoutFile: (path: string, opts?: ContainerWithoutFileOpts) => Container; + /** + * Return a new container spanshot with specified files removed + * @param paths Paths of the files to remove. Example: ["foo.txt, "/root/.ssh/config" + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of paths according to the current environment variables defined in the container (e.g. "/$VAR/foo.txt"). + */ + withoutFiles: (paths: string[], opts?: ContainerWithoutFilesOpts) => Container; + /** + * Retrieves this container minus the given environment label. + * @param name The name of the label to remove (e.g., "org.opencontainers.artifact.created"). + */ + withoutLabel: (name: string) => Container; + /** + * Retrieves this container after unmounting everything at the given path. + * @param path Location of the cache directory (e.g., "/root/.npm"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withoutMount: (path: string, opts?: ContainerWithoutMountOpts) => Container; + /** + * Retrieves this container without the registry authentication of a given address. + * @param address Registry's address to remove the authentication from. + * + * Formatted as [host]/[user]/[repo]:[tag] (e.g. docker.io/dagger/dagger:main). + */ + withoutRegistryAuth: (address: string) => Container; + /** + * Retrieves this container minus the given environment variable containing the secret. + * @param name The name of the environment variable (e.g., "HOST"). + */ + withoutSecretVariable: (name: string) => Container; + /** + * Retrieves this container with a previously added Unix socket removed. + * @param path Location of the socket to remove (e.g., "/tmp/socket"). + * @param opts.expand Replace "${VAR}" or "$VAR" in the value of path according to the current environment variables defined in the container (e.g. "/$VAR/foo"). + */ + withoutUnixSocket: (path: string, opts?: ContainerWithoutUnixSocketOpts) => Container; + /** + * Retrieves this container with an unset command user. + * + * Should default to root. + */ + withoutUser: () => Container; + /** + * Retrieves this container minus the given volatile environment variable. + * @param name The name of the volatile environment variable (e.g., "CI_RUN_ID"). + */ + withoutVolatileVariable: (name: string) => Container; + /** + * Unset the container's working directory. + * + * Should default to "/". + */ + withoutWorkdir: () => Container; + /** + * Retrieves the working directory for all commands. + */ + workdir: () => Promise; + /** + * Call the provided function with current Container. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Container) => Container) => Container; +} +/** + * Reflective module API provided to functions at runtime. + */ +declare class CurrentModule extends BaseClient { + private readonly _id?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string); + /** + * A unique identifier for this CurrentModule. + */ + id: () => Promise; + /** + * Treat the currently executing module as an SDK installed in the given workspace, exposing the modules and clients it manages. + * + * Errors if the current module is not installed as an SDK in this workspace. + * @param opts.workspace The workspace to resolve SDK-role data against. Defaults to the current workspace. + */ + asSDK: (opts?: CurrentModuleAsSdkOpts) => CurrentModuleAsSDK; + /** + * The dependencies of the module. + */ + dependencies: () => Promise; + /** + * The generated files and directories made on top of the module source's context directory. + */ + generatedContextDirectory: () => Directory; + /** + * Return all generators defined by the module + * @param opts.include Only include generators matching the specified patterns + * @experimental + */ + generators: (opts?: CurrentModuleGeneratorsOpts) => GeneratorGroup; + /** + * The name of the module being executed in + */ + name: () => Promise; + /** + * The directory containing the module's source code loaded into the engine (plus any generated code that may have been created). + */ + source: () => Directory; + /** + * Load a directory from the module's scratch working directory, including any changes that may have been made to it during module function execution. + * @param path Location of the directory to access (e.g., "."). + * @param opts.exclude Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + * @param opts.include Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + * @param opts.gitignore Apply .gitignore filter rules inside the directory + */ + workdir: (path: string, opts?: CurrentModuleWorkdirOpts) => Directory; + /** + * Load a file from the module's scratch working directory, including any changes that may have been made to it during module function execution.Load a file from the module's scratch working directory, including any changes that may have been made to it during module function execution. + * @param path Location of the file to retrieve (e.g., "README.md"). + */ + workdirFile: (path: string) => File; +} +/** + * The SDK-role data for the currently executing module, as installed in the active workspace. + */ +declare class CurrentModuleAsSDK extends BaseClient { + private readonly _id?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string); + /** + * A unique identifier for this CurrentModuleAsSDK. + */ + id: () => Promise; + /** + * The generated clients this SDK produces in the workspace. + */ + clients: () => Promise; + /** + * The workspace-local modules this SDK authors and manages. + */ + modules: () => Promise; + /** + * The user-facing name of this SDK in the workspace. + */ + name: () => Promise; +} +/** + * A generated client the current SDK produces in the workspace. + */ +declare class CurrentModuleAsSDKClient extends BaseClient { + private readonly _id?; + private readonly _module?; + private readonly _path?; + private readonly _pin?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _module?: string, _path?: string, _pin?: string); + /** + * A unique identifier for this CurrentModuleAsSDKClient. + */ + id: () => Promise; + /** + * The module the client is bound to (workspace-relative path or canonical ref). + */ + module_: () => Promise; + /** + * The resolved module source this client is bound to, including its dependency closure and pinned version. + */ + moduleSource: () => ModuleSource; + /** + * Workspace-root-relative path of the generated client. + */ + path: () => Promise; + /** + * The pinned version of the bound module, if any. + */ + pin: () => Promise; +} +/** + * A workspace-local module managed by the current SDK. + */ +declare class CurrentModuleAsSDKModule extends BaseClient { + private readonly _id?; + private readonly _path?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _path?: string); + /** + * A unique identifier for this CurrentModuleAsSDKModule. + */ + id: () => Promise; + /** + * Workspace-root-relative path to the managed module. + */ + path: () => Promise; +} +declare class DiffStat extends BaseClient { + private readonly _id?; + private readonly _addedLines?; + private readonly _kind?; + private readonly _oldPath?; + private readonly _path?; + private readonly _removedLines?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _addedLines?: number, _kind?: DiffStatKind, _oldPath?: string, _path?: string, _removedLines?: number); + /** + * A unique identifier for this DiffStat. + */ + id: () => Promise; + /** + * Number of added lines for this path. + */ + addedLines: () => Promise; + /** + * Type of change. + */ + kind: () => Promise; + /** + * Previous path of the file, set only for renames. + */ + oldPath: () => Promise; + /** + * Path of the changed file or directory. + */ + path: () => Promise; + /** + * Number of removed lines for this path. + */ + removedLines: () => Promise; +} +/** + * A directory. + */ +declare class Directory extends BaseClient { + private readonly _id?; + private readonly _digest?; + private readonly _exists?; + private readonly _export?; + private readonly _findUp?; + private readonly _name?; + private readonly _sync?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _digest?: string, _exists?: boolean, _export?: string, _findUp?: string, _name?: string, _sync?: ID); + /** + * A unique identifier for this Directory. + */ + id: () => Promise; + /** + * Converts this directory to a local git repository + */ + asGit: () => GitRepository; + /** + * Load the directory as a Dagger module source + * @param opts.sourceRootPath An optional subpath of the directory which contains the module's configuration file. + * + * If not set, the module source code is loaded from the root of the directory. + */ + asModule: (opts?: DirectoryAsModuleOpts) => Module_; + /** + * Load the directory as a Dagger module source + * @param opts.sourceRootPath An optional subpath of the directory which contains the module's configuration file. + * + * If not set, the module source code is loaded from the root of the directory. + */ + asModuleSource: (opts?: DirectoryAsModuleSourceOpts) => ModuleSource; + /** + * Creates a synthetic workspace from this directory. + * @param opts.cwd Current working directory inside the workspace root. Defaults to the workspace root. + */ + asWorkspace: (opts?: DirectoryAsWorkspaceOpts) => Workspace; + /** + * Return the difference between this directory and another directory, typically an older snapshot. + * + * The difference is encoded as a changeset, which also tracks removed files, and can be applied to other directories. + * @param from The base directory snapshot to compare against + */ + changes: (from: Directory) => Changeset; + /** + * Change the owner of the directory contents recursively. + * @param path Path of the directory to change ownership of (e.g., "/"). + * @param owner A user:group to set for the mounted directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + chown: (path: string, owner: string) => Directory; + /** + * Return the difference between this directory and an another directory. The difference is encoded as a directory. + * @param other The directory to compare against + */ + diff: (other: Directory) => Directory; + /** + * Return the directory's digest. The format of the digest is not guaranteed to be stable between releases of Dagger. It is guaranteed to be stable between invocations of the same Dagger engine. + */ + digest: () => Promise; + /** + * Retrieves a directory at the given path. + * @param path Location of the directory to retrieve. Example: "/src" + */ + directory: (path: string) => Directory; + /** + * Use Dockerfile compatibility to build a container from this directory. Only use this function for Dockerfile compatibility. Otherwise use the native Container type directly, it is feature-complete and supports all Dockerfile features. + * @param opts.dockerfile Path to the Dockerfile to use (e.g., "frontend.Dockerfile"). + * @param opts.platform The platform to build. + * @param opts.buildArgs Build arguments to use in the build. + * @param opts.target Target build stage to build. + * @param opts.secrets Secrets to pass to the build. + * + * They will be mounted at /run/secrets/[secret-name]. + * @param opts.noInit If set, skip the automatic init process injected into containers created by RUN statements. + * + * This should only be used if the user requires that their exec processes be the pid 1 process in the container. Otherwise it may result in unexpected behavior. + * @param opts.ssh A socket to use for SSH authentication during the build + * + * (e.g., for Dockerfile RUN --mount=type=ssh instructions). + * + * Typically obtained via host.unixSocket() pointing to the SSH_AUTH_SOCK. + */ + dockerBuild: (opts?: DirectoryDockerBuildOpts) => Container; + /** + * Returns a list of files and directories at the given path. + * @param opts.path Location of the directory to look at (e.g., "/src"). + */ + entries: (opts?: DirectoryEntriesOpts) => Promise; + /** + * check if a file or directory exists + * @param path Path to check (e.g., "/file.txt"). + * @param opts.expectedType If specified, also validate the type of file (e.g. "REGULAR_TYPE", "DIRECTORY_TYPE", or "SYMLINK_TYPE"). + * @param opts.doNotFollowSymlinks If specified, do not follow symlinks. + */ + exists: (path: string, opts?: DirectoryExistsOpts) => Promise; + /** + * Writes the contents of the directory to a path on the host. + * @param path Location of the copied directory (e.g., "logs/"). + * @param opts.wipe If true, then the host directory will be wiped clean before exporting so that it exactly matches the directory being exported; this means it will delete any files on the host that aren't in the exported dir. If false (the default), the contents of the directory will be merged with any existing contents of the host directory, leaving any existing files on the host that aren't in the exported directory alone. + */ + export: (path: string, opts?: DirectoryExportOpts) => Promise; + /** + * Retrieve a file at the given path. + * @param path Location of the file to retrieve (e.g., "README.md"). + */ + file: (path: string) => File; + /** + * Return a snapshot with some paths included or excluded + * @param opts.exclude If set, paths matching one of these glob patterns is excluded from the new snapshot. Example: ["node_modules/", ".git*", ".env"] + * @param opts.include If set, only paths matching one of these glob patterns is included in the new snapshot. Example: (e.g., ["app/", "package.*"]). + * @param opts.gitignore If set, apply .gitignore rules when filtering the directory. + */ + filter: (opts?: DirectoryFilterOpts) => Directory; + /** + * Search up the directory tree for a file or directory, and return its path. If no match, return null + * @param name The name of the file or directory to search for + * @param start The path to start the search from + */ + findUp: (name: string, start: string) => Promise; + /** + * Returns a list of files and directories that matche the given pattern. + * @param pattern Pattern to match (e.g., "*.md"). + */ + glob: (pattern: string) => Promise; + /** + * Returns the name of the directory. + */ + name: () => Promise; + /** + * Searches for content matching the given regular expression or literal string. + * + * Uses Rust regex syntax; escape literal ., [, ], {, }, | with backslashes. + * @param opts.paths Directory or file paths to search + * @param opts.globs Glob patterns to match (e.g., "*.md") + * @param opts.pattern The text to match. + * @param opts.literal Interpret the pattern as a literal string instead of a regular expression. + * @param opts.multiline Enable searching across multiple lines. + * @param opts.dotall Allow the . pattern to match newlines in multiline mode. + * @param opts.insensitive Enable case-insensitive matching. + * @param opts.skipIgnored Honor .gitignore, .ignore, and .rgignore files. + * @param opts.skipHidden Skip hidden files (files starting with .). + * @param opts.filesOnly Only return matching files, not lines and content + * @param opts.limit Limit the number of results to return + */ + search: (opts?: DirectorySearchOpts) => Promise; + /** + * Return file status + * @param path Path to stat (e.g., "/file.txt"). + * @param opts.doNotFollowSymlinks If specified, do not follow symlinks. + */ + stat: (path: string, opts?: DirectoryStatOpts) => Stat; + /** + * Force evaluation in the engine. + */ + sync: () => Promise; + /** + * Opens an interactive terminal in new container with this directory mounted inside. + * @param opts.container If set, override the default container used for the terminal. + * @param opts.cmd If set, override the container's default terminal command and invoke these command arguments instead. + * @param opts.experimentalPrivilegedNesting Provides Dagger access to the executed command. + * @param opts.insecureRootCapabilities Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands. + */ + terminal: (opts?: DirectoryTerminalOpts) => Directory; + /** + * Return a directory with changes from another directory applied to it. + * @param changes Changes to apply to the directory + */ + withChanges: (changes: Changeset) => Directory; + /** + * Return a snapshot with a directory added + * @param path Location of the written directory (e.g., "/src/"). + * @param source Identifier of the directory to copy. + * @param opts.exclude Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + * @param opts.include Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + * @param opts.gitignore Apply .gitignore filter rules inside the directory + * @param opts.owner A user:group to set for the copied directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + * @param opts.permissions Permission given to the copied directory and contents (e.g., 0755). + */ + withDirectory: (path: string, source: Directory, opts?: DirectoryWithDirectoryOpts) => Directory; + /** + * Raise an error. + * @param err Message of the error to raise. If empty, the error will be ignored. + */ + withError: (err: string) => Directory; + /** + * Retrieves this directory plus the contents of the given file copied to the given path. + * @param path Location of the copied file (e.g., "/file.txt"). + * @param source Identifier of the file to copy. + * @param opts.permissions Permission given to the copied file (e.g., 0600). + * @param opts.owner A user:group to set for the copied directory and its contents. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + withFile: (path: string, source: File, opts?: DirectoryWithFileOpts) => Directory; + /** + * Retrieves this directory plus the contents of the given files copied to the given path. + * @param path Location where copied files should be placed (e.g., "/src"). + * @param sources Identifiers of the files to copy. + * @param opts.permissions Permission given to the copied files (e.g., 0600). + */ + withFiles: (path: string, sources: File[], opts?: DirectoryWithFilesOpts) => Directory; + /** + * Retrieves this directory plus a new directory created at the given path. + * @param path Location of the directory created (e.g., "/logs"). + * @param opts.permissions Permission granted to the created directory (e.g., 0777). + */ + withNewDirectory: (path: string, opts?: DirectoryWithNewDirectoryOpts) => Directory; + /** + * Return a snapshot with a new file added + * @param path Path of the new file. Example: "foo/bar.txt" + * @param contents Contents of the new file. Example: "Hello world!" + * @param opts.permissions Permissions of the new file. Example: 0600 + */ + withNewFile: (path: string, contents: string, opts?: DirectoryWithNewFileOpts) => Directory; + /** + * Retrieves this directory with the given Git-compatible patch applied. + * @param patch Patch to apply (e.g., "diff --git a/file.txt b/file.txt\nindex 1234567..abcdef8 100644\n--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n-Hello\n+World\n"). + * @experimental + */ + withPatch: (patch: string) => Directory; + /** + * Retrieves this directory with the given Git-compatible patch file applied. + * @param patch File containing the patch to apply + * @experimental + */ + withPatchFile: (patch: File) => Directory; + /** + * Return a snapshot with a symlink + * @param target Location of the file or directory to link to (e.g., "/existing/file"). + * @param linkName Location where the symbolic link will be created (e.g., "/new-file-link"). + */ + withSymlink: (target: string, linkName: string) => Directory; + /** + * Retrieves this directory with all file/dir timestamps set to the given time. + * @param timestamp Timestamp to set dir/files in. + * + * Formatted in seconds following Unix epoch (e.g., 1672531199). + */ + withTimestamps: (timestamp: number) => Directory; + /** + * Return a snapshot with a subdirectory removed + * @param path Path of the subdirectory to remove. Example: ".github/workflows" + */ + withoutDirectory: (path: string) => Directory; + /** + * Return a snapshot with a file removed + * @param path Path of the file to remove (e.g., "/file.txt"). + */ + withoutFile: (path: string) => Directory; + /** + * Return a snapshot with files removed + * @param paths Paths of the files to remove (e.g., ["/file.txt"]). + */ + withoutFiles: (paths: string[]) => Directory; + /** + * Call the provided function with current Directory. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Directory) => Directory) => Directory; +} +/** + * The Dagger engine configuration and state + */ +declare class Engine extends BaseClient { + private readonly _id?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string); + /** + * A unique identifier for this Engine. + */ + id: () => Promise; + /** + * The list of connected client IDs + */ + clients: () => Promise; + /** + * The local engine cache state tracked by dagql + */ + localCache: () => EngineCache; + /** + * The name of the engine instance. + */ + name: () => Promise; +} +/** + * A cache storage for the Dagger engine + */ +declare class EngineCache extends BaseClient { + private readonly _id?; + private readonly _maxUsedSpace?; + private readonly _minFreeSpace?; + private readonly _prune?; + private readonly _reservedSpace?; + private readonly _targetSpace?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _maxUsedSpace?: number, _minFreeSpace?: number, _prune?: Void, _reservedSpace?: number, _targetSpace?: number); + /** + * A unique identifier for this EngineCache. + */ + id: () => Promise; + /** + * The current set of entries in the cache + */ + entrySet: (opts?: EngineCacheEntrySetOpts) => EngineCacheEntrySet; + /** + * The maximum bytes to keep in the cache without pruning. + */ + maxUsedSpace: () => Promise; + /** + * The target amount of free disk space the garbage collector will attempt to leave. + */ + minFreeSpace: () => Promise; + /** + * Prune the cache of releaseable entries + * @param opts.useDefaultPolicy Use the engine-wide default pruning policy if true, otherwise prune the whole cache of any releasable entries. + * @param opts.maxUsedSpace Override the maximum disk space to keep before pruning (e.g. "200GB" or "80%"). + * @param opts.reservedSpace Override the minimum disk space to retain during pruning (e.g. "500GB" or "10%"). + * @param opts.minFreeSpace Override the minimum free disk space target during pruning (e.g. "20GB" or "20%"). + * @param opts.targetSpace Override the target disk space to keep after pruning (e.g. "200GB" or "50%"). + */ + prune: (opts?: EngineCachePruneOpts) => Promise; + /** + * The minimum amount of disk space this policy is guaranteed to retain. + */ + reservedSpace: () => Promise; + /** + * The target number of bytes to keep when pruning. + */ + targetSpace: () => Promise; +} +/** + * An individual cache entry in a cache entry set + */ +declare class EngineCacheEntry extends BaseClient { + private readonly _id?; + private readonly _activelyUsed?; + private readonly _createdTimeUnixNano?; + private readonly _dagqlCall?; + private readonly _description?; + private readonly _diskSpaceBytes?; + private readonly _mostRecentUseTimeUnixNano?; + private readonly _recordType?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _activelyUsed?: boolean, _createdTimeUnixNano?: number, _dagqlCall?: string, _description?: string, _diskSpaceBytes?: number, _mostRecentUseTimeUnixNano?: number, _recordType?: string); + /** + * A unique identifier for this EngineCacheEntry. + */ + id: () => Promise; + /** + * Whether the cache entry is actively being used. + */ + activelyUsed: () => Promise; + /** + * The time the cache entry was created, in Unix nanoseconds. + */ + createdTimeUnixNano: () => Promise; + /** + * The DagQL call that produced this cache entry. + */ + dagqlCall: () => Promise; + /** + * The description of the cache entry. + */ + description: () => Promise; + /** + * The disk space used by the cache entry. + */ + diskSpaceBytes: () => Promise; + /** + * The most recent time the cache entry was used, in Unix nanoseconds. + */ + mostRecentUseTimeUnixNano: () => Promise; + /** + * The type of the cache record (e.g. regular, internal, frontend, source.local, source.git.checkout, exec.cachemount). + */ + recordType: () => Promise; + /** + * The storage record types represented by this cache entry. + */ + recordTypes: () => Promise; +} +/** + * A set of cache entries returned by a query to a cache + */ +declare class EngineCacheEntrySet extends BaseClient { + private readonly _id?; + private readonly _diskSpaceBytes?; + private readonly _entryCount?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _diskSpaceBytes?: number, _entryCount?: number); + /** + * A unique identifier for this EngineCacheEntrySet. + */ + id: () => Promise; + /** + * The total disk space used by the cache entries in this set. + */ + diskSpaceBytes: () => Promise; + /** + * The list of individual cache entries in the set + */ + entries: () => Promise; + /** + * The number of cache entries in this set. + */ + entryCount: () => Promise; +} +/** + * A definition of a custom enum defined in a Module. + */ +declare class EnumTypeDef extends BaseClient { + private readonly _id?; + private readonly _description?; + private readonly _name?; + private readonly _sourceModuleName?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _description?: string, _name?: string, _sourceModuleName?: string); + /** + * A unique identifier for this EnumTypeDef. + */ + id: () => Promise; + /** + * A doc string for the enum, if any. + */ + description: () => Promise; + /** + * The members of the enum. + */ + members: () => Promise; + /** + * The name of the enum. + */ + name: () => Promise; + /** + * The location of this enum declaration. + */ + sourceMap: () => SourceMap; + /** + * If this EnumTypeDef is associated with a Module, the name of the module. Unset otherwise. + */ + sourceModuleName: () => Promise; + /** + * The members of the enum. + * @deprecated use members instead + */ + values: () => Promise; +} +/** + * A definition of a value in a custom enum defined in a Module. + */ +declare class EnumValueTypeDef extends BaseClient { + private readonly _id?; + private readonly _deprecated?; + private readonly _description?; + private readonly _name?; + private readonly _value?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _deprecated?: string, _description?: string, _name?: string, _value?: string); + /** + * A unique identifier for this EnumValueTypeDef. + */ + id: () => Promise; + /** + * The reason this enum member is deprecated, if any. + */ + deprecated: () => Promise; + /** + * A doc string for the enum member, if any. + */ + description: () => Promise; + /** + * The name of the enum member. + */ + name: () => Promise; + /** + * The location of this enum member declaration. + */ + sourceMap: () => SourceMap; + /** + * The value of the enum member + */ + value: () => Promise; +} +declare class Env extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this Env. + */ + id: () => Promise; + /** + * Return the check with the given name from the installed modules. Must match exactly one check. + * @param name The name of the check to retrieve + * @experimental + */ + check: (name: string) => Check; + /** + * Return all checks defined by the installed modules + * @param opts.include Only include checks matching the specified patterns + * @param opts.noGenerate When true, only return annotated check functions; exclude generate-as-checks + * @experimental + */ + checks: (opts?: EnvChecksOpts) => CheckGroup; + /** + * Retrieves an input binding by name + */ + input: (name: string) => Binding; + /** + * Returns all input bindings provided to the environment + */ + inputs: () => Promise; + /** + * Retrieves an output binding by name + */ + output: (name: string) => Binding; + /** + * Returns all declared output bindings for the environment + */ + outputs: () => Promise; + /** + * Return all services defined by the installed modules + * @param opts.include Only include services matching the specified patterns + * @experimental + */ + services: (opts?: EnvServicesOpts) => UpGroup; + /** + * Create or update a binding of type Address in the environment + * @param name The name of the binding + * @param value The Address value to assign to the binding + * @param description The purpose of the input + */ + withAddressInput: (name: string, value: Address, description: string) => Env; + /** + * Declare a desired Address output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withAddressOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type CacheVolume in the environment + * @param name The name of the binding + * @param value The CacheVolume value to assign to the binding + * @param description The purpose of the input + */ + withCacheVolumeInput: (name: string, value: CacheVolume, description: string) => Env; + /** + * Declare a desired CacheVolume output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withCacheVolumeOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Changeset in the environment + * @param name The name of the binding + * @param value The Changeset value to assign to the binding + * @param description The purpose of the input + */ + withChangesetInput: (name: string, value: Changeset, description: string) => Env; + /** + * Declare a desired Changeset output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withChangesetOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type CheckGroup in the environment + * @param name The name of the binding + * @param value The CheckGroup value to assign to the binding + * @param description The purpose of the input + */ + withCheckGroupInput: (name: string, value: CheckGroup, description: string) => Env; + /** + * Declare a desired CheckGroup output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withCheckGroupOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Check in the environment + * @param name The name of the binding + * @param value The Check value to assign to the binding + * @param description The purpose of the input + */ + withCheckInput: (name: string, value: Check, description: string) => Env; + /** + * Declare a desired Check output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withCheckOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Cloud in the environment + * @param name The name of the binding + * @param value The Cloud value to assign to the binding + * @param description The purpose of the input + */ + withCloudInput: (name: string, value: Cloud, description: string) => Env; + /** + * Declare a desired Cloud output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withCloudOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Container in the environment + * @param name The name of the binding + * @param value The Container value to assign to the binding + * @param description The purpose of the input + */ + withContainerInput: (name: string, value: Container, description: string) => Env; + /** + * Declare a desired Container output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withContainerOutput: (name: string, description: string) => Env; + /** + * Installs the current module into the environment, exposing its functions to the model + * + * Contextual path arguments will be populated using the environment's workspace. + */ + withCurrentModule: () => Env; + /** + * Create or update a binding of type CurrentModuleAsSDKClient in the environment + * @param name The name of the binding + * @param value The CurrentModuleAsSDKClient value to assign to the binding + * @param description The purpose of the input + */ + withCurrentModuleAsSDKClientInput: (name: string, value: CurrentModuleAsSDKClient, description: string) => Env; + /** + * Declare a desired CurrentModuleAsSDKClient output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withCurrentModuleAsSDKClientOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type CurrentModuleAsSDK in the environment + * @param name The name of the binding + * @param value The CurrentModuleAsSDK value to assign to the binding + * @param description The purpose of the input + */ + withCurrentModuleAsSDKInput: (name: string, value: CurrentModuleAsSDK, description: string) => Env; + /** + * Create or update a binding of type CurrentModuleAsSDKModule in the environment + * @param name The name of the binding + * @param value The CurrentModuleAsSDKModule value to assign to the binding + * @param description The purpose of the input + */ + withCurrentModuleAsSDKModuleInput: (name: string, value: CurrentModuleAsSDKModule, description: string) => Env; + /** + * Declare a desired CurrentModuleAsSDKModule output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withCurrentModuleAsSDKModuleOutput: (name: string, description: string) => Env; + /** + * Declare a desired CurrentModuleAsSDK output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withCurrentModuleAsSDKOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type DiffStat in the environment + * @param name The name of the binding + * @param value The DiffStat value to assign to the binding + * @param description The purpose of the input + */ + withDiffStatInput: (name: string, value: DiffStat, description: string) => Env; + /** + * Declare a desired DiffStat output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withDiffStatOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Directory in the environment + * @param name The name of the binding + * @param value The Directory value to assign to the binding + * @param description The purpose of the input + */ + withDirectoryInput: (name: string, value: Directory, description: string) => Env; + /** + * Declare a desired Directory output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withDirectoryOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type EnvFile in the environment + * @param name The name of the binding + * @param value The EnvFile value to assign to the binding + * @param description The purpose of the input + */ + withEnvFileInput: (name: string, value: EnvFile, description: string) => Env; + /** + * Declare a desired EnvFile output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withEnvFileOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Env in the environment + * @param name The name of the binding + * @param value The Env value to assign to the binding + * @param description The purpose of the input + */ + withEnvInput: (name: string, value: Env, description: string) => Env; + /** + * Declare a desired Env output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withEnvOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type File in the environment + * @param name The name of the binding + * @param value The File value to assign to the binding + * @param description The purpose of the input + */ + withFileInput: (name: string, value: File, description: string) => Env; + /** + * Declare a desired File output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withFileOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type GeneratorGroup in the environment + * @param name The name of the binding + * @param value The GeneratorGroup value to assign to the binding + * @param description The purpose of the input + */ + withGeneratorGroupInput: (name: string, value: GeneratorGroup, description: string) => Env; + /** + * Declare a desired GeneratorGroup output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withGeneratorGroupOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Generator in the environment + * @param name The name of the binding + * @param value The Generator value to assign to the binding + * @param description The purpose of the input + */ + withGeneratorInput: (name: string, value: Generator, description: string) => Env; + /** + * Declare a desired Generator output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withGeneratorOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type GitRef in the environment + * @param name The name of the binding + * @param value The GitRef value to assign to the binding + * @param description The purpose of the input + */ + withGitRefInput: (name: string, value: GitRef, description: string) => Env; + /** + * Declare a desired GitRef output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withGitRefOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type GitRepository in the environment + * @param name The name of the binding + * @param value The GitRepository value to assign to the binding + * @param description The purpose of the input + */ + withGitRepositoryInput: (name: string, value: GitRepository, description: string) => Env; + /** + * Declare a desired GitRepository output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withGitRepositoryOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type HTTPState in the environment + * @param name The name of the binding + * @param value The HTTPState value to assign to the binding + * @param description The purpose of the input + */ + withHTTPStateInput: (name: string, value: HTTPState, description: string) => Env; + /** + * Declare a desired HTTPState output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withHTTPStateOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type JSONValue in the environment + * @param name The name of the binding + * @param value The JSONValue value to assign to the binding + * @param description The purpose of the input + */ + withJSONValueInput: (name: string, value: JSONValue, description: string) => Env; + /** + * Declare a desired JSONValue output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withJSONValueOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type LLMContentBlock in the environment + * @param name The name of the binding + * @param value The LLMContentBlock value to assign to the binding + * @param description The purpose of the input + */ + withLLMContentBlockInput: (name: string, value: LLMContentBlock, description: string) => Env; + /** + * Declare a desired LLMContentBlock output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withLLMContentBlockOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type LLMMessage in the environment + * @param name The name of the binding + * @param value The LLMMessage value to assign to the binding + * @param description The purpose of the input + */ + withLLMMessageInput: (name: string, value: LLMMessage, description: string) => Env; + /** + * Declare a desired LLMMessage output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withLLMMessageOutput: (name: string, description: string) => Env; + /** + * Sets the main module for this environment (the project being worked on) + * + * Contextual path arguments will be populated using the environment's workspace. + */ + withMainModule: (module_: Module_) => Env; + /** + * Installs a module into the environment, exposing its functions to the model + * + * Contextual path arguments will be populated using the environment's workspace. + * @deprecated Use withMainModule instead + */ + withModule: (module_: Module_) => Env; + /** + * Create or update a binding of type ModuleConfigClient in the environment + * @param name The name of the binding + * @param value The ModuleConfigClient value to assign to the binding + * @param description The purpose of the input + */ + withModuleConfigClientInput: (name: string, value: ModuleConfigClient, description: string) => Env; + /** + * Declare a desired ModuleConfigClient output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withModuleConfigClientOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Module in the environment + * @param name The name of the binding + * @param value The Module value to assign to the binding + * @param description The purpose of the input + */ + withModuleInput: (name: string, value: Module_, description: string) => Env; + /** + * Declare a desired Module output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withModuleOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type ModuleSource in the environment + * @param name The name of the binding + * @param value The ModuleSource value to assign to the binding + * @param description The purpose of the input + */ + withModuleSourceInput: (name: string, value: ModuleSource, description: string) => Env; + /** + * Declare a desired ModuleSource output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withModuleSourceOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Schema in the environment + * @param name The name of the binding + * @param value The Schema value to assign to the binding + * @param description The purpose of the input + */ + withSchemaInput: (name: string, value: Schema, description: string) => Env; + /** + * Declare a desired Schema output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withSchemaOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type SearchResult in the environment + * @param name The name of the binding + * @param value The SearchResult value to assign to the binding + * @param description The purpose of the input + */ + withSearchResultInput: (name: string, value: SearchResult, description: string) => Env; + /** + * Declare a desired SearchResult output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withSearchResultOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type SearchSubmatch in the environment + * @param name The name of the binding + * @param value The SearchSubmatch value to assign to the binding + * @param description The purpose of the input + */ + withSearchSubmatchInput: (name: string, value: SearchSubmatch, description: string) => Env; + /** + * Declare a desired SearchSubmatch output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withSearchSubmatchOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Secret in the environment + * @param name The name of the binding + * @param value The Secret value to assign to the binding + * @param description The purpose of the input + */ + withSecretInput: (name: string, value: Secret, description: string) => Env; + /** + * Declare a desired Secret output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withSecretOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Service in the environment + * @param name The name of the binding + * @param value The Service value to assign to the binding + * @param description The purpose of the input + */ + withServiceInput: (name: string, value: Service, description: string) => Env; + /** + * Declare a desired Service output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withServiceOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Socket in the environment + * @param name The name of the binding + * @param value The Socket value to assign to the binding + * @param description The purpose of the input + */ + withSocketInput: (name: string, value: Socket, description: string) => Env; + /** + * Declare a desired Socket output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withSocketOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Stat in the environment + * @param name The name of the binding + * @param value The Stat value to assign to the binding + * @param description The purpose of the input + */ + withStatInput: (name: string, value: Stat, description: string) => Env; + /** + * Declare a desired Stat output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withStatOutput: (name: string, description: string) => Env; + /** + * Provides a string input binding to the environment + * @param name The name of the binding + * @param value The string value to assign to the binding + * @param description The description of the input + */ + withStringInput: (name: string, value: string, description: string) => Env; + /** + * Declares a desired string output binding + * @param name The name of the binding + * @param description The description of the output + */ + withStringOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type UpGroup in the environment + * @param name The name of the binding + * @param value The UpGroup value to assign to the binding + * @param description The purpose of the input + */ + withUpGroupInput: (name: string, value: UpGroup, description: string) => Env; + /** + * Declare a desired UpGroup output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withUpGroupOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Up in the environment + * @param name The name of the binding + * @param value The Up value to assign to the binding + * @param description The purpose of the input + */ + withUpInput: (name: string, value: Up, description: string) => Env; + /** + * Declare a desired Up output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withUpOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Volume in the environment + * @param name The name of the binding + * @param value The Volume value to assign to the binding + * @param description The purpose of the input + */ + withVolumeInput: (name: string, value: Volume, description: string) => Env; + /** + * Declare a desired Volume output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withVolumeOutput: (name: string, description: string) => Env; + /** + * Returns a new environment with the provided workspace + * @param workspace The directory to set as the host filesystem + */ + withWorkspace: (workspace: Directory) => Env; + /** + * Create or update a binding of type WorkspaceGit in the environment + * @param name The name of the binding + * @param value The WorkspaceGit value to assign to the binding + * @param description The purpose of the input + */ + withWorkspaceGitInput: (name: string, value: WorkspaceGit, description: string) => Env; + /** + * Declare a desired WorkspaceGit output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withWorkspaceGitOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type Workspace in the environment + * @param name The name of the binding + * @param value The Workspace value to assign to the binding + * @param description The purpose of the input + */ + withWorkspaceInput: (name: string, value: Workspace, description: string) => Env; + /** + * Create or update a binding of type WorkspaceMigration in the environment + * @param name The name of the binding + * @param value The WorkspaceMigration value to assign to the binding + * @param description The purpose of the input + */ + withWorkspaceMigrationInput: (name: string, value: WorkspaceMigration, description: string) => Env; + /** + * Declare a desired WorkspaceMigration output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withWorkspaceMigrationOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type WorkspaceMigrationStep in the environment + * @param name The name of the binding + * @param value The WorkspaceMigrationStep value to assign to the binding + * @param description The purpose of the input + */ + withWorkspaceMigrationStepInput: (name: string, value: WorkspaceMigrationStep, description: string) => Env; + /** + * Declare a desired WorkspaceMigrationStep output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withWorkspaceMigrationStepOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type WorkspaceModule in the environment + * @param name The name of the binding + * @param value The WorkspaceModule value to assign to the binding + * @param description The purpose of the input + */ + withWorkspaceModuleInput: (name: string, value: WorkspaceModule, description: string) => Env; + /** + * Declare a desired WorkspaceModule output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withWorkspaceModuleOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type WorkspaceModuleSetting in the environment + * @param name The name of the binding + * @param value The WorkspaceModuleSetting value to assign to the binding + * @param description The purpose of the input + */ + withWorkspaceModuleSettingInput: (name: string, value: WorkspaceModuleSetting, description: string) => Env; + /** + * Declare a desired WorkspaceModuleSetting output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withWorkspaceModuleSettingOutput: (name: string, description: string) => Env; + /** + * Declare a desired Workspace output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withWorkspaceOutput: (name: string, description: string) => Env; + /** + * Create or update a binding of type WorkspaceSDK in the environment + * @param name The name of the binding + * @param value The WorkspaceSDK value to assign to the binding + * @param description The purpose of the input + */ + withWorkspaceSDKInput: (name: string, value: WorkspaceSDK, description: string) => Env; + /** + * Declare a desired WorkspaceSDK output to be assigned in the environment + * @param name The name of the binding + * @param description A description of the desired value of the binding + */ + withWorkspaceSDKOutput: (name: string, description: string) => Env; + /** + * Returns a new environment without any outputs + */ + withoutOutputs: () => Env; + workspace: () => Directory; + /** + * Call the provided function with current Env. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Env) => Env) => Env; +} +/** + * A collection of environment variables. + */ +declare class EnvFile extends BaseClient { + private readonly _id?; + private readonly _exists?; + private readonly _get?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _exists?: boolean, _get?: string); + /** + * A unique identifier for this EnvFile. + */ + id: () => Promise; + /** + * Return as a file + */ + asFile: () => File; + /** + * Check if a variable exists + * @param name Variable name + */ + exists: (name: string) => Promise; + /** + * Lookup a variable (last occurrence wins) and return its value, or an empty string + * @param name Variable name + * @param opts.raw Return the value exactly as written to the file. No quote removal or variable expansion + */ + get: (name: string, opts?: EnvFileGetOpts) => Promise; + /** + * Filters variables by prefix and removes the pref from keys. Variables without the prefix are excluded. For example, with the prefix "MY_APP_" and variables: MY_APP_TOKEN=topsecret MY_APP_NAME=hello FOO=bar the resulting environment will contain: TOKEN=topsecret NAME=hello + * @param prefix The prefix to filter by + */ + namespace_: (prefix: string) => EnvFile; + /** + * Return all variables + * @param opts.raw Return values exactly as written to the file. No quote removal or variable expansion + */ + variables: (opts?: EnvFileVariablesOpts) => Promise; + /** + * Add a variable + * @param name Variable name + * @param value Variable value + */ + withVariable: (name: string, value: string) => EnvFile; + /** + * Remove all occurrences of the named variable + * @param name Variable name + */ + withoutVariable: (name: string) => EnvFile; + /** + * Call the provided function with current EnvFile. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: EnvFile) => EnvFile) => EnvFile; +} +/** + * An environment variable name and value. + */ +declare class EnvVariable extends BaseClient { + private readonly _id?; + private readonly _name?; + private readonly _value?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string, _value?: string); + /** + * A unique identifier for this EnvVariable. + */ + id: () => Promise; + /** + * The environment variable name. + */ + name: () => Promise; + /** + * The environment variable value. + */ + value: () => Promise; +} +declare class Error$1 extends BaseClient { + private readonly _id?; + private readonly _message?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _message?: string); + /** + * A unique identifier for this Error. + */ + id: () => Promise; + /** + * A description of the error. + */ + message: () => Promise; + /** + * The extensions of the error. + */ + values: () => Promise; + /** + * Add a value to the error. + * @param name The name of the value. + * @param value The value to store on the error. + */ + withValue: (name: string, value: JSON) => Error$1; + /** + * Call the provided function with current Error. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Error$1) => Error$1) => Error$1; +} +declare class ErrorValue extends BaseClient { + private readonly _id?; + private readonly _name?; + private readonly _value?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string, _value?: JSON); + /** + * A unique identifier for this ErrorValue. + */ + id: () => Promise; + /** + * The name of the value. + */ + name: () => Promise; + /** + * The value. + */ + value: () => Promise; +} +/** + * An object that can be exported to the host. + * + * Calling export writes the object to a path on the host filesystem and returns the path that was written. + */ +interface Exportable { + id(): Promise; + export(path: string): Promise; +} +declare class _ExportableClient extends BaseClient { + private readonly _id?; + private readonly _export?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _export?: string); + id: () => Promise; + export: (path: string) => Promise; +} +/** + * A definition of a field on a custom object defined in a Module. + * + * A field on an object has a static value, as opposed to a function on an object whose value is computed by invoking code (and can accept arguments). + */ +declare class FieldTypeDef extends BaseClient { + private readonly _id?; + private readonly _deprecated?; + private readonly _description?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _deprecated?: string, _description?: string, _name?: string); + /** + * A unique identifier for this FieldTypeDef. + */ + id: () => Promise; + /** + * The reason this enum member is deprecated, if any. + */ + deprecated: () => Promise; + /** + * A doc string for the field, if any. + */ + description: () => Promise; + /** + * The name of the field in lowerCamelCase format. + */ + name: () => Promise; + /** + * The location of this field declaration. + */ + sourceMap: () => SourceMap; + /** + * The type of the field. + */ + typeDef: () => TypeDef; +} +/** + * A file. + */ +declare class File extends BaseClient { + private readonly _id?; + private readonly _contents?; + private readonly _digest?; + private readonly _export?; + private readonly _name?; + private readonly _size?; + private readonly _sync?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _contents?: string, _digest?: string, _export?: string, _name?: string, _size?: number, _sync?: ID); + /** + * A unique identifier for this File. + */ + id: () => Promise; + /** + * Parse as an env file + * @param opts.expand Replace "${VAR}" or "$VAR" with the value of other vars + */ + asEnvFile: (opts?: FileAsEnvFileOpts) => EnvFile; + /** + * Parse the file contents as JSON. + */ + asJSON: () => JSONValue; + /** + * Change the owner of the file recursively. + * @param owner A user:group to set for the file. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + chown: (owner: string) => File; + /** + * Retrieves the contents of the file. + * @param opts.offsetLines Start reading after this line + * @param opts.limitLines Maximum number of lines to read + */ + contents: (opts?: FileContentsOpts) => Promise; + /** + * Return the file's digest. The format of the digest is not guaranteed to be stable between releases of Dagger. It is guaranteed to be stable between invocations of the same Dagger engine. + * @param opts.excludeMetadata If true, exclude metadata from the digest. + */ + digest: (opts?: FileDigestOpts) => Promise; + /** + * Writes the file to a file path on the host. + * @param path Location of the written directory (e.g., "output.txt"). + * @param opts.allowParentDirPath If allowParentDirPath is true, the path argument can be a directory path, in which case the file will be created in that directory. + */ + export: (path: string, opts?: FileExportOpts) => Promise; + /** + * Retrieves the name of the file. + */ + name: () => Promise; + /** + * Searches for content matching the given regular expression or literal string. + * + * Uses Rust regex syntax; escape literal ., [, ], {, }, | with backslashes. + * @param pattern The text to match. + * @param opts.literal Interpret the pattern as a literal string instead of a regular expression. + * @param opts.multiline Enable searching across multiple lines. + * @param opts.dotall Allow the . pattern to match newlines in multiline mode. + * @param opts.insensitive Enable case-insensitive matching. + * @param opts.skipIgnored Honor .gitignore, .ignore, and .rgignore files. + * @param opts.skipHidden Skip hidden files (files starting with .). + * @param opts.filesOnly Only return matching files, not lines and content + * @param opts.limit Limit the number of results to return + */ + search: (pattern: string, opts?: FileSearchOpts) => Promise; + /** + * Retrieves the size of the file, in bytes. + */ + size: () => Promise; + /** + * Return file status + */ + stat: () => Stat; + /** + * Force evaluation in the engine. + */ + sync: () => Promise; + /** + * Retrieves this file with its name set to the given name. + * @param name Name to set file to. + */ + withName: (name: string) => File; + /** + * Retrieves the file with content replaced with the given text. + * + * If 'all' is true, all occurrences of the pattern will be replaced. + * + * If 'firstAfter' is specified, only the first match starting at the specified line will be replaced. + * + * If neither are specified, and there are multiple matches for the pattern, this will error. + * + * If there are no matches for the pattern, this will error. + * @param search The text to match. + * @param replacement The text to match. + * @param opts.all Replace all occurrences of the pattern. + * @param opts.firstFrom Replace the first match starting from the specified line. + */ + withReplaced: (search: string, replacement: string, opts?: FileWithReplacedOpts) => File; + /** + * Retrieves this file with its created/modified timestamps set to the given time. + * @param timestamp Timestamp to set dir/files in. + * + * Formatted in seconds following Unix epoch (e.g., 1672531199). + */ + withTimestamps: (timestamp: number) => File; + /** + * Call the provided function with current File. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: File) => File) => File; +} +/** + * Function represents a resolver provided by a Module. + * + * A function always evaluates against a parent object and is given a set of named arguments. + */ +declare class Function_ extends BaseClient { + private readonly _id?; + private readonly _deprecated?; + private readonly _description?; + private readonly _name?; + private readonly _sourceModuleName?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _deprecated?: string, _description?: string, _name?: string, _sourceModuleName?: string); + /** + * A unique identifier for this Function. + */ + id: () => Promise; + /** + * Arguments accepted by the function, if any. + */ + args: () => Promise; + /** + * The reason this function is deprecated, if any. + */ + deprecated: () => Promise; + /** + * A doc string for the function, if any. + */ + description: () => Promise; + /** + * The name of the function. + */ + name: () => Promise; + /** + * The type returned by the function. + */ + returnType: () => TypeDef; + /** + * The location of this function declaration. + */ + sourceMap: () => SourceMap; + /** + * If this function is provided by a module, the name of the module. Unset otherwise. + */ + sourceModuleName: () => Promise; + /** + * Returns the function with the provided argument + * @param name The name of the argument + * @param typeDef The type of the argument + * @param opts.description A doc string for the argument, if any + * @param opts.defaultValue A default value to use for this argument if not explicitly set by the caller, if any + * @param opts.defaultPath If the argument is a Directory or File type, default to load path from context directory, relative to root directory. + * @param opts.ignore Patterns to ignore when loading the contextual argument value. + * @param opts.sourceMap The source map for the argument definition. + * @param opts.deprecated If deprecated, the reason or migration path. + */ + withArg: (name: string, typeDef: TypeDef, opts?: FunctionWithArgOpts) => Function_; + /** + * Returns the function updated to use the provided cache policy. + * @param policy The cache policy to use. + * @param opts.timeToLive The TTL for the cache policy, if applicable. Provided as a duration string, e.g. "5m", "1h30s". + */ + withCachePolicy: (policy: FunctionCachePolicy, opts?: FunctionWithCachePolicyOpts) => Function_; + /** + * Returns the function with a flag indicating it's a check. + */ + withCheck: () => Function_; + /** + * Returns the function with the provided deprecation reason. + * @param opts.reason Reason or migration path describing the deprecation. + */ + withDeprecated: (opts?: FunctionWithDeprecatedOpts) => Function_; + /** + * Returns the function with the given doc string. + * @param description The doc string to set. + */ + withDescription: (description: string) => Function_; + /** + * Returns the function with a flag indicating it's a generator. + */ + withGenerator: () => Function_; + /** + * Returns the function with the given source map. + * @param sourceMap The source map for the function definition. + */ + withSourceMap: (sourceMap: SourceMap) => Function_; + /** + * Returns the function with a flag indicating it returns a service for dagger up. + */ + withUp: () => Function_; + /** + * Call the provided function with current Function. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Function_) => Function_) => Function_; +} +/** + * An argument accepted by a function. + * + * This is a specification for an argument at function definition time, not an argument passed at function call time. + */ +declare class FunctionArg extends BaseClient { + private readonly _id?; + private readonly _defaultAddress?; + private readonly _defaultPath?; + private readonly _defaultValue?; + private readonly _deprecated?; + private readonly _description?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _defaultAddress?: string, _defaultPath?: string, _defaultValue?: JSON, _deprecated?: string, _description?: string, _name?: string); + /** + * A unique identifier for this FunctionArg. + */ + id: () => Promise; + /** + * Only applies to arguments of type Container. If the argument is not set, load it from the given address (e.g. alpine:latest) + */ + defaultAddress: () => Promise; + /** + * Only applies to arguments of type File or Directory. If the argument is not set, load it from the given path in the context directory + */ + defaultPath: () => Promise; + /** + * A default value to use for this argument when not explicitly set by the caller, if any. + */ + defaultValue: () => Promise; + /** + * The reason this function is deprecated, if any. + */ + deprecated: () => Promise; + /** + * A doc string for the argument, if any. + */ + description: () => Promise; + /** + * Only applies to arguments of type Directory. The ignore patterns are applied to the input directory, and matching entries are filtered out, in a cache-efficient manner. + */ + ignore: () => Promise; + /** + * The name of the argument in lowerCamelCase format. + */ + name: () => Promise; + /** + * The location of this arg declaration. + */ + sourceMap: () => SourceMap; + /** + * The type of the argument. + */ + typeDef: () => TypeDef; +} +/** + * An active function call. + */ +declare class FunctionCall extends BaseClient { + private readonly _id?; + private readonly _name?; + private readonly _parent?; + private readonly _parentName?; + private readonly _returnError?; + private readonly _returnValue?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string, _parent?: JSON, _parentName?: string, _returnError?: Void, _returnValue?: Void); + /** + * A unique identifier for this FunctionCall. + */ + id: () => Promise; + /** + * The argument values the function is being invoked with. + */ + inputArgs: () => Promise; + /** + * The name of the function being called. + */ + name: () => Promise; + /** + * The value of the parent object of the function being called. If the function is top-level to the module, this is always an empty object. + */ + parent: () => Promise; + /** + * The name of the parent object of the function being called. If the function is top-level to the module, this is the name of the module. + */ + parentName: () => Promise; + /** + * Return an error from the function. + * @param error The error to return. + */ + returnError: (error: Error$1) => Promise; + /** + * Set the return value of the function call to the provided value. + * @param value JSON serialization of the return value. + */ + returnValue: (value: JSON) => Promise; +} +/** + * A value passed as a named argument to a function call. + */ +declare class FunctionCallArgValue extends BaseClient { + private readonly _id?; + private readonly _name?; + private readonly _value?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string, _value?: JSON); + /** + * A unique identifier for this FunctionCallArgValue. + */ + id: () => Promise; + /** + * The name of the argument. + */ + name: () => Promise; + /** + * The value of the argument represented as a JSON serialized string. + */ + value: () => Promise; +} +/** + * The result of running an SDK's codegen. + */ +declare class GeneratedCode extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this GeneratedCode. + */ + id: () => Promise; + /** + * The directory containing the generated code. + */ + code: () => Directory; + /** + * List of paths to mark generated in version control (i.e. .gitattributes). + */ + vcsGeneratedPaths: () => Promise; + /** + * List of paths to ignore in version control (i.e. .gitignore). + */ + vcsIgnoredPaths: () => Promise; + /** + * Set the list of paths to mark generated in version control. + */ + withVCSGeneratedPaths: (paths: string[]) => GeneratedCode; + /** + * Set the list of paths to ignore in version control. + */ + withVCSIgnoredPaths: (paths: string[]) => GeneratedCode; + /** + * Call the provided function with current GeneratedCode. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: GeneratedCode) => GeneratedCode) => GeneratedCode; +} +declare class Generator extends BaseClient { + private readonly _id?; + private readonly _completed?; + private readonly _description?; + private readonly _isEmpty?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _completed?: boolean, _description?: string, _isEmpty?: boolean, _name?: string); + /** + * A unique identifier for this Generator. + */ + id: () => Promise; + /** + * The generated changeset from the last run + */ + changes: () => Changeset; + /** + * Whether the generator complete + */ + completed: () => Promise; + /** + * Return the description of the generator + */ + description: () => Promise; + /** + * Whether changeset from the last generator run is empty or not + */ + isEmpty: () => Promise; + /** + * Return the fully qualified name of the generator + */ + name: () => Promise; + /** + * The original module in which the generator has been defined + */ + originalModule: () => Module_; + /** + * The path of the generator within its module + */ + path: () => Promise; + /** + * Execute the generator + */ + run: () => Generator; + /** + * Call the provided function with current Generator. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Generator) => Generator) => Generator; +} +declare class GeneratorGroup extends BaseClient { + private readonly _id?; + private readonly _isEmpty?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _isEmpty?: boolean); + /** + * A unique identifier for this GeneratorGroup. + */ + id: () => Promise; + /** + * The combined changes from the last run of the generators + * + * If any conflict occurs, for instance if the same file is modified by multiple generators, or if a file is both modified and deleted, an error is raised and the merge of the changesets will failed. + * + * Set 'continueOnConflicts' flag to force to merge the changes in a 'last write wins' strategy. + * @param opts.onConflict Strategy to apply on conflicts between generators + */ + changes: (opts?: GeneratorGroupChangesOpts) => Changeset; + /** + * Whether the generated changeset from the last run is empty or not + */ + isEmpty: () => Promise; + /** + * Return a list of individual generators and their details + */ + list: () => Promise; + /** + * Load failures tolerated while collecting the generators. + * + * Empty unless a workspace module could not be loaded during an unscoped 'dagger generate' (no selector), where load failures are tolerated so the modules that do load still generate. Each entry is a human-readable error message. An explicit selector keeps failing hard instead. + */ + loadFailures: () => Promise; + /** + * Execute all selected generators + */ + run: () => GeneratorGroup; + /** + * Call the provided function with current GeneratorGroup. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: GeneratorGroup) => GeneratorGroup) => GeneratorGroup; +} +/** + * A git ref (tag, branch, or commit). + */ +declare class GitRef extends BaseClient { + private readonly _id?; + private readonly _commit?; + private readonly _ref?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _commit?: string, _ref?: string); + /** + * A unique identifier for this GitRef. + */ + id: () => Promise; + /** + * Creates a synthetic workspace from this git ref. + * @param opts.cwd Current working directory inside the workspace root. Defaults to the workspace root. + */ + asWorkspace: (opts?: GitRefAsWorkspaceOpts) => Workspace; + /** + * The resolved commit id at this ref. + */ + commit: () => Promise; + /** + * Find the best common ancestor between this ref and another ref. + * @param other The other ref to compare against. + */ + commonAncestor: (other: GitRef) => GitRef; + /** + * The resolved ref name at this ref. + */ + ref: () => Promise; + /** + * The filesystem tree at this ref. + * @param opts.discardGitDir Set to true to discard .git directory. + * @param opts.depth The depth of the tree to fetch. + * @param opts.includeTags Set to true to populate tag refs in the local checkout .git. + */ + tree: (opts?: GitRefTreeOpts) => Directory; + /** + * Call the provided function with current GitRef. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: GitRef) => GitRef) => GitRef; +} +/** + * A git repository. + */ +declare class GitRepository extends BaseClient { + private readonly _id?; + private readonly _url?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _url?: string); + /** + * A unique identifier for this GitRepository. + */ + id: () => Promise; + /** + * Creates a synthetic workspace from this git repository. + * @param opts.cwd Current working directory inside the workspace root. Defaults to the workspace root. + */ + asWorkspace: (opts?: GitRepositoryAsWorkspaceOpts) => Workspace; + /** + * Returns details of a branch. + * @param name Branch's name (e.g., "main"). + */ + branch: (name: string) => GitRef; + /** + * branches that match any of the given glob patterns. + * @param opts.patterns Glob patterns (e.g., "refs/tags/v*"). + */ + branches: (opts?: GitRepositoryBranchesOpts) => Promise; + /** + * Returns details of a commit. + * @param id Identifier of the commit (e.g., "b6315d8f2810962c601af73f86831f6866ea798b"). + */ + commit: (id: string) => GitRef; + /** + * Returns details for HEAD. + */ + head: () => GitRef; + /** + * Returns details for the latest semver tag. + */ + latestVersion: () => GitRef; + /** + * Returns details of a ref. + * @param name Ref's name (can be a commit identifier, a tag name, a branch name, or a fully-qualified ref). + */ + ref: (name: string) => GitRef; + /** + * Returns details of a tag. + * @param name Tag's name (e.g., "v0.3.9"). + */ + tag: (name: string) => GitRef; + /** + * tags that match any of the given glob patterns. + * @param opts.patterns Glob patterns (e.g., "refs/tags/v*"). + */ + tags: (opts?: GitRepositoryTagsOpts) => Promise; + /** + * Returns the changeset of uncommitted changes in the git repository. + */ + uncommitted: () => Changeset; + /** + * The URL of the git repository. + */ + url: () => Promise; +} +/** + * An internal persistent HTTP state. + */ +declare class HTTPState extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this HTTPState. + */ + id: () => Promise; +} +/** + * Image healthcheck configuration. + */ +declare class HealthcheckConfig extends BaseClient { + private readonly _id?; + private readonly _interval?; + private readonly _retries?; + private readonly _shell?; + private readonly _startInterval?; + private readonly _startPeriod?; + private readonly _timeout?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _interval?: string, _retries?: number, _shell?: boolean, _startInterval?: string, _startPeriod?: string, _timeout?: string); + /** + * A unique identifier for this HealthcheckConfig. + */ + id: () => Promise; + /** + * Healthcheck command arguments. + */ + args: () => Promise; + /** + * Interval between running healthcheck. Example:30s + */ + interval: () => Promise; + /** + * The maximum number of consecutive failures before the container is marked as unhealthy. Example:3 + */ + retries: () => Promise; + /** + * Healthcheck command is a shell command. + */ + shell: () => Promise; + /** + * StartInterval configures the duration between checks during the startup phase. Example:5s + */ + startInterval: () => Promise; + /** + * StartPeriod allows for failures during this initial startup period which do not count towards maximum number of retries. Example:0s + */ + startPeriod: () => Promise; + /** + * Healthcheck timeout. Example:3s + */ + timeout: () => Promise; +} +/** + * Information about the host environment. + */ +declare class Host extends BaseClient { + private readonly _id?; + private readonly _findUp?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _findUp?: string); + /** + * A unique identifier for this Host. + */ + id: () => Promise; + /** + * Accesses a container image on the host. + * @param name Name of the image to access. + */ + containerImage: (name: string) => Container; + /** + * Accesses a directory on the host. + * @param path Location of the directory to access (e.g., "."). + * @param opts.exclude Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + * @param opts.include Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + * @param opts.noCache If true, the directory will always be reloaded from the host. + * @param opts.gitignore Apply .gitignore filter rules inside the directory + */ + directory: (path: string, opts?: HostDirectoryOpts) => Directory; + /** + * Accesses a file on the host. + * @param path Location of the file to retrieve (e.g., "README.md"). + * @param opts.noCache If true, the file will always be reloaded from the host. + */ + file: (path: string, opts?: HostFileOpts) => File; + /** + * Search for a file or directory by walking up the tree from system workdir. Return its relative path. If no match, return null + * @param name name of the file or directory to search for + */ + findUp: (name: string, opts?: HostFindUpOpts) => Promise; + /** + * Creates a service that forwards traffic to a specified address via the host. + * @param ports Ports to expose via the service, forwarding through the host network. + * + * If a port's frontend is unspecified or 0, it defaults to the same as the backend port. + * + * An empty set of ports is not valid; an error will be returned. + * @param opts.host Upstream host to forward traffic to. + */ + service: (ports: PortForward[], opts?: HostServiceOpts) => Service; + /** + * Creates a tunnel that forwards traffic from the host to a service. + * @param service Service to send traffic from the tunnel. + * @param opts.native Map each service port to the same port on the host, as if the service were running natively. + * + * Note: enabling may result in port conflicts. + * @param opts.ports Configure explicit port forwarding rules for the tunnel. + * + * If a port's frontend is unspecified or 0, a random port will be chosen by the host. + * + * If no ports are given, all of the service's ports are forwarded. If native is true, each port maps to the same port on the host. If native is false, each port maps to a random port chosen by the host. + * + * If ports are given and native is true, the ports are additive. + */ + tunnel: (service: Service, opts?: HostTunnelOpts) => Service; + /** + * Accesses a Unix socket on the host. + * @param path Location of the Unix socket (e.g., "/var/run/docker.sock"). + */ + unixSocket: (path: string) => Socket; +} +/** + * A graphql input type, which is essentially just a group of named args. + * This is currently only used to represent pre-existing usage of graphql input types + * in the core API. It is not used by user modules and shouldn't ever be as user + * module accept input objects via their id rather than graphql input types. + */ +declare class InputTypeDef extends BaseClient { + private readonly _id?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string); + /** + * A unique identifier for this InputTypeDef. + */ + id: () => Promise; + /** + * Static fields defined on this input object, if any. + */ + fields: () => Promise; + /** + * The name of the input object. + */ + name: () => Promise; +} +/** + * A definition of a custom interface defined in a Module. + */ +declare class InterfaceTypeDef extends BaseClient { + private readonly _id?; + private readonly _description?; + private readonly _name?; + private readonly _sourceModuleName?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _description?: string, _name?: string, _sourceModuleName?: string); + /** + * A unique identifier for this InterfaceTypeDef. + */ + id: () => Promise; + /** + * The doc string for the interface, if any. + */ + description: () => Promise; + /** + * Functions defined on this interface, if any. + */ + functions: () => Promise; + /** + * The name of the interface. + */ + name: () => Promise; + /** + * The location of this interface declaration. + */ + sourceMap: () => SourceMap; + /** + * If this InterfaceTypeDef is associated with a Module, the name of the module. Unset otherwise. + */ + sourceModuleName: () => Promise; +} +declare class JSONValue extends BaseClient { + private readonly _id?; + private readonly _asBoolean?; + private readonly _asInteger?; + private readonly _asString?; + private readonly _contents?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _asBoolean?: boolean, _asInteger?: number, _asString?: string, _contents?: JSON); + /** + * A unique identifier for this JSONValue. + */ + id: () => Promise; + /** + * Decode an array from json + */ + asArray: () => Promise; + /** + * Decode a boolean from json + */ + asBoolean: () => Promise; + /** + * Decode an integer from json + */ + asInteger: () => Promise; + /** + * Decode a string from json + */ + asString: () => Promise; + /** + * Return the value encoded as json + * @param opts.pretty Pretty-print + * @param opts.indent Optional line prefix + */ + contents: (opts?: JSONValueContentsOpts) => Promise; + /** + * Lookup the field at the given path, and return its value. + * @param path Path of the field to lookup, encoded as an array of field names + */ + field: (path: string[]) => JSONValue; + /** + * List fields of the encoded object + */ + fields: () => Promise; + /** + * Encode a boolean to json + * @param value New boolean value + */ + newBoolean: (value: boolean) => JSONValue; + /** + * Encode an integer to json + * @param value New integer value + */ + newInteger: (value: number) => JSONValue; + /** + * Encode a string to json + * @param value New string value + */ + newString: (value: string) => JSONValue; + /** + * Return a new json value, decoded from the given content + * @param contents New JSON-encoded contents + */ + withContents: (contents: JSON) => JSONValue; + /** + * Set a new field at the given path + * @param path Path of the field to set, encoded as an array of field names + * @param value The new value of the field + */ + withField: (path: string[], value: JSONValue) => JSONValue; + /** + * Call the provided function with current JSONValue. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: JSONValue) => JSONValue) => JSONValue; +} +/** + * A conversation with a large language model (LLM): queue prompts, expose tools, and step the model until it completes its turn. + */ +declare class LLM extends BaseClient { + private readonly _id?; + private readonly _contextWindow?; + private readonly _hasPending?; + private readonly _lastReply?; + private readonly _model?; + private readonly _portableID?; + private readonly _provider?; + private readonly _replay?; + private readonly _sync?; + private readonly _tools?; + private readonly _transcript?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _contextWindow?: number, _hasPending?: boolean, _lastReply?: string, _model?: string, _portableID?: ID, _provider?: string, _replay?: ID, _sync?: ID, _tools?: string, _transcript?: string); + /** + * A unique identifier for this LLM. + */ + id: () => Promise; + /** + * returns the type of the current state + */ + bindResult: (name: string) => Binding; + /** + * The model's total context window in tokens, or null if unknown (e.g. a local or uncatalogued model). + */ + contextWindow: () => Promise; + /** + * return the LLM's current environment + */ + env: () => Env; + /** + * Fork the conversation, so that otherwise-identical follow-ups evaluate independently instead of deduplicating to a single cached result. + * @param label A label distinguishing this fork from its siblings, e.g. "attempt-2" when retrying a flaky evaluation. + */ + fork: (label: string) => LLM; + /** + * Report whether anything is queued to send to the model: an unsent prompt or unevaluated tool results. When true, another step will do work; when false, the turn is complete. + */ + hasPending: () => Promise; + /** + * The text of the model's most recent reply. + */ + lastReply: () => Promise; + /** + * Send the queued prompt and step the model against the available tools, until it ends its turn: a reply with no tool calls and nothing left queued. + * @param opts.maxSteps Cap the number of steps. The loop fails if the cap is reached before the model ends its turn. + * @param opts.maxTokens Cap the model's output tokens on each step. Defaults to the model's maximum. + */ + loop: (opts?: LLMLoopOpts) => LLM; + /** + * The full message history, as structured messages. + */ + messages: () => Promise; + /** + * The model the conversation is running against, after resolving any configured default. + */ + model: () => Promise; + /** + * A portable, self-contained ID for the conversation that node() can resolve in any session. Unlike id, which may return an engine-local runtime handle valid only within the current session, this returns the recipe form suitable for persisting and later restoring the conversation. + */ + portableID: () => Promise; + /** + * The provider serving the model, e.g. "anthropic", "openai", "google", or "local". + */ + provider: () => Promise; + /** + * Re-emit telemetry spans for the full message history, so a loaded conversation displays in the TUI. + */ + replay: () => Promise; + /** + * Advance the conversation by a single step: send the queued prompt or tool results to the model, evaluate any tool calls it makes, and queue their results. Use loop to step until the model ends its turn. + * @param opts.maxTokens Cap the model's output tokens for this step. Defaults to the model's maximum. + */ + step: (opts?: LLMStepOpts) => LLM; + /** + * Force evaluation of the conversation's pending operations (prompts, steps, loops) in the engine. + */ + sync: () => Promise; + /** + * The cumulative token usage, summed across every API call in the conversation. + */ + tokenUsage: () => LLMTokenUsage; + /** + * Render documentation for the tools currently exposed to the model. + */ + tools: () => Promise; + /** + * The message history rendered as a plain-text transcript, suitable for feeding back to an LLM (e.g. for summarization). + */ + transcript: () => Promise; + /** + * Return a new LLM with the specified function no longer exposed as a tool + * @param typeName The type name whose function will be blocked + * @param function The function to block + * + * Will be converted to lowerCamelCase if necessary. + */ + withBlockedFunction: (typeName: string, function_: string) => LLM; + /** + * allow the LLM to interact with an environment via MCP + */ + withEnv: (env: Env) => LLM; + /** + * Add an external MCP server to the LLM + * @param name The name of the MCP server + * @param service The MCP service to run and communicate with over stdio + */ + withMCPServer: (name: string, service: Service) => LLM; + /** + * Change the model for the rest of the conversation. The message history is preserved; the new model takes effect on the next step. + * @param model The model to use, e.g. "claude-sonnet-4-5" or "gpt-5.4". + * @param opts.provider The provider serving the model, e.g. "openai". Overrides the provider otherwise inferred from the model name — useful when the name matches no known pattern (e.g. a fine-tune), or matches the wrong one. + */ + withModel: (model: string, opts?: LLMWithModelOpts) => LLM; + /** + * Track an object so the LLM can reference it in subsequent tool calls. + * @param tag Arbitrary string tag for the object, typically in TypeName#Number format + * @param object The object to track, as a generic ID + */ + withObject: (tag: string, object: ID) => LLM; + /** + * Queue a user prompt, to be sent to the model on the next step or loop. + * @param prompt The prompt to send + */ + withPrompt: (prompt: string) => LLM; + /** + * Queue a file's contents as a user prompt, like withPrompt. + * @param file The file to read the prompt from + */ + withPromptFile: (file: File) => LLM; + /** + * Append an assistant response to the message history without calling the model, e.g. to reconstruct a conversation from another source. + * @param content The response content + * @param opts.inputTokens Uncached input tokens sent + * @param opts.outputTokens Tokens received from the model, including text and tool calls + * @param opts.cachedTokenReads Cached input tokens read + * @param opts.cachedTokenWrites Cached input tokens written + * @param opts.totalTokens Total tokens consumed by this response + */ + withResponse: (content: LLMContentBlockInput[], opts?: LLMWithResponseOpts) => LLM; + /** + * Use a static set of tools for method calls, e.g. for MCP clients that do not support dynamic tool registration + */ + withStaticTools: () => LLM; + /** + * Add a system prompt, instructing the model across the whole conversation. + * @param prompt The system prompt to send + */ + withSystemPrompt: (prompt: string) => LLM; + /** + * Append the result of a tool call to the message history. + * @param callId The ID of the tool call this result responds to + * @param content The content returned by the tool + * @param errored Whether the tool call resulted in an error + */ + withToolResult: (callId: string, content: string, errored: boolean) => LLM; + /** + * Disable the default system prompt + */ + withoutDefaultSystemPrompt: () => LLM; + /** + * Clear the message history, keeping only the system prompts. + */ + withoutMessageHistory: () => LLM; + /** + * Clear the user-added system prompts, keeping only the default system prompt. + */ + withoutSystemPrompts: () => LLM; + /** + * Call the provided function with current LLM. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: LLM) => LLM) => LLM; +} +/** + * A single piece of content within an LLM message. + */ +declare class LLMContentBlock extends BaseClient { + private readonly _id?; + private readonly _arguments?; + private readonly _callId?; + private readonly _errored?; + private readonly _kind?; + private readonly _signature?; + private readonly _text?; + private readonly _toolName?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _arguments?: JSON, _callId?: string, _errored?: boolean, _kind?: LLMContentBlockKind, _signature?: string, _text?: string, _toolName?: string); + /** + * A unique identifier for this LLMContentBlock. + */ + id: () => Promise; + /** + * The arguments passed to the tool, JSON-encoded (for TOOL_CALL kind). + */ + arguments: () => Promise; + /** + * The unique ID of a tool call (for TOOL_CALL or TOOL_RESULT kinds). + */ + callId: () => Promise; + /** + * Whether the tool call resulted in an error (for TOOL_RESULT kind). + */ + errored: () => Promise; + /** + * The kind of content block, which determines the other populated fields. + */ + kind: () => Promise; + /** + * Provider-specific opaque data (e.g. Anthropic thinking signature). Preserve it when reconstructing a conversation. + */ + signature: () => Promise; + /** + * Text content (for TEXT, THINKING, or TOOL_RESULT kinds). + */ + text: () => Promise; + /** + * The name of the tool called (for TOOL_CALL kind). + */ + toolName: () => Promise; +} +/** + * A single message in an LLM conversation. + */ +declare class LLMMessage extends BaseClient { + private readonly _id?; + private readonly _role?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _role?: LLMMessageRole); + /** + * A unique identifier for this LLMMessage. + */ + id: () => Promise; + /** + * The message's content blocks, in the order the model produced them. + */ + content: () => Promise; + /** + * The role that produced this message. + */ + role: () => Promise; + /** + * Token usage reported by the provider for the API call that produced this message; all zeros except on assistant responses. + */ + tokenUsage: () => LLMTokenUsage; +} +/** + * A count of tokens consumed by LLM API calls. + */ +declare class LLMTokenUsage extends BaseClient { + private readonly _id?; + private readonly _cachedTokenReads?; + private readonly _cachedTokenWrites?; + private readonly _inputTokens?; + private readonly _outputTokens?; + private readonly _totalTokens?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _cachedTokenReads?: number, _cachedTokenWrites?: number, _inputTokens?: number, _outputTokens?: number, _totalTokens?: number); + /** + * A unique identifier for this LLMTokenUsage. + */ + id: () => Promise; + /** + * Input tokens served from the provider's prompt cache. + */ + cachedTokenReads: () => Promise; + /** + * Input tokens written to the provider's prompt cache. + */ + cachedTokenWrites: () => Promise; + /** + * Uncached input tokens sent to the model. + */ + inputTokens: () => Promise; + /** + * Tokens received from the model, including text and tool calls. + */ + outputTokens: () => Promise; + /** + * Total tokens consumed, as reported by the provider. + */ + totalTokens: () => Promise; +} +/** + * A simple key value object that represents a label. + */ +declare class Label extends BaseClient { + private readonly _id?; + private readonly _name?; + private readonly _value?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string, _value?: string); + /** + * A unique identifier for this Label. + */ + id: () => Promise; + /** + * The label name. + */ + name: () => Promise; + /** + * The label value. + */ + value: () => Promise; +} +/** + * A definition of a list type in a Module. + */ +declare class ListTypeDef extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this ListTypeDef. + */ + id: () => Promise; + /** + * The type of the elements in the list. + */ + elementTypeDef: () => TypeDef; +} +/** + * A Dagger module. + */ +declare class Module_ extends BaseClient { + private readonly _id?; + private readonly _description?; + private readonly _name?; + private readonly _serve?; + private readonly _sync?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _description?: string, _name?: string, _serve?: Void, _sync?: ID); + /** + * A unique identifier for this Module. + */ + id: () => Promise; + /** + * Return the check defined by the module with the given name. Must match to exactly one check. + * @param name The name of the check to retrieve + * @experimental + */ + check: (name: string) => Check; + /** + * Return all checks defined by the module + * @param opts.include Only include checks matching the specified patterns + * @param opts.noGenerate When true, only return annotated check functions; exclude generate-as-checks + * @experimental + */ + checks: (opts?: ModuleChecksOpts) => CheckGroup; + /** + * The dependencies of the module. + */ + dependencies: () => Promise; + /** + * The doc string of the module, if any + */ + description: () => Promise; + /** + * Enumerations served by this module. + */ + enums: () => Promise; + /** + * The generated files and directories made on top of the module source's context directory. + */ + generatedContextDirectory: () => Directory; + /** + * Return the generator defined by the module with the given name. Must match to exactly one generator. + * @param name The name of the generator to retrieve + * @experimental + */ + generator: (name: string) => Generator; + /** + * Return all generators defined by the module + * @param opts.include Only include generators matching the specified patterns + * @experimental + */ + generators: (opts?: ModuleGeneratorsOpts) => GeneratorGroup; + /** + * Interfaces served by this module. + */ + interfaces: () => Promise; + /** + * The introspection schema JSON file for this module. + * + * This file represents the schema visible to the module's source code, including all core types and those from the dependencies. + * + * Note: this is in the context of a module, so some core types may be hidden. + */ + introspectionSchemaJSON: () => File; + /** + * The name of the module + */ + name: () => Promise; + /** + * Objects served by this module. + */ + objects: () => Promise; + /** + * The container that runs the module's entrypoint. It will fail to execute if the module doesn't compile. + */ + runtime: () => Container; + /** + * The SDK config used by this module. + */ + sdk: () => SDKConfig; + /** + * Serve a module's API in the current session. + * + * Note: this can only be called once per session. In the future, it could return a stream or service to remove the side effect. + * @param opts.includeDependencies Expose the dependencies of this module to the client + * @param opts.entrypoint Install the module as the entrypoint, promoting its main-object methods onto the Query root + */ + serve: (opts?: ModuleServeOpts) => Promise; + /** + * Return all services defined by the module + * @param opts.include Only include services matching the specified patterns + * @experimental + */ + services: (opts?: ModuleServicesOpts) => UpGroup; + /** + * The source for the module. + */ + source: () => ModuleSource; + /** + * Forces evaluation of the module, including any loading into the engine and associated validation. + */ + sync: () => Promise; + /** + * User-defined default values, loaded from local .env files. + */ + userDefaults: () => EnvFile; + /** + * Retrieves the module with the given description + * @param description The description to set + */ + withDescription: (description: string) => Module_; + /** + * This module plus the given Enum type and associated values + */ + withEnum: (enum_: TypeDef) => Module_; + /** + * This module plus the given Interface type and associated functions + */ + withInterface: (iface: TypeDef) => Module_; + /** + * This module plus the given Object type and associated functions. + */ + withObject: (object: TypeDef) => Module_; + /** + * Call the provided function with current Module. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Module_) => Module_) => Module_; +} +/** + * The client generated for the module. + */ +declare class ModuleConfigClient extends BaseClient { + private readonly _id?; + private readonly _directory?; + private readonly _generator?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _directory?: string, _generator?: string); + /** + * A unique identifier for this ModuleConfigClient. + */ + id: () => Promise; + /** + * The directory the client is generated in. + */ + directory: () => Promise; + /** + * The generator to use + */ + generator: () => Promise; +} +/** + * The source needed to load and run a module, along with any metadata about the source such as versions/urls/etc. + */ +declare class ModuleSource extends BaseClient { + private readonly _id?; + private readonly _asString?; + private readonly _cloneRef?; + private readonly _commit?; + private readonly _configExists?; + private readonly _digest?; + private readonly _engineVersion?; + private readonly _htmlRepoURL?; + private readonly _htmlURL?; + private readonly _kind?; + private readonly _localContextDirectoryPath?; + private readonly _moduleName?; + private readonly _moduleOriginalName?; + private readonly _originalSubpath?; + private readonly _pin?; + private readonly _repoRootPath?; + private readonly _sourceRootSubpath?; + private readonly _sourceSubpath?; + private readonly _sync?; + private readonly _version?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _asString?: string, _cloneRef?: string, _commit?: string, _configExists?: boolean, _digest?: string, _engineVersion?: string, _htmlRepoURL?: string, _htmlURL?: string, _kind?: ModuleSourceKind, _localContextDirectoryPath?: string, _moduleName?: string, _moduleOriginalName?: string, _originalSubpath?: string, _pin?: string, _repoRootPath?: string, _sourceRootSubpath?: string, _sourceSubpath?: string, _sync?: ID, _version?: string); + /** + * A unique identifier for this ModuleSource. + */ + id: () => Promise; + /** + * Load the source as a module. If this is a local source, the parent directory must have been provided during module source creation + */ + asModule: () => Module_; + /** + * A human readable ref string representation of this module source. + */ + asString: () => Promise; + /** + * The blueprint referenced by the module source. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in dagger.toml instead. + */ + blueprint: () => ModuleSource; + /** + * The client-facing introspection schema JSON file for this module source. + * + * This is the schema consumed by client codegen: unlike introspectionSchemaJSON (the module-facing schema), it hides no core types and installs this module (reached via dag.) so a generated client can bind it. The module's dependencies are excluded: a client is generated for a single module plus core, not its dependency graph. + */ + clientSchemaIntrospectionJSON: () => File; + /** + * The ref to clone the root of the git repo from. Only valid for git sources. + */ + cloneRef: () => Promise; + /** + * The resolved commit of the git repo this source points to. + */ + commit: () => Promise; + /** + * The clients generated for the module. + */ + configClients: () => Promise; + /** + * Whether an existing module config file was found. + */ + configExists: () => Promise; + /** + * The full directory loaded for the module source, including the source code as a subdirectory. + */ + contextDirectory: () => Directory; + /** + * The dependencies of the module source. + */ + dependencies: () => Promise; + /** + * A content-hash of the module source. Module sources with the same digest will output the same generated context and convert into the same module instance. + */ + digest: () => Promise; + /** + * The directory containing the module configuration and source code (source code may be in a subdir). + * @param path A subpath from the source directory to select. + */ + directory: (path: string) => Directory; + /** + * The engine version of the module. + */ + engineVersion: () => Promise; + /** + * Generate this module's transitive local dependency closure and return the staged changes as a single changeset against the unstaged workspace root. + * + * Each local dependency is generated by its own SDK against a workspace scoped to it, carrying the dependency's own already-generated dependencies. Remote (git) dependencies are assumed committed and skipped. Overlay the result onto the workspace before generating this module; it is not this module's own generated code. + * @param workspace The workspace to generate the local dependencies against. + */ + generateLocalDependencies: (workspace: Workspace) => Changeset; + /** + * The generated files and directories made on top of the module source's context directory, returned as a Changeset. + */ + generatedContextChangeset: () => Changeset; + /** + * The generated files and directories made on top of the module source's context directory. + */ + generatedContextDirectory: () => Directory; + /** + * The URL to access the web view of the repository (e.g., GitHub, GitLab, Bitbucket). + */ + htmlRepoURL: () => Promise; + /** + * The URL to the source's git repo in a web browser. Only valid for git sources. + */ + htmlURL: () => Promise; + /** + * The introspection schema JSON file for this module source. + * + * This file represents the schema visible to the module's source code, including all core types and those from the dependencies. + * + * Note: this is in the context of a module, so some core types may be hidden. + */ + introspectionSchemaJSON: () => File; + /** + * The kind of module source (currently local, git or dir). + */ + kind: () => Promise; + /** + * The full absolute path to the context directory on the caller's host filesystem that this module source is loaded from. Only valid for local module sources. + */ + localContextDirectoryPath: () => Promise; + /** + * The name of the module, including any setting via the withName API. + */ + moduleName: () => Promise; + /** + * The original name of the module as read from the module config file (or set for the first time with the withName API). + */ + moduleOriginalName: () => Promise; + /** + * The original subpath used when instantiating this module source, relative to the context directory. + */ + originalSubpath: () => Promise; + /** + * The pinned version of this module source. + */ + pin: () => Promise; + /** + * The import path corresponding to the root of the git repo this source points to. Only valid for git sources. + */ + repoRootPath: () => Promise; + /** + * The SDK configuration of the module. + */ + sdk: () => SDKConfig; + /** + * The path, relative to the context directory, that contains the module config. + */ + sourceRootSubpath: () => Promise; + /** + * The path to the directory containing the module's source code, relative to the context directory. + */ + sourceSubpath: () => Promise; + /** + * Forces evaluation of the module source, including any loading into the engine and associated validation. + */ + sync: () => Promise; + /** + * The toolchains referenced by the module source. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in dagger.toml instead. + */ + toolchains: () => Promise; + /** + * The module's dagger.json with any in-memory edits from with* APIs applied, as a diff relative to the source's context directory. + * + * Unlike generatedContextDirectory, this does not run codegen and does not validate the engine version against the running engine, so it can be used to declare an engine requirement newer than the running engine. Loading or serving such a module still fails at moduleSource.asModule. + */ + updatedConfigDirectory: () => Directory; + /** + * User-defined defaults read from local .env files + */ + userDefaults: () => EnvFile; + /** + * The specified version of the git repo this source points to. + */ + version: () => Promise; + /** + * Set a blueprint for the module source. + * @param blueprint The blueprint module to set. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in `dagger.toml` instead. + */ + withBlueprint: (blueprint: ModuleSource) => ModuleSource; + /** + * Update the module source with a new client to generate. + * @param generator The generator to use + * @param outputDir The output directory for the generated client. + */ + withClient: (generator: string, outputDir: string) => ModuleSource; + /** + * Append the provided dependencies to the module source's dependency list. + * @param dependencies The dependencies to append. + */ + withDependencies: (dependencies: ModuleSource[]) => ModuleSource; + /** + * Upgrade the engine version of the module to the given value. + * @param version The engine version to upgrade to. + */ + withEngineVersion: (version: string) => ModuleSource; + /** + * Enable the experimental features for the module source. + * @param features The experimental features to enable. + */ + withExperimentalFeatures: (features: ModuleSourceExperimentalFeature[]) => ModuleSource; + /** + * Update the module source with additional include patterns for files+directories from its context that are required for building it + * @param patterns The new additional include patterns. + */ + withIncludes: (patterns: string[]) => ModuleSource; + /** + * Update the module source with a new name. + * @param name The name to set. + */ + withName: (name: string) => ModuleSource; + /** + * Update the module source with a new SDK. + * @param source The SDK source to set. + */ + withSDK: (source: string) => ModuleSource; + /** + * Update the module source with a new source subpath. + * @param path The path to set as the source subpath. Must be relative to the module source's source root directory. + */ + withSourceSubpath: (path: string) => ModuleSource; + /** + * Add toolchains to the module source. + * @param toolchains The toolchain modules to add. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in `dagger.toml` instead. + */ + withToolchains: (toolchains: ModuleSource[]) => ModuleSource; + /** + * Update the blueprint module to the latest version. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in `dagger.toml` instead. + */ + withUpdateBlueprint: () => ModuleSource; + /** + * Update one or more module dependencies. + * @param dependencies The dependencies to update. + */ + withUpdateDependencies: (dependencies: string[]) => ModuleSource; + /** + * Update one or more toolchains. + * @param toolchains The toolchains to update. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in `dagger.toml` instead. + */ + withUpdateToolchains: (toolchains: string[]) => ModuleSource; + /** + * Update one or more clients. + * @param clients The clients to update + */ + withUpdatedClients: (clients: string[]) => ModuleSource; + /** + * Remove the current blueprint from the module source. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in `dagger.toml` instead. + */ + withoutBlueprint: () => ModuleSource; + /** + * Remove a client from the module source. + * @param path The path of the client to remove. + */ + withoutClient: (path: string) => ModuleSource; + /** + * Remove the provided dependencies from the module source's dependency list. + * @param dependencies The dependencies to remove. + */ + withoutDependencies: (dependencies: string[]) => ModuleSource; + /** + * Disable experimental features for the module source. + * @param features The experimental features to disable. + */ + withoutExperimentalFeatures: (features: ModuleSourceExperimentalFeature[]) => ModuleSource; + /** + * Remove the provided toolchains from the module source. + * @param toolchains The toolchains to remove. + * @deprecated Legacy dagger.json field. Generic module loading no longer honors it; use workspace modules in `dagger.toml` instead. + */ + withoutToolchains: (toolchains: string[]) => ModuleSource; + /** + * Call the provided function with current ModuleSource. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: ModuleSource) => ModuleSource) => ModuleSource; +} +/** + * An object with a globally unique ID. + */ +interface Node { + id(): Promise; +} +declare class _NodeClient extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + id: () => Promise; +} +/** + * A definition of a custom object defined in a Module. + */ +declare class ObjectTypeDef extends BaseClient { + private readonly _id?; + private readonly _deprecated?; + private readonly _description?; + private readonly _name?; + private readonly _sourceModuleName?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _deprecated?: string, _description?: string, _name?: string, _sourceModuleName?: string); + /** + * A unique identifier for this ObjectTypeDef. + */ + id: () => Promise; + /** + * The function used to construct new instances of this object, if any. + */ + constructor_: () => Function_; + /** + * The reason this enum member is deprecated, if any. + */ + deprecated: () => Promise; + /** + * The doc string for the object, if any. + */ + description: () => Promise; + /** + * Static fields defined on this object, if any. + */ + fields: () => Promise; + /** + * Functions defined on this object, if any. + */ + functions: () => Promise; + /** + * The name of the object. + */ + name: () => Promise; + /** + * The location of this object declaration. + */ + sourceMap: () => SourceMap; + /** + * If this ObjectTypeDef is associated with a Module, the name of the module. Unset otherwise. + */ + sourceModuleName: () => Promise; +} +/** + * A port exposed by a container. + */ +declare class Port extends BaseClient { + private readonly _id?; + private readonly _description?; + private readonly _experimentalSkipHealthcheck?; + private readonly _port?; + private readonly _protocol?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _description?: string, _experimentalSkipHealthcheck?: boolean, _port?: number, _protocol?: NetworkProtocol); + /** + * A unique identifier for this Port. + */ + id: () => Promise; + /** + * The port description. + */ + description: () => Promise; + /** + * Skip the health check when run as a service. + */ + experimentalSkipHealthcheck: () => Promise; + /** + * The port number. + */ + port: () => Promise; + /** + * The transport layer protocol. + */ + protocol: () => Promise; +} +/** + * The root of the DAG. + */ +declare class Client extends BaseClient { + private readonly _id?; + private readonly _defaultPlatform?; + private readonly _version?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _defaultPlatform?: Platform, _version?: string); + /** + * Get the Raw GraphQL client. + */ + getGQLClient(): graphql_request.GraphQLClient; + /** + * A unique identifier for this Query. + */ + id: () => Promise; + /** + * initialize an address to load directories, containers, secrets or other object types. + */ + address: (value: string) => Address; + /** + * Constructs a cache volume for a given cache key. + * @param key A string identifier to target this cache volume (e.g., "modules-cache"). + * @param opts.source Identifier of the directory to use as the cache volume's root. + * @param opts.sharing Sharing mode of the cache volume. + * @param opts.owner A user:group to set for the cache volume root. + * + * The user and group can either be an ID (1000:1000) or a name (foo:bar). + * + * If the group is omitted, it defaults to the same as the user. + */ + cacheVolume: (key: string, opts?: ClientCacheVolumeOpts) => CacheVolume; + /** + * Creates an empty changeset + */ + changeset: () => Changeset; + /** + * Dagger Cloud configuration and state + */ + cloud: () => Cloud; + /** + * Creates a scratch container, with no image or metadata. + * + * To pull an image, follow up with the "from" function. + * @param opts.platform Platform to initialize the container with. Defaults to the native platform of the current engine + */ + container: (opts?: ClientContainerOpts) => Container; + /** + * Returns the current environment + * + * When called from a function invoked via an LLM tool call, this will be the LLM's current environment, including any modifications made through calling tools. Env values returned by functions become the new environment for subsequent calls, and Changeset values returned by functions are applied to the environment's workspace. + * + * When called from a module function outside of an LLM, this returns an Env with the current module installed, and with the current module's source directory as its workspace. + * @experimental + */ + currentEnv: () => Env; + /** + * The FunctionCall context that the SDK caller is currently executing in. + * + * If the caller is not currently executing in a function, this will return an error. + */ + currentFunctionCall: () => FunctionCall; + /** + * The module currently being served in the session, if any. + */ + currentModule: () => CurrentModule; + /** + * The TypeDef representations of the objects currently being served in the session. + * @param opts.returnAllTypes Return the full referenced typedef closure instead of only top-level served typedefs. + * @param opts.hideCore Strip core API functions from the Query type, leaving only module-sourced functions (constructors, entrypoint proxies, etc.). + * + * Core types (Container, Directory, etc.) are kept so return types and method chaining still work. + */ + currentTypeDefs: (opts?: ClientCurrentTypeDefsOpts) => Promise; + /** + * Detect and return the current workspace. + * @experimental + */ + currentWorkspace: () => Workspace; + /** + * The default platform of the engine. + */ + defaultPlatform: () => Promise; + /** + * Creates an empty directory. + */ + directory: () => Directory; + /** + * The Dagger engine container configuration and state + */ + engine: () => Engine; + /** + * Initializes a new environment + * @param opts.privileged Give the environment the same privileges as the caller: core API including host access, current module, and dependencies + * @param opts.writable Allow new outputs to be declared and saved in the environment + * @experimental + */ + env: (opts?: ClientEnvOpts) => Env; + /** + * Initialize an environment file + * @param opts.expand Replace "${VAR}" or "$VAR" with the value of other vars + */ + envFile: (opts?: ClientEnvFileOpts) => EnvFile; + /** + * Create a new error. + * @param message A brief description of the error. + */ + error: (message: string) => Error$1; + /** + * Creates a file with the specified contents. + * @param name Name of the new file. Example: "foo.txt" + * @param contents Contents of the new file. Example: "Hello world!" + * @param opts.permissions Permissions of the new file. Example: 0600 + */ + file: (name: string, contents: string, opts?: ClientFileOpts) => File; + /** + * Creates a function. + * @param name Name of the function, in its original format from the implementation language. + * @param returnType Return type of the function. + */ + function_: (name: string, returnType: TypeDef) => Function_; + /** + * Create a code generation result, given a directory containing the generated code. + */ + generatedCode: (code: Directory) => GeneratedCode; + /** + * Queries a Git repository. + * @param url URL of the git repository. + * + * Can be formatted as `https://{host}/{owner}/{repo}`, `git@{host}:{owner}/{repo}`. + * + * Suffix ".git" is optional. + * @param opts.keepGitDir DEPRECATED: Set to true to keep .git directory. + * @param opts.sshKnownHosts Set SSH known hosts + * @param opts.sshAuthSocket Set SSH auth socket + * @param opts.httpAuthUsername Username used to populate the password during basic HTTP Authorization + * @param opts.httpAuthToken Secret used to populate the password during basic HTTP Authorization + * @param opts.httpAuthHeader Secret used to populate the Authorization HTTP header + * @param opts.experimentalServiceHost A service which must be started before the repo is fetched. + */ + git: (url: string, opts?: ClientGitOpts) => GitRepository; + /** + * Queries the host environment. + */ + host: () => Host; + /** + * Returns a file containing an http remote url content. + * @param url HTTP url to get the content from (e.g., "https://docs.dagger.io"). + * @param opts.name File name to use for the file. Defaults to the last part of the URL. + * @param opts.permissions Permissions to set on the file. + * @param opts.checksum Expected digest of the downloaded content (e.g., "sha256:..."). + * @param opts.authHeader Secret used to populate the Authorization HTTP header + * @param opts.experimentalServiceHost A service which must be started before the URL is fetched. + */ + http: (url: string, opts?: ClientHttpOpts) => File; + /** + * Initialize a JSON value + */ + json: () => JSONValue; + /** + * Initialize a new LLM conversation. + * @param opts.model The model to converse with, e.g. "claude-sonnet-4-5" or "gpt-5.4". Defaults to the configured default model. + * @param opts.provider The provider serving the model, e.g. "openai". Overrides the provider otherwise inferred from the model name — useful when the name matches no known pattern (e.g. a fine-tune), or matches the wrong one. + * @experimental + */ + llm: (opts?: ClientLLMOpts) => LLM; + /** + * Create a new module. + */ + module_: () => Module_; + /** + * Create a new module source instance from a source ref string + * @param refString The string ref representation of the module source + * @param opts.refPin The pinned version of the module source + * @param opts.disableFindUp If true, do not attempt to find a module config file in a parent directory of the provided path. Only relevant for local module sources. + * @param opts.allowNotExists If true, do not error out if the provided ref string is a local path and does not exist yet. Useful when initializing new modules in directories that don't exist yet. + * @param opts.requireKind If set, error out if the ref string is not of the provided requireKind. + */ + moduleSource: (refString: string, opts?: ClientModuleSourceOpts) => ModuleSource; + /** + * Load any object by its ID. + */ + node: (id: ID) => Node; + /** + * Load a GraphQL introspection schema for merging. + * @param json The introspection schema JSON to load. + */ + schema: (json: JSON) => Schema; + /** + * Creates a new secret. + * @param uri The URI of the secret store + * @param opts.cacheKey If set, the given string will be used as the cache key for this secret. This means that any secrets with the same cache key will be considered equivalent in terms of cache lookups, even if they have different URIs or plaintext values. + * + * For example, two secrets with the same cache key provided as secret env vars to other wise equivalent containers will result in the container withExecs hitting the cache for each other. + * + * If not set, the cache key for the secret will be derived from its plaintext value as looked up when the secret is constructed. + */ + secret: (uri: string, opts?: ClientSecretOpts) => Secret; + /** + * Sets a secret given a user defined name to its plaintext and returns the secret. + * + * The plaintext value is limited to a size of 128000 bytes. + * @param name The user defined name for this secret + * @param plaintext The plaintext of the secret + */ + setSecret: (name: string, plaintext: string) => Secret; + /** + * Creates source map metadata. + * @param filename The filename from the module source. + * @param line The line number within the filename. + * @param column The column number within the line. + */ + sourceMap: (filename: string, line: number, column: number) => SourceMap; + /** + * Constructs an SSHFS volume. + * @param endpoint SSHFS endpoint URL in the form sshfs://user@host[:port]/absolute/path. + * @param privateKey Private key secret used to authenticate to the remote host. + * @param opts.knownHosts known_hosts material used to verify the remote host key. Required unless insecureSkipHostKeyCheck is true. + * @param opts.cacheKey Optional cache equivalence key. If set, volumes with the same cacheKey may be considered equivalent for cache lookups, still subject to their resource dependencies. + * @param opts.insecureSkipHostKeyCheck Disable SSH host key verification. This is insecure and must be explicitly opted into. + * @param opts.experimentalServiceHost Service to use as the SSHFS network endpoint while verifying the original host key. + */ + sshfsVolume: (endpoint: string, privateKey: Secret, opts?: ClientSshfsVolumeOpts) => Volume; + /** + * Create a new TypeDef. + */ + typeDef: () => TypeDef; + /** + * Get the current Dagger Engine version. + */ + version: () => Promise; +} +/** + * An internal persistent bare git mirror. + */ +declare class RemoteGitMirror extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this RemoteGitMirror. + */ + id: () => Promise; +} +/** + * The SDK config of the module. + */ +declare class SDKConfig extends BaseClient { + private readonly _id?; + private readonly _debug?; + private readonly _source?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _debug?: boolean, _source?: string); + /** + * A unique identifier for this SDKConfig. + */ + id: () => Promise; + /** + * Whether to start the SDK runtime in debug mode with an interactive terminal. + */ + debug: () => Promise; + /** + * Source of the SDK. Either a name of a builtin SDK or a module source ref string pointing to the SDK's implementation. + */ + source: () => Promise; +} +/** + * A definition of a custom scalar defined in a Module. + */ +declare class ScalarTypeDef extends BaseClient { + private readonly _id?; + private readonly _description?; + private readonly _name?; + private readonly _sourceModuleName?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _description?: string, _name?: string, _sourceModuleName?: string); + /** + * A unique identifier for this ScalarTypeDef. + */ + id: () => Promise; + /** + * A doc string for the scalar, if any. + */ + description: () => Promise; + /** + * The name of the scalar. + */ + name: () => Promise; + /** + * If this ScalarTypeDef is associated with a Module, the name of the module. Unset otherwise. + */ + sourceModuleName: () => Promise; +} +/** + * A GraphQL introspection schema that can be inspected and merged. + */ +declare class Schema extends BaseClient { + private readonly _id?; + private readonly _contents?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _contents?: JSON); + /** + * A unique identifier for this Schema. + */ + id: () => Promise; + /** + * Serialize the schema back to introspection JSON. + */ + contents: () => Promise; + /** + * Merge a module's introspection-shaped type definitions into the schema, returning the combined schema. + * @param moduleTypes Introspection JSON describing the types the module defines. Object, interface and enum types are appended to the schema, and a constructor field for the module is added to the Query type. + * @param moduleName The name of the module whose types are being merged. Used to stamp the @sourceMap directive and to derive the module's constructor field. + */ + merge: (moduleTypes: JSON, moduleName: string) => Schema; + /** + * Call the provided function with current Schema. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Schema) => Schema) => Schema; +} +declare class SearchResult extends BaseClient { + private readonly _id?; + private readonly _absoluteOffset?; + private readonly _filePath?; + private readonly _lineNumber?; + private readonly _matchedLines?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _absoluteOffset?: number, _filePath?: string, _lineNumber?: number, _matchedLines?: string); + /** + * A unique identifier for this SearchResult. + */ + id: () => Promise; + /** + * The byte offset of this line within the file. + */ + absoluteOffset: () => Promise; + /** + * The path to the file that matched. + */ + filePath: () => Promise; + /** + * The first line that matched. + */ + lineNumber: () => Promise; + /** + * The line content that matched. + */ + matchedLines: () => Promise; + /** + * Sub-match positions and content within the matched lines. + */ + submatches: () => Promise; +} +declare class SearchSubmatch extends BaseClient { + private readonly _id?; + private readonly _end?; + private readonly _start?; + private readonly _text?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _end?: number, _start?: number, _text?: string); + /** + * A unique identifier for this SearchSubmatch. + */ + id: () => Promise; + /** + * The match's end offset within the matched lines. + */ + end: () => Promise; + /** + * The match's start offset within the matched lines. + */ + start: () => Promise; + /** + * The matched text. + */ + text: () => Promise; +} +/** + * A reference to a secret value, which can be handled more safely than the value itself. + */ +declare class Secret extends BaseClient { + private readonly _id?; + private readonly _name?; + private readonly _plaintext?; + private readonly _uri?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string, _plaintext?: string, _uri?: string); + /** + * A unique identifier for this Secret. + */ + id: () => Promise; + /** + * The name of this secret. + */ + name: () => Promise; + /** + * The value of this secret. + */ + plaintext: () => Promise; + /** + * The URI of this secret. + */ + uri: () => Promise; +} +/** + * A content-addressed service providing TCP connectivity. + */ +declare class Service extends BaseClient { + private readonly _id?; + private readonly _endpoint?; + private readonly _hostname?; + private readonly _start?; + private readonly _stop?; + private readonly _sync?; + private readonly _up?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _endpoint?: string, _hostname?: string, _start?: ID, _stop?: ID, _sync?: ID, _up?: Void); + /** + * A unique identifier for this Service. + */ + id: () => Promise; + /** + * Retrieves an endpoint that clients can use to reach this container. + * + * If no port is specified, the first exposed port is used. If none exist an error is returned. + * + * If a scheme is specified, a URL is returned. Otherwise, a host:port pair is returned. + * @param opts.port The exposed port number for the endpoint + * @param opts.scheme Return a URL with the given scheme, eg. http for http:// + */ + endpoint: (opts?: ServiceEndpointOpts) => Promise; + /** + * Retrieves a hostname which can be used by clients to reach this container. + */ + hostname: () => Promise; + /** + * Retrieves the list of ports provided by the service. + */ + ports: () => Promise; + /** + * Start the service and wait for its health checks to succeed. + * + * Services bound to a Container do not need to be manually started. + */ + start: () => Promise; + /** + * Stop the service. + * @param opts.kill Immediately kill the service without waiting for a graceful exit + */ + stop: (opts?: ServiceStopOpts) => Promise; + /** + * Forces evaluation of the pipeline in the engine. + */ + sync: () => Promise; + terminal: (opts?: ServiceTerminalOpts) => Service; + /** + * Creates a tunnel that forwards traffic from the caller's network to this service. + * @param opts.ports List of frontend/backend port mappings to forward. + * + * Frontend is the port accepting traffic on the host, backend is the service port. + * @param opts.random Bind each tunnel port to a random port on the host. + */ + up: (opts?: ServiceUpOpts) => Promise; + /** + * Configures a hostname which can be used by clients within the session to reach this container. + * @param hostname The hostname to use. + */ + withHostname: (hostname: string) => Service; + /** + * Call the provided function with current Service. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Service) => Service) => Service; +} +/** + * A Unix or TCP/IP socket that can be mounted into a container. + */ +declare class Socket extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this Socket. + */ + id: () => Promise; +} +/** + * Source location information. + */ +declare class SourceMap extends BaseClient { + private readonly _id?; + private readonly _column?; + private readonly _filename?; + private readonly _line?; + private readonly _module?; + private readonly _url?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _column?: number, _filename?: string, _line?: number, _module?: string, _url?: string); + /** + * A unique identifier for this SourceMap. + */ + id: () => Promise; + /** + * The column number within the line. + */ + column: () => Promise; + /** + * The filename from the module source. + */ + filename: () => Promise; + /** + * The line number within the filename. + */ + line: () => Promise; + /** + * The module dependency this was declared in. + */ + module_: () => Promise; + /** + * The URL to the file, if any. This can be used to link to the source map in the browser. + */ + url: () => Promise; +} +/** + * A file or directory status object. + */ +declare class Stat extends BaseClient { + private readonly _id?; + private readonly _fileType?; + private readonly _name?; + private readonly _permissions?; + private readonly _size?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _fileType?: FileType, _name?: string, _permissions?: number, _size?: number); + /** + * A unique identifier for this Stat. + */ + id: () => Promise; + /** + * file type + */ + fileType: () => Promise; + /** + * file name + */ + name: () => Promise; + /** + * permission bits + */ + permissions: () => Promise; + /** + * file size + */ + size: () => Promise; +} +/** + * An object that can be force-evaluated. + * + * Calling sync ensures that the object's entire dependency DAG has been evaluated, returning the object's ID once complete. + */ +interface Syncer { + id(): Promise; + sync(): Promise; +} +declare class _SyncerClient extends BaseClient { + private readonly _id?; + private readonly _sync?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _sync?: ID); + id: () => Promise; + sync: () => Promise; +} +/** + * An interactive terminal that clients can connect to. + */ +declare class Terminal extends BaseClient { + private readonly _id?; + private readonly _sync?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _sync?: ID); + /** + * A unique identifier for this Terminal. + */ + id: () => Promise; + /** + * Forces evaluation of the pipeline in the engine. + * + * It doesn't run the default command if no exec has been set. + */ + sync: () => Promise; +} +/** + * A definition of a parameter or return type in a Module. + */ +declare class TypeDef extends BaseClient { + private readonly _id?; + private readonly _kind?; + private readonly _name?; + private readonly _optional?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _kind?: TypeDefKind, _name?: string, _optional?: boolean); + /** + * A unique identifier for this TypeDef. + */ + id: () => Promise; + /** + * If kind is ENUM, the enum-specific type definition. If kind is not ENUM, this will be null. + */ + asEnum: () => EnumTypeDef; + /** + * If kind is INPUT, the input-specific type definition. If kind is not INPUT, this will be null. + */ + asInput: () => InputTypeDef; + /** + * If kind is INTERFACE, the interface-specific type definition. If kind is not INTERFACE, this will be null. + */ + asInterface: () => InterfaceTypeDef; + /** + * If kind is LIST, the list-specific type definition. If kind is not LIST, this will be null. + */ + asList: () => ListTypeDef; + /** + * If kind is OBJECT, the object-specific type definition. If kind is not OBJECT, this will be null. + */ + asObject: () => ObjectTypeDef; + /** + * If kind is SCALAR, the scalar-specific type definition. If kind is not SCALAR, this will be null. + */ + asScalar: () => ScalarTypeDef; + /** + * The kind of type this is (e.g. primitive, list, object). + */ + kind: () => Promise; + /** + * The canonical non-optional name of the type. + */ + name: () => Promise; + /** + * Whether this type can be set to null. Defaults to false. + */ + optional: () => Promise; + /** + * Adds a function for constructing a new instance of an Object TypeDef, failing if the type is not an object. + */ + withConstructor: (function_: Function_) => TypeDef; + /** + * Returns a TypeDef of kind Enum with the provided name. + * + * Note that an enum's values may be omitted if the intent is only to refer to an enum. This is how functions are able to return their own, or any other circular reference. + * @param name The name of the enum + * @param opts.description A doc string for the enum, if any + * @param opts.sourceMap The source map for the enum definition. + */ + withEnum: (name: string, opts?: TypeDefWithEnumOpts) => TypeDef; + /** + * Adds a static value for an Enum TypeDef, failing if the type is not an enum. + * @param name The name of the member in the enum + * @param opts.value The value of the member in the enum + * @param opts.description A doc string for the member, if any + * @param opts.sourceMap The source map for the enum member definition. + * @param opts.deprecated If deprecated, the reason or migration path. + */ + withEnumMember: (name: string, opts?: TypeDefWithEnumMemberOpts) => TypeDef; + /** + * Adds a static value for an Enum TypeDef, failing if the type is not an enum. + * @param value The name of the value in the enum + * @param opts.description A doc string for the value, if any + * @param opts.sourceMap The source map for the enum value definition. + * @param opts.deprecated If deprecated, the reason or migration path. + * @deprecated Use withEnumMember instead + */ + withEnumValue: (value: string, opts?: TypeDefWithEnumValueOpts) => TypeDef; + /** + * Adds a static field for an Object TypeDef, failing if the type is not an object. + * @param name The name of the field in the object + * @param typeDef The type of the field + * @param opts.description A doc string for the field, if any + * @param opts.sourceMap The source map for the field definition. + * @param opts.deprecated If deprecated, the reason or migration path. + */ + withField: (name: string, typeDef: TypeDef, opts?: TypeDefWithFieldOpts) => TypeDef; + /** + * Adds a function for an Object or Interface TypeDef, failing if the type is not one of those kinds. + */ + withFunction: (function_: Function_) => TypeDef; + /** + * Returns a TypeDef of kind Interface with the provided name. + */ + withInterface: (name: string, opts?: TypeDefWithInterfaceOpts) => TypeDef; + /** + * Sets the kind of the type. + */ + withKind: (kind: TypeDefKind) => TypeDef; + /** + * Returns a TypeDef of kind List with the provided type for its elements. + */ + withListOf: (elementType: TypeDef) => TypeDef; + /** + * Returns a TypeDef of kind Object with the provided name. + * + * Note that an object's fields and functions may be omitted if the intent is only to refer to an object. This is how functions are able to return their own object, or any other circular reference. + */ + withObject: (name: string, opts?: TypeDefWithObjectOpts) => TypeDef; + /** + * Sets whether this type can be set to null. + */ + withOptional: (optional: boolean) => TypeDef; + /** + * Returns a TypeDef of kind Scalar with the provided name. + */ + withScalar: (name: string, opts?: TypeDefWithScalarOpts) => TypeDef; + /** + * Call the provided function with current TypeDef. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: TypeDef) => TypeDef) => TypeDef; +} +declare class Up extends BaseClient { + private readonly _id?; + private readonly _description?; + private readonly _name?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _description?: string, _name?: string); + /** + * A unique identifier for this Up. + */ + id: () => Promise; + /** + * The description of the service + */ + description: () => Promise; + /** + * Return the fully qualified name of the service + */ + name: () => Promise; + /** + * The original module in which the service has been defined + */ + originalModule: () => Module_; + /** + * The path of the service within its module + */ + path: () => Promise; + /** + * Execute the service function + */ + run: () => Up; + /** + * Call the provided function with current Up. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Up) => Up) => Up; +} +declare class UpGroup extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this UpGroup. + */ + id: () => Promise; + /** + * Return a list of individual services and their details + */ + list: () => Promise; + /** + * Execute all selected service functions + */ + run: () => UpGroup; + /** + * Call the provided function with current UpGroup. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: UpGroup) => UpGroup) => UpGroup; +} +/** + * A filesystem volume that can be mounted into containers. + */ +declare class Volume extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this Volume. + */ + id: () => Promise; +} +/** + * A Dagger workspace detected from the current working directory or constructed from a Directory. + */ +declare class Workspace extends BaseClient { + private readonly _id?; + private readonly _address?; + private readonly _configFile?; + private readonly _configRead?; + private readonly _cwd?; + private readonly _export?; + private readonly _findUp?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _address?: string, _configFile?: string, _configRead?: string, _cwd?: string, _export?: Void, _findUp?: string); + /** + * A unique identifier for this Workspace. + */ + id: () => Promise; + /** + * Canonical Dagger address of the workspace location, or an opaque identity for synthetic workspaces. + */ + address: () => Promise; + /** + * Return this workspace's pending overlay changes. + */ + changes: () => Changeset; + /** + * Return all checks from modules loaded in the workspace. + * @param opts.include Only include checks matching the specified patterns + * @param opts.skip Skip checks matching the specified patterns + * @param opts.noGenerate When true, only return annotated check functions; exclude generate-as-checks + * @param opts.onlyGenerate When true, only return generate-as-checks; exclude annotated check functions + */ + checks: (opts?: WorkspaceChecksOpts) => CheckGroup; + /** + * Selected native workspace config file relative to the workspace cwd, if any. + */ + configFile: () => Promise; + /** + * Read a configuration value from dagger.toml. + * + * If key is empty, returns the full config. + * + * If key points to a scalar, returns the value. + * + * If key points to a table, returns flattened dotted-key output. + * @param opts.key Dotted key path (e.g. modules.greeter.source). Empty for full config. + */ + configRead: (opts?: WorkspaceConfigReadOpts) => Promise; + /** + * Current location within the workspace root. + * + * The workspace root is returned as "/". + * + * Relative paths in workspace APIs resolve from here. + */ + cwd: () => Promise; + /** + * Returns a Directory from the workspace. + * + * Relative paths resolve from the workspace cwd. Absolute paths resolve from the workspace root. + * @param path Location of the directory to retrieve. Relative paths (e.g., "src") resolve from the workspace cwd; absolute paths (e.g., "/src") resolve from the workspace root. + * @param opts.exclude Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]). + * @param opts.include Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]). + * @param opts.gitignore Apply .gitignore filter rules inside the directory. + */ + directory: (path: string, opts?: WorkspaceDirectoryOpts) => Directory; + /** + * List named environments defined in the workspace configuration. + */ + envList: () => Promise; + /** + * Write this workspace's pending changes to its local Git workspace. + */ + export: () => Promise; + /** + * Returns a File from the workspace. + * + * Relative paths resolve from the workspace cwd. Absolute paths resolve from the workspace root. + * @param path Location of the file to retrieve. Relative paths (e.g., "go.mod") resolve from the workspace cwd; absolute paths (e.g., "/go.mod") resolve from the workspace root. + */ + file: (path: string) => File; + /** + * Search for a file or directory by walking up from the start path within the workspace. + * + * Returns the absolute workspace path if found, or null if not found. + * + * Relative start paths resolve from the workspace cwd. + * + * The search stops at the workspace root and will not traverse above it. + * @param name The name of the file or directory to search for. + * @param opts.from Path to start the search from. Relative paths resolve from the workspace cwd; absolute paths resolve from the workspace root. + */ + findUp: (name: string, opts?: WorkspaceFindUpOpts) => Promise; + /** + * Return all generators from modules loaded in the workspace. + * @param opts.include Only include generators matching the specified patterns + */ + generators: (opts?: WorkspaceGeneratorsOpts) => GeneratorGroup; + /** + * Git state for this workspace. Errors if the workspace is not in a git repository. + */ + git: () => WorkspaceGit; + /** + * Returns a list of files and directories that match the given pattern. + * + * Patterns match paths relative to the workspace root. + * @param pattern Pattern to match (e.g., "*.md"). + */ + glob: (pattern: string) => Promise; + /** + * Plan the explicit migration needed for the current workspace. + * + * The returned plan has an empty changeset and no steps when no migration is needed. + */ + migrate: () => WorkspaceMigration; + /** + * Return a module defined in the workspace configuration. + * @param name Module name to inspect. + */ + module_: (name: string) => WorkspaceModule; + /** + * Load a module source from a path within the workspace. + * + * Relative paths (e.g., "foo") resolve from the workspace cwd; absolute paths (e.g., "/foo") resolve from the workspace root. + * + * Fails if the path does not point to an initialized module. + * @param path Location of the module source to load, relative to the workspace cwd or absolute from the workspace root. + */ + moduleSource: (path: string) => ModuleSource; + /** + * List modules defined in the workspace configuration. + */ + modules: () => Promise; + /** + * An installed SDK, by name. + * @param name SDK name to look up. + */ + sdk: (name: string) => WorkspaceSDK; + /** + * Installed SDKs. + */ + sdks: () => Promise; + /** + * Searches for content matching the given regular expression or literal string. + * + * Uses Rust regex syntax; escape literal ., [, ], {, }, | with backslashes. + * + * Runs ripgrep on the client host, falling back to grep if unavailable. + * @param opts.paths Directory or file paths to search + * @param opts.globs Glob patterns to match (e.g., "*.md") + * @param opts.pattern The text to match. + * @param opts.literal Interpret the pattern as a literal string instead of a regular expression. + * @param opts.multiline Enable searching across multiple lines. + * @param opts.dotall Allow the . pattern to match newlines in multiline mode. + * @param opts.insensitive Enable case-insensitive matching. + * @param opts.skipIgnored Honor .gitignore, .ignore, and .rgignore files. + * @param opts.skipHidden Skip hidden files (files starting with .). + * @param opts.filesOnly Only return matching files, not lines and content + * @param opts.limit Limit the number of results to return + */ + search: (opts?: WorkspaceSearchOpts) => Promise; + /** + * Return all services from modules loaded in the workspace. + * @param opts.include Only include services matching the specified patterns + */ + services: (opts?: WorkspaceServicesOpts) => UpGroup; + /** + * Return this workspace with a changeset applied, without mutating the source. + * @param changes Changes to apply. + */ + withChanges: (changes: Changeset) => Workspace; + /** + * Return this workspace with a named config environment created. + * @param name Environment name. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withConfigEnv: (name: string, opts?: WorkspaceWithConfigEnvOpts) => Workspace; + /** + * Return this workspace with a configuration value written. + * @param key Dotted key path. + * @param value Value to set. Bools, integers, and comma-separated arrays are auto-detected. + * @param opts.values List value to set. Elements are stored verbatim, with no auto-detection. Mutually exclusive with value. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withConfigValue: (key: string, value: string, opts?: WorkspaceWithConfigValueOpts) => Workspace; + /** + * Return this workspace with a generated API client initialized. + * @param path Workspace-relative output directory for the generated client. + * @param sdk Workspace SDK name or module entry name to use. + * @param module Workspace-relative path or canonical ref for the module the client binds to. + * @param opts.args SDK-specific init arguments. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withInitClient: (path: string, sdk: string, module_: string, opts?: WorkspaceWithInitClientOpts) => Workspace; + /** + * Return this workspace with a new module initialized. + * @param name Name of the new module. + * @param sdk Workspace SDK name or module entry name to use. + * @param opts.path Workspace-relative path for the new module. + * @param opts.source Source subpath within the new module. + * @param opts.include Additional include patterns for the module. + * @param opts.args SDK-specific init arguments. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withInitModule: (name: string, sdk: string, opts?: WorkspaceWithInitModuleOpts) => Workspace; + /** + * Return this workspace with a module installed in its config. + * @param ref Module reference to install. + * @param opts.name Override name for the installed module entry. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withModule: (ref: string, opts?: WorkspaceWithModuleOpts) => Workspace; + /** + * Return this workspace with a directory added, without mutating the source. + * @param path Path of the added directory. Relative paths resolve from the workspace cwd. + * @param source Directory to add. + */ + withNewDirectory: (path: string, source: Directory) => Workspace; + /** + * Return this workspace with a new or replaced file, without mutating the source. + * @param path Path of the new file. Relative paths resolve from the workspace cwd. + * @param contents Contents of the new file. + * @param opts.permissions Permissions of the new file. + */ + withNewFile: (path: string, contents: string, opts?: WorkspaceWithNewFileOpts) => Workspace; + /** + * Return this workspace with an SDK installed in its config. + * @param ref SDK module reference to install. + * @param opts.name Override name for the installed SDK entry. + * @param opts.here Write to the workspace config directory at the workspace cwd. + * @param opts.asSdkName User-facing SDK name to persist under `[modules..as-sdk] name = ...`. + */ + withSDK: (ref: string, opts?: WorkspaceWithSdkOpts) => Workspace; + /** + * Return this workspace with refreshed lockfile state. + */ + withUpdatedLock: () => Workspace; + /** + * Return this workspace with its working directory pointed at the given workspace-relative path. + * @param path Workspace-relative path to use as the working directory. + */ + withWorkdir: (path: string) => Workspace; + /** + * Return this workspace with a named config environment removed. + * @param name Environment name. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withoutConfigEnv: (name: string, opts?: WorkspaceWithoutConfigEnvOpts) => Workspace; + /** + * Return this workspace with a configuration value removed. + * + * Errors when the key is not currently set. + * @param key Dotted key path (e.g. modules.greeter.settings.greeting). + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withoutConfigValue: (key: string, opts?: WorkspaceWithoutConfigValueOpts) => Workspace; + /** + * Return this workspace with a module removed from its config. + * @param name Name of the installed module entry to remove. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withoutModule: (name: string, opts?: WorkspaceWithoutModuleOpts) => Workspace; + /** + * Return this workspace with an SDK removed from its config. + * @param name Name of the installed SDK entry to remove. + * @param opts.here Write to the workspace config directory at the workspace cwd. + */ + withoutSDK: (name: string, opts?: WorkspaceWithoutSdkOpts) => Workspace; + /** + * Call the provided function with current Workspace. + * + * This is useful for reusability and readability by not breaking the calling chain. + */ + with: (arg: (param: Workspace) => Workspace) => Workspace; +} +/** + * Local git state for a workspace. + */ +declare class WorkspaceGit extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this WorkspaceGit. + */ + id: () => Promise; + /** + * The checked-out HEAD of this workspace. + */ + head: () => GitRef; + /** + * Uncommitted changes in this workspace, using the same rules as GitRepository.uncommitted. + */ + uncommitted: () => Changeset; +} +/** + * A planned workspace migration. + */ +declare class WorkspaceMigration extends BaseClient { + private readonly _id?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID); + /** + * A unique identifier for this WorkspaceMigration. + */ + id: () => Promise; + /** + * Filesystem changes for the full migration plan. + */ + changes: () => Changeset; + /** + * Logical migration steps, each identified by a stable code. + */ + steps: () => Promise; +} +/** + * A single logical part of a workspace migration. + */ +declare class WorkspaceMigrationStep extends BaseClient { + private readonly _id?; + private readonly _code?; + private readonly _description?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _code?: string, _description?: string); + /** + * A unique identifier for this WorkspaceMigrationStep. + */ + id: () => Promise; + /** + * Filesystem changes for this step. + */ + changes: () => Changeset; + /** + * Stable code identifying this logical migration step. + */ + code: () => Promise; + /** + * Generic summary of this step's purpose and impact. + */ + description: () => Promise; + /** + * Non-fatal warnings raised while planning this step. + */ + warnings: () => Promise; +} +/** + * A module entry in the workspace configuration. + */ +declare class WorkspaceModule extends BaseClient { + private readonly _id?; + private readonly _entrypoint?; + private readonly _name?; + private readonly _source?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _entrypoint?: boolean, _name?: string, _source?: string); + /** + * A unique identifier for this WorkspaceModule. + */ + id: () => Promise; + /** + * Whether the module is the workspace entrypoint (functions aliased to Query root). + */ + entrypoint: () => Promise; + /** + * The module name. + */ + name: () => Promise; + /** + * List constructor-backed settings for this module. + */ + settings: () => Promise; + /** + * The module source path. + */ + source: () => Promise; +} +/** + * A constructor-backed module setting. + */ +declare class WorkspaceModuleSetting extends BaseClient { + private readonly _id?; + private readonly _description?; + private readonly _isList?; + private readonly _key?; + private readonly _value?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _description?: string, _isList?: boolean, _key?: string, _value?: string); + /** + * A unique identifier for this WorkspaceModuleSetting. + */ + id: () => Promise; + /** + * The constructor argument description. + */ + description: () => Promise; + /** + * Whether the setting accepts a list of values. + */ + isList: () => Promise; + /** + * The setting key. + */ + key: () => Promise; + /** + * The configured value after applying the selected workspace environment, or empty when unset. + */ + value: () => Promise; +} +/** + * An installed SDK: a module marked for scaffolding other modules and clients. + */ +declare class WorkspaceSDK extends BaseClient { + private readonly _id?; + private readonly _name?; + private readonly _ref?; + /** + * Constructor is used for internal usage only, do not create object from it. + */ + constructor(ctx?: Context, _id?: ID, _name?: string, _ref?: string); + /** + * A unique identifier for this WorkspaceSDK. + */ + id: () => Promise; + /** + * Clients generated with this SDK. + */ + clients: () => Promise; + /** + * Modules authored with this SDK. + */ + modules: () => Promise; + /** + * The user-facing SDK name. + */ + name: () => Promise; + /** + * The module reference this SDK was installed from. + */ + ref: () => Promise; +} +declare const dag: Client; + +declare const ERROR_CODES: { + /** + * {@link GraphQLRequestError} + */ + readonly GraphQLRequestError: "D100"; + /** + * {@link UnknownDaggerError} + */ + readonly UnknownDaggerError: "D101"; + /** + * {@link TooManyNestedObjectsError} + */ + readonly TooManyNestedObjectsError: "D102"; + /** + * {@link EngineSessionConnectParamsParseError} + */ + readonly EngineSessionConnectParamsParseError: "D103"; + /** + * {@link EngineSessionConnectionTimeoutError} + */ + readonly EngineSessionConnectionTimeoutError: "D104"; + /** + * {@link EngineSessionError} + */ + readonly EngineSessionError: "D105"; + /** + * {@link InitEngineSessionBinaryError} + */ + readonly InitEngineSessionBinaryError: "D106"; + /** + * {@link DockerImageRefValidationError} + */ + readonly DockerImageRefValidationError: "D107"; + /** + * {@link NotAwaitedRequestError} + */ + readonly NotAwaitedRequestError: "D108"; + /** + * (@link ExecError} + */ + readonly ExecError: "D109"; + /** + * {@link IntrospectionError} + */ + readonly IntrospectionError: "D110"; +}; +type ErrorCodesType = typeof ERROR_CODES; +type ErrorNames = keyof ErrorCodesType; +type ErrorCodes = ErrorCodesType[ErrorNames]; + +interface DaggerSDKErrorOptions { + cause?: Error; +} +/** + * The base error. Every other error inherits this error. + */ +declare abstract class DaggerSDKError extends Error { + /** + * The name of the dagger error. + */ + abstract readonly name: ErrorNames; + /** + * The dagger specific error code. + * Use this to identify dagger errors programmatically. + */ + abstract readonly code: ErrorCodes; + /** + * The original error, which caused the DaggerSDKError. + */ + cause?: Error; + protected constructor(message: string, options?: DaggerSDKErrorOptions); + /** + * @hidden + */ + get [Symbol.toStringTag](): "DockerImageRefValidationError" | "EngineSessionConnectParamsParseError" | "EngineSessionConnectionTimeoutError" | "EngineSessionError" | "ExecError" | "GraphQLRequestError" | "InitEngineSessionBinaryError" | "IntrospectionError" | "NotAwaitedRequestError" | "TooManyNestedObjectsError" | "UnknownDaggerError"; + /** + * Pretty prints the error + */ + printStackTrace(): void; +} + +/** + * This error is thrown if the dagger SDK does not identify the error and just wraps the cause. + */ +declare class UnknownDaggerError extends DaggerSDKError { + name: "UnknownDaggerError"; + code: "D101"; + /** + * @hidden + */ + constructor(message: string, options: DaggerSDKErrorOptions); +} + +interface DockerImageRefValidationErrorOptions extends DaggerSDKErrorOptions { + ref: string; +} +/** + * This error is thrown if the passed image reference does not pass validation and is not compliant with the + * DockerImage constructor. + */ +declare class DockerImageRefValidationError extends DaggerSDKError { + name: "DockerImageRefValidationError"; + code: "D107"; + /** + * The docker image reference, which caused the error. + */ + ref: string; + /** + * @hidden + */ + constructor(message: string, options: DockerImageRefValidationErrorOptions); +} + +interface EngineSessionConnectParamsParseErrorOptions extends DaggerSDKErrorOptions { + parsedLine: string; +} +/** + * This error is thrown if the EngineSession does not manage to parse the required connection parameters from the session binary + */ +declare class EngineSessionConnectParamsParseError extends DaggerSDKError { + name: "EngineSessionConnectParamsParseError"; + code: "D103"; + /** + * the line, which caused the error during parsing, if the error was caused because of parsing. + */ + parsedLine: string; + /** + * @hidden + */ + constructor(message: string, options: EngineSessionConnectParamsParseErrorOptions); +} + +interface ExecErrorOptions extends DaggerSDKErrorOptions { + cmd: string[]; + exitCode: number; + stdout: string; + stderr: string; + extensions?: GraphQLErrorExtensions; +} +/** + * API error from an exec operation in a pipeline. + */ +declare class ExecError extends DaggerSDKError { + name: "ExecError"; + code: "D109"; + /** + * The command that caused the error. + */ + cmd: string[]; + /** + * The exit code of the command. + */ + exitCode: number; + /** + * The stdout of the command. + */ + stdout: string; + /** + * The stderr of the command. + */ + stderr: string; + /** + * GraphQL error extensions + */ + extensions?: GraphQLErrorExtensions; + /** + * @hidden + */ + constructor(message: string, options: ExecErrorOptions); +} + +interface GraphQLRequestErrorOptions extends DaggerSDKErrorOptions { + error: ClientError; +} +/** + * This error originates from the dagger engine. It means that some error was thrown and sent back via GraphQL. + */ +declare class GraphQLRequestError extends DaggerSDKError { + name: "GraphQLRequestError"; + code: "D100"; + /** + * The query and variables, which caused the error. + */ + requestContext: ClientError["request"]; + /** + * the GraphQL response containing the error. + */ + response: ClientError["response"]; + /** + * The GraphQL error extentions. + */ + extensions?: GraphQLErrorExtensions; + /** + * @hidden + */ + constructor(message: string, options: GraphQLRequestErrorOptions); +} + +/** + * This error is thrown if the dagger binary cannot be copied from the dagger docker image and copied to the local host. + */ +declare class InitEngineSessionBinaryError extends DaggerSDKError { + name: "InitEngineSessionBinaryError"; + code: "D106"; + /** + * @hidden + */ + constructor(message: string, options?: DaggerSDKErrorOptions); +} + +interface TooManyNestedObjectsErrorOptions extends DaggerSDKErrorOptions { + response: unknown; +} +/** + * Dagger only expects one response value from the engine. If the engine returns more than one value this error is thrown. + */ +declare class TooManyNestedObjectsError extends DaggerSDKError { + name: "TooManyNestedObjectsError"; + code: "D102"; + /** + * the response containing more than one value. + */ + response: unknown; + /** + * @hidden + */ + constructor(message: string, options: TooManyNestedObjectsErrorOptions); +} + +type EngineSessionErrorOptions = DaggerSDKErrorOptions; +/** + * This error is thrown if the EngineSession does not manage to parse the required port successfully because a EOF is read before any valid port. + * This usually happens if no connection can be established. + */ +declare class EngineSessionError extends DaggerSDKError { + name: "EngineSessionError"; + code: "D105"; + /** + * @hidden + */ + constructor(message: string, options?: EngineSessionErrorOptions); +} + +interface EngineSessionConnectionTimeoutErrorOptions extends DaggerSDKErrorOptions { + timeOutDuration: number; +} +/** + * This error is thrown if the EngineSession does not manage to parse the required port successfully because the sessions connection timed out. + */ +declare class EngineSessionConnectionTimeoutError extends DaggerSDKError { + name: "EngineSessionConnectionTimeoutError"; + code: "D104"; + /** + * The duration until the timeout occurred in ms. + */ + timeOutDuration: number; + /** + * @hidden + */ + constructor(message: string, options: EngineSessionConnectionTimeoutErrorOptions); +} + +/** + * This error is thrown when the compute function isn't awaited. + */ +declare class NotAwaitedRequestError extends DaggerSDKError { + name: "NotAwaitedRequestError"; + code: "D108"; + /** + * @hidden + */ + constructor(message: string, options?: DaggerSDKErrorOptions); +} + +declare class FunctionNotFound extends DaggerSDKError { + name: "ExecError"; + code: "D109"; + constructor(message: string, options?: DaggerSDKErrorOptions); +} + +declare class IntrospectionError extends DaggerSDKError { + name: "IntrospectionError"; + code: "D110"; + constructor(message: string, options?: DaggerSDKErrorOptions); +} + +/** + * ConnectOpts defines option used to connect to an engine. + */ +interface ConnectOpts { + /** + * Use to overwrite Dagger workdir + * @defaultValue process.cwd() + */ + Workdir?: string; + /** + * Opt into loading workspace modules for this connection. + * By default, only the core API is exposed. + */ + LoadWorkspaceModules?: boolean; + /** + * Enable logs output + * @example + * LogOutput + * ```ts + * connect(async (client: Client) => { + const source = await client.host().workdir().id() + ... + }, {LogOutput: process.stdout}) + ``` + */ + LogOutput?: Writable; +} + +type CallbackFct = (client: Client) => Promise; +/** + * connection executes the given function using the default global Dagger client. + * + * @example + * ```ts + * await connection( + * async () => { + * await dag + * .container() + * .from("alpine") + * .withExec(["apk", "add", "curl"]) + * .withExec(["curl", "https://dagger.io/"]) + * .sync() + * }, { LogOutput: process.stderr } + * ) + * ``` + */ +declare function connection(fct: () => Promise, cfg?: ConnectOpts): Promise; +/** + * connect runs GraphQL server and initializes a + * GraphQL client to execute query on it through its callback. + * This implementation is based on the existing Go SDK. + */ +declare function connect(cb: CallbackFct, config?: ConnectOpts): Promise; + +type Class = { + new (...args: any[]): any; +}; +type ArgumentOptions = { + /** + * The contextual value to use for the argument. + * + * This should only be used for Directory/File or GitRepository/GitRef types. + * + * An absolute path would be related to the context source directory (the git repo root or the module source root). + * A relative path would be relative to the module source root. + */ + defaultPath?: string; + /** + * The default container address to use for the argument. + * + * This should only be used for Container types. + * + * If the argument is not set, the container will be loaded from this address. + */ + defaultAddress?: string; + /** + * Patterns to ignore when loading the contextual argument value. + * + * This should only be used for Directory types. + */ + ignore?: string[]; +}; +type FunctionOptions = { + /** + * The caching behavior of this function. + * "never" means no caching. + * "session" means caching only for the duration of the current client's session. + * A duration string (e.g., "5m", "1h") means persistent caching for that duration. + * By default, caching is enabled with a long default set by the engine. + */ + cache?: "never" | "session" | string; + /** + * An optional alias to use for the function when exposed on the API. + */ + alias?: string; +}; +/** + * Retrieve a class registered via the `@object()` decorator by its name. + * + * Useful for generated code (e.g. the static dispatch entrypoint) when the + * user's class isn't `export`'d but still needs to be reachable to construct + * instances and walk its prototype. + */ +declare function getRegisteredClass(name: string): Class | undefined; + +/** + * The definition of the `@object` decorator that should be on top of any + * class module that must be exposed to the Dagger API. + * + */ +declare const object: () => ((constructor: T) => T); +/** + * The definition of @func decorator that should be on top of any + * class' method that must be exposed to the Dagger API. + * + * @param alias The alias to use for the field when exposed on the API. + * @param cache The cache setting to use for that function. + */ +declare const func: (opts?: FunctionOptions | string) => ((target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor) => void); +/** + * The definition of @check decorator that marks a function as a check. + * Checks are functions that return void/error to indicate pass/fail. + */ +declare const check: () => ((target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor) => void); +/** + * The definition of @generate decorator that marks a function as a generator. + * Generators are functions that return a Changeset representing changes to be applied. + */ +declare const generate: () => ((target: object, propertyKey: string | symbol, descriptor?: PropertyDescriptor) => void); +/** + * The definition of @up decorator that marks a function as a service for dagger up. + */ +declare const up: () => ((target: object, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor); +/** + * The definition of @field decorator that should be on top of any + * class' property that must be exposed to the Dagger API. + * + * @deprecated In favor of `@func` + * @param alias The alias to use for the field when exposed on the API. + */ +declare const field: (alias?: string) => ((target: object, propertyKey: string) => void); +/** + * The definition of the `@enumType` decorator that should be on top of any + * class module that must be exposed to the Dagger API as enumeration. + * + * @deprecated In favor of using TypeScript `enum` types. + */ +declare const enumType: () => ((constructor: T) => T); +/** + * Add a `@argument` decorator to an argument of type `Directory` or `File` to load + * its contents from the module context directory. + * + * The context directory is the git repository containing the module. + * If there's no git repository, the context directory is the directory containing + * the module source code. + * + * @param opts.defaultPath Only applies to arguments of type File or Directory. If the argument is not set, + * load it from the given path in the context directory. + * @param opts.ignore Only applies to arguments of type Directory. The ignore patterns are applied to the input directory, + * and matching entries are filtered out, in a cache-efficient manner.. + * + * Relative paths are relative to the current source files. + * Absolute paths are rooted to the module context directory. + */ +declare const argument: (opts?: ArgumentOptions) => ((target: object, propertyKey: string | undefined, parameterIndex: number) => void); + +declare function entrypoint(files: string[]): Promise; + +export { Address, BaseClient, Binding, CacheSharingMode, CacheSharingModeNameToValue, CacheSharingModeValueToName, CacheVolume, Changeset, ChangesetMergeConflict, ChangesetMergeConflictNameToValue, ChangesetMergeConflictValueToName, ChangesetsMergeConflict, ChangesetsMergeConflictNameToValue, ChangesetsMergeConflictValueToName, Check, CheckGroup, Client, ClientFilesyncMirror, Cloud, Container, Context, CurrentModule, CurrentModuleAsSDK, CurrentModuleAsSDKClient, CurrentModuleAsSDKModule, DaggerSDKError, DiffStat, DiffStatKind, DiffStatKindNameToValue, DiffStatKindValueToName, Directory, DockerImageRefValidationError, ERROR_CODES, Engine, EngineCache, EngineCacheEntry, EngineCacheEntrySet, EngineSessionConnectParamsParseError, EngineSessionConnectionTimeoutError, EngineSessionError, EnumTypeDef, EnumValueTypeDef, Env, EnvFile, EnvVariable, Error$1 as Error, ErrorValue, ExecError, ExistsType, ExistsTypeNameToValue, ExistsTypeValueToName, FieldTypeDef, File, FileType, FileTypeNameToValue, FileTypeValueToName, FunctionArg, FunctionCachePolicy, FunctionCachePolicyNameToValue, FunctionCachePolicyValueToName, FunctionCall, FunctionCallArgValue, FunctionNotFound, Function_, GeneratedCode, Generator, GeneratorGroup, GitRef, GitRepository, GraphQLRequestError, HTTPState, HealthcheckConfig, Host, ImageLayerCompression, ImageLayerCompressionNameToValue, ImageLayerCompressionValueToName, ImageMediaTypes, ImageMediaTypesNameToValue, ImageMediaTypesValueToName, InitEngineSessionBinaryError, InputTypeDef, InterfaceTypeDef, IntrospectionError, JSONValue, LLM, LLMContentBlock, LLMContentBlockKind, LLMContentBlockKindNameToValue, LLMContentBlockKindValueToName, LLMMessage, LLMMessageRole, LLMMessageRoleNameToValue, LLMMessageRoleValueToName, LLMTokenUsage, Label, ListTypeDef, ModuleConfigClient, ModuleSource, ModuleSourceExperimentalFeature, ModuleSourceExperimentalFeatureNameToValue, ModuleSourceExperimentalFeatureValueToName, ModuleSourceKind, ModuleSourceKindNameToValue, ModuleSourceKindValueToName, Module_, NetworkProtocol, NetworkProtocolNameToValue, NetworkProtocolValueToName, NotAwaitedRequestError, ObjectTypeDef, Port, RegistryProtocol, RegistryProtocolNameToValue, RegistryProtocolValueToName, RemoteGitMirror, ReturnType, ReturnTypeNameToValue, ReturnTypeValueToName, SDKConfig, ScalarTypeDef, Schema, SearchResult, SearchSubmatch, Secret, Service, Socket, SourceMap, Stat, Terminal, TooManyNestedObjectsError, TypeDef, TypeDefKind, TypeDefKindNameToValue, TypeDefKindValueToName, UnknownDaggerError, Up, UpGroup, Volume, Workspace, WorkspaceGit, WorkspaceMigration, WorkspaceMigrationStep, WorkspaceModule, WorkspaceModuleSetting, WorkspaceSDK, _ExportableClient, _NodeClient, _SyncerClient, argument, check, connect, connection, dag, entrypoint, enumType, field, func, generate, getRegisteredClass, getTracer, object, up }; +export type { AddressDirectoryOpts, AddressFileOpts, BuildArg, CallbackFct, ChangesetWithChangesetOpts, ChangesetWithChangesetsOpts, CheckGroupRunOpts, ClientCacheVolumeOpts, ClientContainerOpts, ClientCurrentTypeDefsOpts, ClientEnvFileOpts, ClientEnvOpts, ClientFileOpts, ClientGitOpts, ClientHttpOpts, ClientLLMOpts, ClientModuleSourceOpts, ClientSecretOpts, ClientSshfsVolumeOpts, ConnectOpts, ContainerAsServiceOpts, ContainerAsTarballOpts, ContainerDirectoryOpts, ContainerExistsOpts, ContainerExportImageOpts, ContainerExportOpts, ContainerFileOpts, ContainerFromOpts, ContainerImportOpts, ContainerLayerOpts, ContainerManifestOpts, ContainerPublishOpts, ContainerStatOpts, ContainerTerminalOpts, ContainerUpOpts, ContainerWithDefaultTerminalCmdOpts, ContainerWithDirectoryOpts, ContainerWithDockerHealthcheckOpts, ContainerWithEntrypointOpts, ContainerWithEnvVariableOpts, ContainerWithExecOpts, ContainerWithExposedPortOpts, ContainerWithFileOpts, ContainerWithFilesOpts, ContainerWithMountedCacheOpts, ContainerWithMountedDirectoryOpts, ContainerWithMountedFileOpts, ContainerWithMountedSecretOpts, ContainerWithMountedTempOpts, ContainerWithMountedVolumeOpts, ContainerWithNewFileOpts, ContainerWithSymlinkOpts, ContainerWithUnixSocketOpts, ContainerWithWorkdirOpts, ContainerWithoutDirectoryOpts, ContainerWithoutEntrypointOpts, ContainerWithoutExposedPortOpts, ContainerWithoutFileOpts, ContainerWithoutFilesOpts, ContainerWithoutMountOpts, ContainerWithoutUnixSocketOpts, CurrentModuleAsSdkOpts, CurrentModuleGeneratorsOpts, CurrentModuleWorkdirOpts, DirectoryAsModuleOpts, DirectoryAsModuleSourceOpts, DirectoryAsWorkspaceOpts, DirectoryDockerBuildOpts, DirectoryEntriesOpts, DirectoryExistsOpts, DirectoryExportOpts, DirectoryFilterOpts, DirectorySearchOpts, DirectoryStatOpts, DirectoryTerminalOpts, DirectoryWithDirectoryOpts, DirectoryWithFileOpts, DirectoryWithFilesOpts, DirectoryWithNewDirectoryOpts, DirectoryWithNewFileOpts, EngineCacheEntrySetOpts, EngineCachePruneOpts, EnvChecksOpts, EnvFileGetOpts, EnvFileVariablesOpts, EnvServicesOpts, Exportable, FileAsEnvFileOpts, FileContentsOpts, FileDigestOpts, FileExportOpts, FileSearchOpts, FileWithReplacedOpts, FunctionWithArgOpts, FunctionWithCachePolicyOpts, FunctionWithDeprecatedOpts, GeneratorGroupChangesOpts, GitRefAsWorkspaceOpts, GitRefTreeOpts, GitRepositoryAsWorkspaceOpts, GitRepositoryBranchesOpts, GitRepositoryTagsOpts, HostDirectoryOpts, HostFileOpts, HostFindUpOpts, HostServiceOpts, HostTunnelOpts, ID, JSON, JSONValueContentsOpts, LLMContentBlockInput, LLMLoopOpts, LLMStepOpts, LLMWithModelOpts, LLMWithResponseOpts, ModuleChecksOpts, ModuleGeneratorsOpts, ModuleServeOpts, ModuleServicesOpts, Node, PipelineLabel, Platform, PortForward, ServiceEndpointOpts, ServiceStopOpts, ServiceTerminalOpts, ServiceUpOpts, Syncer, TypeDefWithEnumMemberOpts, TypeDefWithEnumOpts, TypeDefWithEnumValueOpts, TypeDefWithFieldOpts, TypeDefWithInterfaceOpts, TypeDefWithObjectOpts, TypeDefWithScalarOpts, Void, WorkspaceChecksOpts, WorkspaceConfigReadOpts, WorkspaceDirectoryOpts, WorkspaceFindUpOpts, WorkspaceGeneratorsOpts, WorkspaceSearchOpts, WorkspaceServicesOpts, WorkspaceWithConfigEnvOpts, WorkspaceWithConfigValueOpts, WorkspaceWithInitClientOpts, WorkspaceWithInitModuleOpts, WorkspaceWithModuleOpts, WorkspaceWithNewFileOpts, WorkspaceWithSdkOpts, WorkspaceWithoutConfigEnvOpts, WorkspaceWithoutConfigValueOpts, WorkspaceWithoutModuleOpts, WorkspaceWithoutSdkOpts, __DirectiveArgsOpts, __FieldArgsOpts, __TypeEnumValuesOpts, __TypeFieldsOpts, __TypeInputFieldsOpts, float }; diff --git a/library/bundle/core.js b/library/bundle/core.js new file mode 100644 index 0000000..de7ff1f --- /dev/null +++ b/library/bundle/core.js @@ -0,0 +1,108946 @@ +import { createRequire } from "node:module"; +var __create = Object.create; +var __getProtoOf = Object.getPrototypeOf; +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __toESM = (mod, isNodeMode, target) => { + target = mod != null ? __create(__getProtoOf(mod)) : {}; + const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; + for (let key of __getOwnPropNames(mod)) + if (!__hasOwnProp.call(to, key)) + __defProp(to, key, { + get: () => mod[key], + enumerable: true + }); + return to; +}; +var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { + get: all[name], + enumerable: true, + configurable: true, + set: (newValue) => all[name] = () => newValue + }); +}; +var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); +var __require = /* @__PURE__ */ createRequire(import.meta.url); + +// node_modules/graphql-request/build/legacy/classes/ClientError.js +var ClientError; +var init_ClientError = __esm(() => { + ClientError = class ClientError extends Error { + response; + request; + constructor(response, request) { + const message = `${ClientError.extractMessage(response)}: ${JSON.stringify({ + response, + request + })}`; + super(message); + Object.setPrototypeOf(this, ClientError.prototype); + this.response = response; + this.request = request; + if (typeof Error.captureStackTrace === `function`) { + Error.captureStackTrace(this, ClientError); + } + } + static extractMessage(response) { + return response.errors?.[0]?.message ?? `GraphQL Error (Code: ${String(response.status)})`; + } + }; +}); + +// node_modules/graphql-request/build/lib/prelude.js +var uppercase = (str) => str.toUpperCase(), callOrIdentity = (value) => { + return typeof value === `function` ? value() : value; +}, zip = (a, b) => a.map((k, i) => [k, b[i]]), HeadersInitToPlainObject = (headers) => { + let oHeaders = {}; + if (headers instanceof Headers) { + oHeaders = HeadersInstanceToPlainObject(headers); + } else if (Array.isArray(headers)) { + headers.forEach(([name, value]) => { + if (name && value !== undefined) { + oHeaders[name] = value; + } + }); + } else if (headers) { + oHeaders = headers; + } + return oHeaders; +}, HeadersInstanceToPlainObject = (headers) => { + const o = {}; + headers.forEach((v, k) => { + o[k] = v; + }); + return o; +}, tryCatch = (fn) => { + try { + const result = fn(); + if (isPromiseLikeValue(result)) { + return result.catch((error) => { + return errorFromMaybeError(error); + }); + } + return result; + } catch (error) { + return errorFromMaybeError(error); + } +}, errorFromMaybeError = (maybeError) => { + if (maybeError instanceof Error) + return maybeError; + return new Error(String(maybeError)); +}, isPromiseLikeValue = (value) => { + return typeof value === `object` && value !== null && `then` in value && typeof value.then === `function` && `catch` in value && typeof value.catch === `function` && `finally` in value && typeof value.finally === `function`; +}, casesExhausted = (value) => { + throw new Error(`Unhandled case: ${String(value)}`); +}, isPlainObject = (value) => { + return typeof value === `object` && value !== null && !Array.isArray(value); +}; + +// node_modules/graphql-request/build/legacy/functions/batchRequests.js +var parseBatchRequestArgs = (documentsOrOptions, requestHeaders) => { + return documentsOrOptions.documents ? documentsOrOptions : { + documents: documentsOrOptions, + requestHeaders, + signal: undefined + }; +}; +var init_batchRequests = __esm(() => { + init_GraphQLClient(); +}); + +// node_modules/graphql-request/build/legacy/functions/rawRequest.js +var parseRawRequestArgs = (queryOrOptions, variables, requestHeaders) => { + return queryOrOptions.query ? queryOrOptions : { + query: queryOrOptions, + variables, + requestHeaders, + signal: undefined + }; +}; +var init_rawRequest = __esm(() => { + init_GraphQLClient(); +}); + +// node_modules/graphql/jsutils/inspect.js +var require_inspect = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.inspect = inspect; + var MAX_ARRAY_LENGTH = 10; + var MAX_RECURSIVE_DEPTH = 2; + function inspect(value) { + return formatValue(value, []); + } + function formatValue(value, seenValues) { + switch (typeof value) { + case "string": + return JSON.stringify(value); + case "function": + return value.name ? `[function ${value.name}]` : "[function]"; + case "object": + return formatObjectValue(value, seenValues); + default: + return String(value); + } + } + function formatObjectValue(value, previouslySeenValues) { + if (value === null) { + return "null"; + } + if (previouslySeenValues.includes(value)) { + return "[Circular]"; + } + const seenValues = [...previouslySeenValues, value]; + if (isJSONable(value)) { + const jsonValue = value.toJSON(); + if (jsonValue !== value) { + return typeof jsonValue === "string" ? jsonValue : formatValue(jsonValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + return formatObject(value, seenValues); + } + function isJSONable(value) { + return typeof value.toJSON === "function"; + } + function formatObject(object, seenValues) { + const entries = Object.entries(object); + if (entries.length === 0) { + return "{}"; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return "[" + getObjectTag(object) + "]"; + } + const properties = entries.map(([key, value]) => key + ": " + formatValue(value, seenValues)); + return "{ " + properties.join(", ") + " }"; + } + function formatArray(array, seenValues) { + if (array.length === 0) { + return "[]"; + } + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return "[Array]"; + } + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + for (let i = 0;i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + if (remaining === 1) { + items.push("... 1 more item"); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + return "[" + items.join(", ") + "]"; + } + function getObjectTag(object) { + const tag = Object.prototype.toString.call(object).replace(/^\[object /, "").replace(/]$/, ""); + if (tag === "Object" && typeof object.constructor === "function") { + const name = object.constructor.name; + if (typeof name === "string" && name !== "") { + return name; + } + } + return tag; + } +}); + +// node_modules/graphql/jsutils/instanceOf.js +var require_instanceOf = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.instanceOf = undefined; + exports.enableDevInstanceOf = enableDevInstanceOf; + var inspect_ts_1 = require_inspect(); + function devInstanceOf(value, symbol, constructor) { + if (value?.__kind === symbol) { + return true; + } + if (typeof value === "object" && value !== null) { + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = Symbol.toStringTag in value ? value[Symbol.toStringTag] : value.constructor?.name; + if (className === valueClassName) { + const stringifiedValue = (0, inspect_ts_1.inspect)(value); + throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`); + } + } + return false; + } + function prodInstanceOf(value, symbol) { + return value?.__kind === symbol; + } + exports.instanceOf = prodInstanceOf; + function enableDevInstanceOf() { + exports.instanceOf = devInstanceOf; + } +}); + +// node_modules/graphql/devMode.js +var require_devMode = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.enableDevMode = enableDevMode; + exports.isDevModeEnabled = isDevModeEnabled; + var instanceOf_ts_1 = require_instanceOf(); + var devMode = false; + function enableDevMode() { + devMode = true; + (0, instanceOf_ts_1.enableDevInstanceOf)(); + } + function isDevModeEnabled() { + return devMode; + } +}); + +// node_modules/graphql/version.js +var require_version = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.versionInfo = exports.version = undefined; + exports.version = "17.0.1"; + exports.versionInfo = Object.freeze({ + major: 17, + minor: 0, + patch: 1, + preReleaseTag: null + }); +}); + +// node_modules/graphql/jsutils/isPromise.js +var require_isPromise = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPromise = isPromise; + exports.isPromiseLike = isPromiseLike; + function isPromise(value) { + return value instanceof Promise; + } + function isPromiseLike(value) { + return typeof value?.then === "function"; + } +}); + +// node_modules/graphql/jsutils/toError.js +var require_toError = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toError = toError; + var inspect_ts_1 = require_inspect(); + function toError(thrownValue) { + return thrownValue instanceof Error ? thrownValue : new NonErrorThrown(thrownValue); + } + + class NonErrorThrown extends Error { + constructor(thrownValue) { + super("Unexpected error value: " + (0, inspect_ts_1.inspect)(thrownValue)); + this.name = "NonErrorThrown"; + this.thrownValue = thrownValue; + } + } +}); + +// node_modules/graphql/jsutils/isObjectLike.js +var require_isObjectLike = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isObjectLike = isObjectLike; + function isObjectLike(value) { + return typeof value == "object" && value !== null; + } +}); + +// node_modules/graphql/jsutils/invariant.js +var require_invariant = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.invariant = invariant; + function invariant(condition, message) { + if (!condition) { + throw new Error(message ?? "Unexpected invariant triggered."); + } + } +}); + +// node_modules/graphql/language/location.js +var require_location = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getLocation = getLocation; + var invariant_ts_1 = require_invariant(); + var LineRegExp = /\r\n|[\n\r]/g; + function getLocation(source, position) { + let lastLineStart = 0; + let line = 1; + for (const match of source.body.matchAll(LineRegExp)) { + if (!(typeof match.index === "number")) + (0, invariant_ts_1.invariant)(false); + if (match.index >= position) { + break; + } + lastLineStart = match.index + match[0].length; + line += 1; + } + return { line, column: position + 1 - lastLineStart }; + } +}); + +// node_modules/graphql/language/printLocation.js +var require_printLocation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.printLocation = printLocation; + exports.printSourceLocation = printSourceLocation; + var location_ts_1 = require_location(); + function printLocation(location) { + return printSourceLocation(location.source, (0, location_ts_1.getLocation)(location.source, location.start)); + } + function printSourceLocation(source, sourceLocation) { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = "".padStart(firstLineColumnOffset) + source.body; + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum} +`; + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + for (let i = 0;i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + return locationStr + printPrefixedLines([ + [`${lineNum} |`, subLines[0]], + ...subLines.slice(1, subLineIndex + 1).map((subLine) => ["|", subLine]), + ["|", "^".padStart(subLineColumnNum)], + ["|", subLines[subLineIndex + 1]] + ]); + } + return locationStr + printPrefixedLines([ + [`${lineNum - 1} |`, lines[lineIndex - 1]], + [`${lineNum} |`, locationLine], + ["|", "^".padStart(columnNum)], + [`${lineNum + 1} |`, lines[lineIndex + 1]] + ]); + } + function printPrefixedLines(lines) { + const existingLines = lines.filter(([_, line]) => line !== undefined); + const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); + return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? " " + line : "")).join(` +`); + } +}); + +// node_modules/graphql/error/GraphQLError.js +var require_GraphQLError = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GraphQLError = undefined; + var isObjectLike_ts_1 = require_isObjectLike(); + var location_ts_1 = require_location(); + var printLocation_ts_1 = require_printLocation(); + + class GraphQLError extends Error { + constructor(message, options = {}) { + const { nodes, source, positions, path, originalError, cause, extensions } = options; + const hasCause = "cause" in options; + const errorCause = hasCause ? cause : originalError; + const errorOptions = hasCause || originalError != null ? { cause: errorCause } : undefined; + super(message, errorOptions); + this.name = "GraphQLError"; + this.path = path ?? undefined; + const underlyingError = originalError ?? (cause instanceof Error ? cause : undefined); + this.originalError = underlyingError; + this.nodes = undefinedIfEmpty(Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined); + const nodeLocations = undefinedIfEmpty(this.nodes?.map((node) => node.loc).filter((loc) => loc != null)); + this.source = source ?? nodeLocations?.[0]?.source; + this.positions = positions ?? nodeLocations?.map((loc) => loc.start); + this.locations = positions && source ? positions.map((pos) => (0, location_ts_1.getLocation)(source, pos)) : nodeLocations?.map((loc) => (0, location_ts_1.getLocation)(loc.source, loc.start)); + const originalExtensions = (0, isObjectLike_ts_1.isObjectLike)(underlyingError?.extensions) ? underlyingError.extensions : undefined; + this.extensions = extensions ?? originalExtensions ?? Object.create(null); + Object.defineProperties(this, { + message: { + writable: true, + enumerable: true + }, + name: { enumerable: false }, + nodes: { enumerable: false }, + source: { enumerable: false }, + positions: { enumerable: false }, + originalError: { enumerable: false } + }); + if (originalError?.stack != null) { + Object.defineProperty(this, "stack", { + value: originalError.stack, + writable: true, + configurable: true + }); + } else if (Error.captureStackTrace != null) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, "stack", { + value: Error().stack, + writable: true, + configurable: true + }); + } + } + get [Symbol.toStringTag]() { + return "GraphQLError"; + } + toString() { + let output = this.message; + if (this.nodes) { + for (const node of this.nodes) { + if (node.loc) { + output += ` + +` + (0, printLocation_ts_1.printLocation)(node.loc); + } + } + } else if (this.source && this.locations) { + for (const location of this.locations) { + output += ` + +` + (0, printLocation_ts_1.printSourceLocation)(this.source, location); + } + } + return output; + } + toJSON() { + const formattedError = { + message: this.message + }; + if (this.locations != null) { + formattedError.locations = this.locations; + } + if (this.path != null) { + formattedError.path = this.path; + } + if (this.extensions != null && Object.keys(this.extensions).length > 0) { + formattedError.extensions = this.extensions; + } + return formattedError; + } + } + exports.GraphQLError = GraphQLError; + function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; + } +}); + +// node_modules/graphql/error/ensureGraphQLError.js +var require_ensureGraphQLError = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ensureGraphQLError = ensureGraphQLError; + var toError_ts_1 = require_toError(); + var GraphQLError_ts_1 = require_GraphQLError(); + function ensureGraphQLError(rawError) { + if (rawError instanceof GraphQLError_ts_1.GraphQLError) { + return rawError; + } + const originalError = (0, toError_ts_1.toError)(rawError); + return new GraphQLError_ts_1.GraphQLError(originalError.message, { originalError }); + } +}); + +// node_modules/graphql/jsutils/AccumulatorMap.js +var require_AccumulatorMap = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AccumulatorMap = undefined; + + class AccumulatorMap extends Map { + get [Symbol.toStringTag]() { + return "AccumulatorMap"; + } + add(key, item) { + const group = this.get(key); + if (group === undefined) { + this.set(key, [item]); + } else { + group.push(item); + } + } + } + exports.AccumulatorMap = AccumulatorMap; +}); + +// node_modules/graphql/jsutils/capitalize.js +var require_capitalize = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.capitalize = capitalize; + function capitalize(str) { + return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); + } +}); + +// node_modules/graphql/jsutils/formatList.js +var require_formatList = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.orList = orList; + exports.andList = andList; + var invariant_ts_1 = require_invariant(); + function orList(items) { + return formatList("or", items); + } + function andList(items) { + return formatList("and", items); + } + function formatList(conjunction, items) { + if (!(items.length !== 0)) + (0, invariant_ts_1.invariant)(false); + switch (items.length) { + case 1: + return items[0]; + case 2: + return items[0] + " " + conjunction + " " + items[1]; + } + const allButLast = items.slice(0, -1); + const lastItem = items.at(-1); + return allButLast.join(", ") + ", " + conjunction + " " + lastItem; + } +}); + +// node_modules/graphql/jsutils/isIterableObject.js +var require_isIterableObject = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isIterableObject = isIterableObject; + function isIterableObject(maybeIterable) { + return typeof maybeIterable === "object" && typeof maybeIterable?.[Symbol.iterator] === "function"; + } +}); + +// node_modules/graphql/jsutils/keyMap.js +var require_keyMap = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.keyMap = keyMap; + function keyMap(list, keyFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = item; + } + return result; + } +}); + +// node_modules/graphql/jsutils/mapValue.js +var require_mapValue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.mapValue = mapValue; + function mapValue(map, fn) { + const result = Object.create(null); + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key); + } + return result; + } +}); + +// node_modules/graphql/jsutils/printPathArray.js +var require_printPathArray = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.printPathArray = printPathArray; + function printPathArray(path) { + if (path.length === 0) { + return ""; + } + return ` at ${path.map((key) => typeof key === "number" ? `[${key}]` : `.${key}`).join("")}`; + } +}); + +// node_modules/graphql/language/ast.js +var require_ast = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OperationTypeNode = exports.QueryDocumentKeys = exports.Token = exports.Location = undefined; + exports.isNode = isNode; + + class Location { + constructor(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + get [Symbol.toStringTag]() { + return "Location"; + } + toJSON() { + return { start: this.start, end: this.end }; + } + } + exports.Location = Location; + + class Token { + constructor(kind2, start, end, line, column, value) { + this.kind = kind2; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = null; + this.next = null; + } + get [Symbol.toStringTag]() { + return "Token"; + } + toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; + } + } + exports.Token = Token; + exports.QueryDocumentKeys = { + Name: [], + Document: ["definitions"], + OperationDefinition: [ + "description", + "name", + "variableDefinitions", + "directives", + "selectionSet" + ], + VariableDefinition: [ + "description", + "variable", + "type", + "defaultValue", + "directives" + ], + Variable: ["name"], + SelectionSet: ["selections"], + Field: ["alias", "name", "arguments", "directives", "selectionSet"], + Argument: ["name", "value"], + FragmentArgument: ["name", "value"], + FragmentSpread: [ + "name", + "arguments", + "directives" + ], + InlineFragment: ["typeCondition", "directives", "selectionSet"], + FragmentDefinition: [ + "description", + "name", + "variableDefinitions", + "typeCondition", + "directives", + "selectionSet" + ], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ["values"], + ObjectValue: ["fields"], + ObjectField: ["name", "value"], + Directive: ["name", "arguments"], + NamedType: ["name"], + ListType: ["type"], + NonNullType: ["type"], + SchemaDefinition: ["description", "directives", "operationTypes"], + OperationTypeDefinition: ["type"], + ScalarTypeDefinition: ["description", "name", "directives"], + ObjectTypeDefinition: [ + "description", + "name", + "interfaces", + "directives", + "fields" + ], + FieldDefinition: ["description", "name", "arguments", "type", "directives"], + InputValueDefinition: [ + "description", + "name", + "type", + "defaultValue", + "directives" + ], + InterfaceTypeDefinition: [ + "description", + "name", + "interfaces", + "directives", + "fields" + ], + UnionTypeDefinition: ["description", "name", "directives", "types"], + EnumTypeDefinition: ["description", "name", "directives", "values"], + EnumValueDefinition: ["description", "name", "directives"], + InputObjectTypeDefinition: ["description", "name", "directives", "fields"], + DirectiveDefinition: [ + "description", + "name", + "arguments", + "directives", + "locations" + ], + SchemaExtension: ["directives", "operationTypes"], + DirectiveExtension: ["name", "directives"], + ScalarTypeExtension: ["name", "directives"], + ObjectTypeExtension: ["name", "interfaces", "directives", "fields"], + InterfaceTypeExtension: ["name", "interfaces", "directives", "fields"], + UnionTypeExtension: ["name", "directives", "types"], + EnumTypeExtension: ["name", "directives", "values"], + InputObjectTypeExtension: ["name", "directives", "fields"], + TypeCoordinate: ["name"], + MemberCoordinate: ["name", "memberName"], + ArgumentCoordinate: ["name", "fieldName", "argumentName"], + DirectiveCoordinate: ["name"], + DirectiveArgumentCoordinate: ["name", "argumentName"] + }; + var kindValues = new Set(Object.keys(exports.QueryDocumentKeys)); + function isNode(maybeNode) { + const maybeKind = maybeNode?.kind; + return typeof maybeKind === "string" && kindValues.has(maybeKind); + } + exports.OperationTypeNode = { + QUERY: "query", + MUTATION: "mutation", + SUBSCRIPTION: "subscription" + }; +}); + +// node_modules/graphql/language/kinds_.js +var require_kinds_ = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DIRECTIVE_ARGUMENT_COORDINATE = exports.DIRECTIVE_COORDINATE = exports.ARGUMENT_COORDINATE = exports.MEMBER_COORDINATE = exports.TYPE_COORDINATE = exports.INPUT_OBJECT_TYPE_EXTENSION = exports.ENUM_TYPE_EXTENSION = exports.UNION_TYPE_EXTENSION = exports.INTERFACE_TYPE_EXTENSION = exports.OBJECT_TYPE_EXTENSION = exports.SCALAR_TYPE_EXTENSION = exports.DIRECTIVE_EXTENSION = exports.SCHEMA_EXTENSION = exports.DIRECTIVE_DEFINITION = exports.INPUT_OBJECT_TYPE_DEFINITION = exports.ENUM_VALUE_DEFINITION = exports.ENUM_TYPE_DEFINITION = exports.UNION_TYPE_DEFINITION = exports.INTERFACE_TYPE_DEFINITION = exports.INPUT_VALUE_DEFINITION = exports.FIELD_DEFINITION = exports.OBJECT_TYPE_DEFINITION = exports.SCALAR_TYPE_DEFINITION = exports.OPERATION_TYPE_DEFINITION = exports.SCHEMA_DEFINITION = exports.NON_NULL_TYPE = exports.LIST_TYPE = exports.NAMED_TYPE = exports.DIRECTIVE = exports.OBJECT_FIELD = exports.OBJECT = exports.LIST = exports.ENUM = exports.NULL = exports.BOOLEAN = exports.STRING = exports.FLOAT = exports.INT = exports.VARIABLE = exports.FRAGMENT_DEFINITION = exports.INLINE_FRAGMENT = exports.FRAGMENT_SPREAD = exports.FRAGMENT_ARGUMENT = exports.ARGUMENT = exports.FIELD = exports.SELECTION_SET = exports.VARIABLE_DEFINITION = exports.OPERATION_DEFINITION = exports.DOCUMENT = exports.NAME = undefined; + exports.NAME = "Name"; + exports.DOCUMENT = "Document"; + exports.OPERATION_DEFINITION = "OperationDefinition"; + exports.VARIABLE_DEFINITION = "VariableDefinition"; + exports.SELECTION_SET = "SelectionSet"; + exports.FIELD = "Field"; + exports.ARGUMENT = "Argument"; + exports.FRAGMENT_ARGUMENT = "FragmentArgument"; + exports.FRAGMENT_SPREAD = "FragmentSpread"; + exports.INLINE_FRAGMENT = "InlineFragment"; + exports.FRAGMENT_DEFINITION = "FragmentDefinition"; + exports.VARIABLE = "Variable"; + exports.INT = "IntValue"; + exports.FLOAT = "FloatValue"; + exports.STRING = "StringValue"; + exports.BOOLEAN = "BooleanValue"; + exports.NULL = "NullValue"; + exports.ENUM = "EnumValue"; + exports.LIST = "ListValue"; + exports.OBJECT = "ObjectValue"; + exports.OBJECT_FIELD = "ObjectField"; + exports.DIRECTIVE = "Directive"; + exports.NAMED_TYPE = "NamedType"; + exports.LIST_TYPE = "ListType"; + exports.NON_NULL_TYPE = "NonNullType"; + exports.SCHEMA_DEFINITION = "SchemaDefinition"; + exports.OPERATION_TYPE_DEFINITION = "OperationTypeDefinition"; + exports.SCALAR_TYPE_DEFINITION = "ScalarTypeDefinition"; + exports.OBJECT_TYPE_DEFINITION = "ObjectTypeDefinition"; + exports.FIELD_DEFINITION = "FieldDefinition"; + exports.INPUT_VALUE_DEFINITION = "InputValueDefinition"; + exports.INTERFACE_TYPE_DEFINITION = "InterfaceTypeDefinition"; + exports.UNION_TYPE_DEFINITION = "UnionTypeDefinition"; + exports.ENUM_TYPE_DEFINITION = "EnumTypeDefinition"; + exports.ENUM_VALUE_DEFINITION = "EnumValueDefinition"; + exports.INPUT_OBJECT_TYPE_DEFINITION = "InputObjectTypeDefinition"; + exports.DIRECTIVE_DEFINITION = "DirectiveDefinition"; + exports.SCHEMA_EXTENSION = "SchemaExtension"; + exports.DIRECTIVE_EXTENSION = "DirectiveExtension"; + exports.SCALAR_TYPE_EXTENSION = "ScalarTypeExtension"; + exports.OBJECT_TYPE_EXTENSION = "ObjectTypeExtension"; + exports.INTERFACE_TYPE_EXTENSION = "InterfaceTypeExtension"; + exports.UNION_TYPE_EXTENSION = "UnionTypeExtension"; + exports.ENUM_TYPE_EXTENSION = "EnumTypeExtension"; + exports.INPUT_OBJECT_TYPE_EXTENSION = "InputObjectTypeExtension"; + exports.TYPE_COORDINATE = "TypeCoordinate"; + exports.MEMBER_COORDINATE = "MemberCoordinate"; + exports.ARGUMENT_COORDINATE = "ArgumentCoordinate"; + exports.DIRECTIVE_COORDINATE = "DirectiveCoordinate"; + exports.DIRECTIVE_ARGUMENT_COORDINATE = "DirectiveArgumentCoordinate"; +}); + +// node_modules/graphql/language/kinds.js +var require_kinds = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) + if (Object.prototype.hasOwnProperty.call(o2, k)) + ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k = ownKeys(mod), i = 0;i < k.length; i++) + if (k[i] !== "default") + __createBinding(result, mod, k[i]); + } + __setModuleDefault(result, mod); + return result; + }; + }(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Kind = undefined; + exports.Kind = __importStar(require_kinds_()); +}); + +// node_modules/graphql/jsutils/devAssert.js +var require_devAssert = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.devAssert = devAssert; + function devAssert(condition, message) { + if (!condition) { + throw new Error(message); + } + } +}); + +// node_modules/graphql/jsutils/didYouMean.js +var require_didYouMean = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.didYouMean = didYouMean; + var formatList_ts_1 = require_formatList(); + var MAX_SUGGESTIONS = 5; + function didYouMean(firstArg, secondArg) { + const [subMessage, suggestions] = secondArg ? [firstArg, secondArg] : [undefined, firstArg]; + if (suggestions.length === 0) { + return ""; + } + let message = " Did you mean "; + if (subMessage != null) { + message += subMessage + " "; + } + const suggestionList = (0, formatList_ts_1.orList)(suggestions.slice(0, MAX_SUGGESTIONS).map((x) => `"${x}"`)); + return message + suggestionList + "?"; + } +}); + +// node_modules/graphql/jsutils/identityFunc.js +var require_identityFunc = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.identityFunc = identityFunc; + function identityFunc(x) { + return x; + } +}); + +// node_modules/graphql/jsutils/keyValMap.js +var require_keyValMap = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.keyValMap = keyValMap; + function keyValMap(list, keyFn, valFn) { + const result = Object.create(null); + for (const item of list) { + result[keyFn(item)] = valFn(item); + } + return result; + } +}); + +// node_modules/graphql/jsutils/naturalCompare.js +var require_naturalCompare = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.naturalCompare = naturalCompare; + function naturalCompare(aStr, bStr) { + let aIndex = 0; + let bIndex = 0; + while (aIndex < aStr.length && bIndex < bStr.length) { + let aChar = aStr.charCodeAt(aIndex); + let bChar = bStr.charCodeAt(bIndex); + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + do { + ++aIndex; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIndex); + } while (isDigit(aChar) && aNum > 0); + let bNum = 0; + do { + ++bIndex; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIndex); + } while (isDigit(bChar) && bNum > 0); + if (aNum < bNum) { + return -1; + } + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + if (aChar > bChar) { + return 1; + } + ++aIndex; + ++bIndex; + } + } + return aStr.length - bStr.length; + } + var DIGIT_0 = 48; + var DIGIT_9 = 57; + function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; + } +}); + +// node_modules/graphql/jsutils/suggestionList.js +var require_suggestionList = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.suggestionList = suggestionList; + var naturalCompare_ts_1 = require_naturalCompare(); + function suggestionList(input, options) { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + const threshold = Math.floor(input.length * 0.4) + 1; + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 ? distanceDiff : (0, naturalCompare_ts_1.naturalCompare)(a, b); + }); + } + + class LexicalDistance { + constructor(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [ + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0) + ]; + } + measure(option, threshold) { + if (this._input === option) { + return 0; + } + const optionLowerCase = option.toLowerCase(); + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; + } + const aLength = a.length; + const bLength = b.length; + if (aLength - bLength > threshold) { + return; + } + const rows = this._rows; + for (let j = 0;j <= bLength; j++) { + rows[0][j] = j; + } + for (let i = 1;i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + let smallestCell = currentRow[0] = i; + for (let j = 1;j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let currentCell = Math.min(upRow[j] + 1, currentRow[j - 1] + 1, upRow[j - 1] + cost); + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + currentRow[j] = currentCell; + } + if (smallestCell > threshold) { + return; + } + } + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + } + } + function stringToArray(str) { + const strLength = str.length; + const array = new Array(strLength); + for (let i = 0;i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + return array; + } +}); + +// node_modules/graphql/jsutils/toObjMap.js +var require_toObjMap = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toObjMap = toObjMap; + exports.toObjMapWithSymbols = toObjMapWithSymbols; + function toObjMap(obj) { + if (obj == null) { + return Object.create(null); + } + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + const map = Object.create(null); + for (const [key, value] of Object.entries(obj)) { + map[key] = value; + } + return map; + } + function toObjMapWithSymbols(obj) { + if (obj == null) { + return Object.create(null); + } + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + const map = Object.create(null); + for (const [key, value] of Object.entries(obj)) { + map[key] = value; + } + for (const key of Object.getOwnPropertySymbols(obj)) { + map[key] = obj[key]; + } + return map; + } +}); + +// node_modules/graphql/language/characterClasses.js +var require_characterClasses = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isWhiteSpace = isWhiteSpace; + exports.isDigit = isDigit; + exports.isLetter = isLetter; + exports.isNameStart = isNameStart; + exports.isNameContinue = isNameContinue; + function isWhiteSpace(code) { + return code === 9 || code === 32; + } + function isDigit(code) { + return code >= 48 && code <= 57; + } + function isLetter(code) { + return code >= 97 && code <= 122 || code >= 65 && code <= 90; + } + function isNameStart(code) { + return isLetter(code) || code === 95; + } + function isNameContinue(code) { + return isLetter(code) || isDigit(code) || code === 95; + } +}); + +// node_modules/graphql/language/blockString.js +var require_blockString = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dedentBlockStringLines = dedentBlockStringLines; + exports.isPrintableAsBlockString = isPrintableAsBlockString; + exports.printBlockString = printBlockString; + var characterClasses_ts_1 = require_characterClasses(); + function dedentBlockStringLines(lines) { + let commonIndent = Number.MAX_SAFE_INTEGER; + let firstNonEmptyLine = null; + let lastNonEmptyLine = -1; + for (let i = 0;i < lines.length; ++i) { + const line = lines[i]; + const indent = leadingWhitespace(line); + if (indent === line.length) { + continue; + } + firstNonEmptyLine ??= i; + lastNonEmptyLine = i; + if (i !== 0 && indent < commonIndent) { + commonIndent = indent; + } + } + return lines.map((line, i) => i === 0 ? line : line.slice(commonIndent)).slice(firstNonEmptyLine ?? 0, lastNonEmptyLine + 1); + } + function leadingWhitespace(str) { + let i = 0; + while (i < str.length && (0, characterClasses_ts_1.isWhiteSpace)(str.charCodeAt(i))) { + ++i; + } + return i; + } + function isPrintableAsBlockString(value) { + if (value === "") { + return true; + } + let isEmptyLine = true; + let hasIndent = false; + let hasCommonIndent = true; + let seenNonEmptyLine = false; + for (let i = 0;i < value.length; ++i) { + switch (value.codePointAt(i)) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 11: + case 12: + case 14: + case 15: + return false; + case 13: + return false; + case 10: + if (isEmptyLine && !seenNonEmptyLine) { + return false; + } + seenNonEmptyLine = true; + isEmptyLine = true; + hasIndent = false; + break; + case 9: + case 32: + hasIndent ||= isEmptyLine; + break; + default: + hasCommonIndent &&= hasIndent; + isEmptyLine = false; + } + } + if (isEmptyLine) { + return false; + } + if (hasCommonIndent && seenNonEmptyLine) { + return false; + } + return true; + } + function printBlockString(value, options) { + const escapedValue = value.replaceAll('"""', '\\"""'); + const lines = escapedValue.split(/\r\n|[\n\r]/g); + const isSingleLine = lines.length === 1; + const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every((line) => line.length === 0 || (0, characterClasses_ts_1.isWhiteSpace)(line.charCodeAt(0))); + const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); + const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; + const hasTrailingSlash = value.endsWith("\\"); + const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; + const printAsMultipleLines = !options?.minimize && (!isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes); + let result = ""; + const skipLeadingNewLine = isSingleLine && (0, characterClasses_ts_1.isWhiteSpace)(value.charCodeAt(0)); + if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) { + result += ` +`; + } + result += escapedValue; + if (printAsMultipleLines || forceTrailingNewline) { + result += ` +`; + } + return '"""' + result + '"""'; + } +}); + +// node_modules/graphql/language/printString.js +var require_printString = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.printString = printString; + function printString(str) { + return `"${str.replace(escapedRegExp, escapedReplacer)}"`; + } + var escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; + function escapedReplacer(str) { + return escapeSequences[str.charCodeAt(0)]; + } + var escapeSequences = [ + "\\u0000", + "\\u0001", + "\\u0002", + "\\u0003", + "\\u0004", + "\\u0005", + "\\u0006", + "\\u0007", + "\\b", + "\\t", + "\\n", + "\\u000B", + "\\f", + "\\r", + "\\u000E", + "\\u000F", + "\\u0010", + "\\u0011", + "\\u0012", + "\\u0013", + "\\u0014", + "\\u0015", + "\\u0016", + "\\u0017", + "\\u0018", + "\\u0019", + "\\u001A", + "\\u001B", + "\\u001C", + "\\u001D", + "\\u001E", + "\\u001F", + "", + "", + "\\\"", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "\\\\", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "\\u007F", + "\\u0080", + "\\u0081", + "\\u0082", + "\\u0083", + "\\u0084", + "\\u0085", + "\\u0086", + "\\u0087", + "\\u0088", + "\\u0089", + "\\u008A", + "\\u008B", + "\\u008C", + "\\u008D", + "\\u008E", + "\\u008F", + "\\u0090", + "\\u0091", + "\\u0092", + "\\u0093", + "\\u0094", + "\\u0095", + "\\u0096", + "\\u0097", + "\\u0098", + "\\u0099", + "\\u009A", + "\\u009B", + "\\u009C", + "\\u009D", + "\\u009E", + "\\u009F" + ]; +}); + +// node_modules/graphql/language/visitor.js +var require_visitor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BREAK = undefined; + exports.visit = visit; + exports.visitInParallel = visitInParallel; + exports.getEnterLeaveForKind = getEnterLeaveForKind; + var devAssert_ts_1 = require_devAssert(); + var inspect_ts_1 = require_inspect(); + var ast_ts_1 = require_ast(); + var kinds_ts_1 = require_kinds(); + exports.BREAK = Object.freeze({}); + function visit(root, visitor, visitorKeys = ast_ts_1.QueryDocumentKeys) { + const enterLeaveMap = new Map; + for (const kind2 of Object.values(kinds_ts_1.Kind)) { + enterLeaveMap.set(kind2, getEnterLeaveForKind(visitor, kind2)); + } + let stack = undefined; + let inArray = Array.isArray(root); + let keys = [root]; + let index = -1; + let edits = []; + let node = root; + let key = undefined; + let parent = undefined; + const path = []; + const ancestors = []; + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + let editOffset = 0; + for (const [editKey, editValue] of edits) { + const arrayKey = editKey - editOffset; + if (editValue === null) { + node.splice(arrayKey, 1); + editOffset++; + } else { + node[arrayKey] = editValue; + } + } + } else { + node = { ...node }; + for (const [editKey, editValue] of edits) { + node[editKey] = editValue; + } + } + } + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else if (parent != null) { + key = inArray ? index : keys[index]; + node = parent[key]; + if (node === null || node === undefined) { + continue; + } + path.push(key); + } + let result; + if (!Array.isArray(node)) { + if (!(0, ast_ts_1.isNode)(node)) + (0, devAssert_ts_1.devAssert)(false, `Invalid AST Node: ${(0, inspect_ts_1.inspect)(node)}.`); + const visitFn = isLeaving ? enterLeaveMap.get(node.kind)?.leave : enterLeaveMap.get(node.kind)?.enter; + result = visitFn?.call(visitor, node, key, parent, path, ancestors); + if (result === exports.BREAK) { + break; + } + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + if (!isLeaving) { + if ((0, ast_ts_1.isNode)(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + if (result === undefined && isEdited) { + edits.push([key, node]); + } + if (isLeaving) { + path.pop(); + } else { + stack = { inArray, index, keys, edits, prev: stack }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] ?? []; + index = -1; + edits = []; + if (parent != null) { + ancestors.push(parent); + } + parent = node; + } + } while (stack !== undefined); + if (edits.length !== 0) { + return edits.at(-1)[1]; + } + return root; + } + function visitInParallel(visitors) { + const skipping = new Array(visitors.length).fill(null); + const mergedVisitor = Object.create(null); + for (const kind2 of Object.values(kinds_ts_1.Kind)) { + let hasVisitor = false; + const enterList = new Array(visitors.length).fill(undefined); + const leaveList = new Array(visitors.length).fill(undefined); + for (let i = 0;i < visitors.length; ++i) { + const { enter, leave } = getEnterLeaveForKind(visitors[i], kind2); + hasVisitor ||= enter != null || leave != null; + enterList[i] = enter; + leaveList[i] = leave; + } + if (!hasVisitor) { + continue; + } + const mergedEnterLeave = { + enter(...args) { + const node = args[0]; + for (let i = 0;i < visitors.length; i++) { + if (skipping[i] === null) { + const result = enterList[i]?.apply(visitors[i], args); + if (result === false) { + skipping[i] = node; + } else if (result === exports.BREAK) { + skipping[i] = exports.BREAK; + } else if (result !== undefined) { + return result; + } + } + } + }, + leave(...args) { + const node = args[0]; + for (let i = 0;i < visitors.length; i++) { + if (skipping[i] === null) { + const result = leaveList[i]?.apply(visitors[i], args); + if (result === exports.BREAK) { + skipping[i] = exports.BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; + mergedVisitor[kind2] = mergedEnterLeave; + } + return mergedVisitor; + } + function getEnterLeaveForKind(visitor, kind2) { + const kindVisitor = visitor[kind2]; + if (typeof kindVisitor === "object") { + return kindVisitor; + } else if (typeof kindVisitor === "function") { + return { enter: kindVisitor, leave: undefined }; + } + return { enter: visitor.enter, leave: visitor.leave }; + } +}); + +// node_modules/graphql/language/printer.js +var require_printer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.print = print; + var blockString_ts_1 = require_blockString(); + var printString_ts_1 = require_printString(); + var visitor_ts_1 = require_visitor(); + function print(ast) { + return (0, visitor_ts_1.visit)(ast, printDocASTReducer); + } + var MAX_LINE_LENGTH = 80; + var printDocASTReducer = { + Name: { leave: (node) => node.value }, + Variable: { leave: (node) => "$" + node.name }, + Document: { + leave: (node) => join(node.definitions, ` + +`) + }, + OperationDefinition: { + leave(node) { + const varDefs = hasMultilineItems(node.variableDefinitions) ? wrap(`( +`, join(node.variableDefinitions, ` +`), ` +)`) : wrap("(", join(node.variableDefinitions, ", "), ")"); + const prefix = wrap("", node.description, ` +`) + join([ + node.operation, + join([node.name, varDefs]), + join(node.directives, " ") + ], " "); + return (prefix === "query" ? "" : prefix + " ") + node.selectionSet; + } + }, + VariableDefinition: { + leave: ({ variable, type, defaultValue, directives, description }) => wrap("", description, ` +`) + variable + ": " + type + wrap(" = ", defaultValue) + wrap(" ", join(directives, " ")) + }, + SelectionSet: { leave: ({ selections }) => block(selections) }, + Field: { + leave({ alias, name, arguments: args, directives, selectionSet }) { + const prefix = join([wrap("", alias, ": "), name], ""); + return join([ + wrappedLineAndArgs(prefix, args), + wrap(" ", join(directives, " ")), + wrap(" ", selectionSet) + ]); + } + }, + Argument: { leave: ({ name, value }) => name + ": " + value }, + FragmentArgument: { leave: ({ name, value }) => name + ": " + value }, + FragmentSpread: { + leave: ({ name, arguments: args, directives }) => { + const prefix = "..." + name; + return wrappedLineAndArgs(prefix, args) + wrap(" ", join(directives, " ")); + } + }, + InlineFragment: { + leave: ({ typeCondition, directives, selectionSet }) => join([ + "...", + wrap("on ", typeCondition), + join(directives, " "), + selectionSet + ], " ") + }, + FragmentDefinition: { + leave: ({ name, typeCondition, variableDefinitions, directives, selectionSet, description }) => wrap("", description, ` +`) + `fragment ${name}${wrap("(", join(variableDefinitions, ", "), ")")} ` + `on ${typeCondition} ${wrap("", join(directives, " "), " ")}` + selectionSet + }, + IntValue: { leave: ({ value }) => value }, + FloatValue: { leave: ({ value }) => value }, + StringValue: { + leave: ({ value, block: isBlockString }) => isBlockString === true ? (0, blockString_ts_1.printBlockString)(value) : (0, printString_ts_1.printString)(value) + }, + BooleanValue: { leave: ({ value }) => value ? "true" : "false" }, + NullValue: { leave: () => "null" }, + EnumValue: { leave: ({ value }) => value }, + ListValue: { + leave: ({ values }) => { + const valuesLine = "[" + join(values, ", ") + "]"; + if (valuesLine.length > MAX_LINE_LENGTH) { + return `[ +` + indent(join(values, ` +`)) + ` +]`; + } + return valuesLine; + } + }, + ObjectValue: { + leave: ({ fields }) => { + const fieldsLine = "{ " + join(fields, ", ") + " }"; + return fieldsLine.length > MAX_LINE_LENGTH ? block(fields) : fieldsLine; + } + }, + ObjectField: { leave: ({ name, value }) => name + ": " + value }, + Directive: { + leave: ({ name, arguments: args }) => "@" + name + wrap("(", join(args, ", "), ")") + }, + NamedType: { leave: ({ name }) => name }, + ListType: { leave: ({ type }) => "[" + type + "]" }, + NonNullType: { leave: ({ type }) => type + "!" }, + SchemaDefinition: { + leave: ({ description, directives, operationTypes }) => wrap("", description, ` +`) + join(["schema", join(directives, " "), block(operationTypes)], " ") + }, + OperationTypeDefinition: { + leave: ({ operation, type }) => operation + ": " + type + }, + ScalarTypeDefinition: { + leave: ({ description, name, directives }) => wrap("", description, ` +`) + join(["scalar", name, join(directives, " ")], " ") + }, + ObjectTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, ` +`) + join([ + "type", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields) + ], " ") + }, + FieldDefinition: { + leave: ({ description, name, arguments: args, type, directives }) => wrap("", description, ` +`) + name + (hasMultilineItems(args) ? wrap(`( +`, indent(join(args, ` +`)), ` +)`) : wrap("(", join(args, ", "), ")")) + ": " + type + wrap(" ", join(directives, " ")) + }, + InputValueDefinition: { + leave: ({ description, name, type, defaultValue, directives }) => wrap("", description, ` +`) + join([name + ": " + type, wrap("= ", defaultValue), join(directives, " ")], " ") + }, + InterfaceTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => wrap("", description, ` +`) + join([ + "interface", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields) + ], " ") + }, + UnionTypeDefinition: { + leave: ({ description, name, directives, types }) => wrap("", description, ` +`) + join(["union", name, join(directives, " "), wrap("= ", join(types, " | "))], " ") + }, + EnumTypeDefinition: { + leave: ({ description, name, directives, values }) => wrap("", description, ` +`) + join(["enum", name, join(directives, " "), block(values)], " ") + }, + EnumValueDefinition: { + leave: ({ description, name, directives }) => wrap("", description, ` +`) + join([name, join(directives, " ")], " ") + }, + InputObjectTypeDefinition: { + leave: ({ description, name, directives, fields }) => wrap("", description, ` +`) + join(["input", name, join(directives, " "), block(fields)], " ") + }, + DirectiveDefinition: { + leave: ({ description, name, arguments: args, directives, repeatable, locations }) => wrap("", description, ` +`) + "directive @" + name + (hasMultilineItems(args) ? wrap(`( +`, indent(join(args, ` +`)), ` +)`) : wrap("(", join(args, ", "), ")")) + wrap(" ", join(directives, " ")) + (repeatable ? " repeatable" : "") + " on " + join(locations, " | ") + }, + SchemaExtension: { + leave: ({ directives, operationTypes }) => join(["extend schema", join(directives, " "), block(operationTypes)], " ") + }, + ScalarTypeExtension: { + leave: ({ name, directives }) => join(["extend scalar", name, join(directives, " ")], " ") + }, + ObjectTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => join([ + "extend type", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields) + ], " ") + }, + InterfaceTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => join([ + "extend interface", + name, + wrap("implements ", join(interfaces, " & ")), + join(directives, " "), + block(fields) + ], " ") + }, + UnionTypeExtension: { + leave: ({ name, directives, types }) => join([ + "extend union", + name, + join(directives, " "), + wrap("= ", join(types, " | ")) + ], " ") + }, + EnumTypeExtension: { + leave: ({ name, directives, values }) => join(["extend enum", name, join(directives, " "), block(values)], " ") + }, + InputObjectTypeExtension: { + leave: ({ name, directives, fields }) => join(["extend input", name, join(directives, " "), block(fields)], " ") + }, + DirectiveExtension: { + leave: ({ name, directives }) => join(["extend directive @" + name, join(directives, " ")], " ") + }, + TypeCoordinate: { leave: ({ name }) => name }, + MemberCoordinate: { + leave: ({ name, memberName }) => join([name, wrap(".", memberName)]) + }, + ArgumentCoordinate: { + leave: ({ name, fieldName, argumentName }) => join([name, wrap(".", fieldName), wrap("(", argumentName, ":)")]) + }, + DirectiveCoordinate: { leave: ({ name }) => join(["@", name]) }, + DirectiveArgumentCoordinate: { + leave: ({ name, argumentName }) => join(["@", name, wrap("(", argumentName, ":)")]) + } + }; + function join(maybeArray, separator = "") { + return maybeArray?.filter((x) => x !== undefined && x !== "").join(separator) ?? ""; + } + function block(array) { + return wrap(`{ +`, indent(join(array, ` +`)), ` +}`); + } + function wrap(start, maybeString, end = "") { + return maybeString != null && maybeString !== "" ? start + maybeString + end : ""; + } + function indent(str) { + return wrap(" ", str.replaceAll(` +`, ` + `)); + } + function hasMultilineItems(maybeArray) { + return maybeArray?.some((str) => str.includes(` +`)) ?? false; + } + function wrappedLineAndArgs(prefix, args) { + let argsLine = prefix + wrap("(", join(args, ", "), ")"); + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap(`( +`, indent(join(args, ` +`)), ` +)`); + } + return argsLine; + } +}); + +// node_modules/graphql/utilities/valueFromASTUntyped.js +var require_valueFromASTUntyped = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.valueFromASTUntyped = valueFromASTUntyped; + var keyValMap_ts_1 = require_keyValMap(); + var kinds_ts_1 = require_kinds(); + function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case kinds_ts_1.Kind.NULL: + return null; + case kinds_ts_1.Kind.INT: + return parseInt(valueNode.value, 10); + case kinds_ts_1.Kind.FLOAT: + return parseFloat(valueNode.value); + case kinds_ts_1.Kind.STRING: + case kinds_ts_1.Kind.ENUM: + case kinds_ts_1.Kind.BOOLEAN: + return valueNode.value; + case kinds_ts_1.Kind.LIST: + return valueNode.values.map((node) => valueFromASTUntyped(node, variables)); + case kinds_ts_1.Kind.OBJECT: + return (0, keyValMap_ts_1.keyValMap)(valueNode.fields, (field) => field.name.value, (field) => valueFromASTUntyped(field.value, variables)); + case kinds_ts_1.Kind.VARIABLE: + return variables?.[valueNode.name.value]; + } + } +}); + +// node_modules/graphql/type/assertName.js +var require_assertName = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assertName = assertName; + exports.assertEnumValueName = assertEnumValueName; + var GraphQLError_ts_1 = require_GraphQLError(); + var characterClasses_ts_1 = require_characterClasses(); + function assertName(name) { + if (name.length === 0) { + throw new GraphQLError_ts_1.GraphQLError("Expected name to be a non-empty string."); + } + for (let i = 1;i < name.length; ++i) { + if (!(0, characterClasses_ts_1.isNameContinue)(name.charCodeAt(i))) { + throw new GraphQLError_ts_1.GraphQLError(`Names must only contain [_a-zA-Z0-9] but "${name}" does not.`); + } + } + if (!(0, characterClasses_ts_1.isNameStart)(name.charCodeAt(0))) { + throw new GraphQLError_ts_1.GraphQLError(`Names must start with [_a-zA-Z] but "${name}" does not.`); + } + return name; + } + function assertEnumValueName(name) { + if (name === "true" || name === "false" || name === "null") { + throw new GraphQLError_ts_1.GraphQLError(`Enum values cannot be named: ${name}`); + } + return assertName(name); + } +}); + +// node_modules/graphql/type/definition.js +var require_definition = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GraphQLInputField = exports.GraphQLInputObjectType = exports.GraphQLEnumValue = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLArgument = exports.GraphQLField = exports.GraphQLObjectType = exports.GraphQLScalarType = exports.GraphQLNonNull = exports.GraphQLList = undefined; + exports.isType = isType; + exports.assertType = assertType; + exports.isScalarType = isScalarType; + exports.assertScalarType = assertScalarType; + exports.isObjectType = isObjectType; + exports.assertObjectType = assertObjectType; + exports.isField = isField; + exports.assertField = assertField; + exports.isArgument = isArgument; + exports.assertArgument = assertArgument; + exports.isInterfaceType = isInterfaceType; + exports.assertInterfaceType = assertInterfaceType; + exports.isUnionType = isUnionType; + exports.assertUnionType = assertUnionType; + exports.isEnumType = isEnumType; + exports.assertEnumType = assertEnumType; + exports.isEnumValue = isEnumValue; + exports.assertEnumValue = assertEnumValue; + exports.isInputObjectType = isInputObjectType; + exports.assertInputObjectType = assertInputObjectType; + exports.isInputField = isInputField; + exports.assertInputField = assertInputField; + exports.isListType = isListType; + exports.assertListType = assertListType; + exports.isNonNullType = isNonNullType; + exports.assertNonNullType = assertNonNullType; + exports.isInputType = isInputType; + exports.assertInputType = assertInputType; + exports.isOutputType = isOutputType; + exports.assertOutputType = assertOutputType; + exports.isLeafType = isLeafType; + exports.assertLeafType = assertLeafType; + exports.isCompositeType = isCompositeType; + exports.assertCompositeType = assertCompositeType; + exports.isAbstractType = isAbstractType; + exports.assertAbstractType = assertAbstractType; + exports.isWrappingType = isWrappingType; + exports.assertWrappingType = assertWrappingType; + exports.isNullableType = isNullableType; + exports.assertNullableType = assertNullableType; + exports.getNullableType = getNullableType; + exports.isNamedType = isNamedType; + exports.assertNamedType = assertNamedType; + exports.getNamedType = getNamedType; + exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; + exports.resolveObjMapThunk = resolveObjMapThunk; + exports.isRequiredArgument = isRequiredArgument; + exports.isRequiredInputField = isRequiredInputField; + var devAssert_ts_1 = require_devAssert(); + var didYouMean_ts_1 = require_didYouMean(); + var identityFunc_ts_1 = require_identityFunc(); + var inspect_ts_1 = require_inspect(); + var instanceOf_ts_1 = require_instanceOf(); + var keyMap_ts_1 = require_keyMap(); + var keyValMap_ts_1 = require_keyValMap(); + var mapValue_ts_1 = require_mapValue(); + var suggestionList_ts_1 = require_suggestionList(); + var toObjMap_ts_1 = require_toObjMap(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var printer_ts_1 = require_printer(); + var valueFromASTUntyped_ts_1 = require_valueFromASTUntyped(); + var assertName_ts_1 = require_assertName(); + function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); + } + function assertType(type) { + if (!isType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL type.`); + } + return type; + } + var scalarSymbol = Symbol("Scalar"); + function isScalarType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, scalarSymbol, GraphQLScalarType); + } + function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL Scalar type.`); + } + return type; + } + var objectSymbol = Symbol("Object"); + function isObjectType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, objectSymbol, GraphQLObjectType); + } + function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL Object type.`); + } + return type; + } + var fieldSymbol = Symbol("Field"); + function isField(field) { + return (0, instanceOf_ts_1.instanceOf)(field, fieldSymbol, GraphQLField); + } + function assertField(field) { + if (!isField(field)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(field)} to be a GraphQL field.`); + } + return field; + } + var argumentSymbol = Symbol("Argument"); + function isArgument(arg) { + return (0, instanceOf_ts_1.instanceOf)(arg, argumentSymbol, GraphQLArgument); + } + function assertArgument(arg) { + if (!isArgument(arg)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(arg)} to be a GraphQL argument.`); + } + return arg; + } + var interfaceSymbol = Symbol("Interface"); + function isInterfaceType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, interfaceSymbol, GraphQLInterfaceType); + } + function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL Interface type.`); + } + return type; + } + var unionSymbol = Symbol("Union"); + function isUnionType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, unionSymbol, GraphQLUnionType); + } + function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL Union type.`); + } + return type; + } + var enumSymbol = Symbol("Enum"); + function isEnumType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, enumSymbol, GraphQLEnumType); + } + function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL Enum type.`); + } + return type; + } + var enumValueSymbol = Symbol("EnumValue"); + function isEnumValue(value) { + return (0, instanceOf_ts_1.instanceOf)(value, enumValueSymbol, GraphQLEnumValue); + } + function assertEnumValue(value) { + if (!isEnumValue(value)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(value)} to be a GraphQL Enum value.`); + } + return value; + } + var inputObjectSymbol = Symbol("InputObject"); + function isInputObjectType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, inputObjectSymbol, GraphQLInputObjectType); + } + function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL Input Object type.`); + } + return type; + } + var inputFieldSymbol = Symbol("InputField"); + function isInputField(field) { + return (0, instanceOf_ts_1.instanceOf)(field, inputFieldSymbol, GraphQLInputField); + } + function assertInputField(field) { + if (!isInputField(field)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(field)} to be a GraphQL input field.`); + } + return field; + } + var listSymbol = Symbol("List"); + function isListType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, listSymbol, GraphQLList); + } + function assertListType(type) { + if (!isListType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL List type.`); + } + return type; + } + var nonNullSymbol = Symbol("NonNull"); + function isNonNullType(type) { + return (0, instanceOf_ts_1.instanceOf)(type, nonNullSymbol, GraphQLNonNull); + } + function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL Non-Null type.`); + } + return type; + } + function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); + } + function assertInputType(type) { + if (!isInputType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL input type.`); + } + return type; + } + function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); + } + function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL output type.`); + } + return type; + } + function isLeafType(type) { + return isScalarType(type) || isEnumType(type); + } + function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL leaf type.`); + } + return type; + } + function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); + } + function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL composite type.`); + } + return type; + } + function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); + } + function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL abstract type.`); + } + return type; + } + + class GraphQLList { + constructor(ofType) { + this.__kind = listSymbol; + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return "GraphQLList"; + } + toString() { + return "[" + String(this.ofType) + "]"; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLList = GraphQLList; + + class GraphQLNonNull { + constructor(ofType) { + this.__kind = nonNullSymbol; + this.ofType = ofType; + } + get [Symbol.toStringTag]() { + return "GraphQLNonNull"; + } + toString() { + return String(this.ofType) + "!"; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLNonNull = GraphQLNonNull; + function isWrappingType(type) { + return isListType(type) || isNonNullType(type); + } + function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL wrapping type.`); + } + return type; + } + function isNullableType(type) { + return isType(type) && !isNonNullType(type); + } + function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL nullable type.`); + } + return type; + } + function getNullableType(type) { + if (type) { + return isNonNullType(type) ? type.ofType : type; + } + } + function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); + } + function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(type)} to be a GraphQL named type.`); + } + return type; + } + function getNamedType(type) { + if (type) { + let unwrappedType = type; + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + return unwrappedType; + } + } + function resolveReadonlyArrayThunk(thunk) { + return typeof thunk === "function" ? thunk() : thunk; + } + function resolveObjMapThunk(thunk) { + return typeof thunk === "function" ? thunk() : thunk; + } + + class GraphQLScalarType { + constructor(config) { + this.__kind = scalarSymbol; + this.name = (0, assertName_ts_1.assertName)(config.name); + this.description = config.description; + this.specifiedByURL = config.specifiedByURL; + this.serialize = config.serialize ?? config.coerceOutputValue ?? identityFunc_ts_1.identityFunc; + this.parseValue = config.parseValue ?? config.coerceInputValue ?? identityFunc_ts_1.identityFunc; + this.parseLiteral = config.parseLiteral ?? ((node, variables) => this.coerceInputValue((0, valueFromASTUntyped_ts_1.valueFromASTUntyped)(node, variables))); + this.coerceOutputValue = config.coerceOutputValue ?? this.serialize; + this.coerceInputValue = config.coerceInputValue ?? this.parseValue; + this.coerceInputLiteral = config.coerceInputLiteral; + this.valueToLiteral = config.valueToLiteral; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + if (config.parseLiteral) { + if (!(typeof config.parseValue === "function" && typeof config.parseLiteral === "function")) + (0, devAssert_ts_1.devAssert)(false, `${this.name} must provide both "parseValue" and "parseLiteral" functions.`); + } + if (config.coerceInputLiteral) { + if (!(typeof config.coerceInputValue === "function" && typeof config.coerceInputLiteral === "function")) + (0, devAssert_ts_1.devAssert)(false, `${this.name} must provide both "coerceInputValue" and "coerceInputLiteral" functions.`); + } + } + get [Symbol.toStringTag]() { + return "GraphQLScalarType"; + } + toConfig() { + return { + name: this.name, + description: this.description, + specifiedByURL: this.specifiedByURL, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + coerceOutputValue: this.coerceOutputValue, + coerceInputValue: this.coerceInputValue, + coerceInputLiteral: this.coerceInputLiteral, + valueToLiteral: this.valueToLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLScalarType = GraphQLScalarType; + + class GraphQLObjectType { + constructor(config) { + this.__kind = objectSymbol; + this.__kind = objectSymbol; + this.name = (0, assertName_ts_1.assertName)(config.name); + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + this._fields = defineFieldMap.bind(undefined, this, config.fields); + this._interfaces = defineInterfaces.bind(undefined, config.interfaces); + } + get [Symbol.toStringTag]() { + return "GraphQLObjectType"; + } + getFields() { + if (typeof this._fields === "function") { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === "function") { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: (0, mapValue_ts_1.mapValue)(this.getFields(), (field) => field.toConfig()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLObjectType = GraphQLObjectType; + function defineInterfaces(interfaces) { + return resolveReadonlyArrayThunk(interfaces ?? []); + } + function defineFieldMap(parentType, fields) { + const fieldMap = resolveObjMapThunk(fields); + return (0, mapValue_ts_1.mapValue)(fieldMap, (fieldConfig, fieldName) => new GraphQLField(parentType, fieldName, fieldConfig)); + } + + class GraphQLField { + constructor(parentType, name, config) { + this.__kind = fieldSymbol; + this.parentType = parentType; + this.name = (0, assertName_ts_1.assertName)(name); + this.description = config.description; + this.type = config.type; + const argsConfig = config.args; + this.args = argsConfig ? Object.entries(argsConfig).map(([argName, argConfig]) => new GraphQLArgument(this, argName, argConfig)) : []; + this.resolve = config.resolve; + this.subscribe = config.subscribe; + this.deprecationReason = config.deprecationReason; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + } + get [Symbol.toStringTag]() { + return "GraphQLField"; + } + toConfig() { + return { + description: this.description, + type: this.type, + args: (0, keyValMap_ts_1.keyValMap)(this.args, (arg) => arg.name, (arg) => arg.toConfig()), + resolve: this.resolve, + subscribe: this.subscribe, + deprecationReason: this.deprecationReason, + extensions: this.extensions, + astNode: this.astNode + }; + } + toString() { + return `${this.parentType ?? ""}.${this.name}`; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLField = GraphQLField; + + class GraphQLArgument { + constructor(parent, name, config) { + this.__kind = argumentSymbol; + this.parent = parent; + this.name = (0, assertName_ts_1.assertName)(name); + this.description = config.description; + this.type = config.type; + this.defaultValue = config.defaultValue; + this.default = config.default; + this._memoizedCoercedDefaultValue = undefined; + this.deprecationReason = config.deprecationReason; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + } + get [Symbol.toStringTag]() { + return "GraphQLArgument"; + } + toConfig() { + return { + description: this.description, + type: this.type, + defaultValue: this.defaultValue, + default: this.default, + deprecationReason: this.deprecationReason, + extensions: this.extensions, + astNode: this.astNode + }; + } + toString() { + return `${this.parent}(${this.name}:)`; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLArgument = GraphQLArgument; + function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.default === undefined && arg.defaultValue === undefined; + } + + class GraphQLInterfaceType { + constructor(config) { + this.__kind = interfaceSymbol; + this.name = (0, assertName_ts_1.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + this._fields = defineFieldMap.bind(undefined, this, config.fields); + this._interfaces = defineInterfaces.bind(undefined, config.interfaces); + } + get [Symbol.toStringTag]() { + return "GraphQLInterfaceType"; + } + getFields() { + if (typeof this._fields === "function") { + this._fields = this._fields(); + } + return this._fields; + } + getInterfaces() { + if (typeof this._interfaces === "function") { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: (0, mapValue_ts_1.mapValue)(this.getFields(), (field) => field.toConfig()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLInterfaceType = GraphQLInterfaceType; + + class GraphQLUnionType { + constructor(config) { + this.__kind = unionSymbol; + this.name = (0, assertName_ts_1.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + this._types = defineTypes.bind(undefined, config.types); + } + get [Symbol.toStringTag]() { + return "GraphQLUnionType"; + } + getTypes() { + if (typeof this._types === "function") { + this._types = this._types(); + } + return this._types; + } + toConfig() { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLUnionType = GraphQLUnionType; + function defineTypes(types) { + return resolveReadonlyArrayThunk(types); + } + + class GraphQLEnumType { + constructor(config) { + this.__kind = enumSymbol; + this.name = (0, assertName_ts_1.assertName)(config.name); + this.description = config.description; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + this._values = defineEnumValues.bind(undefined, this, config.values); + this._valueLookup = null; + this._nameLookup = null; + } + get [Symbol.toStringTag]() { + return "GraphQLEnumType"; + } + getValues() { + if (typeof this._values === "function") { + this._values = this._values(); + } + return this._values; + } + getValue(name) { + this._nameLookup ??= (0, keyMap_ts_1.keyMap)(this.getValues(), (value) => value.name); + return this._nameLookup[name]; + } + serialize(outputValue) { + return this.coerceOutputValue(outputValue); + } + coerceOutputValue(outputValue) { + this._valueLookup ??= new Map(this.getValues().map((enumValue2) => [enumValue2.value, enumValue2])); + const enumValue = this._valueLookup.get(outputValue); + if (enumValue === undefined) { + throw new GraphQLError_ts_1.GraphQLError(`Enum "${this.name}" cannot represent value: ${(0, inspect_ts_1.inspect)(outputValue)}`); + } + return enumValue.name; + } + parseValue(inputValue, hideSuggestions) { + return this.coerceInputValue(inputValue, hideSuggestions); + } + coerceInputValue(inputValue, hideSuggestions) { + if (typeof inputValue !== "string") { + const valueStr = (0, inspect_ts_1.inspect)(inputValue); + throw new GraphQLError_ts_1.GraphQLError(`Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + (hideSuggestions ? "" : didYouMeanEnumValue(this, valueStr))); + } + const enumValue = this.getValue(inputValue); + if (enumValue == null) { + throw new GraphQLError_ts_1.GraphQLError(`Value "${inputValue}" does not exist in "${this.name}" enum.` + (hideSuggestions ? "" : didYouMeanEnumValue(this, inputValue))); + } + return enumValue.value; + } + parseLiteral(valueNode, _variables, hideSuggestions) { + return this.coerceInputLiteral(valueNode, hideSuggestions); + } + coerceInputLiteral(valueNode, hideSuggestions) { + if (valueNode.kind !== kinds_ts_1.Kind.ENUM) { + const valueStr = (0, printer_ts_1.print)(valueNode); + throw new GraphQLError_ts_1.GraphQLError(`Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + (hideSuggestions ? "" : didYouMeanEnumValue(this, valueStr)), { nodes: valueNode }); + } + const enumValue = this.getValue(valueNode.value); + if (enumValue == null) { + const valueStr = (0, printer_ts_1.print)(valueNode); + throw new GraphQLError_ts_1.GraphQLError(`Value "${valueStr}" does not exist in "${this.name}" enum.` + (hideSuggestions ? "" : didYouMeanEnumValue(this, valueStr)), { nodes: valueNode }); + } + return enumValue.value; + } + valueToLiteral(value) { + if (typeof value === "string" && this.getValue(value)) { + return { kind: kinds_ts_1.Kind.ENUM, value }; + } + } + toConfig() { + return { + name: this.name, + description: this.description, + values: (0, keyValMap_ts_1.keyValMap)(this.getValues(), (value) => value.name, (value) => value.toConfig()), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLEnumType = GraphQLEnumType; + function defineEnumValues(parentEnum, values) { + const valueMap = resolveObjMapThunk(values); + return Object.entries(valueMap).map(([valueName, valueConfig]) => new GraphQLEnumValue(parentEnum, valueName, valueConfig)); + } + function didYouMeanEnumValue(enumType, unknownValueStr) { + const allNames = enumType.getValues().map((value) => value.name); + const suggestedValues = (0, suggestionList_ts_1.suggestionList)(unknownValueStr, allNames); + return (0, didYouMean_ts_1.didYouMean)("the enum value", suggestedValues); + } + + class GraphQLEnumValue { + constructor(parentEnum, name, config) { + this.__kind = enumValueSymbol; + this.parentEnum = parentEnum; + this.name = (0, assertName_ts_1.assertEnumValueName)(name); + this.description = config.description; + this.value = config.value !== undefined ? config.value : name; + this.deprecationReason = config.deprecationReason; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + } + get [Symbol.toStringTag]() { + return "GraphQLEnumValue"; + } + toConfig() { + return { + description: this.description, + value: this.value, + deprecationReason: this.deprecationReason, + extensions: this.extensions, + astNode: this.astNode + }; + } + toString() { + return `${this.parentEnum.name}.${this.name}`; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLEnumValue = GraphQLEnumValue; + + class GraphQLInputObjectType { + constructor(config) { + this.__kind = inputObjectSymbol; + this.name = (0, assertName_ts_1.assertName)(config.name); + this.description = config.description; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + this.isOneOf = config.isOneOf ?? false; + this._fields = defineInputFieldMap.bind(undefined, this, config.fields); + } + get [Symbol.toStringTag]() { + return "GraphQLInputObjectType"; + } + getFields() { + if (typeof this._fields === "function") { + this._fields = this._fields(); + } + return this._fields; + } + toConfig() { + return { + name: this.name, + description: this.description, + fields: (0, mapValue_ts_1.mapValue)(this.getFields(), (field) => field.toConfig()), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + isOneOf: this.isOneOf + }; + } + toString() { + return this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLInputObjectType = GraphQLInputObjectType; + function defineInputFieldMap(parentType, fields) { + const fieldMap = resolveObjMapThunk(fields); + return (0, mapValue_ts_1.mapValue)(fieldMap, (fieldConfig, fieldName) => new GraphQLInputField(parentType, fieldName, fieldConfig)); + } + + class GraphQLInputField { + constructor(parentType, name, config) { + if (!!("resolve" in config)) + (0, devAssert_ts_1.devAssert)(false, `${parentType}.${name} field has a resolve property, but Input Types cannot define resolvers.`); + this.__kind = inputFieldSymbol; + this.parentType = parentType; + this.name = (0, assertName_ts_1.assertName)(name); + this.description = config.description; + this.type = config.type; + this.defaultValue = config.defaultValue; + this.default = config.default; + this._memoizedCoercedDefaultValue = undefined; + this.deprecationReason = config.deprecationReason; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + } + get [Symbol.toStringTag]() { + return "GraphQLInputField"; + } + toConfig() { + return { + description: this.description, + type: this.type, + defaultValue: this.defaultValue, + default: this.default, + deprecationReason: this.deprecationReason, + extensions: this.extensions, + astNode: this.astNode + }; + } + toString() { + return `${this.parentType}.${this.name}`; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLInputField = GraphQLInputField; + function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined && field.default === undefined; + } +}); + +// node_modules/graphql/utilities/typeComparators.js +var require_typeComparators = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isEqualType = isEqualType; + exports.isTypeSubTypeOf = isTypeSubTypeOf; + exports.doTypesOverlap = doTypesOverlap; + var definition_ts_1 = require_definition(); + function isEqualType(typeA, typeB) { + if (typeA === typeB) { + return true; + } + if ((0, definition_ts_1.isNonNullType)(typeA) && (0, definition_ts_1.isNonNullType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } + if ((0, definition_ts_1.isListType)(typeA) && (0, definition_ts_1.isListType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } + return false; + } + function isTypeSubTypeOf(schema, maybeSubType, superType) { + if (maybeSubType === superType) { + return true; + } + if ((0, definition_ts_1.isNonNullType)(superType)) { + if ((0, definition_ts_1.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if ((0, definition_ts_1.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } + if ((0, definition_ts_1.isListType)(superType)) { + if ((0, definition_ts_1.isListType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if ((0, definition_ts_1.isListType)(maybeSubType)) { + return false; + } + return (0, definition_ts_1.isAbstractType)(superType) && ((0, definition_ts_1.isInterfaceType)(maybeSubType) || (0, definition_ts_1.isObjectType)(maybeSubType)) && schema.isSubType(superType, maybeSubType); + } + function doTypesOverlap(schema, typeA, typeB) { + if (typeA === typeB) { + return true; + } + if ((0, definition_ts_1.isAbstractType)(typeA)) { + if ((0, definition_ts_1.isAbstractType)(typeB)) { + return schema.getPossibleTypes(typeA).some((type) => schema.isSubType(typeB, type)); + } + return schema.isSubType(typeA, typeB); + } + if ((0, definition_ts_1.isAbstractType)(typeB)) { + return schema.isSubType(typeB, typeA); + } + return false; + } +}); + +// node_modules/graphql/jsutils/Path.js +var require_Path = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.addPath = addPath; + exports.pathToArray = pathToArray; + function addPath(prev, key, typename) { + return { prev, key, typename }; + } + function pathToArray(path) { + const flattened = []; + let curr = path; + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + return flattened.reverse(); + } +}); + +// node_modules/graphql/utilities/valueToLiteral.js +var require_valueToLiteral = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.valueToLiteral = valueToLiteral; + exports.defaultScalarValueToLiteral = defaultScalarValueToLiteral; + var inspect_ts_1 = require_inspect(); + var isIterableObject_ts_1 = require_isIterableObject(); + var isObjectLike_ts_1 = require_isObjectLike(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + function valueToLiteral(value, type) { + if ((0, definition_ts_1.isNonNullType)(type)) { + if (value == null) { + return; + } + return valueToLiteral(value, type.ofType); + } + if (value == null) { + return { kind: kinds_ts_1.Kind.NULL }; + } + if ((0, definition_ts_1.isListType)(type)) { + if (!(0, isIterableObject_ts_1.isIterableObject)(value)) { + return valueToLiteral(value, type.ofType); + } + const values = []; + for (const itemValue of value) { + const itemNode = valueToLiteral(itemValue, type.ofType); + if (!itemNode) { + return; + } + values.push(itemNode); + } + return { kind: kinds_ts_1.Kind.LIST, values }; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + if (!(0, isObjectLike_ts_1.isObjectLike)(value)) { + return; + } + const fields = []; + const fieldDefs = type.getFields(); + const hasUndefinedField = Object.keys(value).some((name) => value[name] !== undefined && !Object.hasOwn(fieldDefs, name)); + if (hasUndefinedField) { + return; + } + for (const field of Object.values(type.getFields())) { + const fieldValue = value[field.name]; + if (fieldValue === undefined) { + if ((0, definition_ts_1.isRequiredInputField)(field)) { + return; + } + } else { + const fieldNode = valueToLiteral(value[field.name], field.type); + if (!fieldNode) { + return; + } + fields.push({ + kind: kinds_ts_1.Kind.OBJECT_FIELD, + name: { kind: kinds_ts_1.Kind.NAME, value: field.name }, + value: fieldNode + }); + } + } + return { kind: kinds_ts_1.Kind.OBJECT, fields }; + } + const leafType = (0, definition_ts_1.assertLeafType)(type); + if (leafType.valueToLiteral) { + try { + return leafType.valueToLiteral(value); + } catch (_error) { + return; + } + } + return defaultScalarValueToLiteral(value); + } + function defaultScalarValueToLiteral(value) { + if (value == null) { + return { kind: kinds_ts_1.Kind.NULL }; + } + switch (typeof value) { + case "boolean": + return { kind: kinds_ts_1.Kind.BOOLEAN, value }; + case "string": + return { kind: kinds_ts_1.Kind.STRING, value, block: false }; + case "bigint": + return { kind: kinds_ts_1.Kind.INT, value: value.toString() }; + case "number": { + if (!Number.isFinite(value)) { + return { kind: kinds_ts_1.Kind.NULL }; + } + const stringValue = String(value); + return /^-?(?:0|[1-9][0-9]*)$/.test(stringValue) ? { kind: kinds_ts_1.Kind.INT, value: stringValue } : { kind: kinds_ts_1.Kind.FLOAT, value: stringValue }; + } + case "object": { + if ((0, isIterableObject_ts_1.isIterableObject)(value)) { + return { + kind: kinds_ts_1.Kind.LIST, + values: Array.from(value, defaultScalarValueToLiteral) + }; + } + const objValue = value; + const fields = []; + for (const fieldName of Object.keys(objValue)) { + const fieldValue = objValue[fieldName]; + if (fieldValue !== undefined) { + fields.push({ + kind: kinds_ts_1.Kind.OBJECT_FIELD, + name: { kind: kinds_ts_1.Kind.NAME, value: fieldName }, + value: defaultScalarValueToLiteral(fieldValue) + }); + } + } + return { kind: kinds_ts_1.Kind.OBJECT, fields }; + } + } + throw new TypeError(`Cannot convert value to AST: ${(0, inspect_ts_1.inspect)(value)}.`); + } +}); + +// node_modules/graphql/utilities/replaceVariables.js +var require_replaceVariables = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.replaceVariables = replaceVariables; + var kinds_ts_1 = require_kinds(); + var valueToLiteral_ts_1 = require_valueToLiteral(); + function replaceVariables(valueNode, variableValues, fragmentVariableValues) { + switch (valueNode.kind) { + case kinds_ts_1.Kind.VARIABLE: { + const varName = valueNode.name.value; + const fragmentVariableValueSource = fragmentVariableValues?.sources[varName]; + if (fragmentVariableValueSource) { + const value = fragmentVariableValueSource.value; + if (value === undefined) { + const defaultValue = fragmentVariableValueSource.signature.default; + if (defaultValue !== undefined) { + return defaultValue.literal; + } + return { kind: kinds_ts_1.Kind.NULL }; + } + return replaceVariables(value, variableValues, fragmentVariableValueSource.fragmentVariableValues); + } + const variableValueSource = variableValues?.sources[varName]; + if (variableValueSource == null) { + return { kind: kinds_ts_1.Kind.NULL }; + } + if (variableValueSource.value === undefined) { + const defaultValue = variableValueSource.signature.default; + if (defaultValue !== undefined) { + return defaultValue.literal; + } + } + return (0, valueToLiteral_ts_1.valueToLiteral)(variableValueSource.value, variableValueSource.signature.type); + } + case kinds_ts_1.Kind.OBJECT: { + const newFields = []; + for (const field of valueNode.fields) { + if (field.value.kind === kinds_ts_1.Kind.VARIABLE) { + const scopedVariableSource = fragmentVariableValues?.sources[field.value.name.value] ?? variableValues?.sources[field.value.name.value]; + if (scopedVariableSource?.value === undefined && scopedVariableSource?.signature.default === undefined) { + continue; + } + } + const newFieldNodeValue = replaceVariables(field.value, variableValues, fragmentVariableValues); + newFields.push({ + ...field, + value: newFieldNodeValue + }); + } + return { + ...valueNode, + fields: newFields + }; + } + case kinds_ts_1.Kind.LIST: { + const newValues = []; + for (const value of valueNode.values) { + const newItemNodeValue = replaceVariables(value, variableValues, fragmentVariableValues); + newValues.push(newItemNodeValue); + } + return { + ...valueNode, + values: newValues + }; + } + default: { + return valueNode; + } + } + } +}); + +// node_modules/graphql/utilities/validateInputValue.js +var require_validateInputValue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateInputValue = validateInputValue; + exports.validateInputLiteral = validateInputLiteral; + var didYouMean_ts_1 = require_didYouMean(); + var inspect_ts_1 = require_inspect(); + var isIterableObject_ts_1 = require_isIterableObject(); + var isObjectLike_ts_1 = require_isObjectLike(); + var keyMap_ts_1 = require_keyMap(); + var Path_ts_1 = require_Path(); + var suggestionList_ts_1 = require_suggestionList(); + var ensureGraphQLError_ts_1 = require_ensureGraphQLError(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var replaceVariables_ts_1 = require_replaceVariables(); + function validateInputValue(inputValue, type, onError, hideSuggestions) { + return validateInputValueImpl(inputValue, type, onError, hideSuggestions, undefined); + } + function validateInputValueImpl(inputValue, type, onError, hideSuggestions, path) { + if ((0, definition_ts_1.isNonNullType)(type)) { + if (inputValue === undefined) { + reportInvalidValue(onError, `Expected a value of non-null type "${type}" to be provided.`, path); + return; + } + if (inputValue === null) { + reportInvalidValue(onError, `Expected value of non-null type "${type}" not to be null.`, path); + return; + } + return validateInputValueImpl(inputValue, type.ofType, onError, hideSuggestions, path); + } + if (inputValue == null) { + return; + } + if ((0, definition_ts_1.isListType)(type)) { + if (!(0, isIterableObject_ts_1.isIterableObject)(inputValue)) { + validateInputValueImpl(inputValue, type.ofType, onError, hideSuggestions, path); + } else { + let index = 0; + for (const itemValue of inputValue) { + validateInputValueImpl(itemValue, type.ofType, onError, hideSuggestions, (0, Path_ts_1.addPath)(path, index++, undefined)); + } + } + } else if ((0, definition_ts_1.isInputObjectType)(type)) { + if (!(0, isObjectLike_ts_1.isObjectLike)(inputValue) || Array.isArray(inputValue)) { + reportInvalidValue(onError, `Expected value of type "${type}" to be an object, found: ${(0, inspect_ts_1.inspect)(inputValue)}.`, path); + return; + } + const fieldDefs = type.getFields(); + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; + if (fieldValue === undefined) { + if ((0, definition_ts_1.isRequiredInputField)(field)) { + reportInvalidValue(onError, `Expected value of type "${type}" to include required field "${field.name}", found: ${(0, inspect_ts_1.inspect)(inputValue)}.`, path); + } + } else { + validateInputValueImpl(fieldValue, field.type, onError, hideSuggestions, (0, Path_ts_1.addPath)(path, field.name, type.name)); + } + } + const fields = []; + for (const fieldName of Object.keys(inputValue)) { + if (inputValue[fieldName] === undefined) { + continue; + } + if (!Object.hasOwn(fieldDefs, fieldName)) { + const suggestion = hideSuggestions ? "" : (0, didYouMean_ts_1.didYouMean)((0, suggestionList_ts_1.suggestionList)(fieldName, Object.keys(fieldDefs))); + reportInvalidValue(onError, `Expected value of type "${type}" not to include unknown field "${fieldName}"${suggestion ? `.${suggestion} Found` : ", found"}: ${(0, inspect_ts_1.inspect)(inputValue)}.`, path); + continue; + } + fields.push(fieldName); + } + if (type.isOneOf) { + if (fields.length !== 1) { + reportInvalidValue(onError, getOneOfInputObjectErrorMessage(type), path); + } + const field = fields[0]; + const value = inputValue[field]; + if (value === null) { + reportInvalidValue(onError, getOneOfInputObjectErrorMessage(type), (0, Path_ts_1.addPath)(path, field, type.name)); + } + } + } else { + (0, definition_ts_1.assertLeafType)(type); + let result; + let caughtError; + try { + result = type.coerceInputValue(inputValue, hideSuggestions); + } catch (error) { + if (error instanceof GraphQLError_ts_1.GraphQLError) { + onError(error, (0, Path_ts_1.pathToArray)(path)); + return; + } + caughtError = error; + } + if (result === undefined) { + reportInvalidValue(onError, `Expected value of type "${type}"${caughtError != null ? `, but encountered error "${getCaughtErrorMessage(caughtError)}"; found` : ", found"}: ${(0, inspect_ts_1.inspect)(inputValue)}.`, path, (0, ensureGraphQLError_ts_1.ensureGraphQLError)(caughtError)); + } + } + } + function reportInvalidValue(onError, message, path, originalError) { + onError(new GraphQLError_ts_1.GraphQLError(message, { originalError }), (0, Path_ts_1.pathToArray)(path)); + } + function validateInputLiteral(valueNode, type, onError, variables, fragmentVariableValues, hideSuggestions) { + const context = { + static: !variables && !fragmentVariableValues, + onError, + variables, + fragmentVariableValues + }; + return validateInputLiteralImpl(context, valueNode, type, hideSuggestions, undefined); + } + function validateInputLiteralImpl(context, valueNode, type, hideSuggestions, path) { + if (valueNode.kind === kinds_ts_1.Kind.VARIABLE) { + if (context.static) { + return; + } + const scopedVariableValues = getScopedVariableValues(context, valueNode); + const value = scopedVariableValues?.coerced[valueNode.name.value]; + if ((0, definition_ts_1.isNonNullType)(type)) { + if (value === undefined) { + reportInvalidLiteral(context.onError, `Expected variable "$${valueNode.name.value}" provided to type "${type}" to provide a runtime value.`, valueNode, path); + } else if (value === null) { + reportInvalidLiteral(context.onError, `Expected variable "$${valueNode.name.value}" provided to non-null type "${type}" not to be null.`, valueNode, path); + } + } + return; + } + if ((0, definition_ts_1.isNonNullType)(type)) { + if (valueNode.kind === kinds_ts_1.Kind.NULL) { + reportInvalidLiteral(context.onError, `Expected value of non-null type "${type}" not to be null.`, valueNode, path); + return; + } + return validateInputLiteralImpl(context, valueNode, type.ofType, hideSuggestions, path); + } + if (valueNode.kind === kinds_ts_1.Kind.NULL) { + return; + } + if ((0, definition_ts_1.isListType)(type)) { + if (valueNode.kind !== kinds_ts_1.Kind.LIST) { + validateInputLiteralImpl(context, valueNode, type.ofType, hideSuggestions, path); + } else { + let index = 0; + for (const itemNode of valueNode.values) { + validateInputLiteralImpl(context, itemNode, type.ofType, hideSuggestions, (0, Path_ts_1.addPath)(path, index++, undefined)); + } + } + } else if ((0, definition_ts_1.isInputObjectType)(type)) { + if (valueNode.kind !== kinds_ts_1.Kind.OBJECT) { + reportInvalidLiteral(context.onError, `Expected value of type "${type}" to be an object, found: ${(0, printer_ts_1.print)(valueNode)}.`, valueNode, path); + return; + } + const fieldDefs = type.getFields(); + const fieldNodes = (0, keyMap_ts_1.keyMap)(valueNode.fields, (field) => field.name.value); + for (const field of Object.values(fieldDefs)) { + const fieldNode = fieldNodes[field.name]; + if (fieldNode === undefined) { + if ((0, definition_ts_1.isRequiredInputField)(field)) { + reportInvalidLiteral(context.onError, `Expected value of type "${type}" to include required field "${field.name}", found: ${(0, printer_ts_1.print)(valueNode)}.`, valueNode, path); + } + } else { + const fieldValueNode = fieldNode.value; + if (fieldValueNode.kind === kinds_ts_1.Kind.VARIABLE && !context.static) { + const scopedVariableValues = getScopedVariableValues(context, fieldValueNode); + const variableName = fieldValueNode.name.value; + const value = scopedVariableValues?.coerced[variableName]; + if (type.isOneOf) { + if (value === undefined) { + reportInvalidLiteral(context.onError, `Expected variable "$${variableName}" provided to field "${field.name}" for OneOf Input Object type "${type}" to provide a runtime value.`, valueNode, path); + } else if (value === null) { + reportInvalidLiteral(context.onError, `Expected variable "$${variableName}" provided to field "${field.name}" for OneOf Input Object type "${type}" not to be null.`, valueNode, path); + } + } else if (value === undefined && !(0, definition_ts_1.isRequiredInputField)(field)) { + continue; + } + } + validateInputLiteralImpl(context, fieldValueNode, field.type, hideSuggestions, (0, Path_ts_1.addPath)(path, field.name, type.name)); + } + } + const fields = valueNode.fields; + const knownFields = []; + for (const fieldNode of fields) { + const fieldName = fieldNode.name.value; + if (!Object.hasOwn(fieldDefs, fieldName)) { + const suggestion = hideSuggestions ? "" : (0, didYouMean_ts_1.didYouMean)((0, suggestionList_ts_1.suggestionList)(fieldName, Object.keys(fieldDefs))); + reportInvalidLiteral(context.onError, `Expected value of type "${type}" not to include unknown field "${fieldName}"${suggestion ? `.${suggestion} Found` : ", found"}: ${(0, printer_ts_1.print)(valueNode)}.`, fieldNode, path); + } else { + knownFields.push(fieldNode); + } + } + if (type.isOneOf) { + const isNotExactlyOneField = knownFields.length !== 1; + if (isNotExactlyOneField) { + reportInvalidLiteral(context.onError, getOneOfInputObjectErrorMessage(type), valueNode, path); + return; + } + const fieldValueNode = knownFields[0].value; + if (fieldValueNode.kind === kinds_ts_1.Kind.NULL) { + const fieldName = knownFields[0].name.value; + reportInvalidLiteral(context.onError, getOneOfInputObjectErrorMessage(type), valueNode, (0, Path_ts_1.addPath)(path, fieldName, undefined)); + } + } + } else { + (0, definition_ts_1.assertLeafType)(type); + let result; + let caughtError; + try { + result = type.coerceInputLiteral ? type.coerceInputLiteral((0, replaceVariables_ts_1.replaceVariables)(valueNode, context.variables, context.fragmentVariableValues), hideSuggestions) : type.parseLiteral(valueNode, undefined, hideSuggestions); + } catch (error) { + if (error instanceof GraphQLError_ts_1.GraphQLError) { + context.onError(error, (0, Path_ts_1.pathToArray)(path)); + return; + } + caughtError = error; + } + if (result === undefined) { + reportInvalidLiteral(context.onError, `Expected value of type "${type}"${caughtError != null ? `, but encountered error "${getCaughtErrorMessage(caughtError)}"; found` : ", found"}: ${(0, printer_ts_1.print)(valueNode)}.`, valueNode, path, (0, ensureGraphQLError_ts_1.ensureGraphQLError)(caughtError)); + } + } + } + function getScopedVariableValues(context, valueNode) { + const variableName = valueNode.name.value; + const { fragmentVariableValues, variables } = context; + return fragmentVariableValues?.sources[variableName] ? fragmentVariableValues : variables; + } + function reportInvalidLiteral(onError, message, valueNode, path, originalError) { + onError(new GraphQLError_ts_1.GraphQLError(message, { + nodes: valueNode, + originalError + }), (0, Path_ts_1.pathToArray)(path)); + } + function getCaughtErrorMessage(caughtError) { + if ((0, isObjectLike_ts_1.isObjectLike)(caughtError)) { + const message = caughtError.message; + if (typeof message === "string" && message !== "") { + return message; + } + } + return String(caughtError); + } + function getOneOfInputObjectErrorMessage(type) { + return `Within OneOf Input Object type "${type}", exactly one field must be specified, and the value for that field must be non-null.`; + } +}); + +// node_modules/graphql/language/directiveLocation.js +var require_directiveLocation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DirectiveLocation = undefined; + exports.DirectiveLocation = { + QUERY: "QUERY", + MUTATION: "MUTATION", + SUBSCRIPTION: "SUBSCRIPTION", + FIELD: "FIELD", + FRAGMENT_DEFINITION: "FRAGMENT_DEFINITION", + FRAGMENT_SPREAD: "FRAGMENT_SPREAD", + INLINE_FRAGMENT: "INLINE_FRAGMENT", + VARIABLE_DEFINITION: "VARIABLE_DEFINITION", + FRAGMENT_VARIABLE_DEFINITION: "FRAGMENT_VARIABLE_DEFINITION", + SCHEMA: "SCHEMA", + SCALAR: "SCALAR", + OBJECT: "OBJECT", + FIELD_DEFINITION: "FIELD_DEFINITION", + ARGUMENT_DEFINITION: "ARGUMENT_DEFINITION", + INTERFACE: "INTERFACE", + UNION: "UNION", + ENUM: "ENUM", + ENUM_VALUE: "ENUM_VALUE", + INPUT_OBJECT: "INPUT_OBJECT", + INPUT_FIELD_DEFINITION: "INPUT_FIELD_DEFINITION", + DIRECTIVE_DEFINITION: "DIRECTIVE_DEFINITION" + }; +}); + +// node_modules/graphql/type/scalars.js +var require_scalars = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.specifiedScalarTypes = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = exports.GRAPHQL_MIN_INT = exports.GRAPHQL_MAX_INT = undefined; + exports.isSpecifiedScalarType = isSpecifiedScalarType; + var inspect_ts_1 = require_inspect(); + var isObjectLike_ts_1 = require_isObjectLike(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var printer_ts_1 = require_printer(); + var valueToLiteral_ts_1 = require_valueToLiteral(); + var definition_ts_1 = require_definition(); + exports.GRAPHQL_MAX_INT = 2147483647; + exports.GRAPHQL_MIN_INT = -2147483648; + exports.GraphQLInt = new definition_ts_1.GraphQLScalarType({ + name: "Int", + description: "The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.", + coerceOutputValue(outputValue) { + const coercedValue = coerceOutputValueObject(outputValue); + if (typeof coercedValue === "number") { + return coerceIntFromNumber(coercedValue); + } + if (typeof coercedValue === "boolean") { + return coercedValue ? 1 : 0; + } + if (typeof coercedValue === "string") { + return coerceIntFromString(coercedValue); + } + if (typeof coercedValue === "bigint") { + return coerceIntFromBigInt(coercedValue); + } + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non-integer value: ${(0, inspect_ts_1.inspect)(coercedValue)}`); + }, + coerceInputValue(inputValue) { + if (typeof inputValue === "number") { + return coerceIntFromNumber(inputValue); + } + if (typeof inputValue === "bigint") { + return coerceIntFromBigInt(inputValue); + } + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non-integer value: ${(0, inspect_ts_1.inspect)(inputValue)}`); + }, + coerceInputLiteral(valueNode) { + if (valueNode.kind !== kinds_ts_1.Kind.INT) { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non-integer value: ${(0, printer_ts_1.print)(valueNode)}`, { nodes: valueNode }); + } + const num = parseInt(valueNode.value, 10); + if (num > exports.GRAPHQL_MAX_INT || num < exports.GRAPHQL_MIN_INT) { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, { nodes: valueNode }); + } + return num; + }, + valueToLiteral(value) { + if ((typeof value === "number" && Number.isInteger(value) || typeof value === "bigint") && value <= exports.GRAPHQL_MAX_INT && value >= exports.GRAPHQL_MIN_INT) { + return { kind: kinds_ts_1.Kind.INT, value: String(value) }; + } + } + }); + exports.GraphQLFloat = new definition_ts_1.GraphQLScalarType({ + name: "Float", + description: "The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).", + coerceOutputValue(outputValue) { + const coercedValue = coerceOutputValueObject(outputValue); + if (typeof coercedValue === "number") { + return coerceFloatFromNumber(coercedValue); + } + if (typeof coercedValue === "boolean") { + return coercedValue ? 1 : 0; + } + if (typeof coercedValue === "string") { + return coerceFloatFromString(coercedValue); + } + if (typeof coercedValue === "bigint") { + return coerceFloatFromBigInt(coercedValue); + } + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, inspect_ts_1.inspect)(coercedValue)}`); + }, + coerceInputValue(inputValue) { + if (typeof inputValue === "number") { + return coerceFloatFromNumber(inputValue); + } + if (typeof inputValue === "bigint") { + return coerceFloatFromBigInt(inputValue); + } + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, inspect_ts_1.inspect)(inputValue)}`); + }, + coerceInputLiteral(valueNode) { + if (valueNode.kind !== kinds_ts_1.Kind.FLOAT && valueNode.kind !== kinds_ts_1.Kind.INT) { + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, printer_ts_1.print)(valueNode)}`, { nodes: valueNode }); + } + return parseFloat(valueNode.value); + }, + valueToLiteral(value) { + const literal = (0, valueToLiteral_ts_1.defaultScalarValueToLiteral)(value); + if (literal.kind === kinds_ts_1.Kind.FLOAT || literal.kind === kinds_ts_1.Kind.INT) { + return literal; + } + } + }); + exports.GraphQLString = new definition_ts_1.GraphQLScalarType({ + name: "String", + description: "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.", + coerceOutputValue(outputValue) { + const coercedValue = coerceOutputValueObject(outputValue); + if (typeof coercedValue === "string") { + return coercedValue; + } + if (typeof coercedValue === "boolean") { + return coercedValue ? "true" : "false"; + } + if (typeof coercedValue === "number") { + return coerceStringFromNumber(coercedValue); + } + if (typeof coercedValue === "bigint") { + return String(coercedValue); + } + throw new GraphQLError_ts_1.GraphQLError(`String cannot represent value: ${(0, inspect_ts_1.inspect)(outputValue)}`); + }, + coerceInputValue(inputValue) { + if (typeof inputValue !== "string") { + throw new GraphQLError_ts_1.GraphQLError(`String cannot represent a non string value: ${(0, inspect_ts_1.inspect)(inputValue)}`); + } + return inputValue; + }, + coerceInputLiteral(valueNode) { + if (valueNode.kind !== kinds_ts_1.Kind.STRING) { + throw new GraphQLError_ts_1.GraphQLError(`String cannot represent a non string value: ${(0, printer_ts_1.print)(valueNode)}`, { nodes: valueNode }); + } + return valueNode.value; + }, + valueToLiteral(value) { + const literal = (0, valueToLiteral_ts_1.defaultScalarValueToLiteral)(value); + if (literal.kind === kinds_ts_1.Kind.STRING) { + return literal; + } + } + }); + exports.GraphQLBoolean = new definition_ts_1.GraphQLScalarType({ + name: "Boolean", + description: "The `Boolean` scalar type represents `true` or `false`.", + coerceOutputValue(outputValue) { + const coercedValue = coerceOutputValueObject(outputValue); + if (typeof coercedValue === "boolean") { + return coercedValue; + } + if (typeof coercedValue === "number") { + return coerceBooleanFromNumber(coercedValue); + } + if (typeof coercedValue === "bigint") { + return coercedValue !== 0n; + } + throw new GraphQLError_ts_1.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, inspect_ts_1.inspect)(coercedValue)}`); + }, + coerceInputValue(inputValue) { + if (typeof inputValue !== "boolean") { + throw new GraphQLError_ts_1.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, inspect_ts_1.inspect)(inputValue)}`); + } + return inputValue; + }, + coerceInputLiteral(valueNode) { + if (valueNode.kind !== kinds_ts_1.Kind.BOOLEAN) { + throw new GraphQLError_ts_1.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, printer_ts_1.print)(valueNode)}`, { nodes: valueNode }); + } + return valueNode.value; + }, + valueToLiteral(value) { + const literal = (0, valueToLiteral_ts_1.defaultScalarValueToLiteral)(value); + if (literal.kind === kinds_ts_1.Kind.BOOLEAN) { + return literal; + } + } + }); + exports.GraphQLID = new definition_ts_1.GraphQLScalarType({ + name: "ID", + description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.', + coerceOutputValue(outputValue) { + const coercedValue = coerceOutputValueObject(outputValue); + if (typeof coercedValue === "string") { + return coercedValue; + } + if (typeof coercedValue === "number") { + return coerceIDFromNumber(coercedValue); + } + if (typeof coercedValue === "bigint") { + return String(coercedValue); + } + throw new GraphQLError_ts_1.GraphQLError(`ID cannot represent value: ${(0, inspect_ts_1.inspect)(outputValue)}`); + }, + coerceInputValue(inputValue) { + if (typeof inputValue === "string") { + return inputValue; + } + if (typeof inputValue === "number") { + return coerceIDFromNumber(inputValue); + } + if (typeof inputValue === "bigint") { + return String(inputValue); + } + throw new GraphQLError_ts_1.GraphQLError(`ID cannot represent value: ${(0, inspect_ts_1.inspect)(inputValue)}`); + }, + coerceInputLiteral(valueNode) { + if (valueNode.kind !== kinds_ts_1.Kind.STRING && valueNode.kind !== kinds_ts_1.Kind.INT) { + throw new GraphQLError_ts_1.GraphQLError("ID cannot represent a non-string and non-integer value: " + (0, printer_ts_1.print)(valueNode), { nodes: valueNode }); + } + return valueNode.value; + }, + valueToLiteral(value) { + if (typeof value === "string") { + return /^-?(?:0|[1-9][0-9]*)$/.test(value) ? { kind: kinds_ts_1.Kind.INT, value } : { kind: kinds_ts_1.Kind.STRING, value, block: false }; + } + if (typeof value === "number") { + return { kind: kinds_ts_1.Kind.INT, value: coerceIDFromNumber(value) }; + } + if (typeof value === "bigint") { + return { kind: kinds_ts_1.Kind.INT, value: String(value) }; + } + } + }); + exports.specifiedScalarTypes = Object.freeze([ + exports.GraphQLString, + exports.GraphQLInt, + exports.GraphQLFloat, + exports.GraphQLBoolean, + exports.GraphQLID + ]); + function isSpecifiedScalarType(type) { + return exports.specifiedScalarTypes.some(({ name }) => type.name === name); + } + function coerceOutputValueObject(outputValue) { + if ((0, isObjectLike_ts_1.isObjectLike)(outputValue)) { + if (typeof outputValue.valueOf === "function") { + const valueOfResult = outputValue.valueOf(); + if (!(0, isObjectLike_ts_1.isObjectLike)(valueOfResult)) { + return valueOfResult; + } + } + if (typeof outputValue.toJSON === "function") { + return outputValue.toJSON(); + } + } + return outputValue; + } + function coerceIntFromNumber(value) { + if (!Number.isInteger(value)) { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non-integer value: ${(0, inspect_ts_1.inspect)(value)}`); + } + if (value > exports.GRAPHQL_MAX_INT || value < exports.GRAPHQL_MIN_INT) { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${(0, inspect_ts_1.inspect)(value)}`); + } + return value; + } + function coerceIntFromString(value) { + if (value === "") { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non-integer value: ${(0, inspect_ts_1.inspect)(value)}`); + } + const num = Number(value); + if (!Number.isInteger(num)) { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non-integer value: ${(0, inspect_ts_1.inspect)(value)}`); + } + if (num > exports.GRAPHQL_MAX_INT || num < exports.GRAPHQL_MIN_INT) { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${(0, inspect_ts_1.inspect)(value)}`); + } + return num; + } + function coerceIntFromBigInt(value) { + if (value > exports.GRAPHQL_MAX_INT || value < exports.GRAPHQL_MIN_INT) { + throw new GraphQLError_ts_1.GraphQLError(`Int cannot represent non 32-bit signed integer value: ${String(value)}`); + } + return Number(value); + } + function coerceFloatFromNumber(value) { + if (!Number.isFinite(value)) { + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, inspect_ts_1.inspect)(value)}`); + } + return value; + } + function coerceFloatFromString(value) { + if (value === "") { + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, inspect_ts_1.inspect)(value)}`); + } + const num = Number(value); + if (!Number.isFinite(num)) { + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, inspect_ts_1.inspect)(value)}`); + } + return num; + } + function coerceFloatFromBigInt(coercedValue) { + const num = Number(coercedValue); + if (!Number.isFinite(num)) { + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, inspect_ts_1.inspect)(coercedValue)} (value is too large)`); + } + if (BigInt(num) !== coercedValue) { + throw new GraphQLError_ts_1.GraphQLError(`Float cannot represent non numeric value: ${(0, inspect_ts_1.inspect)(coercedValue)} (value would lose precision)`); + } + return num; + } + function coerceStringFromNumber(value) { + if (!Number.isFinite(value)) { + throw new GraphQLError_ts_1.GraphQLError(`String cannot represent value: ${(0, inspect_ts_1.inspect)(value)}`); + } + return String(value); + } + function coerceBooleanFromNumber(value) { + if (!Number.isFinite(value)) { + throw new GraphQLError_ts_1.GraphQLError(`Boolean cannot represent a non boolean value: ${(0, inspect_ts_1.inspect)(value)}`); + } + return value !== 0; + } + function coerceIDFromNumber(value) { + if (!Number.isInteger(value)) { + throw new GraphQLError_ts_1.GraphQLError(`ID cannot represent value: ${(0, inspect_ts_1.inspect)(value)}`); + } + return String(value); + } +}); + +// node_modules/graphql/type/directives.js +var require_directives = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.specifiedDirectives = exports.GraphQLDisableErrorPropagationDirective = exports.GraphQLOneOfDirective = exports.GraphQLSpecifiedByDirective = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLStreamDirective = exports.GraphQLDeferDirective = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = undefined; + exports.isDirective = isDirective; + exports.assertDirective = assertDirective; + exports.isSpecifiedDirective = isSpecifiedDirective; + var devAssert_ts_1 = require_devAssert(); + var inspect_ts_1 = require_inspect(); + var instanceOf_ts_1 = require_instanceOf(); + var isObjectLike_ts_1 = require_isObjectLike(); + var keyValMap_ts_1 = require_keyValMap(); + var toObjMap_ts_1 = require_toObjMap(); + var directiveLocation_ts_1 = require_directiveLocation(); + var assertName_ts_1 = require_assertName(); + var definition_ts_1 = require_definition(); + var scalars_ts_1 = require_scalars(); + var directiveSymbol = Symbol("Directive"); + function isDirective(directive) { + return (0, instanceOf_ts_1.instanceOf)(directive, directiveSymbol, GraphQLDirective); + } + function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(directive)} to be a GraphQL directive.`); + } + return directive; + } + + class GraphQLDirective { + constructor(config) { + this.__kind = directiveSymbol; + this.name = (0, assertName_ts_1.assertName)(config.name); + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = config.isRepeatable ?? false; + this.deprecationReason = config.deprecationReason; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + if (!Array.isArray(config.locations)) + (0, devAssert_ts_1.devAssert)(false, `@${this.name} locations must be an Array.`); + const args = config.args ?? {}; + if (!((0, isObjectLike_ts_1.isObjectLike)(args) && !Array.isArray(args))) + (0, devAssert_ts_1.devAssert)(false, `@${this.name} args must be an object with argument names as keys.`); + this.args = Object.entries(args).map(([argName, argConfig]) => new definition_ts_1.GraphQLArgument(this, argName, argConfig)); + } + get [Symbol.toStringTag]() { + return "GraphQLDirective"; + } + toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: (0, keyValMap_ts_1.keyValMap)(this.args, (arg) => arg.name, (arg) => arg.toConfig()), + isRepeatable: this.isRepeatable, + deprecationReason: this.deprecationReason, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes + }; + } + toString() { + return "@" + this.name; + } + toJSON() { + return this.toString(); + } + } + exports.GraphQLDirective = GraphQLDirective; + exports.GraphQLIncludeDirective = new GraphQLDirective({ + name: "include", + description: "Directs the executor to include this field or fragment only when the `if` argument is true.", + locations: [ + directiveLocation_ts_1.DirectiveLocation.FIELD, + directiveLocation_ts_1.DirectiveLocation.FRAGMENT_SPREAD, + directiveLocation_ts_1.DirectiveLocation.INLINE_FRAGMENT + ], + args: { + if: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + description: "Included when true." + } + } + }); + exports.GraphQLSkipDirective = new GraphQLDirective({ + name: "skip", + description: "Directs the executor to skip this field or fragment when the `if` argument is true.", + locations: [ + directiveLocation_ts_1.DirectiveLocation.FIELD, + directiveLocation_ts_1.DirectiveLocation.FRAGMENT_SPREAD, + directiveLocation_ts_1.DirectiveLocation.INLINE_FRAGMENT + ], + args: { + if: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + description: "Skipped when true." + } + } + }); + exports.GraphQLDeferDirective = new GraphQLDirective({ + name: "defer", + description: "Directs the executor to defer this fragment when the `if` argument is true or undefined.", + locations: [ + directiveLocation_ts_1.DirectiveLocation.FRAGMENT_SPREAD, + directiveLocation_ts_1.DirectiveLocation.INLINE_FRAGMENT + ], + args: { + if: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + description: "Deferred when true or undefined.", + default: { value: true } + }, + label: { + type: scalars_ts_1.GraphQLString, + description: "Unique name" + } + } + }); + exports.GraphQLStreamDirective = new GraphQLDirective({ + name: "stream", + description: "Directs the executor to stream plural fields when the `if` argument is true or undefined.", + locations: [directiveLocation_ts_1.DirectiveLocation.FIELD], + args: { + initialCount: { + default: { value: 0 }, + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLInt), + description: "Number of items to return immediately" + }, + if: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + description: "Stream when true or undefined.", + default: { value: true } + }, + label: { + type: scalars_ts_1.GraphQLString, + description: "Unique name" + } + } + }); + exports.DEFAULT_DEPRECATION_REASON = "No longer supported"; + exports.GraphQLDeprecatedDirective = new GraphQLDirective({ + name: "deprecated", + description: "Marks an element of a GraphQL schema as no longer supported.", + locations: [ + directiveLocation_ts_1.DirectiveLocation.FIELD_DEFINITION, + directiveLocation_ts_1.DirectiveLocation.ARGUMENT_DEFINITION, + directiveLocation_ts_1.DirectiveLocation.INPUT_FIELD_DEFINITION, + directiveLocation_ts_1.DirectiveLocation.ENUM_VALUE, + directiveLocation_ts_1.DirectiveLocation.DIRECTIVE_DEFINITION + ], + args: { + reason: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString), + description: "Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).", + default: { value: exports.DEFAULT_DEPRECATION_REASON } + } + } + }); + exports.GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: "specifiedBy", + description: "Exposes a URL that specifies the behavior of this scalar.", + locations: [directiveLocation_ts_1.DirectiveLocation.SCALAR], + args: { + url: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString), + description: "The URL that specifies the behavior of this scalar." + } + } + }); + exports.GraphQLOneOfDirective = new GraphQLDirective({ + name: "oneOf", + description: "Indicates exactly one field must be supplied and this field must not be `null`.", + locations: [directiveLocation_ts_1.DirectiveLocation.INPUT_OBJECT], + args: {} + }); + exports.GraphQLDisableErrorPropagationDirective = new GraphQLDirective({ + name: "experimental_disableErrorPropagation", + description: "Disables error propagation.", + locations: [ + directiveLocation_ts_1.DirectiveLocation.QUERY, + directiveLocation_ts_1.DirectiveLocation.MUTATION, + directiveLocation_ts_1.DirectiveLocation.SUBSCRIPTION + ] + }); + exports.specifiedDirectives = Object.freeze([ + exports.GraphQLIncludeDirective, + exports.GraphQLSkipDirective, + exports.GraphQLDeprecatedDirective, + exports.GraphQLSpecifiedByDirective, + exports.GraphQLOneOfDirective + ]); + function isSpecifiedDirective(directive) { + return exports.specifiedDirectives.some(({ name }) => name === directive.name); + } +}); + +// node_modules/graphql/utilities/astFromValue.js +var require_astFromValue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.astFromValue = astFromValue; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var isIterableObject_ts_1 = require_isIterableObject(); + var isObjectLike_ts_1 = require_isObjectLike(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + var scalars_ts_1 = require_scalars(); + function astFromValue(value, type) { + if ((0, definition_ts_1.isNonNullType)(type)) { + const astValue = astFromValue(value, type.ofType); + if (astValue?.kind === kinds_ts_1.Kind.NULL) { + return null; + } + return astValue; + } + if (value === null) { + return { kind: kinds_ts_1.Kind.NULL }; + } + if (value === undefined) { + return null; + } + if ((0, definition_ts_1.isListType)(type)) { + const itemType = type.ofType; + if ((0, isIterableObject_ts_1.isIterableObject)(value)) { + const valuesNodes = []; + for (const item of value) { + const itemNode = astFromValue(item, itemType); + if (itemNode != null) { + valuesNodes.push(itemNode); + } + } + return { kind: kinds_ts_1.Kind.LIST, values: valuesNodes }; + } + return astFromValue(value, itemType); + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + if (!(0, isObjectLike_ts_1.isObjectLike)(value)) { + return null; + } + const fieldNodes = []; + for (const field of Object.values(type.getFields())) { + const fieldValue = astFromValue(value[field.name], field.type); + if (fieldValue) { + fieldNodes.push({ + kind: kinds_ts_1.Kind.OBJECT_FIELD, + name: { kind: kinds_ts_1.Kind.NAME, value: field.name }, + value: fieldValue + }); + } + } + return { kind: kinds_ts_1.Kind.OBJECT, fields: fieldNodes }; + } + if ((0, definition_ts_1.isLeafType)(type)) { + const coerced = type.coerceOutputValue(value); + if (coerced == null) { + return null; + } + if (typeof coerced === "boolean") { + return { kind: kinds_ts_1.Kind.BOOLEAN, value: coerced }; + } + if (typeof coerced === "number" && Number.isFinite(coerced)) { + const stringNum = String(coerced); + return integerStringRegExp.test(stringNum) ? { kind: kinds_ts_1.Kind.INT, value: stringNum } : { kind: kinds_ts_1.Kind.FLOAT, value: stringNum }; + } + if (typeof coerced === "bigint") { + return { kind: kinds_ts_1.Kind.INT, value: String(coerced) }; + } + if (typeof coerced === "string") { + if ((0, definition_ts_1.isEnumType)(type)) { + return { kind: kinds_ts_1.Kind.ENUM, value: coerced }; + } + if (type === scalars_ts_1.GraphQLID && integerStringRegExp.test(coerced)) { + return { kind: kinds_ts_1.Kind.INT, value: coerced }; + } + return { + kind: kinds_ts_1.Kind.STRING, + value: coerced + }; + } + throw new TypeError(`Cannot convert value to AST: ${(0, inspect_ts_1.inspect)(coerced)}.`); + } + (0, invariant_ts_1.invariant)(false, "Unexpected input type: " + (0, inspect_ts_1.inspect)(type)); + } + var integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; +}); + +// node_modules/graphql/utilities/getDefaultValueAST.js +var require_getDefaultValueAST = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getDefaultValueAST = getDefaultValueAST; + var invariant_ts_1 = require_invariant(); + var astFromValue_ts_1 = require_astFromValue(); + var valueToLiteral_ts_1 = require_valueToLiteral(); + function getDefaultValueAST(argOrInputField) { + const type = argOrInputField.type; + const defaultInput = argOrInputField.default; + if (defaultInput) { + const literal = defaultInput.literal ?? (0, valueToLiteral_ts_1.valueToLiteral)(defaultInput.value, type); + if (!(literal != null)) + (0, invariant_ts_1.invariant)(false, "Invalid default value"); + return literal; + } + const defaultValue = argOrInputField.defaultValue; + if (defaultValue !== undefined) { + const valueAST = (0, astFromValue_ts_1.astFromValue)(defaultValue, type); + if (!(valueAST != null)) + (0, invariant_ts_1.invariant)(false, "Invalid default value"); + return valueAST; + } + return; + } +}); + +// node_modules/graphql/type/introspection.js +var require_introspection = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.introspectionTypes = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = undefined; + exports.isIntrospectionType = isIntrospectionType; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var directiveLocation_ts_1 = require_directiveLocation(); + var printer_ts_1 = require_printer(); + var getDefaultValueAST_ts_1 = require_getDefaultValueAST(); + var definition_ts_1 = require_definition(); + var scalars_ts_1 = require_scalars(); + exports.__Schema = new definition_ts_1.GraphQLObjectType({ + name: "__Schema", + description: "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.", + fields: () => ({ + description: { + type: scalars_ts_1.GraphQLString, + resolve: (schema) => schema.description + }, + types: { + description: "A list of all types supported by this server.", + type: new definition_ts_1.GraphQLNonNull(new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__Type))), + resolve(schema) { + return Object.values(schema.getTypeMap()); + } + }, + queryType: { + description: "The type that query operations will be rooted at.", + type: new definition_ts_1.GraphQLNonNull(exports.__Type), + resolve: (schema) => schema.getQueryType() + }, + mutationType: { + description: "If this server supports mutation, the type that mutation operations will be rooted at.", + type: exports.__Type, + resolve: (schema) => schema.getMutationType() + }, + subscriptionType: { + description: "If this server support subscription, the type that subscription operations will be rooted at.", + type: exports.__Type, + resolve: (schema) => schema.getSubscriptionType() + }, + directives: { + description: "A list of all directives supported by this server.", + type: new definition_ts_1.GraphQLNonNull(new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__Directive))), + args: { + includeDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + default: { value: false } + } + }, + resolve: (schema, { includeDeprecated }) => includeDeprecated === true ? schema.getDirectives() : schema.getDirectives().filter((directive) => directive.deprecationReason == null) + } + }) + }); + exports.__Directive = new definition_ts_1.GraphQLObjectType({ + name: "__Directive", + description: `A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document. + +In some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.`, + fields: () => ({ + name: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString), + resolve: (directive) => directive.name + }, + description: { + type: scalars_ts_1.GraphQLString, + resolve: (directive) => directive.description + }, + isRepeatable: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + resolve: (directive) => directive.isRepeatable + }, + locations: { + type: new definition_ts_1.GraphQLNonNull(new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__DirectiveLocation))), + resolve: (directive) => directive.locations + }, + args: { + type: new definition_ts_1.GraphQLNonNull(new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__InputValue))), + args: { + includeDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + default: { value: false } + } + }, + resolve(field, { includeDeprecated }) { + return includeDeprecated === true ? field.args : field.args.filter((arg) => arg.deprecationReason == null); + } + }, + isDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + resolve: (directive) => directive.deprecationReason != null + }, + deprecationReason: { + type: scalars_ts_1.GraphQLString, + resolve: (directive) => directive.deprecationReason + } + }) + }); + exports.__DirectiveLocation = new definition_ts_1.GraphQLEnumType({ + name: "__DirectiveLocation", + description: "A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.", + values: { + QUERY: { + value: directiveLocation_ts_1.DirectiveLocation.QUERY, + description: "Location adjacent to a query operation." + }, + MUTATION: { + value: directiveLocation_ts_1.DirectiveLocation.MUTATION, + description: "Location adjacent to a mutation operation." + }, + SUBSCRIPTION: { + value: directiveLocation_ts_1.DirectiveLocation.SUBSCRIPTION, + description: "Location adjacent to a subscription operation." + }, + FIELD: { + value: directiveLocation_ts_1.DirectiveLocation.FIELD, + description: "Location adjacent to a field." + }, + FRAGMENT_DEFINITION: { + value: directiveLocation_ts_1.DirectiveLocation.FRAGMENT_DEFINITION, + description: "Location adjacent to a fragment definition." + }, + FRAGMENT_SPREAD: { + value: directiveLocation_ts_1.DirectiveLocation.FRAGMENT_SPREAD, + description: "Location adjacent to a fragment spread." + }, + INLINE_FRAGMENT: { + value: directiveLocation_ts_1.DirectiveLocation.INLINE_FRAGMENT, + description: "Location adjacent to an inline fragment." + }, + VARIABLE_DEFINITION: { + value: directiveLocation_ts_1.DirectiveLocation.VARIABLE_DEFINITION, + description: "Location adjacent to an operation variable definition." + }, + FRAGMENT_VARIABLE_DEFINITION: { + value: directiveLocation_ts_1.DirectiveLocation.FRAGMENT_VARIABLE_DEFINITION, + description: "Location adjacent to a fragment variable definition." + }, + SCHEMA: { + value: directiveLocation_ts_1.DirectiveLocation.SCHEMA, + description: "Location adjacent to a schema definition." + }, + SCALAR: { + value: directiveLocation_ts_1.DirectiveLocation.SCALAR, + description: "Location adjacent to a scalar definition." + }, + OBJECT: { + value: directiveLocation_ts_1.DirectiveLocation.OBJECT, + description: "Location adjacent to an object type definition." + }, + FIELD_DEFINITION: { + value: directiveLocation_ts_1.DirectiveLocation.FIELD_DEFINITION, + description: "Location adjacent to a field definition." + }, + ARGUMENT_DEFINITION: { + value: directiveLocation_ts_1.DirectiveLocation.ARGUMENT_DEFINITION, + description: "Location adjacent to an argument definition." + }, + INTERFACE: { + value: directiveLocation_ts_1.DirectiveLocation.INTERFACE, + description: "Location adjacent to an interface definition." + }, + UNION: { + value: directiveLocation_ts_1.DirectiveLocation.UNION, + description: "Location adjacent to a union definition." + }, + ENUM: { + value: directiveLocation_ts_1.DirectiveLocation.ENUM, + description: "Location adjacent to an enum definition." + }, + ENUM_VALUE: { + value: directiveLocation_ts_1.DirectiveLocation.ENUM_VALUE, + description: "Location adjacent to an enum value definition." + }, + INPUT_OBJECT: { + value: directiveLocation_ts_1.DirectiveLocation.INPUT_OBJECT, + description: "Location adjacent to an input object type definition." + }, + INPUT_FIELD_DEFINITION: { + value: directiveLocation_ts_1.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: "Location adjacent to an input object field definition." + }, + DIRECTIVE_DEFINITION: { + value: directiveLocation_ts_1.DirectiveLocation.DIRECTIVE_DEFINITION, + description: "Location adjacent to a directive definition." + } + } + }); + exports.__Type = new definition_ts_1.GraphQLObjectType({ + name: "__Type", + description: "The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.", + fields: () => ({ + kind: { + type: new definition_ts_1.GraphQLNonNull(exports.__TypeKind), + resolve(type) { + if ((0, definition_ts_1.isScalarType)(type)) { + return exports.TypeKind.SCALAR; + } + if ((0, definition_ts_1.isObjectType)(type)) { + return exports.TypeKind.OBJECT; + } + if ((0, definition_ts_1.isInterfaceType)(type)) { + return exports.TypeKind.INTERFACE; + } + if ((0, definition_ts_1.isUnionType)(type)) { + return exports.TypeKind.UNION; + } + if ((0, definition_ts_1.isEnumType)(type)) { + return exports.TypeKind.ENUM; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + return exports.TypeKind.INPUT_OBJECT; + } + if ((0, definition_ts_1.isListType)(type)) { + return exports.TypeKind.LIST; + } + if ((0, definition_ts_1.isNonNullType)(type)) { + return exports.TypeKind.NON_NULL; + } + (0, invariant_ts_1.invariant)(false, `Unexpected type: "${(0, inspect_ts_1.inspect)(type)}".`); + } + }, + name: { + type: scalars_ts_1.GraphQLString, + resolve: (type) => ("name" in type) ? type.name : undefined + }, + description: { + type: scalars_ts_1.GraphQLString, + resolve: (type) => ("description" in type) ? type.description : undefined + }, + specifiedByURL: { + type: scalars_ts_1.GraphQLString, + resolve: (obj) => ("specifiedByURL" in obj) ? obj.specifiedByURL : undefined + }, + fields: { + type: new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__Field)), + args: { + includeDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + default: { value: false } + } + }, + resolve(type, { includeDeprecated }) { + if ((0, definition_ts_1.isObjectType)(type) || (0, definition_ts_1.isInterfaceType)(type)) { + const fields = Object.values(type.getFields()); + return includeDeprecated === true ? fields : fields.filter((field) => field.deprecationReason == null); + } + } + }, + interfaces: { + type: new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__Type)), + resolve(type) { + if ((0, definition_ts_1.isObjectType)(type) || (0, definition_ts_1.isInterfaceType)(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__Type)), + resolve(type, _args, _context, { schema }) { + if ((0, definition_ts_1.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__EnumValue)), + args: { + includeDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + default: { value: false } + } + }, + resolve(type, { includeDeprecated }) { + if ((0, definition_ts_1.isEnumType)(type)) { + const values = type.getValues(); + return includeDeprecated === true ? values : values.filter((field) => field.deprecationReason == null); + } + } + }, + inputFields: { + type: new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__InputValue)), + args: { + includeDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + default: { value: false } + } + }, + resolve(type, { includeDeprecated }) { + if ((0, definition_ts_1.isInputObjectType)(type)) { + const values = Object.values(type.getFields()); + return includeDeprecated === true ? values : values.filter((field) => field.deprecationReason == null); + } + } + }, + ofType: { + type: exports.__Type, + resolve: (type) => ("ofType" in type) ? type.ofType : undefined + }, + isOneOf: { + type: scalars_ts_1.GraphQLBoolean, + resolve: (type) => { + if ((0, definition_ts_1.isInputObjectType)(type)) { + return type.isOneOf; + } + } + } + }) + }); + exports.__Field = new definition_ts_1.GraphQLObjectType({ + name: "__Field", + description: "Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.", + fields: () => ({ + name: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString), + resolve: (field) => field.name + }, + description: { + type: scalars_ts_1.GraphQLString, + resolve: (field) => field.description + }, + args: { + type: new definition_ts_1.GraphQLNonNull(new definition_ts_1.GraphQLList(new definition_ts_1.GraphQLNonNull(exports.__InputValue))), + args: { + includeDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + default: { value: false } + } + }, + resolve(field, { includeDeprecated }) { + return includeDeprecated === true ? field.args : field.args.filter((arg) => arg.deprecationReason == null); + } + }, + type: { + type: new definition_ts_1.GraphQLNonNull(exports.__Type), + resolve: (field) => field.type + }, + isDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null + }, + deprecationReason: { + type: scalars_ts_1.GraphQLString, + resolve: (field) => field.deprecationReason + } + }) + }); + exports.__InputValue = new definition_ts_1.GraphQLObjectType({ + name: "__InputValue", + description: "Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.", + fields: () => ({ + name: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString), + resolve: (inputValue) => inputValue.name + }, + description: { + type: scalars_ts_1.GraphQLString, + resolve: (inputValue) => inputValue.description + }, + type: { + type: new definition_ts_1.GraphQLNonNull(exports.__Type), + resolve: (inputValue) => inputValue.type + }, + defaultValue: { + type: scalars_ts_1.GraphQLString, + description: "A GraphQL-formatted string representing the default value for this input value.", + resolve(inputValue) { + const ast = (0, getDefaultValueAST_ts_1.getDefaultValueAST)(inputValue); + if (ast) { + return (0, printer_ts_1.print)(ast); + } + return null; + } + }, + isDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null + }, + deprecationReason: { + type: scalars_ts_1.GraphQLString, + resolve: (obj) => obj.deprecationReason + } + }) + }); + exports.__EnumValue = new definition_ts_1.GraphQLObjectType({ + name: "__EnumValue", + description: "One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.", + fields: () => ({ + name: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString), + resolve: (enumValue) => enumValue.name + }, + description: { + type: scalars_ts_1.GraphQLString, + resolve: (enumValue) => enumValue.description + }, + isDeprecated: { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLBoolean), + resolve: (enumValue) => enumValue.deprecationReason != null + }, + deprecationReason: { + type: scalars_ts_1.GraphQLString, + resolve: (enumValue) => enumValue.deprecationReason + } + }) + }); + exports.TypeKind = { + SCALAR: "SCALAR", + OBJECT: "OBJECT", + INTERFACE: "INTERFACE", + UNION: "UNION", + ENUM: "ENUM", + INPUT_OBJECT: "INPUT_OBJECT", + LIST: "LIST", + NON_NULL: "NON_NULL" + }; + exports.__TypeKind = new definition_ts_1.GraphQLEnumType({ + name: "__TypeKind", + description: "An enum describing what kind of type a given `__Type` is.", + values: { + SCALAR: { + value: exports.TypeKind.SCALAR, + description: "Indicates this type is a scalar." + }, + OBJECT: { + value: exports.TypeKind.OBJECT, + description: "Indicates this type is an object. `fields` and `interfaces` are valid fields." + }, + INTERFACE: { + value: exports.TypeKind.INTERFACE, + description: "Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields." + }, + UNION: { + value: exports.TypeKind.UNION, + description: "Indicates this type is a union. `possibleTypes` is a valid field." + }, + ENUM: { + value: exports.TypeKind.ENUM, + description: "Indicates this type is an enum. `enumValues` is a valid field." + }, + INPUT_OBJECT: { + value: exports.TypeKind.INPUT_OBJECT, + description: "Indicates this type is an input object. `inputFields` is a valid field." + }, + LIST: { + value: exports.TypeKind.LIST, + description: "Indicates this type is a list. `ofType` is a valid field." + }, + NON_NULL: { + value: exports.TypeKind.NON_NULL, + description: "Indicates this type is a non-null. `ofType` is a valid field." + } + } + }); + exports.SchemaMetaFieldDef = new definition_ts_1.GraphQLField(undefined, "__schema", { + type: new definition_ts_1.GraphQLNonNull(exports.__Schema), + description: "Access the current type schema of this server.", + resolve: (_source, _args, _context, { schema }) => schema + }); + exports.TypeMetaFieldDef = new definition_ts_1.GraphQLField(undefined, "__type", { + type: exports.__Type, + description: "Request the type information of a single type.", + args: { name: { type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString) } }, + resolve: (_source, { name }, _context, { schema }) => schema.getType(name) + }); + exports.TypeNameMetaFieldDef = new definition_ts_1.GraphQLField(undefined, "__typename", { + type: new definition_ts_1.GraphQLNonNull(scalars_ts_1.GraphQLString), + description: "The name of the current Object type at runtime.", + resolve: (_source, _args, _context, { parentType }) => parentType.name + }); + exports.introspectionTypes = Object.freeze([ + exports.__Schema, + exports.__Directive, + exports.__DirectiveLocation, + exports.__Type, + exports.__Field, + exports.__InputValue, + exports.__EnumValue, + exports.__TypeKind + ]); + function isIntrospectionType(type) { + return exports.introspectionTypes.some(({ name }) => type.name === name); + } +}); + +// node_modules/graphql/type/schema.js +var require_schema = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GraphQLSchema = undefined; + exports.isSchema = isSchema; + exports.assertSchema = assertSchema; + var inspect_ts_1 = require_inspect(); + var instanceOf_ts_1 = require_instanceOf(); + var toObjMap_ts_1 = require_toObjMap(); + var ast_ts_1 = require_ast(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var introspection_ts_1 = require_introspection(); + function isSchema(schema) { + return (0, instanceOf_ts_1.instanceOf)(schema, schemaSymbol, GraphQLSchema); + } + function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(schema)} to be a GraphQL schema.`); + } + return schema; + } + var schemaSymbol = Symbol("Schema"); + + class GraphQLSchema { + constructor(config) { + this.__kind = schemaSymbol; + this.assumeValid = config.assumeValid ?? false; + this.__validationErrors = config.assumeValid === true ? [] : undefined; + this.description = config.description; + this.extensions = (0, toObjMap_ts_1.toObjMapWithSymbols)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes ?? []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; + this._directives = config.directives ?? directives_ts_1.specifiedDirectives; + const allReferencedTypes = new Set(config.types); + if (config.types != null) { + for (const type of config.types) { + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + for (const directive of this._directives) { + if ((0, directives_ts_1.isDirective)(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + collectReferencedTypes(introspection_ts_1.__Schema, allReferencedTypes); + this._typeMap = Object.create(null); + this._subTypeMap = new Map; + this._implementationsMap = Object.create(null); + for (const namedType of allReferencedTypes) { + if (namedType == null) { + continue; + } + const typeName = namedType.name; + if (this._typeMap[typeName] !== undefined) { + throw new Error(`Schema must contain uniquely named types but contains multiple types named "${typeName}".`); + } + this._typeMap[typeName] = namedType; + if ((0, definition_ts_1.isInterfaceType)(namedType)) { + for (const iface of namedType.getInterfaces()) { + if ((0, definition_ts_1.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + implementations ??= this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] + }; + implementations.interfaces.push(namedType); + } + } + } else if ((0, definition_ts_1.isObjectType)(namedType)) { + for (const iface of namedType.getInterfaces()) { + if ((0, definition_ts_1.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + implementations ??= this._implementationsMap[iface.name] = { + objects: [], + interfaces: [] + }; + implementations.objects.push(namedType); + } + } + } + } + } + get [Symbol.toStringTag]() { + return "GraphQLSchema"; + } + getQueryType() { + return this._queryType; + } + getMutationType() { + return this._mutationType; + } + getSubscriptionType() { + return this._subscriptionType; + } + getRootType(operation) { + switch (operation) { + case ast_ts_1.OperationTypeNode.QUERY: + return this.getQueryType(); + case ast_ts_1.OperationTypeNode.MUTATION: + return this.getMutationType(); + case ast_ts_1.OperationTypeNode.SUBSCRIPTION: + return this.getSubscriptionType(); + } + } + getTypeMap() { + return this._typeMap; + } + getType(name) { + return this.getTypeMap()[name]; + } + getPossibleTypes(abstractType) { + return (0, definition_ts_1.isUnionType)(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects; + } + getImplementations(interfaceType) { + const implementations = this._implementationsMap[interfaceType.name]; + return implementations ?? { objects: [], interfaces: [] }; + } + isSubType(abstractType, maybeSubType) { + let set = this._subTypeMap.get(abstractType); + if (set === undefined) { + if ((0, definition_ts_1.isUnionType)(abstractType)) { + set = new Set(abstractType.getTypes()); + } else { + const implementations = this.getImplementations(abstractType); + set = new Set([ + ...implementations.objects, + ...implementations.interfaces + ]); + } + this._subTypeMap.set(abstractType, set); + } + return set.has(maybeSubType); + } + getDirectives() { + return this._directives; + } + getDirective(name) { + return this.getDirectives().find((directive) => directive.name === name); + } + getField(parentType, fieldName) { + switch (fieldName) { + case introspection_ts_1.SchemaMetaFieldDef.name: + return this.getQueryType() === parentType ? introspection_ts_1.SchemaMetaFieldDef : undefined; + case introspection_ts_1.TypeMetaFieldDef.name: + return this.getQueryType() === parentType ? introspection_ts_1.TypeMetaFieldDef : undefined; + case introspection_ts_1.TypeNameMetaFieldDef.name: + return introspection_ts_1.TypeNameMetaFieldDef; + } + if ("getFields" in parentType) { + return parentType.getFields()[fieldName]; + } + return; + } + toConfig() { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: Object.values(this.getTypeMap()), + directives: this.getDirectives(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + assumeValid: this.assumeValid + }; + } + } + exports.GraphQLSchema = GraphQLSchema; + function collectReferencedTypes(type, typeSet) { + const namedType = (0, definition_ts_1.getNamedType)(type); + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + if ((0, definition_ts_1.isUnionType)(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if ((0, definition_ts_1.isObjectType)(namedType) || (0, definition_ts_1.isInterfaceType)(namedType)) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if ((0, definition_ts_1.isInputObjectType)(namedType)) { + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } + } + } + return typeSet; + } +}); + +// node_modules/graphql/type/validate.js +var require_validate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchema = validateSchema; + exports.assertValidSchema = assertValidSchema; + exports.validateDefaultInput = validateDefaultInput; + var AccumulatorMap_ts_1 = require_AccumulatorMap(); + var capitalize_ts_1 = require_capitalize(); + var formatList_ts_1 = require_formatList(); + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var isIterableObject_ts_1 = require_isIterableObject(); + var isObjectLike_ts_1 = require_isObjectLike(); + var keyMap_ts_1 = require_keyMap(); + var mapValue_ts_1 = require_mapValue(); + var printPathArray_ts_1 = require_printPathArray(); + var GraphQLError_ts_1 = require_GraphQLError(); + var ast_ts_1 = require_ast(); + var kinds_ts_1 = require_kinds(); + var typeComparators_ts_1 = require_typeComparators(); + var validateInputValue_ts_1 = require_validateInputValue(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var introspection_ts_1 = require_introspection(); + var schema_ts_1 = require_schema(); + function validateSchema(schema) { + (0, schema_ts_1.assertSchema)(schema); + if (schema.__validationErrors) { + return schema.__validationErrors; + } + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; + } + function assertValidSchema(schema) { + const errors = validateSchema(schema); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join(` + +`)); + } + } + + class SchemaValidationContext { + constructor(schema) { + this._errors = []; + this.schema = schema; + } + reportError(message, nodes) { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + this._errors.push(new GraphQLError_ts_1.GraphQLError(message, { nodes: _nodes })); + } + getErrors() { + return this._errors; + } + } + function validateRootTypes(context) { + const schema = context.schema; + if (schema.getQueryType() == null) { + context.reportError("Query root type must be provided.", schema.astNode); + } + const rootTypesMap = new AccumulatorMap_ts_1.AccumulatorMap; + for (const operationType of Object.values(ast_ts_1.OperationTypeNode)) { + const rootType = schema.getRootType(operationType); + if (rootType != null) { + if (!(0, definition_ts_1.isObjectType)(rootType)) { + const operationTypeStr = (0, capitalize_ts_1.capitalize)(operationType); + const rootTypeStr = (0, inspect_ts_1.inspect)(rootType); + context.reportError(operationType === ast_ts_1.OperationTypeNode.QUERY ? `${operationTypeStr} root type must be Object type, it cannot be ${rootTypeStr}.` : `${operationTypeStr} root type must be Object type if provided, it cannot be ${rootTypeStr}.`, getOperationTypeNode(schema, operationType) ?? rootType.astNode); + } else { + rootTypesMap.add(rootType, operationType); + } + } + } + for (const [rootType, operationTypes] of rootTypesMap) { + if (operationTypes.length > 1) { + const operationList = (0, formatList_ts_1.andList)(operationTypes); + context.reportError(`All root types must be different, "${rootType}" type is used as ${operationList} root types.`, operationTypes.map((operationType) => getOperationTypeNode(schema, operationType))); + } + } + } + function getOperationTypeNode(schema, operation) { + return [schema.astNode, ...schema.extensionASTNodes].flatMap((schemaNode) => schemaNode?.operationTypes ?? []).find((operationNode) => operationNode.operation === operation)?.type; + } + function validateDirectives(context) { + for (const directive of context.schema.getDirectives()) { + if (!(0, directives_ts_1.isDirective)(directive)) { + context.reportError(`Expected directive but got: ${(0, inspect_ts_1.inspect)(directive)}.`, directive?.astNode); + continue; + } + validateName(context, directive); + if (directive.locations.length === 0) { + context.reportError(`Directive ${directive} must include 1 or more locations.`, directive.astNode); + } + for (const arg of directive.args) { + validateName(context, arg); + if (!(0, definition_ts_1.isInputType)(arg.type)) { + context.reportError(`The type of ${arg} must be Input Type ` + `but got: ${(0, inspect_ts_1.inspect)(arg.type)}.`, arg.astNode); + } + if ((0, definition_ts_1.isRequiredArgument)(arg) && arg.deprecationReason != null) { + context.reportError(`Required argument ${arg} cannot be deprecated.`, [ + getDeprecatedDirectiveNode(arg.astNode), + arg.astNode?.type + ]); + } + validateDefaultValue(context, arg); + } + } + } + function validateDefaultValue(context, inputValue) { + const defaultInput = inputValue.default; + if (!defaultInput) { + return; + } + const errors = []; + validateDefaultInput(defaultInput, inputValue.type, (error, path) => { + errors.push([error, path]); + }); + if (errors.length === 0) { + return; + } + if (!defaultInput.literal) { + try { + const uncoercedValue = uncoerceDefaultValue(defaultInput.value, inputValue.type); + const uncoercedErrors = []; + (0, validateInputValue_ts_1.validateInputValue)(uncoercedValue, inputValue.type, (error, path) => { + uncoercedErrors.push([error, path]); + }); + if (uncoercedErrors.length === 0) { + context.reportError(`${inputValue} has invalid default value: ${(0, inspect_ts_1.inspect)(defaultInput.value)}. Did you mean: ${(0, inspect_ts_1.inspect)(uncoercedValue)}?`, inputValue.astNode?.defaultValue); + return; + } + } catch (_error) {} + } + for (const [error, path] of errors) { + context.reportError(`${inputValue} has invalid default value${(0, printPathArray_ts_1.printPathArray)(path)}: ${error.message}`, error.nodes ?? inputValue.astNode?.defaultValue); + } + } + function validateDefaultInput(defaultInput, inputType, onError, hideSuggestions) { + if (defaultInput.literal) { + (0, validateInputValue_ts_1.validateInputLiteral)(defaultInput.literal, inputType, onError, undefined, undefined, hideSuggestions); + return; + } + (0, validateInputValue_ts_1.validateInputValue)(defaultInput.value, inputType, onError, hideSuggestions); + } + function uncoerceDefaultValue(value, type) { + if ((0, definition_ts_1.isNonNullType)(type)) { + return uncoerceDefaultValue(value, type.ofType); + } + if (value === null) { + return null; + } + if ((0, definition_ts_1.isListType)(type)) { + if ((0, isIterableObject_ts_1.isIterableObject)(value)) { + return Array.from(value, (itemValue) => uncoerceDefaultValue(itemValue, type.ofType)); + } + return [uncoerceDefaultValue(value, type.ofType)]; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + if (!(0, isObjectLike_ts_1.isObjectLike)(value)) + (0, invariant_ts_1.invariant)(false); + const fieldDefs = type.getFields(); + return (0, mapValue_ts_1.mapValue)(value, (fieldValue, fieldName) => { + if (!(fieldName in fieldDefs)) + (0, invariant_ts_1.invariant)(false); + return uncoerceDefaultValue(fieldValue, fieldDefs[fieldName].type); + }); + } + (0, definition_ts_1.assertLeafType)(type); + return type.coerceOutputValue(value); + } + function validateName(context, node) { + if (node.name.startsWith("__")) { + context.reportError(`Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, node.astNode); + } + } + function validateTypes(context) { + const validateInputObjectDefaultValueCircularRefs = createInputObjectDefaultValueCircularRefsValidator(context); + const typeMap = context.schema.getTypeMap(); + const finiteValueStates = new Map; + for (const type of Object.values(typeMap)) { + if (!(0, definition_ts_1.isNamedType)(type)) { + context.reportError(`Expected GraphQL named type but got: ${(0, inspect_ts_1.inspect)(type)}.`, type.astNode); + continue; + } + if (!(0, introspection_ts_1.isIntrospectionType)(type)) { + validateName(context, type); + } + if ((0, definition_ts_1.isObjectType)(type)) { + validateFields(context, type); + validateInterfaces(context, type); + } else if ((0, definition_ts_1.isInterfaceType)(type)) { + validateFields(context, type); + validateInterfaces(context, type); + } else if ((0, definition_ts_1.isUnionType)(type)) { + validateUnionMembers(context, type); + } else if ((0, definition_ts_1.isEnumType)(type)) { + validateEnumValues(context, type); + } else if ((0, definition_ts_1.isInputObjectType)(type)) { + validateInputFields(context, type); + initializeInputObjectFiniteValueState(type); + validateInputObjectDefaultValueCircularRefs(type); + } + } + detectInputObjectNonFiniteValues(context, finiteValueStates); + function initializeInputObjectFiniteValueState(inputObj) { + finiteValueStates.set(inputObj, { + inputObj, + targets: [], + dependents: [], + unresolvedTargetCount: 0, + hasFiniteValue: false + }); + } + } + function validateFields(context, type) { + const fields = Object.values(type.getFields()); + if (fields.length === 0) { + context.reportError(`Type ${type} must define one or more fields.`, [ + type.astNode, + ...type.extensionASTNodes + ]); + } + for (const field of fields) { + validateName(context, field); + if (!(0, definition_ts_1.isOutputType)(field.type)) { + context.reportError(`The type of ${field} must be Output Type ` + `but got: ${(0, inspect_ts_1.inspect)(field.type)}.`, field.astNode?.type); + } + for (const arg of field.args) { + validateName(context, arg); + if (!(0, definition_ts_1.isInputType)(arg.type)) { + context.reportError(`The type of ${arg} must be Input Type but got: ${(0, inspect_ts_1.inspect)(arg.type)}.`, arg.astNode?.type); + } + if ((0, definition_ts_1.isRequiredArgument)(arg) && arg.deprecationReason != null) { + context.reportError(`Required argument ${arg} cannot be deprecated.`, [ + getDeprecatedDirectiveNode(arg.astNode), + arg.astNode?.type + ]); + } + validateDefaultValue(context, arg); + } + } + } + function validateInterfaces(context, type) { + const ifaceTypeNames = new Set; + for (const iface of type.getInterfaces()) { + if (!(0, definition_ts_1.isInterfaceType)(iface)) { + context.reportError(`Type ${type} must only implement Interface types, ` + `it cannot implement ${(0, inspect_ts_1.inspect)(iface)}.`, getAllImplementsInterfaceNodes(type, iface)); + continue; + } + if (type === iface) { + context.reportError(`Type ${type} cannot implement itself because it would create a circular reference.`, getAllImplementsInterfaceNodes(type, iface)); + continue; + } + if (ifaceTypeNames.has(iface.name)) { + context.reportError(`Type ${type} can only implement ${iface} once.`, getAllImplementsInterfaceNodes(type, iface)); + continue; + } + ifaceTypeNames.add(iface.name); + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } + } + function validateTypeImplementsInterface(context, type, iface) { + const typeFieldMap = type.getFields(); + for (const ifaceField of Object.values(iface.getFields())) { + const typeField = typeFieldMap[ifaceField.name]; + if (typeField == null) { + context.reportError(`Interface field ${ifaceField} expected but ${type} does not provide it.`, [ifaceField.astNode, type.astNode, ...type.extensionASTNodes]); + continue; + } + if (!(0, typeComparators_ts_1.isTypeSubTypeOf)(context.schema, typeField.type, ifaceField.type)) { + context.reportError(`Interface field ${ifaceField} expects type ${ifaceField.type} ` + `but ${typeField} is type ${typeField.type}.`, [ifaceField.astNode?.type, typeField.astNode?.type]); + } + for (const ifaceArg of ifaceField.args) { + const typeArg = typeField.args.find((arg) => arg.name === ifaceArg.name); + if (!typeArg) { + context.reportError(`Interface field argument ${ifaceArg} expected but ${typeField} does not provide it.`, [ifaceArg.astNode, typeField.astNode]); + continue; + } + if (!(0, typeComparators_ts_1.isEqualType)(ifaceArg.type, typeArg.type)) { + context.reportError(`Interface field argument ${ifaceArg} expects type ${ifaceArg.type} ` + `but ${typeArg} is type ${typeArg.type}.`, [ifaceArg.astNode?.type, typeArg.astNode?.type]); + } + } + for (const typeArg of typeField.args) { + if ((0, definition_ts_1.isRequiredArgument)(typeArg)) { + const ifaceArg = ifaceField.args.find((arg) => arg.name === typeArg.name); + if (!ifaceArg) { + context.reportError(`Argument "${typeArg}" must not be required type "${typeArg.type}" ` + `if not provided by the Interface field "${ifaceField}".`, [typeArg.astNode, ifaceField.astNode]); + } + } + } + if (typeField.deprecationReason != null && ifaceField.deprecationReason == null) { + context.reportError(`Interface field ${iface.name}.${ifaceField.name} is not deprecated, so ` + `implementation field ${type.name}.${typeField.name} must not be deprecated.`, [ + getDeprecatedDirectiveNode(typeField.astNode), + typeField.astNode?.type + ]); + } + } + } + function validateTypeImplementsAncestors(context, type, iface) { + const ifaceInterfaces = type.getInterfaces(); + for (const transitive of iface.getInterfaces()) { + if (!ifaceInterfaces.includes(transitive)) { + context.reportError(transitive === type ? `Type ${type} cannot implement ${iface} because it would create a circular reference.` : `Type ${type} must implement ${transitive} because it is implemented by ${iface}.`, [ + ...getAllImplementsInterfaceNodes(iface, transitive), + ...getAllImplementsInterfaceNodes(type, iface) + ]); + } + } + } + function validateUnionMembers(context, union) { + const memberTypes = union.getTypes(); + if (memberTypes.length === 0) { + context.reportError(`Union type ${union} must define one or more member types.`, [union.astNode, ...union.extensionASTNodes]); + } + const includedTypeNames = new Set; + for (const memberType of memberTypes) { + if (includedTypeNames.has(memberType.name)) { + context.reportError(`Union type ${union} can only include type ${memberType} once.`, getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + includedTypeNames.add(memberType.name); + if (!(0, definition_ts_1.isObjectType)(memberType)) { + context.reportError(`Union type ${union} can only include Object types, ` + `it cannot include ${(0, inspect_ts_1.inspect)(memberType)}.`, getUnionMemberTypeNodes(union, String(memberType))); + } + } + } + function validateEnumValues(context, enumType) { + const enumValues = enumType.getValues(); + if (enumValues.length === 0) { + context.reportError(`Enum type ${enumType} must define one or more values.`, [enumType.astNode, ...enumType.extensionASTNodes]); + } + for (const enumValue of enumValues) { + validateName(context, enumValue); + } + } + function validateInputFields(context, inputObj) { + const fields = Object.values(inputObj.getFields()); + if (fields.length === 0) { + context.reportError(`Input Object type ${inputObj} must define one or more fields.`, [inputObj.astNode, ...inputObj.extensionASTNodes]); + } + for (const field of fields) { + validateName(context, field); + if (!(0, definition_ts_1.isInputType)(field.type)) { + context.reportError(`The type of ${field} must be Input Type ` + `but got: ${(0, inspect_ts_1.inspect)(field.type)}.`, field.astNode?.type); + } + if ((0, definition_ts_1.isRequiredInputField)(field) && field.deprecationReason != null) { + context.reportError(`Required input field ${field} cannot be deprecated.`, [getDeprecatedDirectiveNode(field.astNode), field.astNode?.type]); + } + validateDefaultValue(context, field); + if (inputObj.isOneOf) { + validateOneOfInputObjectField(inputObj, field, context); + } + } + } + function validateOneOfInputObjectField(type, field, context) { + if ((0, definition_ts_1.isNonNullType)(field.type)) { + context.reportError(`OneOf input field ${type}.${field.name} must be nullable.`, field.astNode?.type); + } + if (field.default !== undefined || field.defaultValue !== undefined) { + context.reportError(`OneOf input field ${type}.${field.name} cannot have a default value.`, field.astNode); + } + } + function detectInputObjectNonFiniteValues(context, finiteValueStates) { + const inputObjectsWithFiniteValues = []; + for (const state of finiteValueStates.values()) { + const inputObj = state.inputObj; + const fields = Object.values(inputObj.getFields()); + for (const field of fields) { + const target = getFiniteValueTarget(inputObj, field.type); + if (target === undefined) { + continue; + } + state.targets.push({ field, target }); + const targetState = finiteValueStates.get(target); + if (targetState !== undefined) { + targetState.dependents.push(state); + } + } + if (inputObj.isOneOf) { + if (fields.length === 0 || state.targets.length < fields.length) { + markInputObjectHasFiniteValue(state); + } + } else { + state.unresolvedTargetCount = state.targets.length; + if (state.targets.length === 0) { + markInputObjectHasFiniteValue(state); + } + } + } + let nextFiniteValueState; + while ((nextFiniteValueState = inputObjectsWithFiniteValues.pop()) !== undefined) { + for (const dependentState of nextFiniteValueState.dependents) { + if (dependentState.hasFiniteValue) { + continue; + } + if (dependentState.inputObj.isOneOf) { + markInputObjectHasFiniteValue(dependentState); + continue; + } + --dependentState.unresolvedTargetCount; + if (dependentState.unresolvedTargetCount === 0) { + markInputObjectHasFiniteValue(dependentState); + } + } + } + const visitedTypes = new Set; + const fieldPath = []; + const fieldPathIndexByType = new Map; + for (const state of finiteValueStates.values()) { + if (!state.hasFiniteValue) { + reportCycleRecursive(state); + } + } + function markInputObjectHasFiniteValue(finiteValueState) { + if (!finiteValueState.hasFiniteValue) { + finiteValueState.hasFiniteValue = true; + inputObjectsWithFiniteValues.push(finiteValueState); + } + } + function reportCycleRecursive(state) { + const inputObj = state.inputObj; + if (visitedTypes.has(inputObj)) { + return; + } + visitedTypes.add(inputObj); + fieldPathIndexByType.set(inputObj, fieldPath.length); + for (const { field, target } of state.targets) { + const targetState = finiteValueStates.get(target); + if (targetState?.hasFiniteValue !== false) { + continue; + } + const cycleIndex = fieldPathIndexByType.get(target); + fieldPath.push({ + fieldStr: `${inputObj}.${field.name}`, + astNode: field.astNode + }); + if (cycleIndex === undefined) { + reportCycleRecursive(targetState); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath.map((p) => p.fieldStr).join(", "); + context.reportError(`Input Object ${target} cannot be provided a finite value because it references itself through fields: ${pathStr}.`, cyclePath.map((p) => p.astNode)); + } + fieldPath.pop(); + } + fieldPathIndexByType.delete(inputObj); + } + } + function getFiniteValueTarget(inputObj, fieldType) { + if (inputObj.isOneOf) { + if ((0, definition_ts_1.isInputObjectType)(fieldType)) { + return fieldType; + } + return; + } + if ((0, definition_ts_1.isNonNullType)(fieldType) && (0, definition_ts_1.isInputObjectType)(fieldType.ofType)) { + return fieldType.ofType; + } + } + function createInputObjectDefaultValueCircularRefsValidator(context) { + const visitedFields = Object.create(null); + const fieldPath = []; + const fieldPathIndex = Object.create(null); + return function validateInputObjectDefaultValueCircularRefs(inputObj) { + return detectValueDefaultValueCycle(inputObj, Object.create(null)); + }; + function detectValueDefaultValueCycle(inputObj, defaultValue) { + if ((0, isIterableObject_ts_1.isIterableObject)(defaultValue)) { + for (const itemValue of defaultValue) { + detectValueDefaultValueCycle(inputObj, itemValue); + } + return; + } else if (!(0, isObjectLike_ts_1.isObjectLike)(defaultValue)) { + return; + } + for (const field of Object.values(inputObj.getFields())) { + const namedFieldType = (0, definition_ts_1.getNamedType)(field.type); + if (!(0, definition_ts_1.isInputObjectType)(namedFieldType)) { + continue; + } + if (Object.hasOwn(defaultValue, field.name)) { + detectValueDefaultValueCycle(namedFieldType, defaultValue[field.name]); + } else { + detectFieldDefaultValueCycle(field, namedFieldType, `${inputObj}.${field.name}`); + } + } + } + function detectLiteralDefaultValueCycle(inputObj, defaultValue) { + if (defaultValue.kind === kinds_ts_1.Kind.LIST) { + for (const itemLiteral of defaultValue.values) { + detectLiteralDefaultValueCycle(inputObj, itemLiteral); + } + return; + } else if (defaultValue.kind !== kinds_ts_1.Kind.OBJECT) { + return; + } + const fieldNodes = (0, keyMap_ts_1.keyMap)(defaultValue.fields, (field) => field.name.value); + for (const field of Object.values(inputObj.getFields())) { + const namedFieldType = (0, definition_ts_1.getNamedType)(field.type); + if (!(0, definition_ts_1.isInputObjectType)(namedFieldType)) { + continue; + } + if (Object.hasOwn(fieldNodes, field.name)) { + detectLiteralDefaultValueCycle(namedFieldType, fieldNodes[field.name].value); + } else { + detectFieldDefaultValueCycle(field, namedFieldType, `${inputObj}.${field.name}`); + } + } + } + function detectFieldDefaultValueCycle(field, fieldType, fieldStr) { + const defaultInput = field.default; + if (defaultInput === undefined) { + return; + } + const cycleIndex = fieldPathIndex[fieldStr]; + if (cycleIndex !== undefined) { + context.reportError(`Invalid circular reference. The default value of Input Object field ${fieldStr} references itself${cycleIndex < fieldPath.length ? ` via the default values of: ${fieldPath.slice(cycleIndex).map(([stringForMessage]) => stringForMessage).join(", ")}` : ""}.`, fieldPath.slice(cycleIndex - 1).map(([, node]) => node)); + return; + } + if (visitedFields[fieldStr] === undefined) { + visitedFields[fieldStr] = true; + fieldPathIndex[fieldStr] = fieldPath.push([ + fieldStr, + field.astNode?.defaultValue + ]); + if (defaultInput.literal) { + detectLiteralDefaultValueCycle(fieldType, defaultInput.literal); + } else { + detectValueDefaultValueCycle(fieldType, defaultInput.value); + } + fieldPath.pop(); + fieldPathIndex[fieldStr] = undefined; + } + } + } + function getAllImplementsInterfaceNodes(type, iface) { + const { astNode, extensionASTNodes } = type; + const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; + return nodes.flatMap((typeNode) => typeNode.interfaces ?? []).filter((ifaceNode) => ifaceNode.name.value === iface.name); + } + function getUnionMemberTypeNodes(union, typeName) { + const { astNode, extensionASTNodes } = union; + const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; + return nodes.flatMap((unionNode) => unionNode.types ?? []).filter((typeNode) => typeNode.name.value === typeName); + } + function getDeprecatedDirectiveNode(definitionNode) { + return definitionNode?.directives?.find((node) => node.name.value === directives_ts_1.GraphQLDeprecatedDirective.name); + } +}); + +// node_modules/graphql/error/syntaxError.js +var require_syntaxError = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.syntaxError = syntaxError; + var GraphQLError_ts_1 = require_GraphQLError(); + function syntaxError(source, position, description) { + return new GraphQLError_ts_1.GraphQLError(`Syntax Error: ${description}`, { + source, + positions: [position] + }); + } +}); + +// node_modules/graphql/diagnostics.js +var require_diagnostics = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveChannel = exports.subscribeChannel = exports.executeRootSelectionSetChannel = exports.executeVariableCoercionChannel = exports.executeChannel = exports.validateChannel = exports.parseChannel = undefined; + exports.shouldTrace = shouldTrace; + exports.traceMixed = traceMixed; + var isPromise_ts_1 = require_isPromise(); + function resolveDiagnosticsChannel() { + let dc2; + try { + const processRef = globalThis.process; + if (typeof processRef?.getBuiltinModule === "function") { + dc2 = processRef.getBuiltinModule("node:diagnostics_channel"); + } + } catch {} + return dc2; + } + var dc = resolveDiagnosticsChannel(); + exports.parseChannel = dc?.tracingChannel("graphql:parse"); + exports.validateChannel = dc?.tracingChannel("graphql:validate"); + exports.executeChannel = dc?.tracingChannel("graphql:execute"); + exports.executeVariableCoercionChannel = dc?.tracingChannel("graphql:execute:variableCoercion"); + exports.executeRootSelectionSetChannel = dc?.tracingChannel("graphql:execute:rootSelectionSet"); + exports.subscribeChannel = dc?.tracingChannel("graphql:subscribe"); + exports.resolveChannel = dc?.tracingChannel("graphql:resolve"); + var SUB_CHANNEL_KEYS = ["start", "end", "asyncStart", "asyncEnd", "error"]; + function shouldTrace(channel) { + if (channel == null) { + return false; + } + const aggregate = channel.hasSubscribers; + if (aggregate !== undefined) { + return aggregate; + } + for (const key of SUB_CHANNEL_KEYS) { + if (channel[key].hasSubscribers) { + return true; + } + } + return false; + } + function traceMixed(channel, contextInput, fn) { + const context = contextInput; + return channel.start.runStores(context, () => { + let result; + try { + result = fn(); + } catch (err) { + context.error = err; + channel.error.publish(context); + channel.end.publish(context); + throw err; + } + if (!(0, isPromise_ts_1.isPromiseLike)(result)) { + context.result = result; + channel.end.publish(context); + return result; + } + channel.end.publish(context); + return result.then((value) => { + context.result = value; + channel.asyncStart.publish(context); + channel.asyncEnd.publish(context); + return value; + }, (err) => { + context.error = err; + channel.error.publish(context); + channel.asyncStart.publish(context); + channel.asyncEnd.publish(context); + throw err; + }); + }); + } +}); + +// node_modules/graphql/language/tokenKind.js +var require_tokenKind = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TokenKind = undefined; + exports.TokenKind = { + SOF: "", + EOF: "", + BANG: "!", + DOLLAR: "$", + AMP: "&", + PAREN_L: "(", + PAREN_R: ")", + DOT: ".", + SPREAD: "...", + COLON: ":", + EQUALS: "=", + AT: "@", + BRACKET_L: "[", + BRACKET_R: "]", + BRACE_L: "{", + PIPE: "|", + BRACE_R: "}", + NAME: "Name", + INT: "Int", + FLOAT: "Float", + STRING: "String", + BLOCK_STRING: "BlockString", + COMMENT: "Comment" + }; +}); + +// node_modules/graphql/language/lexer.js +var require_lexer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Lexer = undefined; + exports.isPunctuatorTokenKind = isPunctuatorTokenKind; + exports.printCodePointAt = printCodePointAt; + exports.createToken = createToken; + exports.readName = readName; + var syntaxError_ts_1 = require_syntaxError(); + var ast_ts_1 = require_ast(); + var blockString_ts_1 = require_blockString(); + var characterClasses_ts_1 = require_characterClasses(); + var tokenKind_ts_1 = require_tokenKind(); + + class Lexer { + constructor(source) { + const startOfFileToken = new ast_ts_1.Token(tokenKind_ts_1.TokenKind.SOF, 0, 0, 0, 0); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + get [Symbol.toStringTag]() { + return "Lexer"; + } + advance() { + this.lastToken = this.token; + const token = this.token = this.lookahead(); + return token; + } + lookahead() { + let token = this.token; + if (token.kind !== tokenKind_ts_1.TokenKind.EOF) { + do { + if (token.next) { + token = token.next; + } else { + const nextToken = readNextToken(this, token.end); + token.next = nextToken; + nextToken.prev = token; + token = nextToken; + } + } while (token.kind === tokenKind_ts_1.TokenKind.COMMENT); + } + return token; + } + } + exports.Lexer = Lexer; + function isPunctuatorTokenKind(kind2) { + return kind2 === tokenKind_ts_1.TokenKind.BANG || kind2 === tokenKind_ts_1.TokenKind.DOLLAR || kind2 === tokenKind_ts_1.TokenKind.AMP || kind2 === tokenKind_ts_1.TokenKind.PAREN_L || kind2 === tokenKind_ts_1.TokenKind.PAREN_R || kind2 === tokenKind_ts_1.TokenKind.DOT || kind2 === tokenKind_ts_1.TokenKind.SPREAD || kind2 === tokenKind_ts_1.TokenKind.COLON || kind2 === tokenKind_ts_1.TokenKind.EQUALS || kind2 === tokenKind_ts_1.TokenKind.AT || kind2 === tokenKind_ts_1.TokenKind.BRACKET_L || kind2 === tokenKind_ts_1.TokenKind.BRACKET_R || kind2 === tokenKind_ts_1.TokenKind.BRACE_L || kind2 === tokenKind_ts_1.TokenKind.PIPE || kind2 === tokenKind_ts_1.TokenKind.BRACE_R; + } + function isUnicodeScalarValue(code) { + return code >= 0 && code <= 55295 || code >= 57344 && code <= 1114111; + } + function isSupplementaryCodePoint(body, location) { + return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1)); + } + function isLeadingSurrogate(code) { + return code >= 55296 && code <= 56319; + } + function isTrailingSurrogate(code) { + return code >= 56320 && code <= 57343; + } + function printCodePointAt(lexer, location) { + const code = lexer.source.body.codePointAt(location); + if (code === undefined) { + return tokenKind_ts_1.TokenKind.EOF; + } else if (code >= 32 && code <= 126) { + const char = String.fromCodePoint(code); + return char === '"' ? `'"'` : `"${char}"`; + } + return "U+" + code.toString(16).toUpperCase().padStart(4, "0"); + } + function createToken(lexer, kind2, start, end, value) { + const line = lexer.line; + const col = 1 + start - lexer.lineStart; + return new ast_ts_1.Token(kind2, start, end, line, col, value); + } + function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start; + while (position < bodyLength) { + const code = body.charCodeAt(position); + switch (code) { + case 65279: + case 9: + case 32: + case 44: + ++position; + continue; + case 10: + ++position; + ++lexer.line; + lexer.lineStart = position; + continue; + case 13: + if (body.charCodeAt(position + 1) === 10) { + position += 2; + } else { + ++position; + } + ++lexer.line; + lexer.lineStart = position; + continue; + case 35: + return readComment(lexer, position); + case 33: + return createToken(lexer, tokenKind_ts_1.TokenKind.BANG, position, position + 1); + case 36: + return createToken(lexer, tokenKind_ts_1.TokenKind.DOLLAR, position, position + 1); + case 38: + return createToken(lexer, tokenKind_ts_1.TokenKind.AMP, position, position + 1); + case 40: + return createToken(lexer, tokenKind_ts_1.TokenKind.PAREN_L, position, position + 1); + case 41: + return createToken(lexer, tokenKind_ts_1.TokenKind.PAREN_R, position, position + 1); + case 46: { + const nextCode = body.charCodeAt(position + 1); + if (nextCode === 46 && body.charCodeAt(position + 2) === 46) { + return createToken(lexer, tokenKind_ts_1.TokenKind.SPREAD, position, position + 3); + } + if (nextCode === 46) { + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, 'Unexpected "..", did you mean "..."?'); + } else if ((0, characterClasses_ts_1.isDigit)(nextCode)) { + const digits = lexer.source.body.slice(position + 1, readDigits(lexer, position + 1, nextCode)); + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid number, expected digit before ".", did you mean "0.${digits}"?`); + } + break; + } + case 58: + return createToken(lexer, tokenKind_ts_1.TokenKind.COLON, position, position + 1); + case 61: + return createToken(lexer, tokenKind_ts_1.TokenKind.EQUALS, position, position + 1); + case 64: + return createToken(lexer, tokenKind_ts_1.TokenKind.AT, position, position + 1); + case 91: + return createToken(lexer, tokenKind_ts_1.TokenKind.BRACKET_L, position, position + 1); + case 93: + return createToken(lexer, tokenKind_ts_1.TokenKind.BRACKET_R, position, position + 1); + case 123: + return createToken(lexer, tokenKind_ts_1.TokenKind.BRACE_L, position, position + 1); + case 124: + return createToken(lexer, tokenKind_ts_1.TokenKind.PIPE, position, position + 1); + case 125: + return createToken(lexer, tokenKind_ts_1.TokenKind.BRACE_R, position, position + 1); + case 34: + if (body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) { + return readBlockString(lexer, position); + } + return readString(lexer, position); + } + if ((0, characterClasses_ts_1.isDigit)(code) || code === 45) { + return readNumber(lexer, position, code); + } + if ((0, characterClasses_ts_1.isNameStart)(code)) { + return readName(lexer, position); + } + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, code === 39 ? `Unexpected single quote character ('), did you mean to use a double quote (")?` : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`); + } + return createToken(lexer, tokenKind_ts_1.TokenKind.EOF, bodyLength, bodyLength); + } + function readComment(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); + if (code === 10 || code === 13) { + break; + } + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + break; + } + } + return createToken(lexer, tokenKind_ts_1.TokenKind.COMMENT, start, position, body.slice(start + 1, position)); + } + function readNumber(lexer, start, firstCode) { + const body = lexer.source.body; + let position = start; + let code = firstCode; + let isFloat = false; + if (code === 45) { + code = body.charCodeAt(++position); + } + if (code === 48) { + code = body.charCodeAt(++position); + if ((0, characterClasses_ts_1.isDigit)(code)) { + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid number, unexpected digit after 0: ${printCodePointAt(lexer, position)}.`); + } + } else { + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } + if (code === 46) { + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } + if (code === 69 || code === 101) { + isFloat = true; + code = body.charCodeAt(++position); + if (code === 43 || code === 45) { + code = body.charCodeAt(++position); + } + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } + if (code === 46 || (0, characterClasses_ts_1.isNameStart)(code)) { + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid number, expected digit but got: ${printCodePointAt(lexer, position)}.`); + } + return createToken(lexer, isFloat ? tokenKind_ts_1.TokenKind.FLOAT : tokenKind_ts_1.TokenKind.INT, start, position, body.slice(start, position)); + } + function readDigits(lexer, start, firstCode) { + if (!(0, characterClasses_ts_1.isDigit)(firstCode)) { + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, start, `Invalid number, expected digit but got: ${printCodePointAt(lexer, start)}.`); + } + const body = lexer.source.body; + let position = start + 1; + while ((0, characterClasses_ts_1.isDigit)(body.charCodeAt(position))) { + ++position; + } + return position; + } + function readString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + let chunkStart = position; + let value = ""; + while (position < bodyLength) { + const code = body.charCodeAt(position); + if (code === 34) { + value += body.slice(chunkStart, position); + return createToken(lexer, tokenKind_ts_1.TokenKind.STRING, start, position + 1, value); + } + if (code === 92) { + value += body.slice(chunkStart, position); + const escape = body.charCodeAt(position + 1) === 117 ? body.charCodeAt(position + 2) === 123 ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position); + value += escape.value; + position += escape.size; + chunkStart = position; + continue; + } + if (code === 10 || code === 13) { + break; + } + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); + } + } + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, "Unterminated string."); + } + function readEscapedUnicodeVariableWidth(lexer, position) { + const body = lexer.source.body; + let point = 0; + let size = 3; + while (size < 12) { + const code = body.charCodeAt(position + size++); + if (code === 125) { + if (size < 5 || !isUnicodeScalarValue(point)) { + break; + } + return { value: String.fromCodePoint(point), size }; + } + point = point << 4 | readHexDigit(code); + if (point < 0) { + break; + } + } + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + size)}".`); + } + function readEscapedUnicodeFixedWidth(lexer, position) { + const body = lexer.source.body; + const code = read16BitHexCode(body, position + 2); + if (isUnicodeScalarValue(code)) { + return { value: String.fromCodePoint(code), size: 6 }; + } + if (isLeadingSurrogate(code)) { + if (body.charCodeAt(position + 6) === 92 && body.charCodeAt(position + 7) === 117) { + const trailingCode = read16BitHexCode(body, position + 8); + if (isTrailingSurrogate(trailingCode)) { + return { value: String.fromCodePoint(code, trailingCode), size: 12 }; + } + } + } + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`); + } + function read16BitHexCode(body, position) { + return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3)); + } + function readHexDigit(code) { + return code >= 48 && code <= 57 ? code - 48 : code >= 65 && code <= 70 ? code - 55 : code >= 97 && code <= 102 ? code - 87 : -1; + } + function readEscapedCharacter(lexer, position) { + const body = lexer.source.body; + const code = body.charCodeAt(position + 1); + switch (code) { + case 34: + return { value: '"', size: 2 }; + case 92: + return { value: "\\", size: 2 }; + case 47: + return { value: "/", size: 2 }; + case 98: + return { value: "\b", size: 2 }; + case 102: + return { value: "\f", size: 2 }; + case 110: + return { value: ` +`, size: 2 }; + case 114: + return { value: "\r", size: 2 }; + case 116: + return { value: "\t", size: 2 }; + } + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid character escape sequence: "${body.slice(position, position + 2)}".`); + } + function readBlockString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let lineStart = lexer.lineStart; + let position = start + 3; + let chunkStart = position; + let currentLine = ""; + const blockLines = []; + while (position < bodyLength) { + const code = body.charCodeAt(position); + if (code === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + const token = createToken(lexer, tokenKind_ts_1.TokenKind.BLOCK_STRING, start, position + 3, (0, blockString_ts_1.dedentBlockStringLines)(blockLines).join(` +`)); + lexer.line += blockLines.length - 1; + lexer.lineStart = lineStart; + return token; + } + if (code === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) { + currentLine += body.slice(chunkStart, position); + chunkStart = position + 1; + position += 4; + continue; + } + if (code === 10 || code === 13) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + if (code === 13 && body.charCodeAt(position + 1) === 10) { + position += 2; + } else { + ++position; + } + currentLine = ""; + chunkStart = position; + lineStart = position; + continue; + } + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid character within String: ${printCodePointAt(lexer, position)}.`); + } + } + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, "Unterminated string."); + } + function readName(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + while (position < bodyLength) { + const code = body.charCodeAt(position); + if ((0, characterClasses_ts_1.isNameContinue)(code)) { + ++position; + } else { + break; + } + } + return createToken(lexer, tokenKind_ts_1.TokenKind.NAME, start, position, body.slice(start, position)); + } +}); + +// node_modules/graphql/language/schemaCoordinateLexer.js +var require_schemaCoordinateLexer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SchemaCoordinateLexer = undefined; + var syntaxError_ts_1 = require_syntaxError(); + var ast_ts_1 = require_ast(); + var characterClasses_ts_1 = require_characterClasses(); + var lexer_ts_1 = require_lexer(); + var tokenKind_ts_1 = require_tokenKind(); + + class SchemaCoordinateLexer { + constructor(source) { + this.line = 1; + this.lineStart = 0; + const startOfFileToken = new ast_ts_1.Token(tokenKind_ts_1.TokenKind.SOF, 0, 0, 0, 0); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + } + get [Symbol.toStringTag]() { + return "SchemaCoordinateLexer"; + } + advance() { + this.lastToken = this.token; + const token = this.token = this.lookahead(); + return token; + } + lookahead() { + let token = this.token; + if (token.kind !== tokenKind_ts_1.TokenKind.EOF) { + const nextToken = readNextToken(this, token.end); + token.next = nextToken; + nextToken.prev = token; + token = nextToken; + } + return token; + } + } + exports.SchemaCoordinateLexer = SchemaCoordinateLexer; + function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + const position = start; + if (position < bodyLength) { + const code = body.charCodeAt(position); + switch (code) { + case 46: + return (0, lexer_ts_1.createToken)(lexer, tokenKind_ts_1.TokenKind.DOT, position, position + 1); + case 40: + return (0, lexer_ts_1.createToken)(lexer, tokenKind_ts_1.TokenKind.PAREN_L, position, position + 1); + case 41: + return (0, lexer_ts_1.createToken)(lexer, tokenKind_ts_1.TokenKind.PAREN_R, position, position + 1); + case 58: + return (0, lexer_ts_1.createToken)(lexer, tokenKind_ts_1.TokenKind.COLON, position, position + 1); + case 64: + return (0, lexer_ts_1.createToken)(lexer, tokenKind_ts_1.TokenKind.AT, position, position + 1); + } + if ((0, characterClasses_ts_1.isNameStart)(code)) { + return (0, lexer_ts_1.readName)(lexer, position); + } + throw (0, syntaxError_ts_1.syntaxError)(lexer.source, position, `Invalid character: ${(0, lexer_ts_1.printCodePointAt)(lexer, position)}.`); + } + return (0, lexer_ts_1.createToken)(lexer, tokenKind_ts_1.TokenKind.EOF, bodyLength, bodyLength); + } +}); + +// node_modules/graphql/language/source.js +var require_source = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Source = undefined; + exports.isSource = isSource; + var devAssert_ts_1 = require_devAssert(); + var instanceOf_ts_1 = require_instanceOf(); + var sourceSymbol = Symbol("Source"); + + class Source { + constructor(body, name = "GraphQL request", locationOffset = { line: 1, column: 1 }) { + this.__kind = sourceSymbol; + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + if (!(this.locationOffset.line > 0)) + (0, devAssert_ts_1.devAssert)(false, "line in locationOffset is 1-indexed and must be positive."); + if (!(this.locationOffset.column > 0)) + (0, devAssert_ts_1.devAssert)(false, "column in locationOffset is 1-indexed and must be positive."); + } + get [Symbol.toStringTag]() { + return "Source"; + } + } + exports.Source = Source; + function isSource(source) { + return (0, instanceOf_ts_1.instanceOf)(source, sourceSymbol, Source); + } +}); + +// node_modules/graphql/language/parser.js +var require_parser = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Parser = undefined; + exports.parse = parse; + exports.parseValue = parseValue; + exports.parseConstValue = parseConstValue; + exports.parseType = parseType; + exports.parseSchemaCoordinate = parseSchemaCoordinate; + var syntaxError_ts_1 = require_syntaxError(); + var diagnostics_ts_1 = require_diagnostics(); + var ast_ts_1 = require_ast(); + var directiveLocation_ts_1 = require_directiveLocation(); + var kinds_ts_1 = require_kinds(); + var lexer_ts_1 = require_lexer(); + var schemaCoordinateLexer_ts_1 = require_schemaCoordinateLexer(); + var source_ts_1 = require_source(); + var tokenKind_ts_1 = require_tokenKind(); + function parse(source, options) { + return (0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.parseChannel) ? diagnostics_ts_1.parseChannel.traceSync(() => parseImpl(source, options), { source }) : parseImpl(source, options); + } + function parseImpl(source, options) { + const parser = new Parser(source, options); + const document2 = parser.parseDocument(); + Object.defineProperty(document2, "tokenCount", { + enumerable: false, + value: parser.tokenCount + }); + return document2; + } + function parseValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(tokenKind_ts_1.TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(tokenKind_ts_1.TokenKind.EOF); + return value; + } + function parseConstValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(tokenKind_ts_1.TokenKind.SOF); + const value = parser.parseConstValueLiteral(); + parser.expectToken(tokenKind_ts_1.TokenKind.EOF); + return value; + } + function parseType(source, options) { + const parser = new Parser(source, options); + parser.expectToken(tokenKind_ts_1.TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(tokenKind_ts_1.TokenKind.EOF); + return type; + } + function parseSchemaCoordinate(source) { + const sourceObj = (0, source_ts_1.isSource)(source) ? source : new source_ts_1.Source(source); + const lexer = new schemaCoordinateLexer_ts_1.SchemaCoordinateLexer(sourceObj); + const parser = new Parser(source, { lexer }); + parser.expectToken(tokenKind_ts_1.TokenKind.SOF); + const coordinate = parser.parseSchemaCoordinate(); + parser.expectToken(tokenKind_ts_1.TokenKind.EOF); + return coordinate; + } + + class Parser { + constructor(source, options = {}) { + const { lexer, ..._options } = options; + if (lexer) { + this._lexer = lexer; + } else { + const sourceObj = (0, source_ts_1.isSource)(source) ? source : new source_ts_1.Source(source); + this._lexer = new lexer_ts_1.Lexer(sourceObj); + } + this._options = _options; + this._tokenCounter = 0; + } + get tokenCount() { + return this._tokenCounter; + } + parseName() { + const token = this.expectToken(tokenKind_ts_1.TokenKind.NAME); + return this.node(token, { + kind: kinds_ts_1.Kind.NAME, + value: token.value + }); + } + parseDocument() { + return this.node(this._lexer.token, { + kind: kinds_ts_1.Kind.DOCUMENT, + definitions: this.many(tokenKind_ts_1.TokenKind.SOF, this.parseDefinition, tokenKind_ts_1.TokenKind.EOF) + }); + } + parseDefinition() { + if (this.peek(tokenKind_ts_1.TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } + const hasDescription = this.peekDescription(); + const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token; + if (hasDescription && keywordToken.kind === tokenKind_ts_1.TokenKind.BRACE_L) { + throw (0, syntaxError_ts_1.syntaxError)(this._lexer.source, this._lexer.token.start, "Unexpected description, descriptions are not supported on shorthand queries."); + } + if (keywordToken.kind === tokenKind_ts_1.TokenKind.NAME) { + switch (keywordToken.value) { + case "schema": + return this.parseSchemaDefinition(); + case "scalar": + return this.parseScalarTypeDefinition(); + case "type": + return this.parseObjectTypeDefinition(); + case "interface": + return this.parseInterfaceTypeDefinition(); + case "union": + return this.parseUnionTypeDefinition(); + case "enum": + return this.parseEnumTypeDefinition(); + case "input": + return this.parseInputObjectTypeDefinition(); + case "directive": + return this.parseDirectiveDefinition(); + } + switch (keywordToken.value) { + case "query": + case "mutation": + case "subscription": + return this.parseOperationDefinition(); + case "fragment": + return this.parseFragmentDefinition(); + } + if (hasDescription) { + throw (0, syntaxError_ts_1.syntaxError)(this._lexer.source, this._lexer.token.start, "Unexpected description, only GraphQL definitions support descriptions."); + } + switch (keywordToken.value) { + case "extend": + return this.parseTypeSystemExtension(); + } + } + throw this.unexpected(keywordToken); + } + parseOperationDefinition() { + const start = this._lexer.token; + if (this.peek(tokenKind_ts_1.TokenKind.BRACE_L)) { + return this.node(start, { + kind: kinds_ts_1.Kind.OPERATION_DEFINITION, + operation: ast_ts_1.OperationTypeNode.QUERY, + description: undefined, + name: undefined, + variableDefinitions: undefined, + directives: undefined, + selectionSet: this.parseSelectionSet() + }); + } + const description = this.parseDescription(); + const operation = this.parseOperationType(); + let name; + if (this.peek(tokenKind_ts_1.TokenKind.NAME)) { + name = this.parseName(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.OPERATION_DEFINITION, + operation, + description, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + parseOperationType() { + const operationToken = this.expectToken(tokenKind_ts_1.TokenKind.NAME); + switch (operationToken.value) { + case "query": + return ast_ts_1.OperationTypeNode.QUERY; + case "mutation": + return ast_ts_1.OperationTypeNode.MUTATION; + case "subscription": + return ast_ts_1.OperationTypeNode.SUBSCRIPTION; + } + throw this.unexpected(operationToken); + } + parseVariableDefinitions() { + return this.optionalMany(tokenKind_ts_1.TokenKind.PAREN_L, this.parseVariableDefinition, tokenKind_ts_1.TokenKind.PAREN_R); + } + parseVariableDefinition() { + return this.node(this._lexer.token, { + kind: kinds_ts_1.Kind.VARIABLE_DEFINITION, + description: this.parseDescription(), + variable: this.parseVariable(), + type: (this.expectToken(tokenKind_ts_1.TokenKind.COLON), this.parseTypeReference()), + defaultValue: this.expectOptionalToken(tokenKind_ts_1.TokenKind.EQUALS) ? this.parseConstValueLiteral() : undefined, + directives: this.parseConstDirectives() + }); + } + parseVariable() { + const start = this._lexer.token; + this.expectToken(tokenKind_ts_1.TokenKind.DOLLAR); + return this.node(start, { + kind: kinds_ts_1.Kind.VARIABLE, + name: this.parseName() + }); + } + parseSelectionSet() { + return this.node(this._lexer.token, { + kind: kinds_ts_1.Kind.SELECTION_SET, + selections: this.many(tokenKind_ts_1.TokenKind.BRACE_L, this.parseSelection, tokenKind_ts_1.TokenKind.BRACE_R) + }); + } + parseSelection() { + return this.peek(tokenKind_ts_1.TokenKind.SPREAD) ? this.parseFragment() : this.parseField(); + } + parseField() { + const start = this._lexer.token; + const nameOrAlias = this.parseName(); + let alias; + let name; + if (this.expectOptionalToken(tokenKind_ts_1.TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + return this.node(start, { + kind: kinds_ts_1.Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(tokenKind_ts_1.TokenKind.BRACE_L) ? this.parseSelectionSet() : undefined + }); + } + parseArguments(isConst) { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany(tokenKind_ts_1.TokenKind.PAREN_L, item, tokenKind_ts_1.TokenKind.PAREN_R); + } + parseFragmentArguments() { + const item = this.parseFragmentArgument; + return this.optionalMany(tokenKind_ts_1.TokenKind.PAREN_L, item, tokenKind_ts_1.TokenKind.PAREN_R); + } + parseArgument(isConst = false) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(tokenKind_ts_1.TokenKind.COLON); + return this.node(start, { + kind: kinds_ts_1.Kind.ARGUMENT, + name, + value: this.parseValueLiteral(isConst) + }); + } + parseConstArgument() { + return this.parseArgument(true); + } + parseFragmentArgument() { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(tokenKind_ts_1.TokenKind.COLON); + return this.node(start, { + kind: kinds_ts_1.Kind.FRAGMENT_ARGUMENT, + name, + value: this.parseValueLiteral(false) + }); + } + parseFragment() { + const start = this._lexer.token; + this.expectToken(tokenKind_ts_1.TokenKind.SPREAD); + const hasTypeCondition = this.expectOptionalKeyword("on"); + if (!hasTypeCondition && this.peek(tokenKind_ts_1.TokenKind.NAME)) { + const name = this.parseFragmentName(); + if (this.peek(tokenKind_ts_1.TokenKind.PAREN_L) && this._options.experimentalFragmentArguments) { + return this.node(start, { + kind: kinds_ts_1.Kind.FRAGMENT_SPREAD, + name, + arguments: this.parseFragmentArguments(), + directives: this.parseDirectives(false) + }); + } + return this.node(start, { + kind: kinds_ts_1.Kind.FRAGMENT_SPREAD, + name, + directives: this.parseDirectives(false) + }); + } + return this.node(start, { + kind: kinds_ts_1.Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + parseFragmentDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("fragment"); + if (this._options.experimentalFragmentArguments === true) { + return this.node(start, { + kind: kinds_ts_1.Kind.FRAGMENT_DEFINITION, + description, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword("on"), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + return this.node(start, { + kind: kinds_ts_1.Kind.FRAGMENT_DEFINITION, + description, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword("on"), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet() + }); + } + parseFragmentName() { + if (this._lexer.token.value === "on") { + throw this.unexpected(); + } + return this.parseName(); + } + parseValueLiteral(isConst) { + const token = this._lexer.token; + switch (token.kind) { + case tokenKind_ts_1.TokenKind.BRACKET_L: + return this.parseList(isConst); + case tokenKind_ts_1.TokenKind.BRACE_L: + return this.parseObject(isConst); + case tokenKind_ts_1.TokenKind.INT: + this.advanceLexer(); + return this.node(token, { + kind: kinds_ts_1.Kind.INT, + value: token.value + }); + case tokenKind_ts_1.TokenKind.FLOAT: + this.advanceLexer(); + return this.node(token, { + kind: kinds_ts_1.Kind.FLOAT, + value: token.value + }); + case tokenKind_ts_1.TokenKind.STRING: + case tokenKind_ts_1.TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + case tokenKind_ts_1.TokenKind.NAME: + this.advanceLexer(); + switch (token.value) { + case "true": + return this.node(token, { + kind: kinds_ts_1.Kind.BOOLEAN, + value: true + }); + case "false": + return this.node(token, { + kind: kinds_ts_1.Kind.BOOLEAN, + value: false + }); + case "null": + return this.node(token, { kind: kinds_ts_1.Kind.NULL }); + default: + return this.node(token, { + kind: kinds_ts_1.Kind.ENUM, + value: token.value + }); + } + case tokenKind_ts_1.TokenKind.DOLLAR: + if (isConst) { + this.expectToken(tokenKind_ts_1.TokenKind.DOLLAR); + if (this._lexer.token.kind === tokenKind_ts_1.TokenKind.NAME) { + const varName = this._lexer.token.value; + throw (0, syntaxError_ts_1.syntaxError)(this._lexer.source, token.start, `Unexpected variable "$${varName}" in constant value.`); + } else { + throw this.unexpected(token); + } + } + return this.parseVariable(); + default: + throw this.unexpected(); + } + } + parseConstValueLiteral() { + return this.parseValueLiteral(true); + } + parseStringLiteral() { + const token = this._lexer.token; + this.advanceLexer(); + return this.node(token, { + kind: kinds_ts_1.Kind.STRING, + value: token.value, + block: token.kind === tokenKind_ts_1.TokenKind.BLOCK_STRING + }); + } + parseList(isConst) { + const item = () => this.parseValueLiteral(isConst); + return this.node(this._lexer.token, { + kind: kinds_ts_1.Kind.LIST, + values: this.any(tokenKind_ts_1.TokenKind.BRACKET_L, item, tokenKind_ts_1.TokenKind.BRACKET_R) + }); + } + parseObject(isConst) { + const item = () => this.parseObjectField(isConst); + return this.node(this._lexer.token, { + kind: kinds_ts_1.Kind.OBJECT, + fields: this.any(tokenKind_ts_1.TokenKind.BRACE_L, item, tokenKind_ts_1.TokenKind.BRACE_R) + }); + } + parseObjectField(isConst) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(tokenKind_ts_1.TokenKind.COLON); + return this.node(start, { + kind: kinds_ts_1.Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst) + }); + } + parseDirectives(isConst) { + const directives = []; + while (this.peek(tokenKind_ts_1.TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + if (directives.length) { + return directives; + } + return; + } + parseConstDirectives() { + return this.parseDirectives(true); + } + parseDirective(isConst) { + const start = this._lexer.token; + this.expectToken(tokenKind_ts_1.TokenKind.AT); + return this.node(start, { + kind: kinds_ts_1.Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst) + }); + } + parseTypeReference() { + const start = this._lexer.token; + let type; + if (this.expectOptionalToken(tokenKind_ts_1.TokenKind.BRACKET_L)) { + const innerType = this.parseTypeReference(); + this.expectToken(tokenKind_ts_1.TokenKind.BRACKET_R); + type = this.node(start, { + kind: kinds_ts_1.Kind.LIST_TYPE, + type: innerType + }); + } else { + type = this.parseNamedType(); + } + if (this.expectOptionalToken(tokenKind_ts_1.TokenKind.BANG)) { + return this.node(start, { + kind: kinds_ts_1.Kind.NON_NULL_TYPE, + type + }); + } + return type; + } + parseNamedType() { + return this.node(this._lexer.token, { + kind: kinds_ts_1.Kind.NAMED_TYPE, + name: this.parseName() + }); + } + peekDescription() { + return this.peek(tokenKind_ts_1.TokenKind.STRING) || this.peek(tokenKind_ts_1.TokenKind.BLOCK_STRING); + } + parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + parseSchemaDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("schema"); + const directives = this.parseConstDirectives(); + const operationTypes = this.many(tokenKind_ts_1.TokenKind.BRACE_L, this.parseOperationTypeDefinition, tokenKind_ts_1.TokenKind.BRACE_R); + return this.node(start, { + kind: kinds_ts_1.Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes + }); + } + parseOperationTypeDefinition() { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(tokenKind_ts_1.TokenKind.COLON); + const type = this.parseNamedType(); + return this.node(start, { + kind: kinds_ts_1.Kind.OPERATION_TYPE_DEFINITION, + operation, + type + }); + } + parseScalarTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("scalar"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: kinds_ts_1.Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives + }); + } + parseObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("type"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: kinds_ts_1.Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields + }); + } + parseImplementsInterfaces() { + return this.expectOptionalKeyword("implements") ? this.delimitedMany(tokenKind_ts_1.TokenKind.AMP, this.parseNamedType) : undefined; + } + parseFieldsDefinition() { + return this.optionalMany(tokenKind_ts_1.TokenKind.BRACE_L, this.parseFieldDefinition, tokenKind_ts_1.TokenKind.BRACE_R); + } + parseFieldDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(tokenKind_ts_1.TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: kinds_ts_1.Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives + }); + } + parseArgumentDefs() { + return this.optionalMany(tokenKind_ts_1.TokenKind.PAREN_L, this.parseInputValueDef, tokenKind_ts_1.TokenKind.PAREN_R); + } + parseInputValueDef() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(tokenKind_ts_1.TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; + if (this.expectOptionalToken(tokenKind_ts_1.TokenKind.EQUALS)) { + defaultValue = this.parseConstValueLiteral(); + } + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: kinds_ts_1.Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives + }); + } + parseInterfaceTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("interface"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: kinds_ts_1.Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields + }); + } + parseUnionTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("union"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + return this.node(start, { + kind: kinds_ts_1.Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types + }); + } + parseUnionMemberTypes() { + return this.expectOptionalToken(tokenKind_ts_1.TokenKind.EQUALS) ? this.delimitedMany(tokenKind_ts_1.TokenKind.PIPE, this.parseNamedType) : undefined; + } + parseEnumTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("enum"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + return this.node(start, { + kind: kinds_ts_1.Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values + }); + } + parseEnumValuesDefinition() { + return this.optionalMany(tokenKind_ts_1.TokenKind.BRACE_L, this.parseEnumValueDefinition, tokenKind_ts_1.TokenKind.BRACE_R); + } + parseEnumValueDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseEnumValueName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: kinds_ts_1.Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives + }); + } + parseEnumValueName() { + if (this._lexer.token.value === "true" || this._lexer.token.value === "false" || this._lexer.token.value === "null") { + throw (0, syntaxError_ts_1.syntaxError)(this._lexer.source, this._lexer.token.start, `${getTokenDesc(this._lexer.token)} is reserved and cannot be used for an enum value.`); + } + return this.parseName(); + } + parseInputObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("input"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + return this.node(start, { + kind: kinds_ts_1.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields + }); + } + parseInputFieldsDefinition() { + return this.optionalMany(tokenKind_ts_1.TokenKind.BRACE_L, this.parseInputValueDef, tokenKind_ts_1.TokenKind.BRACE_R); + } + parseTypeSystemExtension() { + const keywordToken = this._lexer.lookahead(); + if (keywordToken.kind === tokenKind_ts_1.TokenKind.NAME) { + switch (keywordToken.value) { + case "schema": + return this.parseSchemaExtension(); + case "scalar": + return this.parseScalarTypeExtension(); + case "type": + return this.parseObjectTypeExtension(); + case "interface": + return this.parseInterfaceTypeExtension(); + case "union": + return this.parseUnionTypeExtension(); + case "enum": + return this.parseEnumTypeExtension(); + case "input": + return this.parseInputObjectTypeExtension(); + case "directive": + return this.parseDirectiveExtension(); + } + } + throw this.unexpected(keywordToken); + } + parseSchemaExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("schema"); + const directives = this.parseConstDirectives(); + const operationTypes = this.optionalMany(tokenKind_ts_1.TokenKind.BRACE_L, this.parseOperationTypeDefinition, tokenKind_ts_1.TokenKind.BRACE_R); + if (directives === undefined && operationTypes === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.SCHEMA_EXTENSION, + directives, + operationTypes + }); + } + parseScalarTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("scalar"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + if (directives === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.SCALAR_TYPE_EXTENSION, + name, + directives + }); + } + parseObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("type"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if (interfaces === undefined && directives === undefined && fields === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields + }); + } + parseInterfaceTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("interface"); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + if (interfaces === undefined && directives === undefined && fields === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields + }); + } + parseUnionTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("union"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + if (directives === undefined && types === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.UNION_TYPE_EXTENSION, + name, + directives, + types + }); + } + parseEnumTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("enum"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + if (directives === undefined && values === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values + }); + } + parseInputObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("input"); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + if (directives === undefined && fields === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields + }); + } + parseDirectiveExtension() { + const start = this._lexer.token; + this.expectKeyword("extend"); + this.expectKeyword("directive"); + this.expectToken(tokenKind_ts_1.TokenKind.AT); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + if (directives === undefined) { + throw this.unexpected(); + } + return this.node(start, { + kind: kinds_ts_1.Kind.DIRECTIVE_EXTENSION, + name, + directives + }); + } + parseDirectiveDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword("directive"); + this.expectToken(tokenKind_ts_1.TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const directives = this.parseConstDirectives(); + const repeatable = this.expectOptionalKeyword("repeatable"); + this.expectKeyword("on"); + const locations = this.parseDirectiveLocations(); + return this.node(start, { + kind: kinds_ts_1.Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + directives, + repeatable, + locations + }); + } + parseDirectiveLocations() { + return this.delimitedMany(tokenKind_ts_1.TokenKind.PIPE, this.parseDirectiveLocation); + } + parseDirectiveLocation() { + const start = this._lexer.token; + const name = this.parseName(); + if (Object.hasOwn(directiveLocation_ts_1.DirectiveLocation, name.value)) { + return name; + } + throw this.unexpected(start); + } + parseSchemaCoordinate() { + const start = this._lexer.token; + const ofDirective = this.expectOptionalToken(tokenKind_ts_1.TokenKind.AT); + const name = this.parseName(); + let memberName; + if (!ofDirective && this.expectOptionalToken(tokenKind_ts_1.TokenKind.DOT)) { + memberName = this.parseName(); + } + let argumentName; + if ((ofDirective || memberName) && this.expectOptionalToken(tokenKind_ts_1.TokenKind.PAREN_L)) { + argumentName = this.parseName(); + this.expectToken(tokenKind_ts_1.TokenKind.COLON); + this.expectToken(tokenKind_ts_1.TokenKind.PAREN_R); + } + if (ofDirective) { + if (argumentName) { + return this.node(start, { + kind: kinds_ts_1.Kind.DIRECTIVE_ARGUMENT_COORDINATE, + name, + argumentName + }); + } + return this.node(start, { + kind: kinds_ts_1.Kind.DIRECTIVE_COORDINATE, + name + }); + } else if (memberName) { + if (argumentName) { + return this.node(start, { + kind: kinds_ts_1.Kind.ARGUMENT_COORDINATE, + name, + fieldName: memberName, + argumentName + }); + } + return this.node(start, { + kind: kinds_ts_1.Kind.MEMBER_COORDINATE, + name, + memberName + }); + } + return this.node(start, { + kind: kinds_ts_1.Kind.TYPE_COORDINATE, + name + }); + } + node(startToken, node) { + if (this._options.noLocation !== true) { + node.loc = new ast_ts_1.Location(startToken, this._lexer.lastToken, this._lexer.source); + } + return node; + } + peek(kind2) { + return this._lexer.token.kind === kind2; + } + expectToken(kind2) { + const token = this._lexer.token; + if (token.kind === kind2) { + this.advanceLexer(); + return token; + } + throw (0, syntaxError_ts_1.syntaxError)(this._lexer.source, token.start, `Expected ${getTokenKindDesc(kind2)}, found ${getTokenDesc(token)}.`); + } + expectOptionalToken(kind2) { + const token = this._lexer.token; + if (token.kind === kind2) { + this.advanceLexer(); + return true; + } + return false; + } + expectKeyword(value) { + const token = this._lexer.token; + if (token.kind === tokenKind_ts_1.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + } else { + throw (0, syntaxError_ts_1.syntaxError)(this._lexer.source, token.start, `Expected "${value}", found ${getTokenDesc(token)}.`); + } + } + expectOptionalKeyword(value) { + const token = this._lexer.token; + if (token.kind === tokenKind_ts_1.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + return true; + } + return false; + } + unexpected(atToken) { + const token = atToken ?? this._lexer.token; + return (0, syntaxError_ts_1.syntaxError)(this._lexer.source, token.start, `Unexpected ${getTokenDesc(token)}.`); + } + any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + return nodes; + } + optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + return; + } + many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + return nodes; + } + delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + const nodes = []; + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + return nodes; + } + advanceLexer() { + const { maxTokens } = this._options; + const token = this._lexer.advance(); + if (token.kind !== tokenKind_ts_1.TokenKind.EOF) { + ++this._tokenCounter; + if (maxTokens !== undefined && this._tokenCounter > maxTokens) { + throw (0, syntaxError_ts_1.syntaxError)(this._lexer.source, token.start, `Document contains more than ${maxTokens} tokens. Parsing aborted.`); + } + } + } + } + exports.Parser = Parser; + function getTokenDesc(token) { + const value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ""); + } + function getTokenKindDesc(kind2) { + return (0, lexer_ts_1.isPunctuatorTokenKind)(kind2) ? `"${kind2}"` : kind2; + } +}); + +// node_modules/graphql/utilities/typeFromAST.js +var require_typeFromAST = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.typeFromAST = typeFromAST; + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + function typeFromAST(schema, typeNode) { + switch (typeNode.kind) { + case kinds_ts_1.Kind.LIST_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new definition_ts_1.GraphQLList(innerType); + } + case kinds_ts_1.Kind.NON_NULL_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new definition_ts_1.GraphQLNonNull(innerType); + } + case kinds_ts_1.Kind.NAMED_TYPE: + return schema.getType(typeNode.name.value); + } + } +}); + +// node_modules/graphql/utilities/TypeInfo.js +var require_TypeInfo = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TypeInfo = undefined; + exports.visitWithTypeInfo = visitWithTypeInfo; + var ast_ts_1 = require_ast(); + var kinds_ts_1 = require_kinds(); + var visitor_ts_1 = require_visitor(); + var definition_ts_1 = require_definition(); + var typeFromAST_ts_1 = require_typeFromAST(); + + class TypeInfo { + constructor(schema, initialType, fragmentSignatures) { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._fragmentSignaturesByName = fragmentSignatures ?? (() => null); + this._fragmentSignature = null; + this._fragmentArgument = null; + if (initialType) { + if ((0, definition_ts_1.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + if ((0, definition_ts_1.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + if ((0, definition_ts_1.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } + } + } + get [Symbol.toStringTag]() { + return "TypeInfo"; + } + getType() { + return this._typeStack.at(-1); + } + getParentType() { + return this._parentTypeStack.at(-1); + } + getInputType() { + return this._inputTypeStack.at(-1); + } + getParentInputType() { + return this._inputTypeStack.at(-2); + } + getFieldDef() { + return this._fieldDefStack.at(-1); + } + getDefaultValue() { + return this._defaultValueStack.at(-1); + } + getDirective() { + return this._directive; + } + getArgument() { + return this._argument; + } + getFragmentSignature() { + return this._fragmentSignature; + } + getFragmentSignatureByName() { + return this._fragmentSignaturesByName; + } + getFragmentArgument() { + return this._fragmentArgument; + } + getEnumValue() { + return this._enumValue; + } + enter(node) { + const schema = this._schema; + switch (node.kind) { + case kinds_ts_1.Kind.DOCUMENT: { + const fragmentSignatures = getFragmentSignatures(node); + this._fragmentSignaturesByName = (fragmentName) => fragmentSignatures.get(fragmentName); + break; + } + case kinds_ts_1.Kind.SELECTION_SET: { + const namedType = (0, definition_ts_1.getNamedType)(this.getType()); + this._parentTypeStack.push((0, definition_ts_1.isCompositeType)(namedType) ? namedType : undefined); + break; + } + case kinds_ts_1.Kind.FIELD: { + const parentType = this.getParentType(); + let fieldDef; + let fieldType; + if (parentType) { + fieldDef = schema.getField(parentType, node.name.value); + if (fieldDef) { + fieldType = fieldDef.type; + } + } + this._fieldDefStack.push(fieldDef); + this._typeStack.push((0, definition_ts_1.isOutputType)(fieldType) ? fieldType : undefined); + break; + } + case kinds_ts_1.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + case kinds_ts_1.Kind.OPERATION_DEFINITION: { + const rootType = schema.getRootType(node.operation); + this._typeStack.push((0, definition_ts_1.isObjectType)(rootType) ? rootType : undefined); + break; + } + case kinds_ts_1.Kind.FRAGMENT_SPREAD: { + this._fragmentSignature = this.getFragmentSignatureByName()(node.name.value); + break; + } + case kinds_ts_1.Kind.INLINE_FRAGMENT: + case kinds_ts_1.Kind.FRAGMENT_DEFINITION: { + const typeConditionAST = node.typeCondition; + const outputType = typeConditionAST ? (0, typeFromAST_ts_1.typeFromAST)(schema, typeConditionAST) : (0, definition_ts_1.getNamedType)(this.getType()); + this._typeStack.push((0, definition_ts_1.isOutputType)(outputType) ? outputType : undefined); + break; + } + case kinds_ts_1.Kind.VARIABLE_DEFINITION: { + const inputType = (0, typeFromAST_ts_1.typeFromAST)(schema, node.type); + this._inputTypeStack.push((0, definition_ts_1.isInputType)(inputType) ? inputType : undefined); + break; + } + case kinds_ts_1.Kind.ARGUMENT: { + let argDef; + let argType; + const fieldOrDirective = this.getDirective() ?? this.getFieldDef(); + if (fieldOrDirective) { + argDef = fieldOrDirective.args.find((arg) => arg.name === node.name.value); + if (argDef) { + argType = argDef.type; + } + } + this._argument = argDef; + this._defaultValueStack.push(argDef?.default ?? argDef?.defaultValue ?? undefined); + this._inputTypeStack.push((0, definition_ts_1.isInputType)(argType) ? argType : undefined); + break; + } + case kinds_ts_1.Kind.FRAGMENT_ARGUMENT: { + const fragmentSignature = this.getFragmentSignature(); + const argDef = fragmentSignature?.variableDefinitions.get(node.name.value); + this._fragmentArgument = argDef; + let argType; + if (argDef) { + argType = (0, typeFromAST_ts_1.typeFromAST)(this._schema, argDef.type); + } + this._inputTypeStack.push((0, definition_ts_1.isInputType)(argType) ? argType : undefined); + break; + } + case kinds_ts_1.Kind.LIST: { + const listType = (0, definition_ts_1.getNullableType)(this.getInputType()); + const itemType = (0, definition_ts_1.isListType)(listType) ? listType.ofType : undefined; + this._defaultValueStack.push(undefined); + this._inputTypeStack.push((0, definition_ts_1.isInputType)(itemType) ? itemType : undefined); + break; + } + case kinds_ts_1.Kind.OBJECT_FIELD: { + const objectType = (0, definition_ts_1.getNamedType)(this.getInputType()); + let inputFieldType; + let inputField; + if ((0, definition_ts_1.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + if (inputField != null) { + inputFieldType = inputField.type; + } + } + this._defaultValueStack.push(inputField?.default ?? inputField?.defaultValue ?? undefined); + this._inputTypeStack.push((0, definition_ts_1.isInputType)(inputFieldType) ? inputFieldType : undefined); + break; + } + case kinds_ts_1.Kind.ENUM: { + const enumType = (0, definition_ts_1.getNamedType)(this.getInputType()); + let enumValue; + if ((0, definition_ts_1.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + default: + } + } + leave(node) { + switch (node.kind) { + case kinds_ts_1.Kind.DOCUMENT: + this._fragmentSignaturesByName = () => null; + break; + case kinds_ts_1.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + break; + case kinds_ts_1.Kind.FIELD: + this._fieldDefStack.pop(); + this._typeStack.pop(); + break; + case kinds_ts_1.Kind.DIRECTIVE: + this._directive = null; + break; + case kinds_ts_1.Kind.FRAGMENT_SPREAD: + this._fragmentSignature = null; + break; + case kinds_ts_1.Kind.OPERATION_DEFINITION: + case kinds_ts_1.Kind.INLINE_FRAGMENT: + case kinds_ts_1.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + break; + case kinds_ts_1.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + break; + case kinds_ts_1.Kind.ARGUMENT: + this._argument = null; + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case kinds_ts_1.Kind.FRAGMENT_ARGUMENT: { + this._fragmentArgument = null; + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + } + case kinds_ts_1.Kind.LIST: + case kinds_ts_1.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case kinds_ts_1.Kind.ENUM: + this._enumValue = null; + break; + default: + } + } + } + exports.TypeInfo = TypeInfo; + function getFragmentSignatures(document2) { + const fragmentSignatures = new Map; + for (const definition of document2.definitions) { + if (definition.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION) { + const variableDefinitions = new Map; + if (definition.variableDefinitions) { + for (const varDef of definition.variableDefinitions) { + variableDefinitions.set(varDef.variable.name.value, varDef); + } + } + const signature = { definition, variableDefinitions }; + fragmentSignatures.set(definition.name.value, signature); + } + } + return fragmentSignatures; + } + function visitWithTypeInfo(typeInfo, visitor) { + return { + enter(...args) { + const node = args[0]; + typeInfo.enter(node); + const fn = (0, visitor_ts_1.getEnterLeaveForKind)(visitor, node.kind).enter; + if (fn) { + const result = fn.apply(visitor, args); + if (result !== undefined) { + typeInfo.leave(node); + if ((0, ast_ts_1.isNode)(result)) { + typeInfo.enter(result); + } + } + return result; + } + }, + leave(...args) { + const node = args[0]; + const fn = (0, visitor_ts_1.getEnterLeaveForKind)(visitor, node.kind).leave; + let result; + if (fn) { + result = fn.apply(visitor, args); + } + typeInfo.leave(node); + return result; + } + }; + } +}); + +// node_modules/graphql/validation/rules/DeferStreamDirectiveLabelRule.js +var require_DeferStreamDirectiveLabelRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeferStreamDirectiveLabelRule = DeferStreamDirectiveLabelRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var directives_ts_1 = require_directives(); + function DeferStreamDirectiveLabelRule(context) { + const knownLabels = new Map; + return { + Directive(node) { + if (node.name.value === directives_ts_1.GraphQLDeferDirective.name || node.name.value === directives_ts_1.GraphQLStreamDirective.name) { + const labelArgument = node.arguments?.find((arg) => arg.name.value === "label"); + const labelValue = labelArgument?.value; + if (!labelValue || labelValue.kind === kinds_ts_1.Kind.NULL) { + return; + } + if (labelValue.kind !== kinds_ts_1.Kind.STRING) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Argument "@${node.name.value}(label:)" must be a static string.`, { nodes: node })); + return; + } + const knownLabel = knownLabels.get(labelValue.value); + if (knownLabel != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError('Value for arguments "defer(label:)" and "stream(label:)" must be unique across all Defer/Stream directive usages.', { nodes: [knownLabel, node] })); + } else { + knownLabels.set(labelValue.value, node); + } + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/DeferStreamDirectiveOnRootFieldRule.js +var require_DeferStreamDirectiveOnRootFieldRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeferStreamDirectiveOnRootFieldRule = DeferStreamDirectiveOnRootFieldRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var directives_ts_1 = require_directives(); + function DeferStreamDirectiveOnRootFieldRule(context) { + return { + OperationDefinition(node) { + const document2 = context.getDocument(); + const fragments = new Map; + for (const definition of document2.definitions) { + if (definition.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION) { + fragments.set(definition.name.value, definition); + } + } + if (node.operation !== "subscription" && node.operation !== "mutation") { + return; + } + const schema = context.getSchema(); + const rootType = schema.getRootType(node.operation); + if (rootType) { + forbidDeferStream({ + context, + operationType: node.operation, + rootType, + fragments, + selectionSet: node.selectionSet, + visitedFragments: new Set + }); + } + } + }; + } + function forbidDeferStream({ context, operationType, rootType, fragments, selectionSet, visitedFragments }) { + for (const selection of selectionSet.selections) { + if (selection.kind === "Field") { + const stream = selection.directives?.find((d) => d.name.value === directives_ts_1.GraphQLStreamDirective.name); + if (stream) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Stream directive cannot be used on root ${operationType} type "${rootType}".`, { nodes: stream })); + } + } else if (selection.kind === "FragmentSpread") { + const fragmentName = selection.name.value; + if (visitedFragments.has(fragmentName)) { + continue; + } + const fragment = fragments.get(fragmentName); + if (fragment) { + const defer = getDeferDirective(selection); + if (defer !== undefined) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Defer directive cannot be used on root ${operationType} type "${rootType}".`, { nodes: defer })); + } + forbidDeferStream({ + context, + operationType, + rootType, + fragments, + selectionSet: fragment.selectionSet, + visitedFragments + }); + } + visitedFragments.add(fragmentName); + } else if (selection.kind === "InlineFragment") { + const defer = getDeferDirective(selection); + if (defer !== undefined) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Defer directive cannot be used on root ${operationType} type "${rootType}".`, { nodes: defer })); + } + forbidDeferStream({ + context, + operationType, + rootType, + fragments, + selectionSet: selection.selectionSet, + visitedFragments + }); + } + } + } + function getDeferDirective(fragment) { + return fragment.directives?.find((d) => d.name.value === directives_ts_1.GraphQLDeferDirective.name); + } +}); + +// node_modules/graphql/validation/rules/DeferStreamDirectiveOnValidOperationsRule.js +var require_DeferStreamDirectiveOnValidOperationsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeferStreamDirectiveOnValidOperationsRule = DeferStreamDirectiveOnValidOperationsRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var ast_ts_1 = require_ast(); + var kinds_ts_1 = require_kinds(); + var directives_ts_1 = require_directives(); + function ifArgumentCanBeFalse(node) { + const ifArgument = node.arguments?.find((arg) => arg.name.value === "if"); + if (!ifArgument) { + return false; + } + if (ifArgument.value.kind === kinds_ts_1.Kind.BOOLEAN) { + if (ifArgument.value.value) { + return false; + } + } else if (ifArgument.value.kind !== kinds_ts_1.Kind.VARIABLE) { + return false; + } + return true; + } + function canBeSkippedViaSkipDirective(node) { + const ifArgument = node.arguments?.find((arg) => arg.name.value === "if"); + if (!ifArgument) { + return true; + } + if (ifArgument.value.kind === kinds_ts_1.Kind.BOOLEAN) { + if (ifArgument.value.value) { + return true; + } + return false; + } + return true; + } + function canBeSkippedViaIncludeDirective(node) { + const ifArgument = node.arguments?.find((arg) => arg.name.value === "if"); + if (!ifArgument) { + return false; + } + if (ifArgument?.value.kind === kinds_ts_1.Kind.BOOLEAN) { + if (ifArgument.value.value) { + return false; + } + return true; + } + return true; + } + function DeferStreamDirectiveOnValidOperationsRule(context) { + return { + OperationDefinition(operation) { + if (operation.operation !== ast_ts_1.OperationTypeNode.SUBSCRIPTION) { + return; + } + const document2 = context.getDocument(); + const fragments = new Map; + for (const definition of document2.definitions) { + if (definition.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION) { + fragments.set(definition.name.value, definition); + } + } + const visitedFragments = new Set; + forbidUnconditionalDeferStream({ + context, + fragments, + selectionSet: operation.selectionSet, + parentNodes: [], + visitedFragments + }); + } + }; + } + function forbidUnconditionalDeferStream({ context, fragments, selectionSet, parentNodes, visitedFragments }) { + for (const selection of selectionSet.selections) { + const skip = selection.directives?.find((d) => d.name.value === directives_ts_1.GraphQLSkipDirective.name); + if (skip && canBeSkippedViaSkipDirective(skip)) { + continue; + } + const include = selection.directives?.find((d) => d.name.value === directives_ts_1.GraphQLIncludeDirective.name); + if (include && canBeSkippedViaIncludeDirective(include)) { + continue; + } + for (const directive of selection.directives ?? []) { + if (directive.name.value === directives_ts_1.GraphQLDeferDirective.name) { + if (!ifArgumentCanBeFalse(directive)) { + context.reportError(new GraphQLError_ts_1.GraphQLError("Defer directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`.", { nodes: [directive, ...parentNodes] })); + } + } else if (directive.name.value === directives_ts_1.GraphQLStreamDirective.name) { + if (!ifArgumentCanBeFalse(directive)) { + context.reportError(new GraphQLError_ts_1.GraphQLError("Stream directive not supported on subscription operations. Disable `@stream` by setting the `if` argument to `false`.", { nodes: [directive, ...parentNodes] })); + } + } + } + if (selection.kind === "FragmentSpread") { + const fragmentName = selection.name.value; + if (visitedFragments.has(fragmentName)) { + continue; + } + visitedFragments.add(fragmentName); + const fragment = fragments.get(fragmentName); + if (fragment) { + forbidUnconditionalDeferStream({ + context, + fragments, + parentNodes: [selection, ...parentNodes], + selectionSet: fragment?.selectionSet, + visitedFragments + }); + } + } else if (selection.selectionSet) { + forbidUnconditionalDeferStream({ + context, + fragments, + selectionSet: selection.selectionSet, + parentNodes, + visitedFragments + }); + } + } + } +}); + +// node_modules/graphql/language/predicates.js +var require_predicates = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isDefinitionNode = isDefinitionNode; + exports.isExecutableDefinitionNode = isExecutableDefinitionNode; + exports.isSubscriptionOperationDefinitionNode = isSubscriptionOperationDefinitionNode; + exports.isSelectionNode = isSelectionNode; + exports.isValueNode = isValueNode; + exports.isConstValueNode = isConstValueNode; + exports.isTypeNode = isTypeNode; + exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; + exports.isTypeDefinitionNode = isTypeDefinitionNode; + exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; + exports.isTypeExtensionNode = isTypeExtensionNode; + exports.isSchemaCoordinateNode = isSchemaCoordinateNode; + var ast_ts_1 = require_ast(); + var kinds_ts_1 = require_kinds(); + function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); + } + function isExecutableDefinitionNode(node) { + return node.kind === kinds_ts_1.Kind.OPERATION_DEFINITION || node.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION; + } + function isSubscriptionOperationDefinitionNode(node) { + return node.operation === ast_ts_1.OperationTypeNode.SUBSCRIPTION; + } + function isSelectionNode(node) { + return node.kind === kinds_ts_1.Kind.FIELD || node.kind === kinds_ts_1.Kind.FRAGMENT_SPREAD || node.kind === kinds_ts_1.Kind.INLINE_FRAGMENT; + } + function isValueNode(node) { + return node.kind === kinds_ts_1.Kind.VARIABLE || node.kind === kinds_ts_1.Kind.INT || node.kind === kinds_ts_1.Kind.FLOAT || node.kind === kinds_ts_1.Kind.STRING || node.kind === kinds_ts_1.Kind.BOOLEAN || node.kind === kinds_ts_1.Kind.NULL || node.kind === kinds_ts_1.Kind.ENUM || node.kind === kinds_ts_1.Kind.LIST || node.kind === kinds_ts_1.Kind.OBJECT; + } + function isConstValueNode(node) { + return isValueNode(node) && (node.kind === kinds_ts_1.Kind.LIST ? node.values.some(isConstValueNode) : node.kind === kinds_ts_1.Kind.OBJECT ? node.fields.some((field) => isConstValueNode(field.value)) : node.kind !== kinds_ts_1.Kind.VARIABLE); + } + function isTypeNode(node) { + return node.kind === kinds_ts_1.Kind.NAMED_TYPE || node.kind === kinds_ts_1.Kind.LIST_TYPE || node.kind === kinds_ts_1.Kind.NON_NULL_TYPE; + } + function isTypeSystemDefinitionNode(node) { + return node.kind === kinds_ts_1.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === kinds_ts_1.Kind.DIRECTIVE_DEFINITION; + } + function isTypeDefinitionNode(node) { + return node.kind === kinds_ts_1.Kind.SCALAR_TYPE_DEFINITION || node.kind === kinds_ts_1.Kind.OBJECT_TYPE_DEFINITION || node.kind === kinds_ts_1.Kind.INTERFACE_TYPE_DEFINITION || node.kind === kinds_ts_1.Kind.UNION_TYPE_DEFINITION || node.kind === kinds_ts_1.Kind.ENUM_TYPE_DEFINITION || node.kind === kinds_ts_1.Kind.INPUT_OBJECT_TYPE_DEFINITION; + } + function isTypeSystemExtensionNode(node) { + return node.kind === kinds_ts_1.Kind.SCHEMA_EXTENSION || node.kind === kinds_ts_1.Kind.DIRECTIVE_EXTENSION || isTypeExtensionNode(node); + } + function isTypeExtensionNode(node) { + return node.kind === kinds_ts_1.Kind.SCALAR_TYPE_EXTENSION || node.kind === kinds_ts_1.Kind.OBJECT_TYPE_EXTENSION || node.kind === kinds_ts_1.Kind.INTERFACE_TYPE_EXTENSION || node.kind === kinds_ts_1.Kind.UNION_TYPE_EXTENSION || node.kind === kinds_ts_1.Kind.ENUM_TYPE_EXTENSION || node.kind === kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + function isSchemaCoordinateNode(node) { + return node.kind === kinds_ts_1.Kind.TYPE_COORDINATE || node.kind === kinds_ts_1.Kind.MEMBER_COORDINATE || node.kind === kinds_ts_1.Kind.ARGUMENT_COORDINATE || node.kind === kinds_ts_1.Kind.DIRECTIVE_COORDINATE || node.kind === kinds_ts_1.Kind.DIRECTIVE_ARGUMENT_COORDINATE; + } +}); + +// node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js +var require_ExecutableDefinitionsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var predicates_ts_1 = require_predicates(); + function ExecutableDefinitionsRule(context) { + return { + Document(node) { + for (const definition of node.definitions) { + if (!(0, predicates_ts_1.isExecutableDefinitionNode)(definition)) { + const defName = definition.kind === kinds_ts_1.Kind.SCHEMA_DEFINITION || definition.kind === kinds_ts_1.Kind.SCHEMA_EXTENSION ? "schema" : '"' + definition.name.value + '"'; + context.reportError(new GraphQLError_ts_1.GraphQLError(`The ${defName} definition is not executable.`, { + nodes: definition + })); + } + } + return false; + } + }; + } +}); + +// node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js +var require_FieldsOnCorrectTypeRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; + var didYouMean_ts_1 = require_didYouMean(); + var naturalCompare_ts_1 = require_naturalCompare(); + var suggestionList_ts_1 = require_suggestionList(); + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + function FieldsOnCorrectTypeRule(context) { + return { + Field(node) { + const type = context.getParentType(); + if (type) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + const schema = context.getSchema(); + const fieldName = node.name.value; + let suggestion = (0, didYouMean_ts_1.didYouMean)("to use an inline fragment on", context.hideSuggestions ? [] : getSuggestedTypeNames(schema, type, fieldName)); + if (suggestion === "") { + suggestion = (0, didYouMean_ts_1.didYouMean)(context.hideSuggestions ? [] : getSuggestedFieldNames(type, fieldName)); + } + context.reportError(new GraphQLError_ts_1.GraphQLError(`Cannot query field "${fieldName}" on type "${type}".` + suggestion, { nodes: node })); + } + } + } + }; + } + function getSuggestedTypeNames(schema, type, fieldName) { + if (!(0, definition_ts_1.isAbstractType)(type)) { + return []; + } + const suggestedTypes = new Set; + const usageCount = Object.create(null); + for (const possibleType of schema.getPossibleTypes(type)) { + if (possibleType.getFields()[fieldName] == null) { + continue; + } + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + for (const possibleInterface of possibleType.getInterfaces()) { + if (possibleInterface.getFields()[fieldName] == null) { + continue; + } + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = (usageCount[possibleInterface.name] ?? 0) + 1; + } + } + return [...suggestedTypes].sort((typeA, typeB) => { + const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + if (usageCountDiff !== 0) { + return usageCountDiff; + } + if ((0, definition_ts_1.isInterfaceType)(typeA) && schema.isSubType(typeA, typeB)) { + return -1; + } + if ((0, definition_ts_1.isInterfaceType)(typeB) && schema.isSubType(typeB, typeA)) { + return 1; + } + return (0, naturalCompare_ts_1.naturalCompare)(typeA.name, typeB.name); + }).map((x) => x.name); + } + function getSuggestedFieldNames(type, fieldName) { + if ((0, definition_ts_1.isObjectType)(type) || (0, definition_ts_1.isInterfaceType)(type)) { + const possibleFieldNames = Object.keys(type.getFields()); + return (0, suggestionList_ts_1.suggestionList)(fieldName, possibleFieldNames); + } + return []; + } +}); + +// node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js +var require_FragmentsOnCompositeTypesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var typeFromAST_ts_1 = require_typeFromAST(); + function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + if (typeCondition) { + const type = (0, typeFromAST_ts_1.typeFromAST)(context.getSchema(), typeCondition); + if (type && !(0, definition_ts_1.isCompositeType)(type)) { + const typeStr = (0, printer_ts_1.print)(typeCondition); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Fragment cannot condition on non composite type "${typeStr}".`, { nodes: typeCondition })); + } + } + }, + FragmentDefinition(node) { + const type = (0, typeFromAST_ts_1.typeFromAST)(context.getSchema(), node.typeCondition); + if (type && !(0, definition_ts_1.isCompositeType)(type)) { + const typeStr = (0, printer_ts_1.print)(node.typeCondition); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, { nodes: node.typeCondition })); + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/KnownArgumentNamesRule.js +var require_KnownArgumentNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.KnownArgumentNamesRule = KnownArgumentNamesRule; + exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; + var didYouMean_ts_1 = require_didYouMean(); + var suggestionList_ts_1 = require_suggestionList(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var directives_ts_1 = require_directives(); + function KnownArgumentNamesRule(context) { + return { + ...KnownArgumentNamesOnDirectivesRule(context), + FragmentArgument(argNode) { + const fragmentSignature = context.getFragmentSignature(); + if (fragmentSignature) { + const varDef = fragmentSignature.variableDefinitions.get(argNode.name.value); + if (!varDef) { + const argName = argNode.name.value; + const suggestions = context.hideSuggestions ? [] : (0, suggestionList_ts_1.suggestionList)(argName, Array.from(fragmentSignature.variableDefinitions.values()).map((varSignature) => varSignature.variable.name.value)); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Unknown argument "${argName}" on fragment "${fragmentSignature.definition.name.value}".` + (0, didYouMean_ts_1.didYouMean)(suggestions), { nodes: argNode })); + } + } + }, + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + if (!argDef && fieldDef) { + const argName = argNode.name.value; + const suggestions = context.hideSuggestions ? [] : (0, suggestionList_ts_1.suggestionList)(argName, fieldDef.args.map((arg) => arg.name)); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Unknown argument "${argName}" on field "${fieldDef}".` + (0, didYouMean_ts_1.didYouMean)(suggestions), { nodes: argNode })); + } + } + }; + } + function KnownArgumentNamesOnDirectivesRule(context) { + const directiveArgs = new Map; + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : directives_ts_1.specifiedDirectives; + for (const directive of definedDirectives) { + directiveArgs.set(directive.name, directive.args.map((arg) => arg.name)); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === kinds_ts_1.Kind.DIRECTIVE_DEFINITION) { + const argsNodes = def.arguments ?? []; + directiveArgs.set(def.name.value, argsNodes.map((arg) => arg.name.value)); + } + } + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs.get(directiveName); + if (directiveNode.arguments != null && knownArgs != null) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + if (!knownArgs.includes(argName)) { + const suggestions = (0, suggestionList_ts_1.suggestionList)(argName, knownArgs); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Unknown argument "${argName}" on directive "@${directiveName}".` + (context.hideSuggestions ? "" : (0, didYouMean_ts_1.didYouMean)(suggestions)), { nodes: argNode })); + } + } + } + return false; + } + }; + } +}); + +// node_modules/graphql/validation/rules/KnownDirectivesRule.js +var require_KnownDirectivesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.KnownDirectivesRule = KnownDirectivesRule; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var GraphQLError_ts_1 = require_GraphQLError(); + var ast_ts_1 = require_ast(); + var directiveLocation_ts_1 = require_directiveLocation(); + var kinds_ts_1 = require_kinds(); + var directives_ts_1 = require_directives(); + function KnownDirectivesRule(context) { + const locationsMap = new Map; + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : directives_ts_1.specifiedDirectives; + for (const directive of definedDirectives) { + locationsMap.set(directive.name, directive.locations); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === kinds_ts_1.Kind.DIRECTIVE_DEFINITION) { + locationsMap.set(def.name.value, def.locations.map((name) => name.value)); + } + } + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap.get(name); + if (locations == null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Unknown directive "@${name}".`, { nodes: node })); + return; + } + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + if (candidateLocation != null && !locations.includes(candidateLocation)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Directive "@${name}" may not be used on ${candidateLocation}.`, { nodes: node })); + } + } + }; + } + function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors.at(-1); + if (!(appliedTo != null && ("kind" in appliedTo))) + (0, invariant_ts_1.invariant)(false); + switch (appliedTo.kind) { + case kinds_ts_1.Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + case kinds_ts_1.Kind.FIELD: + return directiveLocation_ts_1.DirectiveLocation.FIELD; + case kinds_ts_1.Kind.FRAGMENT_SPREAD: + return directiveLocation_ts_1.DirectiveLocation.FRAGMENT_SPREAD; + case kinds_ts_1.Kind.INLINE_FRAGMENT: + return directiveLocation_ts_1.DirectiveLocation.INLINE_FRAGMENT; + case kinds_ts_1.Kind.FRAGMENT_DEFINITION: + return directiveLocation_ts_1.DirectiveLocation.FRAGMENT_DEFINITION; + case kinds_ts_1.Kind.VARIABLE_DEFINITION: { + const parentNode = ancestors[ancestors.length - 3]; + if (!("kind" in parentNode)) + (0, invariant_ts_1.invariant)(false); + return parentNode.kind === kinds_ts_1.Kind.OPERATION_DEFINITION ? directiveLocation_ts_1.DirectiveLocation.VARIABLE_DEFINITION : directiveLocation_ts_1.DirectiveLocation.FRAGMENT_VARIABLE_DEFINITION; + } + case kinds_ts_1.Kind.SCHEMA_DEFINITION: + case kinds_ts_1.Kind.SCHEMA_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.SCHEMA; + case kinds_ts_1.Kind.SCALAR_TYPE_DEFINITION: + case kinds_ts_1.Kind.SCALAR_TYPE_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.SCALAR; + case kinds_ts_1.Kind.OBJECT_TYPE_DEFINITION: + case kinds_ts_1.Kind.OBJECT_TYPE_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.OBJECT; + case kinds_ts_1.Kind.FIELD_DEFINITION: + return directiveLocation_ts_1.DirectiveLocation.FIELD_DEFINITION; + case kinds_ts_1.Kind.INTERFACE_TYPE_DEFINITION: + case kinds_ts_1.Kind.INTERFACE_TYPE_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.INTERFACE; + case kinds_ts_1.Kind.UNION_TYPE_DEFINITION: + case kinds_ts_1.Kind.UNION_TYPE_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.UNION; + case kinds_ts_1.Kind.ENUM_TYPE_DEFINITION: + case kinds_ts_1.Kind.ENUM_TYPE_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.ENUM; + case kinds_ts_1.Kind.ENUM_VALUE_DEFINITION: + return directiveLocation_ts_1.DirectiveLocation.ENUM_VALUE; + case kinds_ts_1.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.INPUT_OBJECT; + case kinds_ts_1.Kind.INPUT_VALUE_DEFINITION: { + const parentNode = ancestors.at(-3); + if (!(parentNode != null && ("kind" in parentNode))) + (0, invariant_ts_1.invariant)(false); + return parentNode.kind === kinds_ts_1.Kind.INPUT_OBJECT_TYPE_DEFINITION || parentNode.kind === kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION ? directiveLocation_ts_1.DirectiveLocation.INPUT_FIELD_DEFINITION : directiveLocation_ts_1.DirectiveLocation.ARGUMENT_DEFINITION; + } + case kinds_ts_1.Kind.DIRECTIVE_DEFINITION: + case kinds_ts_1.Kind.DIRECTIVE_EXTENSION: + return directiveLocation_ts_1.DirectiveLocation.DIRECTIVE_DEFINITION; + default: + (0, invariant_ts_1.invariant)(false, "Unexpected kind: " + (0, inspect_ts_1.inspect)(appliedTo.kind)); + } + } + function getDirectiveLocationForOperation(operation) { + switch (operation) { + case ast_ts_1.OperationTypeNode.QUERY: + return directiveLocation_ts_1.DirectiveLocation.QUERY; + case ast_ts_1.OperationTypeNode.MUTATION: + return directiveLocation_ts_1.DirectiveLocation.MUTATION; + case ast_ts_1.OperationTypeNode.SUBSCRIPTION: + return directiveLocation_ts_1.DirectiveLocation.SUBSCRIPTION; + } + } +}); + +// node_modules/graphql/validation/rules/KnownFragmentNamesRule.js +var require_KnownFragmentNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.KnownFragmentNamesRule = KnownFragmentNamesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function KnownFragmentNamesRule(context) { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + if (!fragment) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Unknown fragment "${fragmentName}".`, { + nodes: node.name + })); + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/KnownOperationTypesRule.js +var require_KnownOperationTypesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.KnownOperationTypesRule = KnownOperationTypesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function KnownOperationTypesRule(context) { + const schema = context.getSchema(); + return { + OperationDefinition(node) { + const operation = node.operation; + if (!schema.getRootType(operation)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`The ${operation} operation is not supported by the schema.`, { nodes: node })); + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/KnownTypeNamesRule.js +var require_KnownTypeNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.KnownTypeNamesRule = KnownTypeNamesRule; + var didYouMean_ts_1 = require_didYouMean(); + var suggestionList_ts_1 = require_suggestionList(); + var GraphQLError_ts_1 = require_GraphQLError(); + var predicates_ts_1 = require_predicates(); + var introspection_ts_1 = require_introspection(); + var scalars_ts_1 = require_scalars(); + function KnownTypeNamesRule(context) { + const { definitions } = context.getDocument(); + const existingTypesMap = context.getSchema()?.getTypeMap() ?? {}; + const typeNames = new Set([ + ...Object.keys(existingTypesMap), + ...definitions.filter(predicates_ts_1.isTypeDefinitionNode).map((def) => def.name.value) + ]); + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; + if (!typeNames.has(typeName)) { + const definitionNode = ancestors[2] ?? parent; + const isSDL = definitionNode != null && isSDLNode(definitionNode); + if (isSDL && standardTypeNames.has(typeName)) { + return; + } + const suggestedTypes = context.hideSuggestions ? [] : (0, suggestionList_ts_1.suggestionList)(typeName, isSDL ? [...standardTypeNames, ...typeNames] : [...typeNames]); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Unknown type "${typeName}".` + (0, didYouMean_ts_1.didYouMean)(suggestedTypes), { nodes: node })); + } + } + }; + } + var standardTypeNames = new Set([...scalars_ts_1.specifiedScalarTypes, ...introspection_ts_1.introspectionTypes].map((type) => type.name)); + function isSDLNode(value) { + return "kind" in value && ((0, predicates_ts_1.isTypeSystemDefinitionNode)(value) || (0, predicates_ts_1.isTypeSystemExtensionNode)(value)); + } +}); + +// node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js +var require_LoneAnonymousOperationRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + function LoneAnonymousOperationRule(context) { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter((definition) => definition.kind === kinds_ts_1.Kind.OPERATION_DEFINITION).length; + }, + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new GraphQLError_ts_1.GraphQLError("This anonymous operation must be the only defined operation.", { nodes: node })); + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js +var require_LoneSchemaDefinitionRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function LoneSchemaDefinitionRule(context) { + const oldSchema = context.getSchema(); + const alreadyDefined = oldSchema?.astNode ?? oldSchema?.getQueryType() ?? oldSchema?.getMutationType() ?? oldSchema?.getSubscriptionType(); + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new GraphQLError_ts_1.GraphQLError("Cannot define a new schema within a schema extension.", { nodes: node })); + return; + } + if (schemaDefinitionsCount > 0) { + context.reportError(new GraphQLError_ts_1.GraphQLError("Must provide only one schema definition.", { + nodes: node + })); + } + ++schemaDefinitionsCount; + } + }; + } +}); + +// node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.js +var require_MaxIntrospectionDepthRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MaxIntrospectionDepthRule = MaxIntrospectionDepthRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var MAX_LISTS_DEPTH = 3; + function MaxIntrospectionDepthRule(context) { + function checkDepth(node, visitedFragments = Object.create(null), depth = 0) { + if (node.kind === kinds_ts_1.Kind.FRAGMENT_SPREAD) { + const fragmentName = node.name.value; + if (visitedFragments[fragmentName] === true) { + return false; + } + const fragment = context.getFragment(fragmentName); + if (!fragment) { + return false; + } + try { + visitedFragments[fragmentName] = true; + return checkDepth(fragment, visitedFragments, depth); + } finally { + visitedFragments[fragmentName] = undefined; + } + } + if (node.kind === kinds_ts_1.Kind.FIELD && (node.name.value === "fields" || node.name.value === "interfaces" || node.name.value === "possibleTypes" || node.name.value === "inputFields")) { + depth++; + if (depth >= MAX_LISTS_DEPTH) { + return true; + } + } + if ("selectionSet" in node && node.selectionSet) { + for (const child of node.selectionSet.selections) { + if (checkDepth(child, visitedFragments, depth)) { + return true; + } + } + } + return false; + } + return { + Field(node) { + if (node.name.value === "__schema" || node.name.value === "__type") { + if (checkDepth(node)) { + context.reportError(new GraphQLError_ts_1.GraphQLError("Maximum introspection depth exceeded", { + nodes: [node] + })); + return false; + } + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/NoFragmentCyclesRule.js +var require_NoFragmentCyclesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoFragmentCyclesRule = NoFragmentCyclesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function NoFragmentCyclesRule(context) { + const visitedFrags = new Set; + const spreadPath = []; + const spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; + function detectCycleRecursive(fragment) { + if (visitedFrags.has(fragment.name.value)) { + return; + } + const fragmentName = fragment.name.value; + visitedFrags.add(fragmentName); + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + if (spreadNodes.length === 0) { + return; + } + spreadPathIndexByName[fragmentName] = spreadPath.length; + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath.slice(0, -1).map((s) => '"' + s.name.value + '"').join(", "); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Cannot spread fragment "${spreadName}" within itself` + (viaPath !== "" ? ` via ${viaPath}.` : "."), { nodes: cyclePath })); + } + spreadPath.pop(); + } + spreadPathIndexByName[fragmentName] = undefined; + } + } +}); + +// node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js +var require_NoUndefinedVariablesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function NoUndefinedVariablesRule(context) { + return { + OperationDefinition(operation) { + const variableNameDefined = new Set(operation.variableDefinitions?.map((node) => node.variable.name.value)); + const usages = context.getRecursiveVariableUsages(operation); + for (const { node, fragmentVariableDefinition } of usages) { + if (fragmentVariableDefinition) { + continue; + } + const varName = node.name.value; + if (!variableNameDefined.has(varName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(operation.name ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` : `Variable "$${varName}" is not defined.`, { nodes: [node, operation] })); + } + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js +var require_NoUnusedFragmentsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function NoUnusedFragmentsRule(context) { + const fragmentNameUsed = new Set; + const fragmentDefs = []; + return { + OperationDefinition(operation) { + for (const fragment of context.getRecursivelyReferencedFragments(operation)) { + fragmentNameUsed.add(fragment.name.value); + } + return false; + }, + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave() { + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + if (!fragmentNameUsed.has(fragName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Fragment "${fragName}" is never used.`, { + nodes: fragmentDef + })); + } + } + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/NoUnusedVariablesRule.js +var require_NoUnusedVariablesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoUnusedVariablesRule = NoUnusedVariablesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function NoUnusedVariablesRule(context) { + return { + FragmentDefinition(fragment) { + const usages = context.getVariableUsages(fragment); + const argumentNameUsed = new Set(usages.map(({ node }) => node.name.value)); + const variableDefinitions = fragment.variableDefinitions ?? []; + for (const varDef of variableDefinitions) { + const argName = varDef.variable.name.value; + if (!argumentNameUsed.has(argName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Variable "$${argName}" is never used in fragment "${fragment.name.value}".`, { nodes: varDef })); + } + } + }, + OperationDefinition(operation) { + const usages = context.getRecursiveVariableUsages(operation); + const operationVariableNameUsed = new Set; + for (const { node, fragmentVariableDefinition } of usages) { + const varName = node.name.value; + if (!fragmentVariableDefinition) { + operationVariableNameUsed.add(varName); + } + } + const variableDefinitions = operation.variableDefinitions ?? []; + for (const variableDef of variableDefinitions) { + const variableName = variableDef.variable.name.value; + if (!operationVariableNameUsed.has(variableName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(operation.name ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` : `Variable "$${variableName}" is never used.`, { nodes: variableDef })); + } + } + } + }; + } +}); + +// node_modules/graphql/utilities/sortValueNode.js +var require_sortValueNode = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.sortValueNode = sortValueNode; + var naturalCompare_ts_1 = require_naturalCompare(); + var kinds_ts_1 = require_kinds(); + function sortValueNode(valueNode) { + switch (valueNode.kind) { + case kinds_ts_1.Kind.OBJECT: + return { + ...valueNode, + fields: sortFields(valueNode.fields) + }; + case kinds_ts_1.Kind.LIST: + return { + ...valueNode, + values: valueNode.values.map(sortValueNode) + }; + case kinds_ts_1.Kind.INT: + case kinds_ts_1.Kind.FLOAT: + case kinds_ts_1.Kind.STRING: + case kinds_ts_1.Kind.BOOLEAN: + case kinds_ts_1.Kind.NULL: + case kinds_ts_1.Kind.ENUM: + case kinds_ts_1.Kind.VARIABLE: + return valueNode; + } + } + function sortFields(fields) { + return fields.map((fieldNode) => ({ + ...fieldNode, + value: sortValueNode(fieldNode.value) + })).sort((fieldA, fieldB) => (0, naturalCompare_ts_1.naturalCompare)(fieldA.name.value, fieldB.name.value)); + } +}); + +// node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js +var require_OverlappingFieldsCanBeMergedRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; + var inspect_ts_1 = require_inspect(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var sortValueNode_ts_1 = require_sortValueNode(); + var typeFromAST_ts_1 = require_typeFromAST(); + function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(([responseName, subReason]) => `subfields "${responseName}" conflict because ` + reasonMessage(subReason)).join(" and "); + } + return reason; + } + function OverlappingFieldsCanBeMergedRule(context) { + const comparedFieldsAndFragmentPairs = new OrderedPairSet; + const comparedFragmentPairs = new PairSet; + const cachedFieldsAndFragmentSpreads = new Map; + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, context.getParentType(), selectionSet); + for (const [[responseName, reason], fields1, fields2] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, { nodes: fields1.concat(fields2) })); + } + } + }; + } + function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, parentType, selectionSet) { + const conflicts = []; + const [fieldMap, fragmentSpreads] = getFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, parentType, selectionSet, undefined); + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, fieldMap); + if (fragmentSpreads.length !== 0) { + for (let i = 0;i < fragmentSpreads.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, false, fieldMap, fragmentSpreads[i]); + for (let j = i + 1;j < fragmentSpreads.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, false, fragmentSpreads[i], fragmentSpreads[j]); + } + } + } + return conflicts; + } + function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentSpread) { + if (comparedFieldsAndFragmentPairs.has(fieldMap, fragmentSpread.key, areMutuallyExclusive)) { + return; + } + comparedFieldsAndFragmentPairs.add(fieldMap, fragmentSpread.key, areMutuallyExclusive); + const fragment = context.getFragment(fragmentSpread.node.name.value); + if (!fragment) { + return; + } + const [fieldMap2, referencedFragmentSpreads] = getReferencedFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, fragment, fragmentSpread.varMap); + if (fieldMap === fieldMap2) { + return; + } + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fieldMap, undefined, fieldMap2, fragmentSpread.varMap); + for (const referencedFragmentSpread of referencedFragmentSpreads) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fieldMap, referencedFragmentSpread); + } + } + function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fragmentSpread1, fragmentSpread2) { + if (fragmentSpread1.key === fragmentSpread2.key) { + return; + } + if (fragmentSpread1.node.name.value === fragmentSpread2.node.name.value) { + if (!sameArguments(fragmentSpread1.node.arguments, fragmentSpread1.varMap, fragmentSpread2.node.arguments, fragmentSpread2.varMap)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Spreads "${fragmentSpread1.node.name.value}" conflict because ${fragmentSpread1.key} and ${fragmentSpread2.key} have different fragment arguments.`, { nodes: [fragmentSpread1.node, fragmentSpread2.node] })); + return; + } + } + if (comparedFragmentPairs.has(fragmentSpread1.key, fragmentSpread2.key, areMutuallyExclusive)) { + return; + } + comparedFragmentPairs.add(fragmentSpread1.key, fragmentSpread2.key, areMutuallyExclusive); + const fragment1 = context.getFragment(fragmentSpread1.node.name.value); + const fragment2 = context.getFragment(fragmentSpread2.node.name.value); + if (!fragment1 || !fragment2) { + return; + } + const [fieldMap1, referencedFragmentSpreads1] = getReferencedFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, fragment1, fragmentSpread1.varMap); + const [fieldMap2, referencedFragmentSpreads2] = getReferencedFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, fragment2, fragmentSpread2.varMap); + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentSpread1.varMap, fieldMap2, fragmentSpread2.varMap); + for (const referencedFragmentSpread2 of referencedFragmentSpreads2) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fragmentSpread1, referencedFragmentSpread2); + } + for (const referencedFragmentSpread1 of referencedFragmentSpreads1) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, referencedFragmentSpread1, fragmentSpread2); + } + } + function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, varMap1, parentType2, selectionSet2, varMap2) { + const conflicts = []; + const [fieldMap1, fragmentSpreads1] = getFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, parentType1, selectionSet1, varMap1); + const [fieldMap2, fragmentSpreads2] = getFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, parentType2, selectionSet2, varMap2); + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, varMap1, fieldMap2, varMap2); + for (const fragmentSpread2 of fragmentSpreads2) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentSpread2); + } + for (const fragmentSpread1 of fragmentSpreads1) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentSpread1); + } + for (const fragmentSpread1 of fragmentSpreads1) { + for (const fragmentSpread2 of fragmentSpreads2) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, fragmentSpread1, fragmentSpread2); + } + } + return conflicts; + } + function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, fieldMap) { + for (const [responseName, fields] of fieldMap.entries()) { + if (fields.length > 1) { + for (let i = 0;i < fields.length; i++) { + for (let j = i + 1;j < fields.length; j++) { + const conflict = findConflict(context, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, false, responseName, fields[i], undefined, fields[j], undefined); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } + } + function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, varMap1, fieldMap2, varMap2) { + for (const [responseName, fields1] of fieldMap1.entries()) { + const fields2 = fieldMap2.get(responseName); + if (fields2 != null) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict(context, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, varMap1, field2, varMap2); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } + } + function findConflict(context, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, varMap1, field2, varMap2) { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; + const areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, definition_ts_1.isObjectType)(parentType1) && (0, definition_ts_1.isObjectType)(parentType2); + if (!areMutuallyExclusive) { + const name1 = node1.name.value; + const name2 = node2.name.value; + if (name1 !== name2) { + return [ + [responseName, `"${name1}" and "${name2}" are different fields`], + [node1], + [node2] + ]; + } + if (!sameArguments(node1.arguments, varMap1, node2.arguments, varMap2)) { + return [ + [responseName, "they have differing arguments"], + [node1], + [node2] + ]; + } + } + const directives1 = node1.directives; + const directives2 = node2.directives; + const overlappingStreamReason = hasNoOverlappingStreams(directives1, varMap1, directives2, varMap2); + if (overlappingStreamReason !== undefined) { + return [[responseName, overlappingStreamReason], [node1], [node2]]; + } + const type1 = def1?.type; + const type2 = def2?.type; + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types "${(0, inspect_ts_1.inspect)(type1)}" and "${(0, inspect_ts_1.inspect)(type2)}"` + ], + [node1], + [node2] + ]; + } + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentSpreads, comparedFieldsAndFragmentPairs, comparedFragmentPairs, areMutuallyExclusive, (0, definition_ts_1.getNamedType)(type1), selectionSet1, varMap1, (0, definition_ts_1.getNamedType)(type2), selectionSet2, varMap2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } + } + function sameArguments(args1, varMap1, args2, varMap2) { + if (args1 === undefined || args1.length === 0) { + return args2 === undefined || args2.length === 0; + } + if (args2 === undefined || args2.length === 0) { + return false; + } + if (args1.length !== args2.length) { + return false; + } + const values2 = new Map(args2.map(({ name, value }) => [ + name.value, + varMap2 === undefined ? value : replaceFragmentVariables(value, varMap2) + ])); + return args1.every((arg1) => { + let value1 = arg1.value; + if (varMap1) { + value1 = replaceFragmentVariables(value1, varMap1); + } + const value2 = values2.get(arg1.name.value); + if (value2 === undefined) { + return false; + } + return stringifyValue(value1) === stringifyValue(value2); + }); + } + function replaceFragmentVariables(valueNode, varMap) { + switch (valueNode.kind) { + case kinds_ts_1.Kind.VARIABLE: + return varMap.get(valueNode.name.value) ?? valueNode; + case kinds_ts_1.Kind.LIST: + return { + ...valueNode, + values: valueNode.values.map((node) => replaceFragmentVariables(node, varMap)) + }; + case kinds_ts_1.Kind.OBJECT: + return { + ...valueNode, + fields: valueNode.fields.map((field) => ({ + ...field, + value: replaceFragmentVariables(field.value, varMap) + })) + }; + default: { + return valueNode; + } + } + } + function stringifyValue(value) { + return (0, printer_ts_1.print)((0, sortValueNode_ts_1.sortValueNode)(value)); + } + function getStreamDirective(directives) { + return directives?.find((directive) => directive.name.value === "stream"); + } + function hasNoOverlappingStreams(directives1, varMap1, directives2, varMap2) { + const stream1 = getStreamDirective(directives1); + const stream2 = getStreamDirective(directives2); + if (!stream1 && !stream2) { + return; + } else if (stream1 && stream2) { + if (sameArguments(stream1.arguments, varMap1, stream2.arguments, varMap2)) { + return "they have overlapping stream directives. See https://github.com/graphql/defer-stream-wg/discussions/100"; + } + return "they have overlapping stream directives"; + } + return "they have overlapping stream directives"; + } + function doTypesConflict(type1, type2) { + if ((0, definition_ts_1.isListType)(type1)) { + return (0, definition_ts_1.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + if ((0, definition_ts_1.isListType)(type2)) { + return true; + } + if ((0, definition_ts_1.isNonNullType)(type1)) { + return (0, definition_ts_1.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + if ((0, definition_ts_1.isNonNullType)(type2)) { + return true; + } + if ((0, definition_ts_1.isLeafType)(type1) || (0, definition_ts_1.isLeafType)(type2)) { + return type1 !== type2; + } + return false; + } + function getFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, parentType, selectionSet, varMap) { + const cached = cachedFieldsAndFragmentSpreads.get(selectionSet); + if (cached) { + return cached; + } + const nodeAndDefs = new Map; + const fragmentSpreads = new Map; + _collectFieldsAndFragmentSpreads(context, parentType, selectionSet, nodeAndDefs, fragmentSpreads, varMap); + const result = [ + nodeAndDefs, + Array.from(fragmentSpreads.values()) + ]; + cachedFieldsAndFragmentSpreads.set(selectionSet, result); + return result; + } + function getReferencedFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, fragment, varMap) { + const cached = cachedFieldsAndFragmentSpreads.get(fragment.selectionSet); + if (cached) { + return cached; + } + const fragmentType = (0, typeFromAST_ts_1.typeFromAST)(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentSpreads(context, cachedFieldsAndFragmentSpreads, fragmentType, fragment.selectionSet, varMap); + } + function _collectFieldsAndFragmentSpreads(context, parentType, selectionSet, nodeAndDefs, fragmentSpreads, varMap) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case kinds_ts_1.Kind.FIELD: { + const fieldName = selection.name.value; + let fieldDef; + if ((0, definition_ts_1.isObjectType)(parentType) || (0, definition_ts_1.isInterfaceType)(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + const responseName = selection.alias ? selection.alias.value : fieldName; + let nodeAndDefsList = nodeAndDefs.get(responseName); + if (nodeAndDefsList == null) { + nodeAndDefsList = []; + nodeAndDefs.set(responseName, nodeAndDefsList); + } + nodeAndDefsList.push([parentType, selection, fieldDef]); + break; + } + case kinds_ts_1.Kind.FRAGMENT_SPREAD: { + const fragmentSpread = getFragmentSpread(context, selection, varMap); + fragmentSpreads.set(fragmentSpread.key, fragmentSpread); + break; + } + case kinds_ts_1.Kind.INLINE_FRAGMENT: { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition ? (0, typeFromAST_ts_1.typeFromAST)(context.getSchema(), typeCondition) : parentType; + _collectFieldsAndFragmentSpreads(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentSpreads, varMap); + break; + } + } + } + } + function getFragmentSpread(context, fragmentSpreadNode, varMap) { + let key = ""; + const newVarMap = new Map; + const fragmentSignature = context.getFragmentSignatureByName()(fragmentSpreadNode.name.value); + const argMap = new Map; + if (fragmentSpreadNode.arguments) { + for (const arg of fragmentSpreadNode.arguments) { + argMap.set(arg.name.value, arg.value); + } + } + if (fragmentSignature?.variableDefinitions) { + key += fragmentSpreadNode.name.value + "("; + for (const [varName, variable] of fragmentSignature.variableDefinitions) { + const value = argMap.get(varName); + if (value) { + key += varName + ": " + (0, printer_ts_1.print)((0, sortValueNode_ts_1.sortValueNode)(value)); + } + const arg = argMap.get(varName); + if (arg !== undefined) { + newVarMap.set(varName, varMap !== undefined ? replaceFragmentVariables(arg, varMap) : arg); + } else if (variable.defaultValue) { + newVarMap.set(varName, variable.defaultValue); + } + } + key += ")"; + } + return { + key, + node: fragmentSpreadNode, + varMap: newVarMap.size > 0 ? newVarMap : undefined + }; + } + function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + [node1, ...conflicts.map(([, fields1]) => fields1).flat()], + [node2, ...conflicts.map(([, , fields2]) => fields2).flat()] + ]; + } + } + + class OrderedPairSet { + constructor() { + this._data = new Map; + } + has(a, b, weaklyPresent) { + const result = this._data.get(a)?.get(b); + if (result === undefined) { + return false; + } + return weaklyPresent ? true : weaklyPresent === result; + } + add(a, b, weaklyPresent) { + const map = this._data.get(a); + if (map === undefined) { + this._data.set(a, new Map([[b, weaklyPresent]])); + } else { + map.set(b, weaklyPresent); + } + } + } + + class PairSet { + constructor() { + this._orderedPairSet = new OrderedPairSet; + } + has(a, b, weaklyPresent) { + return a < b ? this._orderedPairSet.has(a, b, weaklyPresent) : this._orderedPairSet.has(b, a, weaklyPresent); + } + add(a, b, weaklyPresent) { + if (a < b) { + this._orderedPairSet.add(a, b, weaklyPresent); + } else { + this._orderedPairSet.add(b, a, weaklyPresent); + } + } + } +}); + +// node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js +var require_PossibleFragmentSpreadsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; + var inspect_ts_1 = require_inspect(); + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + var typeComparators_ts_1 = require_typeComparators(); + var typeFromAST_ts_1 = require_typeFromAST(); + function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + if ((0, definition_ts_1.isCompositeType)(fragType) && (0, definition_ts_1.isCompositeType)(parentType) && !(0, typeComparators_ts_1.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + const parentTypeStr = (0, inspect_ts_1.inspect)(parentType); + const fragTypeStr = (0, inspect_ts_1.inspect)(fragType); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { nodes: node })); + } + }, + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + if (fragType && parentType && !(0, typeComparators_ts_1.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + const parentTypeStr = (0, inspect_ts_1.inspect)(parentType); + const fragTypeStr = (0, inspect_ts_1.inspect)(fragType); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, { nodes: node })); + } + } + }; + } + function getFragmentType(context, name) { + const frag = context.getFragment(name); + if (frag) { + const type = (0, typeFromAST_ts_1.typeFromAST)(context.getSchema(), frag.typeCondition); + if ((0, definition_ts_1.isCompositeType)(type)) { + return type; + } + } + } +}); + +// node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js +var require_PossibleTypeExtensionsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; + var didYouMean_ts_1 = require_didYouMean(); + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var suggestionList_ts_1 = require_suggestionList(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var predicates_ts_1 = require_predicates(); + var definition_ts_1 = require_definition(); + function PossibleTypeExtensionsRule(context) { + const schema = context.getSchema(); + const definedTypes = new Map; + for (const def of context.getDocument().definitions) { + if ((0, predicates_ts_1.isTypeDefinitionNode)(def)) { + definedTypes.set(def.name.value, def); + } + } + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension + }; + function checkExtension(node) { + const typeName = node.name.value; + const defNode = definedTypes.get(typeName); + const existingType = schema?.getType(typeName); + let expectedKind; + if (defNode != null) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + if (expectedKind != null) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Cannot extend non-${kindStr} type "${typeName}".`, { + nodes: defNode ? [defNode, node] : node + })); + } + } else { + const allTypeNames = [ + ...definedTypes.keys(), + ...Object.keys(schema?.getTypeMap() ?? {}) + ]; + context.reportError(new GraphQLError_ts_1.GraphQLError(`Cannot extend type "${typeName}" because it is not defined.` + (0, didYouMean_ts_1.didYouMean)((0, suggestionList_ts_1.suggestionList)(typeName, allTypeNames)), { nodes: node.name })); + } + } + } + var defKindToExtKind = { + [kinds_ts_1.Kind.SCALAR_TYPE_DEFINITION]: kinds_ts_1.Kind.SCALAR_TYPE_EXTENSION, + [kinds_ts_1.Kind.OBJECT_TYPE_DEFINITION]: kinds_ts_1.Kind.OBJECT_TYPE_EXTENSION, + [kinds_ts_1.Kind.INTERFACE_TYPE_DEFINITION]: kinds_ts_1.Kind.INTERFACE_TYPE_EXTENSION, + [kinds_ts_1.Kind.UNION_TYPE_DEFINITION]: kinds_ts_1.Kind.UNION_TYPE_EXTENSION, + [kinds_ts_1.Kind.ENUM_TYPE_DEFINITION]: kinds_ts_1.Kind.ENUM_TYPE_EXTENSION, + [kinds_ts_1.Kind.INPUT_OBJECT_TYPE_DEFINITION]: kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION + }; + function typeToExtKind(type) { + if ((0, definition_ts_1.isScalarType)(type)) { + return kinds_ts_1.Kind.SCALAR_TYPE_EXTENSION; + } + if ((0, definition_ts_1.isObjectType)(type)) { + return kinds_ts_1.Kind.OBJECT_TYPE_EXTENSION; + } + if ((0, definition_ts_1.isInterfaceType)(type)) { + return kinds_ts_1.Kind.INTERFACE_TYPE_EXTENSION; + } + if ((0, definition_ts_1.isUnionType)(type)) { + return kinds_ts_1.Kind.UNION_TYPE_EXTENSION; + } + if ((0, definition_ts_1.isEnumType)(type)) { + return kinds_ts_1.Kind.ENUM_TYPE_EXTENSION; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + return kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + (0, invariant_ts_1.invariant)(false, "Unexpected type: " + (0, inspect_ts_1.inspect)(type)); + } + function extensionKindToTypeName(kind2) { + switch (kind2) { + case kinds_ts_1.Kind.SCALAR_TYPE_EXTENSION: + return "scalar"; + case kinds_ts_1.Kind.OBJECT_TYPE_EXTENSION: + return "object"; + case kinds_ts_1.Kind.INTERFACE_TYPE_EXTENSION: + return "interface"; + case kinds_ts_1.Kind.UNION_TYPE_EXTENSION: + return "union"; + case kinds_ts_1.Kind.ENUM_TYPE_EXTENSION: + return "enum"; + case kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return "input object"; + default: + (0, invariant_ts_1.invariant)(false, "Unexpected kind: " + (0, inspect_ts_1.inspect)(kind2)); + } + } +}); + +// node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js +var require_ProvidedRequiredArgumentsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; + exports.ProvidedRequiredArgumentsOnDirectivesRule = ProvidedRequiredArgumentsOnDirectivesRule; + var inspect_ts_1 = require_inspect(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var typeFromAST_ts_1 = require_typeFromAST(); + function ProvidedRequiredArgumentsRule(context) { + return { + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + leave(fieldNode) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; + } + const providedArgs = new Set(fieldNode.arguments?.map((arg) => arg.name.value)); + for (const argDef of fieldDef.args) { + if (!providedArgs.has(argDef.name) && (0, definition_ts_1.isRequiredArgument)(argDef)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Argument "${argDef}" of type "${argDef.type}" is required, but it was not provided.`, { nodes: fieldNode })); + } + } + } + }, + FragmentSpread: { + leave(spreadNode) { + const fragmentSignature = context.getFragmentSignature(); + if (!fragmentSignature) { + return false; + } + const providedArgs = new Set(spreadNode.arguments?.map((arg) => arg.name.value)); + for (const [varName, variableDefinition] of fragmentSignature.variableDefinitions) { + if (!providedArgs.has(varName) && isRequiredArgumentNode(variableDefinition)) { + const type = (0, typeFromAST_ts_1.typeFromAST)(context.getSchema(), variableDefinition.type); + const argTypeStr = (0, inspect_ts_1.inspect)(type); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Fragment "${spreadNode.name.value}" argument "${varName}" of type "${argTypeStr}" is required, but it was not provided.`, { nodes: spreadNode })); + } + } + } + } + }; + } + function ProvidedRequiredArgumentsOnDirectivesRule(context) { + const requiredArgsMap = new Map; + const schema = context.getSchema(); + const definedDirectives = schema?.getDirectives() ?? directives_ts_1.specifiedDirectives; + for (const directive of definedDirectives) { + requiredArgsMap.set(directive.name, new Map(directive.args.filter(definition_ts_1.isRequiredArgument).map((arg) => [arg.name, arg]))); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === kinds_ts_1.Kind.DIRECTIVE_DEFINITION) { + const argNodes = def.arguments ?? []; + requiredArgsMap.set(def.name.value, new Map(argNodes.filter(isRequiredArgumentNode).map((arg) => [arg.name.value, arg]))); + } + } + return { + Directive: { + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap.get(directiveName); + if (requiredArgs != null) { + const argNodes = directiveNode.arguments ?? []; + const argNodeMap = new Set(argNodes.map((arg) => arg.name.value)); + for (const [argName, argDef] of requiredArgs.entries()) { + if (!argNodeMap.has(argName)) { + const argType = (0, definition_ts_1.isType)(argDef.type) ? (0, inspect_ts_1.inspect)(argDef.type) : (0, printer_ts_1.print)(argDef.type); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Argument "@${directiveName}(${argName}:)" of type "${argType}" is required, but it was not provided.`, { nodes: directiveNode })); + } + } + } + } + } + }; + } + function isRequiredArgumentNode(arg) { + return arg.type.kind === kinds_ts_1.Kind.NON_NULL_TYPE && arg.defaultValue == null; + } +}); + +// node_modules/graphql/validation/rules/ScalarLeafsRule.js +var require_ScalarLeafsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ScalarLeafsRule = ScalarLeafsRule; + var inspect_ts_1 = require_inspect(); + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + function ScalarLeafsRule(context) { + return { + Field(node) { + const type = context.getType(); + const selectionSet = node.selectionSet; + if (type) { + if ((0, definition_ts_1.isLeafType)((0, definition_ts_1.getNamedType)(type))) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, inspect_ts_1.inspect)(type); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, { nodes: selectionSet })); + } + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, inspect_ts_1.inspect)(type); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, { nodes: node })); + } else if (selectionSet.selections.length === 0) { + const fieldName = node.name.value; + const typeStr = (0, inspect_ts_1.inspect)(type); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Field "${fieldName}" of type "${typeStr}" must have at least one field selected.`, { nodes: node })); + } + } + } + }; + } +}); + +// node_modules/graphql/utilities/coerceInputValue.js +var require_coerceInputValue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.coerceInputValue = coerceInputValue; + exports.coerceInputLiteral = coerceInputLiteral; + exports.coerceDefaultValue = coerceDefaultValue; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var isIterableObject_ts_1 = require_isIterableObject(); + var isObjectLike_ts_1 = require_isObjectLike(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + var replaceVariables_ts_1 = require_replaceVariables(); + function coerceInputValue(inputValue, type) { + if ((0, definition_ts_1.isNonNullType)(type)) { + if (inputValue == null) { + return; + } + return coerceInputValue(inputValue, type.ofType); + } + if (inputValue == null) { + return null; + } + if ((0, definition_ts_1.isListType)(type)) { + if (!(0, isIterableObject_ts_1.isIterableObject)(inputValue)) { + const coercedItem = coerceInputValue(inputValue, type.ofType); + if (coercedItem === undefined) { + return; + } + return [coercedItem]; + } + const coercedValue = []; + for (const itemValue of inputValue) { + const coercedItem = coerceInputValue(itemValue, type.ofType); + if (coercedItem === undefined) { + return; + } + coercedValue.push(coercedItem); + } + return coercedValue; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + if (!(0, isObjectLike_ts_1.isObjectLike)(inputValue) || Array.isArray(inputValue)) { + return; + } + const coercedValue = Object.create(null); + const fieldDefs = type.getFields(); + let definedFieldCount = 0; + for (const fieldName of Object.keys(inputValue)) { + if (inputValue[fieldName] === undefined) { + continue; + } + definedFieldCount++; + if (!Object.hasOwn(fieldDefs, fieldName)) { + return; + } + } + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; + if (fieldValue === undefined) { + if ((0, definition_ts_1.isRequiredInputField)(field)) { + return; + } + const coercedDefaultValue = coerceDefaultValue(field); + if (coercedDefaultValue !== undefined) { + coercedValue[field.name] = coercedDefaultValue; + } + } else { + const coercedField = coerceInputValue(fieldValue, field.type); + if (coercedField === undefined) { + return; + } + coercedValue[field.name] = coercedField; + } + } + if (type.isOneOf) { + const keys = Object.keys(coercedValue); + if (definedFieldCount !== 1 || keys.length !== 1) { + return; + } + const key = keys[0]; + const value = coercedValue[key]; + if (value === null) { + return; + } + } + return coercedValue; + } + const leafType = (0, definition_ts_1.assertLeafType)(type); + try { + return leafType.coerceInputValue(inputValue); + } catch (_error) {} + } + function coerceInputLiteral(valueNode, type, variableValues, fragmentVariableValues) { + if (valueNode.kind === kinds_ts_1.Kind.VARIABLE) { + const coercedVariableValue = getCoercedVariableValue(valueNode, variableValues, fragmentVariableValues); + if (coercedVariableValue == null && (0, definition_ts_1.isNonNullType)(type)) { + return; + } + return coercedVariableValue; + } + if ((0, definition_ts_1.isNonNullType)(type)) { + if (valueNode.kind === kinds_ts_1.Kind.NULL) { + return; + } + return coerceInputLiteral(valueNode, type.ofType, variableValues, fragmentVariableValues); + } + if (valueNode.kind === kinds_ts_1.Kind.NULL) { + return null; + } + if ((0, definition_ts_1.isListType)(type)) { + if (valueNode.kind !== kinds_ts_1.Kind.LIST) { + const itemValue = coerceInputLiteral(valueNode, type.ofType, variableValues, fragmentVariableValues); + if (itemValue === undefined) { + return; + } + return [itemValue]; + } + const coercedValue = []; + for (const itemNode of valueNode.values) { + let itemValue = coerceInputLiteral(itemNode, type.ofType, variableValues, fragmentVariableValues); + if (itemValue === undefined) { + if (itemNode.kind === kinds_ts_1.Kind.VARIABLE && getCoercedVariableValue(itemNode, variableValues, fragmentVariableValues) == null && !(0, definition_ts_1.isNonNullType)(type.ofType)) { + itemValue = null; + } else { + return; + } + } + coercedValue.push(itemValue); + } + return coercedValue; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + if (valueNode.kind !== kinds_ts_1.Kind.OBJECT) { + return; + } + const coercedValue = Object.create(null); + const fieldDefs = type.getFields(); + const hasUndefinedField = valueNode.fields.some((field) => !Object.hasOwn(fieldDefs, field.name.value)); + if (hasUndefinedField) { + return; + } + const fieldNodes = new Map(valueNode.fields.map((field) => [field.name.value, field])); + for (const field of Object.values(fieldDefs)) { + const fieldNode = fieldNodes.get(field.name); + if (!fieldNode || fieldNode.value.kind === kinds_ts_1.Kind.VARIABLE && isMissingVariable(fieldNode.value, variableValues, fragmentVariableValues)) { + if ((0, definition_ts_1.isRequiredInputField)(field)) { + return; + } + const coercedDefaultValue = coerceDefaultValue(field); + if (coercedDefaultValue !== undefined) { + coercedValue[field.name] = coercedDefaultValue; + } + } else { + const fieldValue = coerceInputLiteral(fieldNode.value, field.type, variableValues, fragmentVariableValues); + if (fieldValue === undefined) { + return; + } + coercedValue[field.name] = fieldValue; + } + } + if (type.isOneOf) { + const coercedKeys = Object.keys(coercedValue); + if (fieldNodes.size !== 1 || coercedKeys.length !== 1) { + return; + } + for (const [fieldName, fieldNode] of fieldNodes) { + if (fieldNode.value.kind === kinds_ts_1.Kind.NULL || coercedValue[fieldName] === null) { + return; + } + } + } + return coercedValue; + } + const leafType = (0, definition_ts_1.assertLeafType)(type); + try { + return leafType.coerceInputLiteral ? leafType.coerceInputLiteral((0, replaceVariables_ts_1.replaceVariables)(valueNode, variableValues, fragmentVariableValues)) : leafType.parseLiteral(valueNode, variableValues?.coerced); + } catch (_error) {} + } + function getCoercedVariableValue(variableNode, variableValues, fragmentVariableValues) { + const varName = variableNode.name.value; + if (fragmentVariableValues?.sources[varName] !== undefined) { + return fragmentVariableValues.coerced[varName]; + } + return variableValues?.coerced[varName]; + } + function isMissingVariable(variableNode, variableValues, fragmentVariableValues) { + const varName = variableNode.name.value; + const scopedValues = fragmentVariableValues?.sources[varName] !== undefined ? fragmentVariableValues.coerced : variableValues?.coerced; + return scopedValues?.[varName] === undefined; + } + function coerceDefaultValue(inputValue) { + let coercedDefaultValue = inputValue._memoizedCoercedDefaultValue; + if (coercedDefaultValue !== undefined) { + return coercedDefaultValue; + } + const defaultInput = inputValue.default; + if (defaultInput !== undefined) { + coercedDefaultValue = defaultInput.literal ? coerceInputLiteral(defaultInput.literal, inputValue.type) : coerceInputValue(defaultInput.value, inputValue.type); + if (!(coercedDefaultValue !== undefined)) + (0, invariant_ts_1.invariant)(false, `Expected value of type "${inputValue.type}" to be valid, found: ${(0, inspect_ts_1.inspect)(defaultInput.literal ?? defaultInput.value)}.`); + inputValue._memoizedCoercedDefaultValue = coercedDefaultValue; + return coercedDefaultValue; + } + const defaultValue = inputValue.defaultValue; + if (defaultValue !== undefined) { + inputValue._memoizedCoercedDefaultValue = defaultValue; + } + return defaultValue; + } +}); + +// node_modules/graphql/execution/getVariableSignature.js +var require_getVariableSignature = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getVariableSignature = getVariableSignature; + var GraphQLError_ts_1 = require_GraphQLError(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var typeFromAST_ts_1 = require_typeFromAST(); + function getVariableSignature(schema, varDefNode) { + const varName = varDefNode.variable.name.value; + const varType = (0, typeFromAST_ts_1.typeFromAST)(schema, varDefNode.type); + if (!(0, definition_ts_1.isInputType)(varType)) { + const varTypeStr = (0, printer_ts_1.print)(varDefNode.type); + return new GraphQLError_ts_1.GraphQLError(`Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, { nodes: varDefNode.type }); + } + const defaultValue = varDefNode.defaultValue; + return { + name: varName, + type: varType, + default: defaultValue && { literal: defaultValue } + }; + } +}); + +// node_modules/graphql/execution/values.js +var require_values = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getVariableValues = getVariableValues; + exports.getFragmentVariableValues = getFragmentVariableValues; + exports.getArgumentValues = getArgumentValues; + exports.getDirectiveValues = getDirectiveValues; + var invariant_ts_1 = require_invariant(); + var printPathArray_ts_1 = require_printPathArray(); + var ensureGraphQLError_ts_1 = require_ensureGraphQLError(); + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + var validate_ts_1 = require_validate(); + var coerceInputValue_ts_1 = require_coerceInputValue(); + var validateInputValue_ts_1 = require_validateInputValue(); + var getVariableSignature_ts_1 = require_getVariableSignature(); + function getVariableValues(schema, varDefNodes, inputs, options) { + const errors = []; + const maxErrors = options?.maxErrors; + try { + const variableValues = coerceVariableValues(schema, varDefNodes, inputs, (error) => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new GraphQLError_ts_1.GraphQLError("Too many errors processing variables, error limit reached. Execution aborted."); + } + errors.push(error); + }, options?.hideSuggestions); + if (errors.length === 0) { + return { variableValues }; + } + } catch (error) { + errors.push((0, ensureGraphQLError_ts_1.ensureGraphQLError)(error)); + } + return { errors }; + } + function coerceVariableValues(schema, varDefNodes, inputs, onError, hideSuggestions) { + const sources = Object.create(null); + const coerced = Object.create(null); + for (const varDefNode of varDefNodes) { + const varSignature = (0, getVariableSignature_ts_1.getVariableSignature)(schema, varDefNode); + if (varSignature instanceof GraphQLError_ts_1.GraphQLError) { + onError(varSignature); + continue; + } + const { name: varName, type: varType } = varSignature; + const value = Object.hasOwn(inputs, varName) ? inputs[varName] : undefined; + if (value === undefined) { + sources[varName] = { signature: varSignature }; + if (varDefNode.defaultValue) { + maybeUseDefaultValue(coerced, varName, varSignature, (error, path) => { + onError(new GraphQLError_ts_1.GraphQLError(`Variable "$${varName}" has invalid default value${(0, printPathArray_ts_1.printPathArray)(path)}: ${error.message}`, { nodes: varDefNode })); + }, hideSuggestions); + continue; + } else if (!(0, definition_ts_1.isNonNullType)(varType)) { + continue; + } + } else { + sources[varName] = { signature: varSignature, value }; + } + const coercedValue = (0, coerceInputValue_ts_1.coerceInputValue)(value, varType); + if (coercedValue !== undefined) { + coerced[varName] = coercedValue; + } else { + (0, validateInputValue_ts_1.validateInputValue)(value, varType, (error, path) => { + onError(new GraphQLError_ts_1.GraphQLError(`Variable "$${varName}" has invalid value${(0, printPathArray_ts_1.printPathArray)(path)}: ${error.message}`, { nodes: varDefNode, originalError: error })); + }, hideSuggestions); + } + } + return { sources, coerced }; + } + function maybeUseDefaultValue(coercedValues, name, inputValue, onError, hideSuggestions) { + try { + const coercedDefaultValue = (0, coerceInputValue_ts_1.coerceDefaultValue)(inputValue); + if (coercedDefaultValue !== undefined) { + coercedValues[name] = coercedDefaultValue; + } + } catch (error) { + const defaultInput = inputValue.default; + if (defaultInput === undefined) { + throw error; + } + let reportedValidationError = false; + (0, validate_ts_1.validateDefaultInput)(defaultInput, inputValue.type, (defaultError, path) => { + reportedValidationError = true; + onError(defaultError, path); + }, hideSuggestions); + if (!reportedValidationError) { + onError((0, ensureGraphQLError_ts_1.ensureGraphQLError)(error), []); + } + } + } + function getFragmentVariableValues(fragmentSpreadNode, fragmentSignatures, variableValues, fragmentVariableValues, hideSuggestions) { + const argumentNodes = fragmentSpreadNode.arguments ?? []; + const argNodeMap = new Map(argumentNodes.map((arg) => [arg.name.value, arg])); + const sources = Object.create(null); + const coerced = Object.create(null); + for (const [varName, varSignature] of Object.entries(fragmentSignatures)) { + const argumentNode = argNodeMap.get(varName); + if (argumentNode !== undefined) { + sources[varName] = fragmentVariableValues == null ? { signature: varSignature, value: argumentNode.value } : { + signature: varSignature, + value: argumentNode.value, + fragmentVariableValues + }; + } else { + sources[varName] = { + signature: varSignature + }; + } + coerceArgument(coerced, fragmentSpreadNode, varName, varSignature, argumentNode, variableValues, fragmentVariableValues, hideSuggestions); + } + return { sources, coerced }; + } + function getArgumentValues(def, node, variableValues, fragmentVariableValues, hideSuggestions) { + const coercedValues = Object.create(null); + const argumentNodes = node.arguments ?? []; + const argNodeMap = new Map(argumentNodes.map((arg) => [arg.name.value, arg])); + for (const argDef of def.args) { + const name = argDef.name; + coerceArgument(coercedValues, node, name, argDef, argNodeMap.get(argDef.name), variableValues, fragmentVariableValues, hideSuggestions); + } + return coercedValues; + } + function coerceArgument(coercedValues, node, argName, argDef, argumentNode, variableValues, fragmentVariableValues, hideSuggestions) { + const argType = argDef.type; + const onArgDefaultValueError = (error, path) => { + throw new GraphQLError_ts_1.GraphQLError(`${printArgumentOrFragmentVariable(argDef, node)} has invalid default value${(0, printPathArray_ts_1.printPathArray)(path)}: ${error.message}`, { nodes: node }); + }; + if (!argumentNode) { + if ((0, definition_ts_1.isRequiredArgument)(argDef)) { + throw new GraphQLError_ts_1.GraphQLError(`${printArgumentOrFragmentVariable(argDef, node)} of required type "${argType}" was not provided.`, { nodes: node }); + } + maybeUseDefaultValue(coercedValues, argName, argDef, onArgDefaultValueError, hideSuggestions); + return; + } + const valueNode = argumentNode.value; + if (valueNode.kind === kinds_ts_1.Kind.VARIABLE) { + const variableName = valueNode.name.value; + const scopedVariableValues = fragmentVariableValues?.sources[variableName] ? fragmentVariableValues : variableValues; + if ((scopedVariableValues == null || !Object.hasOwn(scopedVariableValues.coerced, variableName)) && !(0, definition_ts_1.isRequiredArgument)(argDef)) { + maybeUseDefaultValue(coercedValues, argName, argDef, onArgDefaultValueError, hideSuggestions); + return; + } + } + const coercedValue = (0, coerceInputValue_ts_1.coerceInputLiteral)(valueNode, argType, variableValues, fragmentVariableValues); + if (coercedValue === undefined) { + (0, validateInputValue_ts_1.validateInputLiteral)(valueNode, argType, (error, path) => { + error.message = `${printArgumentOrFragmentVariable(argDef, node)} has invalid value${(0, printPathArray_ts_1.printPathArray)(path)}: ${error.message}`; + throw error; + }, variableValues, fragmentVariableValues, hideSuggestions); + (0, invariant_ts_1.invariant)(false, "Invalid argument"); + } + coercedValues[argName] = coercedValue; + } + function printArgumentOrFragmentVariable(argDef, node) { + return (0, definition_ts_1.isArgument)(argDef) ? `Argument "${argDef}"` : `Variable "$${argDef.name}" defined by fragment "${node.name.value}"`; + } + function getDirectiveValues(directiveDef, node, variableValues, fragmentVariableValues, hideSuggestions) { + const directiveNode = node.directives?.find((directive) => directive.name.value === directiveDef.name); + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues, fragmentVariableValues, hideSuggestions); + } + } +}); + +// node_modules/graphql/execution/collectFields.js +var require_collectFields = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.collectFields = collectFields; + exports.collectSubfields = collectSubfields; + var AccumulatorMap_ts_1 = require_AccumulatorMap(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var typeFromAST_ts_1 = require_typeFromAST(); + var values_ts_1 = require_values(); + function collectFields(schema, fragments, variableValues, runtimeType, selectionSet, hideSuggestions, forbidSkipAndInclude = false) { + const groupedFieldSet = new AccumulatorMap_ts_1.AccumulatorMap; + const newDeferUsages = []; + const context = { + schema, + fragments, + variableValues, + runtimeType, + visitedFragmentNames: new Map, + hideSuggestions, + forbiddenDirectiveInstances: [], + forbidSkipAndInclude + }; + collectFieldsImpl(context, selectionSet, groupedFieldSet, newDeferUsages); + return { + groupedFieldSet, + newDeferUsages, + forbiddenDirectiveInstances: context.forbiddenDirectiveInstances + }; + } + function collectSubfields(schema, fragments, variableValues, returnType, fieldDetailsList, hideSuggestions) { + const context = { + schema, + fragments, + variableValues, + runtimeType: returnType, + visitedFragmentNames: new Map, + hideSuggestions, + forbiddenDirectiveInstances: [], + forbidSkipAndInclude: false + }; + const subGroupedFieldSet = new AccumulatorMap_ts_1.AccumulatorMap; + const newDeferUsages = []; + for (const fieldDetail of fieldDetailsList) { + const selectionSet = fieldDetail.node.selectionSet; + if (selectionSet) { + const { deferUsage, fragmentVariableValues } = fieldDetail; + collectFieldsImpl(context, selectionSet, subGroupedFieldSet, newDeferUsages, deferUsage, fragmentVariableValues); + } + } + return { + groupedFieldSet: subGroupedFieldSet, + newDeferUsages + }; + } + function collectFieldsImpl(context, selectionSet, groupedFieldSet, newDeferUsages, deferUsage, fragmentVariableValues) { + const { schema, fragments, variableValues, runtimeType, visitedFragmentNames, hideSuggestions } = context; + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case kinds_ts_1.Kind.FIELD: { + if (!shouldIncludeNode(context, selection, variableValues, fragmentVariableValues)) { + continue; + } + groupedFieldSet.add(getFieldEntryKey(selection), { + node: selection, + deferUsage, + fragmentVariableValues + }); + break; + } + case kinds_ts_1.Kind.INLINE_FRAGMENT: { + if (!shouldIncludeNode(context, selection, variableValues, fragmentVariableValues) || !doesFragmentConditionMatch(schema, selection, runtimeType)) { + continue; + } + const newDeferUsage = getDeferUsage(variableValues, fragmentVariableValues, selection, deferUsage); + if (!newDeferUsage) { + collectFieldsImpl(context, selection.selectionSet, groupedFieldSet, newDeferUsages, deferUsage, fragmentVariableValues); + } else { + newDeferUsages.push(newDeferUsage); + collectFieldsImpl(context, selection.selectionSet, groupedFieldSet, newDeferUsages, newDeferUsage, fragmentVariableValues); + } + break; + } + case kinds_ts_1.Kind.FRAGMENT_SPREAD: { + const fragName = selection.name.value; + if (!shouldIncludeNode(context, selection, variableValues, fragmentVariableValues)) { + continue; + } + const fragment = fragments[fragName]; + if (fragment == null || !doesFragmentConditionMatch(schema, fragment.definition, runtimeType)) { + continue; + } + const newDeferUsage = getDeferUsage(variableValues, fragmentVariableValues, selection, deferUsage); + const visitedAsDeferred = visitedFragmentNames.get(fragName); + let maybeNewDeferUsage; + if (!newDeferUsage) { + if (visitedAsDeferred === false) { + continue; + } + visitedFragmentNames.set(fragName, false); + maybeNewDeferUsage = deferUsage; + } else { + if (visitedAsDeferred !== undefined) { + continue; + } + visitedFragmentNames.set(fragName, true); + newDeferUsages.push(newDeferUsage); + maybeNewDeferUsage = newDeferUsage; + } + const fragmentVariableSignatures = fragment.variableSignatures; + let newFragmentVariableValues; + if (fragmentVariableSignatures) { + newFragmentVariableValues = (0, values_ts_1.getFragmentVariableValues)(selection, fragmentVariableSignatures, variableValues, fragmentVariableValues, hideSuggestions); + } + collectFieldsImpl(context, fragment.definition.selectionSet, groupedFieldSet, newDeferUsages, maybeNewDeferUsage, newFragmentVariableValues); + break; + } + } + } + } + function getDeferUsage(variableValues, fragmentVariableValues, node, parentDeferUsage) { + const defer = (0, values_ts_1.getDirectiveValues)(directives_ts_1.GraphQLDeferDirective, node, variableValues, fragmentVariableValues); + if (!defer) { + return; + } + if (defer.if === false) { + return; + } + return { + label: typeof defer.label === "string" ? defer.label : undefined, + parentDeferUsage + }; + } + function shouldIncludeNode(context, node, variableValues, fragmentVariableValues) { + const skipDirectiveNode = node.directives?.find((directive) => directive.name.value === directives_ts_1.GraphQLSkipDirective.name); + if (skipDirectiveNode && context.forbidSkipAndInclude) { + context.forbiddenDirectiveInstances.push(skipDirectiveNode); + return false; + } + const skip = skipDirectiveNode ? (0, values_ts_1.getArgumentValues)(directives_ts_1.GraphQLSkipDirective, skipDirectiveNode, variableValues, fragmentVariableValues, context.hideSuggestions) : undefined; + if (skip?.if === true) { + return false; + } + const includeDirectiveNode = node.directives?.find((directive) => directive.name.value === directives_ts_1.GraphQLIncludeDirective.name); + if (includeDirectiveNode && context.forbidSkipAndInclude) { + context.forbiddenDirectiveInstances.push(includeDirectiveNode); + return false; + } + const include = includeDirectiveNode ? (0, values_ts_1.getArgumentValues)(directives_ts_1.GraphQLIncludeDirective, includeDirectiveNode, variableValues, fragmentVariableValues, context.hideSuggestions) : undefined; + if (include?.if === false) { + return false; + } + return true; + } + function doesFragmentConditionMatch(schema, fragment, type) { + const typeConditionNode = fragment.typeCondition; + if (!typeConditionNode) { + return true; + } + const conditionalType = (0, typeFromAST_ts_1.typeFromAST)(schema, typeConditionNode); + if (conditionalType === type) { + return true; + } + if ((0, definition_ts_1.isAbstractType)(conditionalType)) { + return schema.isSubType(conditionalType, type); + } + return false; + } + function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; + } +}); + +// node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js +var require_SingleFieldSubscriptionsRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var collectFields_ts_1 = require_collectFields(); + function toNodes(fieldDetailsList) { + return fieldDetailsList.map((fieldDetails) => fieldDetails.node); + } + function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition(node) { + if (node.operation === "subscription") { + const schema = context.getSchema(); + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + const operationName = node.name ? node.name.value : null; + const variableValues = Object.create(null); + const document2 = context.getDocument(); + const fragments = Object.create(null); + for (const definition of document2.definitions) { + if (definition.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION) { + fragments[definition.name.value] = { definition }; + } + } + const { groupedFieldSet, forbiddenDirectiveInstances } = (0, collectFields_ts_1.collectFields)(schema, fragments, variableValues, subscriptionType, node.selectionSet, context.hideSuggestions, true); + if (forbiddenDirectiveInstances.length > 0) { + context.reportError(new GraphQLError_ts_1.GraphQLError(operationName != null ? `Subscription "${operationName}" must not use \`@skip\` or \`@include\` directives in the top level selection.` : "Anonymous Subscription must not use `@skip` or `@include` directives in the top level selection.", { nodes: forbiddenDirectiveInstances })); + return; + } + if (groupedFieldSet.size > 1) { + const fieldDetailsLists = [...groupedFieldSet.values()]; + const extraFieldDetailsLists = fieldDetailsLists.slice(1); + const extraFieldSelections = extraFieldDetailsLists.flatMap((fieldDetailsList) => toNodes(fieldDetailsList)); + context.reportError(new GraphQLError_ts_1.GraphQLError(operationName != null ? `Subscription "${operationName}" must select only one top level field.` : "Anonymous Subscription must select only one top level field.", { nodes: extraFieldSelections })); + } + for (const fieldDetailsList of groupedFieldSet.values()) { + const fieldName = toNodes(fieldDetailsList)[0].name.value; + if (fieldName.startsWith("__")) { + context.reportError(new GraphQLError_ts_1.GraphQLError(operationName != null ? `Subscription "${operationName}" must not select an introspection top level field.` : "Anonymous Subscription must not select an introspection top level field.", { nodes: toNodes(fieldDetailsList) })); + } + } + } + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/StreamDirectiveOnListFieldRule.js +var require_StreamDirectiveOnListFieldRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StreamDirectiveOnListFieldRule = StreamDirectiveOnListFieldRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + function StreamDirectiveOnListFieldRule(context) { + return { + Directive(node) { + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + if (fieldDef && parentType && node.name.value === directives_ts_1.GraphQLStreamDirective.name && !((0, definition_ts_1.isListType)(fieldDef.type) || (0, definition_ts_1.isWrappingType)(fieldDef.type) && (0, definition_ts_1.isListType)(fieldDef.type.ofType))) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Directive "@stream" cannot be used on non-list field "${parentType}.${fieldDef.name}".`, { nodes: node })); + } + } + }; + } +}); + +// node_modules/graphql/jsutils/groupBy.js +var require_groupBy = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.groupBy = groupBy; + var AccumulatorMap_ts_1 = require_AccumulatorMap(); + function groupBy(list, keyFn) { + const result = new AccumulatorMap_ts_1.AccumulatorMap; + for (const item of list) { + result.add(keyFn(item), item); + } + return result; + } +}); + +// node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.js +var require_UniqueArgumentDefinitionNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; + var groupBy_ts_1 = require_groupBy(); + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueArgumentDefinitionNamesRule(context) { + return { + DirectiveDefinition(directiveNode) { + const argumentNodes = directiveNode.arguments ?? []; + return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); + }, + InterfaceTypeDefinition: checkArgUniquenessPerField, + InterfaceTypeExtension: checkArgUniquenessPerField, + ObjectTypeDefinition: checkArgUniquenessPerField, + ObjectTypeExtension: checkArgUniquenessPerField + }; + function checkArgUniquenessPerField(typeNode) { + const typeName = typeNode.name.value; + const fieldNodes = typeNode.fields ?? []; + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + const argumentNodes = fieldDef.arguments ?? []; + checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); + } + return false; + } + function checkArgUniqueness(parentName, argumentNodes) { + const seenArgs = (0, groupBy_ts_1.groupBy)(argumentNodes, (arg) => arg.name.value); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Argument "${parentName}(${argName}:)" can only be defined once.`, { nodes: argNodes.map((node) => node.name) })); + } + } + return false; + } + } +}); + +// node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js +var require_UniqueArgumentNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; + var groupBy_ts_1 = require_groupBy(); + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueArgumentNamesRule(context) { + return { + Field: checkArgUniqueness, + Directive: checkArgUniqueness + }; + function checkArgUniqueness(parentNode) { + const argumentNodes = parentNode.arguments ?? []; + const seenArgs = (0, groupBy_ts_1.groupBy)(argumentNodes, (arg) => arg.name.value); + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one argument named "${argName}".`, { nodes: argNodes.map((node) => node.name) })); + } + } + } + } +}); + +// node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js +var require_UniqueDirectiveNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueDirectiveNamesRule(context) { + const knownDirectiveNames = new Map; + const schema = context.getSchema(); + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; + if (schema?.getDirective(directiveName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, { nodes: node.name })); + return; + } + const knownName = knownDirectiveNames.get(directiveName); + if (knownName) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one directive named "@${directiveName}".`, { nodes: [knownName, node.name] })); + } else { + knownDirectiveNames.set(directiveName, node.name); + } + return false; + } + }; + } +}); + +// node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js +var require_UniqueDirectivesPerLocationRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var predicates_ts_1 = require_predicates(); + var directives_ts_1 = require_directives(); + function UniqueDirectivesPerLocationRule(context) { + const uniqueDirectiveMap = new Map; + const schema = context.getSchema(); + const definedDirectives = schema ? schema.getDirectives() : directives_ts_1.specifiedDirectives; + for (const directive of definedDirectives) { + uniqueDirectiveMap.set(directive.name, !directive.isRepeatable); + } + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === kinds_ts_1.Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap.set(def.name.value, !def.repeatable); + } + } + const schemaDirectives = new Map; + const typeDirectivesMap = new Map; + const directiveDirectivesMap = new Map; + return { + enter(node) { + if (!("directives" in node) || !node.directives) { + return; + } + let seenDirectives; + if (node.kind === kinds_ts_1.Kind.SCHEMA_DEFINITION || node.kind === kinds_ts_1.Kind.SCHEMA_EXTENSION) { + seenDirectives = schemaDirectives; + } else if ((0, predicates_ts_1.isTypeDefinitionNode)(node) || (0, predicates_ts_1.isTypeExtensionNode)(node)) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap.get(typeName); + if (seenDirectives === undefined) { + seenDirectives = new Map; + typeDirectivesMap.set(typeName, seenDirectives); + } + } else if (node.kind === kinds_ts_1.Kind.DIRECTIVE_DEFINITION || node.kind === kinds_ts_1.Kind.DIRECTIVE_EXTENSION) { + const directiveName = node.name.value; + seenDirectives = directiveDirectivesMap.get(directiveName); + if (seenDirectives === undefined) { + seenDirectives = new Map; + directiveDirectivesMap.set(directiveName, seenDirectives); + } + } else { + seenDirectives = new Map; + } + for (const directive of node.directives) { + const directiveName = directive.name.value; + if (uniqueDirectiveMap.get(directiveName) === true) { + const seenDirective = seenDirectives.get(directiveName); + if (seenDirective != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`The directive "@${directiveName}" can only be used once at this location.`, { nodes: [seenDirective, directive] })); + } else { + seenDirectives.set(directiveName, directive); + } + } + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js +var require_UniqueEnumValueNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + function UniqueEnumValueNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownValueNames = new Map; + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness + }; + function checkValueUniqueness(node) { + const typeName = node.name.value; + let valueNames = knownValueNames.get(typeName); + if (valueNames == null) { + valueNames = new Map; + knownValueNames.set(typeName, valueNames); + } + const valueNodes = node.values ?? []; + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + const existingType = existingTypeMap[typeName]; + if ((0, definition_ts_1.isEnumType)(existingType) && existingType.getValue(valueName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, { nodes: valueDef.name })); + continue; + } + const knownValueName = valueNames.get(valueName); + if (knownValueName != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Enum value "${typeName}.${valueName}" can only be defined once.`, { nodes: [knownValueName, valueDef.name] })); + } else { + valueNames.set(valueName, valueDef.name); + } + } + return false; + } + } +}); + +// node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js +var require_UniqueFieldDefinitionNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + function UniqueFieldDefinitionNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownFieldNames = new Map; + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness + }; + function checkFieldUniqueness(node) { + const typeName = node.name.value; + let fieldNames = knownFieldNames.get(typeName); + if (fieldNames == null) { + fieldNames = new Map; + knownFieldNames.set(typeName, fieldNames); + } + const fieldNodes = node.fields ?? []; + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, { nodes: fieldDef.name })); + continue; + } + const knownFieldName = fieldNames.get(fieldName); + if (knownFieldName != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Field "${typeName}.${fieldName}" can only be defined once.`, { nodes: [knownFieldName, fieldDef.name] })); + } else { + fieldNames.set(fieldName, fieldDef.name); + } + } + return false; + } + } + function hasField(type, fieldName) { + if ((0, definition_ts_1.isObjectType)(type) || (0, definition_ts_1.isInterfaceType)(type) || (0, definition_ts_1.isInputObjectType)(type)) { + return type.getFields()[fieldName] != null; + } + return false; + } +}); + +// node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js +var require_UniqueFragmentNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueFragmentNamesRule(context) { + const knownFragmentNames = new Map; + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + const fragmentName = node.name.value; + const knownFragmentName = knownFragmentNames.get(fragmentName); + if (knownFragmentName != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one fragment named "${fragmentName}".`, { nodes: [knownFragmentName, node.name] })); + } else { + knownFragmentNames.set(fragmentName, node.name); + } + return false; + } + }; + } +}); + +// node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js +var require_UniqueInputFieldNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; + var invariant_ts_1 = require_invariant(); + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueInputFieldNamesRule(context) { + const knownNameStack = []; + let knownNames = new Map; + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = new Map; + }, + leave() { + const prevKnownNames = knownNameStack.pop(); + if (!(prevKnownNames != null)) + (0, invariant_ts_1.invariant)(false); + knownNames = prevKnownNames; + } + }, + ObjectField(node) { + const fieldName = node.name.value; + const knownName = knownNames.get(fieldName); + if (knownName != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one input field named "${fieldName}".`, { nodes: [knownName, node.name] })); + } else { + knownNames.set(fieldName, node.name); + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/UniqueOperationNamesRule.js +var require_UniqueOperationNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueOperationNamesRule = UniqueOperationNamesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueOperationNamesRule(context) { + const knownOperationNames = new Map; + return { + OperationDefinition(node) { + const operationName = node.name; + if (operationName != null) { + const knownOperationName = knownOperationNames.get(operationName.value); + if (knownOperationName != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one operation named "${operationName.value}".`, { nodes: [knownOperationName, operationName] })); + } else { + knownOperationNames.set(operationName.value, operationName); + } + } + return false; + }, + FragmentDefinition: () => false + }; + } +}); + +// node_modules/graphql/validation/rules/UniqueOperationTypesRule.js +var require_UniqueOperationTypesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueOperationTypesRule = UniqueOperationTypesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueOperationTypesRule(context) { + const schema = context.getSchema(); + const definedOperationTypes = new Map; + const existingOperationTypes = schema ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType() + } : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes + }; + function checkOperationTypes(node) { + const operationTypesNodes = node.operationTypes ?? []; + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = definedOperationTypes.get(operation); + if (existingOperationTypes[operation]) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Type for ${operation} already defined in the schema. It cannot be redefined.`, { nodes: operationType })); + } else if (alreadyDefinedOperationType) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one ${operation} type in schema.`, { nodes: [alreadyDefinedOperationType, operationType] })); + } else { + definedOperationTypes.set(operation, operationType); + } + } + return false; + } + } +}); + +// node_modules/graphql/validation/rules/UniqueTypeNamesRule.js +var require_UniqueTypeNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueTypeNamesRule = UniqueTypeNamesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueTypeNamesRule(context) { + const knownTypeNames = new Map; + const schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName + }; + function checkTypeName(node) { + const typeName = node.name.value; + if (schema?.getType(typeName)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, { nodes: node.name })); + return; + } + const knownNameNode = knownTypeNames.get(typeName); + if (knownNameNode != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one type named "${typeName}".`, { + nodes: [knownNameNode, node.name] + })); + } else { + knownTypeNames.set(typeName, node.name); + } + return false; + } + } +}); + +// node_modules/graphql/validation/rules/UniqueVariableNamesRule.js +var require_UniqueVariableNamesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UniqueVariableNamesRule = UniqueVariableNamesRule; + var groupBy_ts_1 = require_groupBy(); + var GraphQLError_ts_1 = require_GraphQLError(); + function UniqueVariableNamesRule(context) { + return { + OperationDefinition(operationNode) { + const variableDefinitions = operationNode.variableDefinitions ?? []; + const seenVariableDefinitions = (0, groupBy_ts_1.groupBy)(variableDefinitions, (node) => node.variable.name.value); + for (const [variableName, variableNodes] of seenVariableDefinitions) { + if (variableNodes.length > 1) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`There can be only one variable named "$${variableName}".`, { nodes: variableNodes.map((node) => node.variable.name) })); + } + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js +var require_ValuesOfCorrectTypeRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; + var validateInputValue_ts_1 = require_validateInputValue(); + function ValuesOfCorrectTypeRule(context) { + return { + NullValue: (node) => isValidValueNode(context, node, context.getInputType()), + ListValue: (node) => isValidValueNode(context, node, context.getParentInputType()), + ObjectValue: (node) => isValidValueNode(context, node, context.getInputType()), + EnumValue: (node) => isValidValueNode(context, node, context.getInputType()), + IntValue: (node) => isValidValueNode(context, node, context.getInputType()), + FloatValue: (node) => isValidValueNode(context, node, context.getInputType()), + StringValue: (node) => isValidValueNode(context, node, context.getInputType()), + BooleanValue: (node) => isValidValueNode(context, node, context.getInputType()) + }; + } + function isValidValueNode(context, node, inputType) { + if (inputType) { + (0, validateInputValue_ts_1.validateInputLiteral)(node, inputType, (error) => { + context.reportError(error); + }, undefined, undefined, context.hideSuggestions); + } + return false; + } +}); + +// node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js +var require_VariablesAreInputTypesRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var typeFromAST_ts_1 = require_typeFromAST(); + function VariablesAreInputTypesRule(context) { + return { + VariableDefinition(node) { + const type = (0, typeFromAST_ts_1.typeFromAST)(context.getSchema(), node.type); + if (type !== undefined && !(0, definition_ts_1.isInputType)(type)) { + const variableName = node.variable.name.value; + const typeName = (0, printer_ts_1.print)(node.type); + context.reportError(new GraphQLError_ts_1.GraphQLError(`Variable "$${variableName}" cannot be non-input type "${typeName}".`, { nodes: node.type })); + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js +var require_VariablesInAllowedPositionRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + var typeComparators_ts_1 = require_typeComparators(); + var typeFromAST_ts_1 = require_typeFromAST(); + function VariablesInAllowedPositionRule(context) { + let varDefMap; + return { + OperationDefinition: { + enter() { + varDefMap = new Map; + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + for (const { node, type, parentType, defaultValue, fragmentVariableDefinition } of usages) { + const varName = node.name.value; + let varDef = fragmentVariableDefinition; + varDef ??= varDefMap.get(varName); + if (varDef && type) { + const schema = context.getSchema(); + const varType = (0, typeFromAST_ts_1.typeFromAST)(schema, varDef.type); + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Variable "$${varName}" of type "${varType}" used in position expecting type "${type}".`, { nodes: [varDef, node] })); + } + if ((0, definition_ts_1.isInputObjectType)(parentType) && parentType.isOneOf && (0, definition_ts_1.isNullableType)(varType)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`Variable "$${varName}" is of type "${varType}" but must be non-nullable to be used for OneOf Input Object "${parentType}".`, { nodes: [varDef, node] })); + } + } + } + } + }, + VariableDefinition(node) { + varDefMap.set(node.variable.name.value, node); + } + }; + } + function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if ((0, definition_ts_1.isNonNullType)(locationType) && !(0, definition_ts_1.isNonNullType)(varType)) { + const hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== kinds_ts_1.Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + const nullableLocationType = locationType.ofType; + return (0, typeComparators_ts_1.isTypeSubTypeOf)(schema, varType, nullableLocationType); + } + return (0, typeComparators_ts_1.isTypeSubTypeOf)(schema, varType, locationType); + } +}); + +// node_modules/graphql/validation/specifiedRules.js +var require_specifiedRules = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.specifiedSDLRules = exports.specifiedRules = exports.recommendedRules = undefined; + var DeferStreamDirectiveLabelRule_ts_1 = require_DeferStreamDirectiveLabelRule(); + var DeferStreamDirectiveOnRootFieldRule_ts_1 = require_DeferStreamDirectiveOnRootFieldRule(); + var DeferStreamDirectiveOnValidOperationsRule_ts_1 = require_DeferStreamDirectiveOnValidOperationsRule(); + var ExecutableDefinitionsRule_ts_1 = require_ExecutableDefinitionsRule(); + var FieldsOnCorrectTypeRule_ts_1 = require_FieldsOnCorrectTypeRule(); + var FragmentsOnCompositeTypesRule_ts_1 = require_FragmentsOnCompositeTypesRule(); + var KnownArgumentNamesRule_ts_1 = require_KnownArgumentNamesRule(); + var KnownDirectivesRule_ts_1 = require_KnownDirectivesRule(); + var KnownFragmentNamesRule_ts_1 = require_KnownFragmentNamesRule(); + var KnownOperationTypesRule_ts_1 = require_KnownOperationTypesRule(); + var KnownTypeNamesRule_ts_1 = require_KnownTypeNamesRule(); + var LoneAnonymousOperationRule_ts_1 = require_LoneAnonymousOperationRule(); + var LoneSchemaDefinitionRule_ts_1 = require_LoneSchemaDefinitionRule(); + var MaxIntrospectionDepthRule_ts_1 = require_MaxIntrospectionDepthRule(); + var NoFragmentCyclesRule_ts_1 = require_NoFragmentCyclesRule(); + var NoUndefinedVariablesRule_ts_1 = require_NoUndefinedVariablesRule(); + var NoUnusedFragmentsRule_ts_1 = require_NoUnusedFragmentsRule(); + var NoUnusedVariablesRule_ts_1 = require_NoUnusedVariablesRule(); + var OverlappingFieldsCanBeMergedRule_ts_1 = require_OverlappingFieldsCanBeMergedRule(); + var PossibleFragmentSpreadsRule_ts_1 = require_PossibleFragmentSpreadsRule(); + var PossibleTypeExtensionsRule_ts_1 = require_PossibleTypeExtensionsRule(); + var ProvidedRequiredArgumentsRule_ts_1 = require_ProvidedRequiredArgumentsRule(); + var ScalarLeafsRule_ts_1 = require_ScalarLeafsRule(); + var SingleFieldSubscriptionsRule_ts_1 = require_SingleFieldSubscriptionsRule(); + var StreamDirectiveOnListFieldRule_ts_1 = require_StreamDirectiveOnListFieldRule(); + var UniqueArgumentDefinitionNamesRule_ts_1 = require_UniqueArgumentDefinitionNamesRule(); + var UniqueArgumentNamesRule_ts_1 = require_UniqueArgumentNamesRule(); + var UniqueDirectiveNamesRule_ts_1 = require_UniqueDirectiveNamesRule(); + var UniqueDirectivesPerLocationRule_ts_1 = require_UniqueDirectivesPerLocationRule(); + var UniqueEnumValueNamesRule_ts_1 = require_UniqueEnumValueNamesRule(); + var UniqueFieldDefinitionNamesRule_ts_1 = require_UniqueFieldDefinitionNamesRule(); + var UniqueFragmentNamesRule_ts_1 = require_UniqueFragmentNamesRule(); + var UniqueInputFieldNamesRule_ts_1 = require_UniqueInputFieldNamesRule(); + var UniqueOperationNamesRule_ts_1 = require_UniqueOperationNamesRule(); + var UniqueOperationTypesRule_ts_1 = require_UniqueOperationTypesRule(); + var UniqueTypeNamesRule_ts_1 = require_UniqueTypeNamesRule(); + var UniqueVariableNamesRule_ts_1 = require_UniqueVariableNamesRule(); + var ValuesOfCorrectTypeRule_ts_1 = require_ValuesOfCorrectTypeRule(); + var VariablesAreInputTypesRule_ts_1 = require_VariablesAreInputTypesRule(); + var VariablesInAllowedPositionRule_ts_1 = require_VariablesInAllowedPositionRule(); + exports.recommendedRules = Object.freeze([ + MaxIntrospectionDepthRule_ts_1.MaxIntrospectionDepthRule + ]); + exports.specifiedRules = Object.freeze([ + ExecutableDefinitionsRule_ts_1.ExecutableDefinitionsRule, + KnownOperationTypesRule_ts_1.KnownOperationTypesRule, + UniqueOperationNamesRule_ts_1.UniqueOperationNamesRule, + LoneAnonymousOperationRule_ts_1.LoneAnonymousOperationRule, + SingleFieldSubscriptionsRule_ts_1.SingleFieldSubscriptionsRule, + KnownTypeNamesRule_ts_1.KnownTypeNamesRule, + FragmentsOnCompositeTypesRule_ts_1.FragmentsOnCompositeTypesRule, + VariablesAreInputTypesRule_ts_1.VariablesAreInputTypesRule, + ScalarLeafsRule_ts_1.ScalarLeafsRule, + FieldsOnCorrectTypeRule_ts_1.FieldsOnCorrectTypeRule, + UniqueFragmentNamesRule_ts_1.UniqueFragmentNamesRule, + KnownFragmentNamesRule_ts_1.KnownFragmentNamesRule, + NoUnusedFragmentsRule_ts_1.NoUnusedFragmentsRule, + PossibleFragmentSpreadsRule_ts_1.PossibleFragmentSpreadsRule, + NoFragmentCyclesRule_ts_1.NoFragmentCyclesRule, + UniqueVariableNamesRule_ts_1.UniqueVariableNamesRule, + NoUndefinedVariablesRule_ts_1.NoUndefinedVariablesRule, + NoUnusedVariablesRule_ts_1.NoUnusedVariablesRule, + KnownDirectivesRule_ts_1.KnownDirectivesRule, + UniqueDirectivesPerLocationRule_ts_1.UniqueDirectivesPerLocationRule, + DeferStreamDirectiveOnRootFieldRule_ts_1.DeferStreamDirectiveOnRootFieldRule, + DeferStreamDirectiveOnValidOperationsRule_ts_1.DeferStreamDirectiveOnValidOperationsRule, + DeferStreamDirectiveLabelRule_ts_1.DeferStreamDirectiveLabelRule, + StreamDirectiveOnListFieldRule_ts_1.StreamDirectiveOnListFieldRule, + KnownArgumentNamesRule_ts_1.KnownArgumentNamesRule, + UniqueArgumentNamesRule_ts_1.UniqueArgumentNamesRule, + ValuesOfCorrectTypeRule_ts_1.ValuesOfCorrectTypeRule, + ProvidedRequiredArgumentsRule_ts_1.ProvidedRequiredArgumentsRule, + VariablesInAllowedPositionRule_ts_1.VariablesInAllowedPositionRule, + OverlappingFieldsCanBeMergedRule_ts_1.OverlappingFieldsCanBeMergedRule, + UniqueInputFieldNamesRule_ts_1.UniqueInputFieldNamesRule, + ...exports.recommendedRules + ]); + exports.specifiedSDLRules = Object.freeze([ + LoneSchemaDefinitionRule_ts_1.LoneSchemaDefinitionRule, + UniqueOperationTypesRule_ts_1.UniqueOperationTypesRule, + UniqueTypeNamesRule_ts_1.UniqueTypeNamesRule, + UniqueEnumValueNamesRule_ts_1.UniqueEnumValueNamesRule, + UniqueFieldDefinitionNamesRule_ts_1.UniqueFieldDefinitionNamesRule, + UniqueArgumentDefinitionNamesRule_ts_1.UniqueArgumentDefinitionNamesRule, + UniqueDirectiveNamesRule_ts_1.UniqueDirectiveNamesRule, + KnownTypeNamesRule_ts_1.KnownTypeNamesRule, + KnownDirectivesRule_ts_1.KnownDirectivesRule, + UniqueDirectivesPerLocationRule_ts_1.UniqueDirectivesPerLocationRule, + PossibleTypeExtensionsRule_ts_1.PossibleTypeExtensionsRule, + KnownArgumentNamesRule_ts_1.KnownArgumentNamesOnDirectivesRule, + UniqueArgumentNamesRule_ts_1.UniqueArgumentNamesRule, + UniqueInputFieldNamesRule_ts_1.UniqueInputFieldNamesRule, + ProvidedRequiredArgumentsRule_ts_1.ProvidedRequiredArgumentsOnDirectivesRule + ]); +}); + +// node_modules/graphql/validation/ValidationContext.js +var require_ValidationContext = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = undefined; + var kinds_ts_1 = require_kinds(); + var visitor_ts_1 = require_visitor(); + var TypeInfo_ts_1 = require_TypeInfo(); + + class ASTValidationContext { + constructor(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map; + this._recursivelyReferencedFragments = new Map; + this._onError = onError; + } + get [Symbol.toStringTag]() { + return "ASTValidationContext"; + } + reportError(error) { + this._onError(error); + } + getDocument() { + return this._ast; + } + getFragment(name) { + let fragments; + if (this._fragments) { + fragments = this._fragments; + } else { + fragments = Object.create(null); + for (const defNode of this.getDocument().definitions) { + if (defNode.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION) { + fragments[defNode.name.value] = defNode; + } + } + this._fragments = fragments; + } + return fragments[name]; + } + getFragmentSpreads(node) { + let spreads = this._fragmentSpreads.get(node); + if (!spreads) { + spreads = []; + const setsToVisit = [node]; + let set; + while (set = setsToVisit.pop()) { + for (const selection of set.selections) { + if (selection.kind === kinds_ts_1.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); + } + return spreads; + } + getRecursivelyReferencedFragments(operation) { + let fragments = this._recursivelyReferencedFragments.get(operation); + if (!fragments) { + fragments = []; + const collectedNames = new Set; + const nodesToVisit = [operation.selectionSet]; + let node; + while (node = nodesToVisit.pop()) { + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + if (!collectedNames.has(fragName)) { + collectedNames.add(fragName); + const fragment = this.getFragment(fragName); + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + this._recursivelyReferencedFragments.set(operation, fragments); + } + return fragments; + } + } + exports.ASTValidationContext = ASTValidationContext; + + class SDLValidationContext extends ASTValidationContext { + constructor(ast, schema, onError) { + super(ast, onError); + this._schema = schema; + } + get hideSuggestions() { + return false; + } + get [Symbol.toStringTag]() { + return "SDLValidationContext"; + } + getSchema() { + return this._schema; + } + } + exports.SDLValidationContext = SDLValidationContext; + + class ValidationContext extends ASTValidationContext { + constructor(schema, ast, typeInfo, onError, hideSuggestions) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map; + this._recursiveVariableUsages = new Map; + this._hideSuggestions = hideSuggestions ?? false; + } + get [Symbol.toStringTag]() { + return "ValidationContext"; + } + get hideSuggestions() { + return this._hideSuggestions; + } + getSchema() { + return this._schema; + } + getVariableUsages(node) { + let usages = this._variableUsages.get(node); + if (!usages) { + const newUsages = []; + const typeInfo = new TypeInfo_ts_1.TypeInfo(this._schema, undefined, this._typeInfo.getFragmentSignatureByName()); + const fragmentDefinition = node.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION ? node : undefined; + (0, visitor_ts_1.visit)(node, (0, TypeInfo_ts_1.visitWithTypeInfo)(typeInfo, { + VariableDefinition: () => false, + Variable(variable) { + let fragmentVariableDefinition; + if (fragmentDefinition) { + const fragmentSignature = typeInfo.getFragmentSignatureByName()(fragmentDefinition.name.value); + fragmentVariableDefinition = fragmentSignature?.variableDefinitions.get(variable.name.value); + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + parentType: typeInfo.getParentInputType(), + defaultValue: undefined, + fragmentVariableDefinition + }); + } else { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + parentType: typeInfo.getParentInputType(), + defaultValue: typeInfo.getDefaultValue(), + fragmentVariableDefinition: undefined + }); + } + } + })); + usages = newUsages; + this._variableUsages.set(node, usages); + } + return usages; + } + getRecursiveVariableUsages(operation) { + let usages = this._recursiveVariableUsages.get(operation); + if (!usages) { + usages = this.getVariableUsages(operation); + for (const frag of this.getRecursivelyReferencedFragments(operation)) { + usages = usages.concat(this.getVariableUsages(frag)); + } + this._recursiveVariableUsages.set(operation, usages); + } + return usages; + } + getType() { + return this._typeInfo.getType(); + } + getParentType() { + return this._typeInfo.getParentType(); + } + getInputType() { + return this._typeInfo.getInputType(); + } + getParentInputType() { + return this._typeInfo.getParentInputType(); + } + getFieldDef() { + return this._typeInfo.getFieldDef(); + } + getDirective() { + return this._typeInfo.getDirective(); + } + getArgument() { + return this._typeInfo.getArgument(); + } + getFragmentSignature() { + return this._typeInfo.getFragmentSignature(); + } + getFragmentSignatureByName() { + return this._typeInfo.getFragmentSignatureByName(); + } + getEnumValue() { + return this._typeInfo.getEnumValue(); + } + } + exports.ValidationContext = ValidationContext; +}); + +// node_modules/graphql/validation/validate.js +var require_validate2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validate = validate; + exports.validateSDL = validateSDL; + exports.assertValidSDL = assertValidSDL; + exports.assertValidSDLExtension = assertValidSDLExtension; + var mapValue_ts_1 = require_mapValue(); + var GraphQLError_ts_1 = require_GraphQLError(); + var ast_ts_1 = require_ast(); + var visitor_ts_1 = require_visitor(); + var validate_ts_1 = require_validate(); + var TypeInfo_ts_1 = require_TypeInfo(); + var diagnostics_ts_1 = require_diagnostics(); + var specifiedRules_ts_1 = require_specifiedRules(); + var ValidationContext_ts_1 = require_ValidationContext(); + var QueryDocumentKeysToValidate = (0, mapValue_ts_1.mapValue)(ast_ts_1.QueryDocumentKeys, (keys) => keys.filter((key) => key !== "description")); + var tooManyValidationErrorsError = new GraphQLError_ts_1.GraphQLError("Too many validation errors, error limit reached. Validation aborted."); + function validate(schema, documentAST, rules = specifiedRules_ts_1.specifiedRules, options) { + return (0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.validateChannel) ? diagnostics_ts_1.validateChannel.traceSync(() => validateImpl(schema, documentAST, rules, options), { schema, document: documentAST }) : validateImpl(schema, documentAST, rules, options); + } + function validateImpl(schema, documentAST, rules, options) { + const maxErrors = options?.maxErrors ?? 100; + const hideSuggestions = options?.hideSuggestions ?? false; + (0, validate_ts_1.assertValidSchema)(schema); + const errors = []; + const typeInfo = new TypeInfo_ts_1.TypeInfo(schema); + const context = new ValidationContext_ts_1.ValidationContext(schema, documentAST, typeInfo, (error) => { + if (errors.length >= maxErrors) { + throw tooManyValidationErrorsError; + } + errors.push(error); + }, hideSuggestions); + const visitor = (0, visitor_ts_1.visitInParallel)(rules.map((rule) => rule(context))); + try { + (0, visitor_ts_1.visit)(documentAST, (0, TypeInfo_ts_1.visitWithTypeInfo)(typeInfo, visitor), QueryDocumentKeysToValidate); + } catch (e) { + if (e === tooManyValidationErrorsError) { + errors.push(tooManyValidationErrorsError); + } else { + throw e; + } + } + return errors; + } + function validateSDL(documentAST, schemaToExtend, rules = specifiedRules_ts_1.specifiedSDLRules) { + const errors = []; + const context = new ValidationContext_ts_1.SDLValidationContext(documentAST, schemaToExtend, (error) => { + errors.push(error); + }); + const visitors = rules.map((rule) => rule(context)); + (0, visitor_ts_1.visit)(documentAST, (0, visitor_ts_1.visitInParallel)(visitors)); + return errors; + } + function assertValidSDL(documentAST) { + const errors = validateSDL(documentAST); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join(` + +`)); + } + } + function assertValidSDLExtension(documentAST, schema) { + const errors = validateSDL(documentAST, schema); + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join(` + +`)); + } + } +}); + +// node_modules/graphql/jsutils/isAsyncIterable.js +var require_isAsyncIterable = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isAsyncIterable = isAsyncIterable; + function isAsyncIterable(maybeAsyncIterable) { + return typeof maybeAsyncIterable?.[Symbol.asyncIterator] === "function"; + } +}); + +// node_modules/graphql/error/locatedError.js +var require_locatedError = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.locatedError = locatedError; + var toError_ts_1 = require_toError(); + var GraphQLError_ts_1 = require_GraphQLError(); + function locatedError(rawOriginalError, nodes, path) { + const originalError = (0, toError_ts_1.toError)(rawOriginalError); + if (isLocatedGraphQLError(originalError)) { + return originalError; + } + return new GraphQLError_ts_1.GraphQLError(originalError.message, { + nodes: originalError.nodes ?? nodes, + source: originalError.source, + positions: originalError.positions, + path, + originalError + }); + } + function isLocatedGraphQLError(error) { + return Array.isArray(error.path); + } +}); + +// node_modules/graphql/type/index.js +var require_type = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getNullableType = exports.assertNamedType = exports.assertNullableType = exports.assertWrappingType = exports.assertAbstractType = exports.assertCompositeType = exports.assertLeafType = exports.assertOutputType = exports.assertInputType = exports.assertNonNullType = exports.assertListType = exports.assertInputField = exports.assertInputObjectType = exports.assertEnumValue = exports.assertEnumType = exports.assertUnionType = exports.assertInterfaceType = exports.assertArgument = exports.assertField = exports.assertObjectType = exports.assertScalarType = exports.assertType = exports.isRequiredInputField = exports.isRequiredArgument = exports.isNamedType = exports.isNullableType = exports.isWrappingType = exports.isAbstractType = exports.isCompositeType = exports.isLeafType = exports.isOutputType = exports.isInputField = exports.isInputType = exports.isNonNullType = exports.isListType = exports.isInputObjectType = exports.isEnumValue = exports.isEnumType = exports.isUnionType = exports.isInterfaceType = exports.isArgument = exports.isField = exports.isObjectType = exports.isScalarType = exports.isType = exports.resolveReadonlyArrayThunk = exports.resolveObjMapThunk = exports.GraphQLSchema = exports.assertSchema = exports.isSchema = undefined; + exports.assertEnumValueName = exports.assertName = exports.assertValidSchema = exports.validateSchema = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.TypeKind = exports.__TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = exports.introspectionTypes = exports.isIntrospectionType = exports.GRAPHQL_MIN_INT = exports.GRAPHQL_MAX_INT = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = exports.specifiedScalarTypes = exports.isSpecifiedScalarType = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLOneOfDirective = exports.GraphQLSpecifiedByDirective = exports.GraphQLDeprecatedDirective = exports.GraphQLStreamDirective = exports.GraphQLDeferDirective = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.specifiedDirectives = exports.isSpecifiedDirective = exports.GraphQLDirective = exports.assertDirective = exports.isDirective = exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = exports.getNamedType = undefined; + var schema_ts_1 = require_schema(); + Object.defineProperty(exports, "isSchema", { enumerable: true, get: function() { + return schema_ts_1.isSchema; + } }); + Object.defineProperty(exports, "assertSchema", { enumerable: true, get: function() { + return schema_ts_1.assertSchema; + } }); + Object.defineProperty(exports, "GraphQLSchema", { enumerable: true, get: function() { + return schema_ts_1.GraphQLSchema; + } }); + var definition_ts_1 = require_definition(); + Object.defineProperty(exports, "resolveObjMapThunk", { enumerable: true, get: function() { + return definition_ts_1.resolveObjMapThunk; + } }); + Object.defineProperty(exports, "resolveReadonlyArrayThunk", { enumerable: true, get: function() { + return definition_ts_1.resolveReadonlyArrayThunk; + } }); + Object.defineProperty(exports, "isType", { enumerable: true, get: function() { + return definition_ts_1.isType; + } }); + Object.defineProperty(exports, "isScalarType", { enumerable: true, get: function() { + return definition_ts_1.isScalarType; + } }); + Object.defineProperty(exports, "isObjectType", { enumerable: true, get: function() { + return definition_ts_1.isObjectType; + } }); + Object.defineProperty(exports, "isField", { enumerable: true, get: function() { + return definition_ts_1.isField; + } }); + Object.defineProperty(exports, "isArgument", { enumerable: true, get: function() { + return definition_ts_1.isArgument; + } }); + Object.defineProperty(exports, "isInterfaceType", { enumerable: true, get: function() { + return definition_ts_1.isInterfaceType; + } }); + Object.defineProperty(exports, "isUnionType", { enumerable: true, get: function() { + return definition_ts_1.isUnionType; + } }); + Object.defineProperty(exports, "isEnumType", { enumerable: true, get: function() { + return definition_ts_1.isEnumType; + } }); + Object.defineProperty(exports, "isEnumValue", { enumerable: true, get: function() { + return definition_ts_1.isEnumValue; + } }); + Object.defineProperty(exports, "isInputObjectType", { enumerable: true, get: function() { + return definition_ts_1.isInputObjectType; + } }); + Object.defineProperty(exports, "isListType", { enumerable: true, get: function() { + return definition_ts_1.isListType; + } }); + Object.defineProperty(exports, "isNonNullType", { enumerable: true, get: function() { + return definition_ts_1.isNonNullType; + } }); + Object.defineProperty(exports, "isInputType", { enumerable: true, get: function() { + return definition_ts_1.isInputType; + } }); + Object.defineProperty(exports, "isInputField", { enumerable: true, get: function() { + return definition_ts_1.isInputField; + } }); + Object.defineProperty(exports, "isOutputType", { enumerable: true, get: function() { + return definition_ts_1.isOutputType; + } }); + Object.defineProperty(exports, "isLeafType", { enumerable: true, get: function() { + return definition_ts_1.isLeafType; + } }); + Object.defineProperty(exports, "isCompositeType", { enumerable: true, get: function() { + return definition_ts_1.isCompositeType; + } }); + Object.defineProperty(exports, "isAbstractType", { enumerable: true, get: function() { + return definition_ts_1.isAbstractType; + } }); + Object.defineProperty(exports, "isWrappingType", { enumerable: true, get: function() { + return definition_ts_1.isWrappingType; + } }); + Object.defineProperty(exports, "isNullableType", { enumerable: true, get: function() { + return definition_ts_1.isNullableType; + } }); + Object.defineProperty(exports, "isNamedType", { enumerable: true, get: function() { + return definition_ts_1.isNamedType; + } }); + Object.defineProperty(exports, "isRequiredArgument", { enumerable: true, get: function() { + return definition_ts_1.isRequiredArgument; + } }); + Object.defineProperty(exports, "isRequiredInputField", { enumerable: true, get: function() { + return definition_ts_1.isRequiredInputField; + } }); + Object.defineProperty(exports, "assertType", { enumerable: true, get: function() { + return definition_ts_1.assertType; + } }); + Object.defineProperty(exports, "assertScalarType", { enumerable: true, get: function() { + return definition_ts_1.assertScalarType; + } }); + Object.defineProperty(exports, "assertObjectType", { enumerable: true, get: function() { + return definition_ts_1.assertObjectType; + } }); + Object.defineProperty(exports, "assertField", { enumerable: true, get: function() { + return definition_ts_1.assertField; + } }); + Object.defineProperty(exports, "assertArgument", { enumerable: true, get: function() { + return definition_ts_1.assertArgument; + } }); + Object.defineProperty(exports, "assertInterfaceType", { enumerable: true, get: function() { + return definition_ts_1.assertInterfaceType; + } }); + Object.defineProperty(exports, "assertUnionType", { enumerable: true, get: function() { + return definition_ts_1.assertUnionType; + } }); + Object.defineProperty(exports, "assertEnumType", { enumerable: true, get: function() { + return definition_ts_1.assertEnumType; + } }); + Object.defineProperty(exports, "assertEnumValue", { enumerable: true, get: function() { + return definition_ts_1.assertEnumValue; + } }); + Object.defineProperty(exports, "assertInputObjectType", { enumerable: true, get: function() { + return definition_ts_1.assertInputObjectType; + } }); + Object.defineProperty(exports, "assertInputField", { enumerable: true, get: function() { + return definition_ts_1.assertInputField; + } }); + Object.defineProperty(exports, "assertListType", { enumerable: true, get: function() { + return definition_ts_1.assertListType; + } }); + Object.defineProperty(exports, "assertNonNullType", { enumerable: true, get: function() { + return definition_ts_1.assertNonNullType; + } }); + Object.defineProperty(exports, "assertInputType", { enumerable: true, get: function() { + return definition_ts_1.assertInputType; + } }); + Object.defineProperty(exports, "assertOutputType", { enumerable: true, get: function() { + return definition_ts_1.assertOutputType; + } }); + Object.defineProperty(exports, "assertLeafType", { enumerable: true, get: function() { + return definition_ts_1.assertLeafType; + } }); + Object.defineProperty(exports, "assertCompositeType", { enumerable: true, get: function() { + return definition_ts_1.assertCompositeType; + } }); + Object.defineProperty(exports, "assertAbstractType", { enumerable: true, get: function() { + return definition_ts_1.assertAbstractType; + } }); + Object.defineProperty(exports, "assertWrappingType", { enumerable: true, get: function() { + return definition_ts_1.assertWrappingType; + } }); + Object.defineProperty(exports, "assertNullableType", { enumerable: true, get: function() { + return definition_ts_1.assertNullableType; + } }); + Object.defineProperty(exports, "assertNamedType", { enumerable: true, get: function() { + return definition_ts_1.assertNamedType; + } }); + Object.defineProperty(exports, "getNullableType", { enumerable: true, get: function() { + return definition_ts_1.getNullableType; + } }); + Object.defineProperty(exports, "getNamedType", { enumerable: true, get: function() { + return definition_ts_1.getNamedType; + } }); + Object.defineProperty(exports, "GraphQLScalarType", { enumerable: true, get: function() { + return definition_ts_1.GraphQLScalarType; + } }); + Object.defineProperty(exports, "GraphQLObjectType", { enumerable: true, get: function() { + return definition_ts_1.GraphQLObjectType; + } }); + Object.defineProperty(exports, "GraphQLInterfaceType", { enumerable: true, get: function() { + return definition_ts_1.GraphQLInterfaceType; + } }); + Object.defineProperty(exports, "GraphQLUnionType", { enumerable: true, get: function() { + return definition_ts_1.GraphQLUnionType; + } }); + Object.defineProperty(exports, "GraphQLEnumType", { enumerable: true, get: function() { + return definition_ts_1.GraphQLEnumType; + } }); + Object.defineProperty(exports, "GraphQLInputObjectType", { enumerable: true, get: function() { + return definition_ts_1.GraphQLInputObjectType; + } }); + Object.defineProperty(exports, "GraphQLList", { enumerable: true, get: function() { + return definition_ts_1.GraphQLList; + } }); + Object.defineProperty(exports, "GraphQLNonNull", { enumerable: true, get: function() { + return definition_ts_1.GraphQLNonNull; + } }); + var directives_ts_1 = require_directives(); + Object.defineProperty(exports, "isDirective", { enumerable: true, get: function() { + return directives_ts_1.isDirective; + } }); + Object.defineProperty(exports, "assertDirective", { enumerable: true, get: function() { + return directives_ts_1.assertDirective; + } }); + Object.defineProperty(exports, "GraphQLDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLDirective; + } }); + Object.defineProperty(exports, "isSpecifiedDirective", { enumerable: true, get: function() { + return directives_ts_1.isSpecifiedDirective; + } }); + Object.defineProperty(exports, "specifiedDirectives", { enumerable: true, get: function() { + return directives_ts_1.specifiedDirectives; + } }); + Object.defineProperty(exports, "GraphQLIncludeDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLIncludeDirective; + } }); + Object.defineProperty(exports, "GraphQLSkipDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLSkipDirective; + } }); + Object.defineProperty(exports, "GraphQLDeferDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLDeferDirective; + } }); + Object.defineProperty(exports, "GraphQLStreamDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLStreamDirective; + } }); + Object.defineProperty(exports, "GraphQLDeprecatedDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLDeprecatedDirective; + } }); + Object.defineProperty(exports, "GraphQLSpecifiedByDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLSpecifiedByDirective; + } }); + Object.defineProperty(exports, "GraphQLOneOfDirective", { enumerable: true, get: function() { + return directives_ts_1.GraphQLOneOfDirective; + } }); + Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { enumerable: true, get: function() { + return directives_ts_1.DEFAULT_DEPRECATION_REASON; + } }); + var scalars_ts_1 = require_scalars(); + Object.defineProperty(exports, "isSpecifiedScalarType", { enumerable: true, get: function() { + return scalars_ts_1.isSpecifiedScalarType; + } }); + Object.defineProperty(exports, "specifiedScalarTypes", { enumerable: true, get: function() { + return scalars_ts_1.specifiedScalarTypes; + } }); + Object.defineProperty(exports, "GraphQLInt", { enumerable: true, get: function() { + return scalars_ts_1.GraphQLInt; + } }); + Object.defineProperty(exports, "GraphQLFloat", { enumerable: true, get: function() { + return scalars_ts_1.GraphQLFloat; + } }); + Object.defineProperty(exports, "GraphQLString", { enumerable: true, get: function() { + return scalars_ts_1.GraphQLString; + } }); + Object.defineProperty(exports, "GraphQLBoolean", { enumerable: true, get: function() { + return scalars_ts_1.GraphQLBoolean; + } }); + Object.defineProperty(exports, "GraphQLID", { enumerable: true, get: function() { + return scalars_ts_1.GraphQLID; + } }); + Object.defineProperty(exports, "GRAPHQL_MAX_INT", { enumerable: true, get: function() { + return scalars_ts_1.GRAPHQL_MAX_INT; + } }); + Object.defineProperty(exports, "GRAPHQL_MIN_INT", { enumerable: true, get: function() { + return scalars_ts_1.GRAPHQL_MIN_INT; + } }); + var introspection_ts_1 = require_introspection(); + Object.defineProperty(exports, "isIntrospectionType", { enumerable: true, get: function() { + return introspection_ts_1.isIntrospectionType; + } }); + Object.defineProperty(exports, "introspectionTypes", { enumerable: true, get: function() { + return introspection_ts_1.introspectionTypes; + } }); + Object.defineProperty(exports, "__Schema", { enumerable: true, get: function() { + return introspection_ts_1.__Schema; + } }); + Object.defineProperty(exports, "__Directive", { enumerable: true, get: function() { + return introspection_ts_1.__Directive; + } }); + Object.defineProperty(exports, "__DirectiveLocation", { enumerable: true, get: function() { + return introspection_ts_1.__DirectiveLocation; + } }); + Object.defineProperty(exports, "__Type", { enumerable: true, get: function() { + return introspection_ts_1.__Type; + } }); + Object.defineProperty(exports, "__Field", { enumerable: true, get: function() { + return introspection_ts_1.__Field; + } }); + Object.defineProperty(exports, "__InputValue", { enumerable: true, get: function() { + return introspection_ts_1.__InputValue; + } }); + Object.defineProperty(exports, "__EnumValue", { enumerable: true, get: function() { + return introspection_ts_1.__EnumValue; + } }); + Object.defineProperty(exports, "__TypeKind", { enumerable: true, get: function() { + return introspection_ts_1.__TypeKind; + } }); + Object.defineProperty(exports, "TypeKind", { enumerable: true, get: function() { + return introspection_ts_1.TypeKind; + } }); + Object.defineProperty(exports, "SchemaMetaFieldDef", { enumerable: true, get: function() { + return introspection_ts_1.SchemaMetaFieldDef; + } }); + Object.defineProperty(exports, "TypeMetaFieldDef", { enumerable: true, get: function() { + return introspection_ts_1.TypeMetaFieldDef; + } }); + Object.defineProperty(exports, "TypeNameMetaFieldDef", { enumerable: true, get: function() { + return introspection_ts_1.TypeNameMetaFieldDef; + } }); + var validate_ts_1 = require_validate(); + Object.defineProperty(exports, "validateSchema", { enumerable: true, get: function() { + return validate_ts_1.validateSchema; + } }); + Object.defineProperty(exports, "assertValidSchema", { enumerable: true, get: function() { + return validate_ts_1.assertValidSchema; + } }); + var assertName_ts_1 = require_assertName(); + Object.defineProperty(exports, "assertName", { enumerable: true, get: function() { + return assertName_ts_1.assertName; + } }); + Object.defineProperty(exports, "assertEnumValueName", { enumerable: true, get: function() { + return assertName_ts_1.assertEnumValueName; + } }); +}); + +// node_modules/graphql/utilities/getOperationAST.js +var require_getOperationAST = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getOperationAST = getOperationAST; + var kinds_ts_1 = require_kinds(); + function getOperationAST(documentAST, operationName) { + let operation = null; + for (const definition of documentAST.definitions) { + if (definition.kind === kinds_ts_1.Kind.OPERATION_DEFINITION) { + if (operationName == null) { + if (operation) { + return null; + } + operation = definition; + } else if (definition.name?.value === operationName) { + return definition; + } + } + } + return operation; + } +}); + +// node_modules/graphql/execution/buildResolveInfo.js +var require_buildResolveInfo = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildResolveInfo = buildResolveInfo; + function buildResolveInfo(validatedExecutionArgs, fieldDef, fieldNodes, parentType, path, getAbortSignal, getAsyncHelpers) { + const { schema, fragmentDefinitions, rootValue, operation, variableValues } = validatedExecutionArgs; + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema, + fragments: fragmentDefinitions, + rootValue, + operation, + variableValues, + getAbortSignal, + getAsyncHelpers + }; + } +}); + +// node_modules/graphql/jsutils/promiseWithResolvers.js +var require_promiseWithResolvers = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.promiseWithResolvers = promiseWithResolvers; + function promiseWithResolvers() { + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; + } +}); + +// node_modules/graphql/execution/cancellablePromise.js +var require_cancellablePromise = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.withCancellation = withCancellation; + exports.cancellablePromise = cancellablePromise; + var promiseWithResolvers_ts_1 = require_promiseWithResolvers(); + function withCancellation(originalPromise) { + const { promise, resolve, reject } = (0, promiseWithResolvers_ts_1.promiseWithResolvers)(); + let settled = false; + const settleResolve = (value) => { + if (settled) { + return; + } + settled = true; + resolve(value); + }; + const settleReject = (error) => { + if (settled) { + return; + } + settled = true; + reject(error); + }; + originalPromise.then(settleResolve, settleReject); + return { + promise, + abort(reason) { + settleReject(reason); + } + }; + } + function cancellablePromise(promise, abortSignal) { + const withAbort = withCancellation(promise); + if (abortSignal.aborted) { + withAbort.abort(abortSignal.reason); + return withAbort.promise; + } + const onAbort = () => { + abortSignal.removeEventListener("abort", onAbort); + withAbort.abort(abortSignal.reason); + }; + abortSignal.addEventListener("abort", onAbort); + withAbort.promise.then(() => { + abortSignal.removeEventListener("abort", onAbort); + }, () => { + abortSignal.removeEventListener("abort", onAbort); + }); + return withAbort.promise; + } +}); + +// node_modules/graphql/execution/AsyncWorkTracker.js +var require_AsyncWorkTracker = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncWorkTracker = undefined; + var isPromise_ts_1 = require_isPromise(); + + class AsyncWorkTracker { + constructor() { + this.pendingAsyncWork = new Set; + } + add(promiseLike) { + const pendingAsyncWork = this.pendingAsyncWork; + const promiseToSettle = promiseLike.then(() => { + pendingAsyncWork.delete(promiseToSettle); + }, () => { + pendingAsyncWork.delete(promiseToSettle); + }); + pendingAsyncWork.add(promiseToSettle); + } + addValues(values) { + for (const value of values) { + if ((0, isPromise_ts_1.isPromiseLike)(value)) { + this.add(value); + } + } + } + wait() { + if (this.pendingAsyncWork.size === 0) { + return; + } + return this.waitForPendingAsyncWork(); + } + promiseAllTrackOnReject(values) { + const promise = Promise.all(values); + promise.then(undefined, () => { + this.addValues(values); + }); + return promise; + } + async waitForPendingAsyncWork() { + while (this.pendingAsyncWork.size > 0) { + await Promise.allSettled(Array.from(this.pendingAsyncWork)); + } + } + } + exports.AsyncWorkTracker = AsyncWorkTracker; +}); + +// node_modules/graphql/execution/createSharedExecutionContext.js +var require_createSharedExecutionContext = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createSharedExecutionContext = createSharedExecutionContext; + var AsyncWorkTracker_ts_1 = require_AsyncWorkTracker(); + function createSharedExecutionContext(abortSignal) { + const asyncWorkTracker = new AsyncWorkTracker_ts_1.AsyncWorkTracker; + let resolveInfoHelpers; + const promiseAll = (values) => asyncWorkTracker.promiseAllTrackOnReject(values); + const getAsyncHelpers = () => resolveInfoHelpers ??= { + promiseAll, + track: (maybePromises) => asyncWorkTracker.addValues(maybePromises) + }; + return { + asyncWorkTracker, + getAbortSignal: () => abortSignal, + getAsyncHelpers, + promiseAll + }; + } +}); + +// node_modules/graphql/jsutils/memoize2.js +var require_memoize2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.memoize2 = memoize2; + function memoize2(fn) { + let cache0; + return function memoized(a1, a2) { + cache0 ??= new WeakMap; + let cache1 = cache0.get(a1); + if (cache1 === undefined) { + cache1 = new WeakMap; + cache0.set(a1, cache1); + } + let fnResult = cache1.get(a2); + if (fnResult === undefined) { + fnResult = fn(a1, a2); + cache1.set(a2, fnResult); + } + return fnResult; + }; + } +}); + +// node_modules/graphql/jsutils/memoize3.js +var require_memoize3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.memoize3 = memoize3; + function memoize3(fn) { + let cache0; + return function memoized(a1, a2, a3) { + cache0 ??= new WeakMap; + let cache1 = cache0.get(a1); + if (cache1 === undefined) { + cache1 = new WeakMap; + cache0.set(a1, cache1); + } + let cache2 = cache1.get(a2); + if (cache2 === undefined) { + cache2 = new WeakMap; + cache1.set(a2, cache2); + } + let fnResult = cache2.get(a3); + if (fnResult === undefined) { + fnResult = fn(a1, a2, a3); + cache2.set(a3, fnResult); + } + return fnResult; + }; + } +}); + +// node_modules/graphql/jsutils/promiseForObject.js +var require_promiseForObject = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.promiseForObject = promiseForObject; + function promiseForObject(object, promiseAll) { + const keys = Object.keys(object); + const values = Object.values(object); + return promiseAll(values).then((resolvedValues) => { + const resolvedObject = Object.create(null); + for (let i = 0;i < keys.length; ++i) { + resolvedObject[keys[i]] = resolvedValues[i]; + } + return resolvedObject; + }); + } +}); + +// node_modules/graphql/jsutils/promiseReduce.js +var require_promiseReduce = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.promiseReduce = promiseReduce; + var isPromise_ts_1 = require_isPromise(); + function promiseReduce(values, callbackFn, initialValue) { + let accumulator = initialValue; + for (const value of values) { + accumulator = (0, isPromise_ts_1.isPromise)(accumulator) ? accumulator.then((resolved) => callbackFn(resolved, value)) : callbackFn(accumulator, value); + } + return accumulator; + } +}); + +// node_modules/graphql/execution/AbortedGraphQLExecutionError.js +var require_AbortedGraphQLExecutionError = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AbortedGraphQLExecutionError = undefined; + + class AbortedGraphQLExecutionError extends Error { + constructor(reason, result) { + super(getAbortReasonMessage(reason), { cause: reason }); + this.name = "AbortedGraphQLExecutionError"; + this.abortedResult = result; + } + get [Symbol.toStringTag]() { + return "AbortedGraphQLExecutionError"; + } + } + exports.AbortedGraphQLExecutionError = AbortedGraphQLExecutionError; + function getAbortReasonMessage(reason) { + if (reason instanceof Error) { + return reason.message; + } + if (typeof reason === "object" && reason !== null && "message" in reason && typeof reason.message === "string") { + return reason.message; + } + return String(reason); + } +}); + +// node_modules/graphql/execution/collectIteratorPromises.js +var require_collectIteratorPromises = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.collectIteratorPromises = collectIteratorPromises; + var isPromise_ts_1 = require_isPromise(); + function collectIteratorPromises(iterator) { + const promises = []; + try { + while (true) { + const iteration = iterator.next(); + if (iteration.done) { + return promises; + } + if ((0, isPromise_ts_1.isPromiseLike)(iteration.value)) { + promises.push(iteration.value); + } + } + } catch { + return promises; + } + } +}); + +// node_modules/graphql/execution/getStreamUsage.js +var require_getStreamUsage = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getStreamUsage = getStreamUsage; + var invariant_ts_1 = require_invariant(); + var ast_ts_1 = require_ast(); + var directives_ts_1 = require_directives(); + var values_ts_1 = require_values(); + function getStreamUsage(validatedExecutionArgs, fieldDetailsList) { + const { operation, variableValues } = validatedExecutionArgs; + const stream = (0, values_ts_1.getDirectiveValues)(directives_ts_1.GraphQLStreamDirective, fieldDetailsList[0].node, variableValues, fieldDetailsList[0].fragmentVariableValues); + if (!stream) { + return; + } + if (stream.if === false) { + return; + } + if (!(typeof stream.initialCount === "number")) + (0, invariant_ts_1.invariant)(false, "initialCount must be a number"); + if (!(stream.initialCount >= 0)) + (0, invariant_ts_1.invariant)(false, "initialCount must be a positive integer"); + if (!(operation.operation !== ast_ts_1.OperationTypeNode.SUBSCRIPTION)) + (0, invariant_ts_1.invariant)(false, "`@stream` directive not supported on subscription operations. Disable `@stream` by setting the `if` argument to `false`."); + const streamedFieldDetailsList = fieldDetailsList.map((fieldDetails) => ({ + node: fieldDetails.node, + deferUsage: undefined, + fragmentVariableValues: fieldDetails.fragmentVariableValues + })); + return { + initialCount: stream.initialCount, + label: typeof stream.label === "string" ? stream.label : undefined, + fieldDetailsList: streamedFieldDetailsList + }; + } +}); + +// node_modules/graphql/execution/hooks.js +var require_hooks = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.runAsyncWorkFinishedHook = runAsyncWorkFinishedHook; + function runHookSafely(hook, info) { + try { + hook?.(info); + } catch {} + } + function runAsyncWorkFinishedHook(validatedExecutionArgs, sharedExecutionContext, asyncWorkFinishedHook) { + const maybeWaitForAsyncWork = sharedExecutionContext.asyncWorkTracker.wait(); + if (maybeWaitForAsyncWork === undefined) { + runHookSafely(asyncWorkFinishedHook, { validatedExecutionArgs }); + return; + } + maybeWaitForAsyncWork.then(() => { + runHookSafely(asyncWorkFinishedHook, { validatedExecutionArgs }); + }).catch(() => { + return; + }); + } +}); + +// node_modules/graphql/execution/returnIteratorCatchingErrors.js +var require_returnIteratorCatchingErrors = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.returnIteratorCatchingErrors = returnIteratorCatchingErrors; + async function returnIteratorCatchingErrors(iterator) { + try { + await iterator.return?.(); + } catch {} + } +}); + +// node_modules/graphql/execution/Executor.js +var require_Executor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Executor = exports.getStreamUsage = exports.collectSubfields = undefined; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var isAsyncIterable_ts_1 = require_isAsyncIterable(); + var isIterableObject_ts_1 = require_isIterableObject(); + var isPromise_ts_1 = require_isPromise(); + var memoize2_ts_1 = require_memoize2(); + var memoize3_ts_1 = require_memoize3(); + var Path_ts_1 = require_Path(); + var promiseForObject_ts_1 = require_promiseForObject(); + var promiseReduce_ts_1 = require_promiseReduce(); + var ensureGraphQLError_ts_1 = require_ensureGraphQLError(); + var GraphQLError_ts_1 = require_GraphQLError(); + var locatedError_ts_1 = require_locatedError(); + var ast_ts_1 = require_ast(); + var definition_ts_1 = require_definition(); + var diagnostics_ts_1 = require_diagnostics(); + var AbortedGraphQLExecutionError_ts_1 = require_AbortedGraphQLExecutionError(); + var buildResolveInfo_ts_1 = require_buildResolveInfo(); + var cancellablePromise_ts_1 = require_cancellablePromise(); + var collectFields_ts_1 = require_collectFields(); + var collectIteratorPromises_ts_1 = require_collectIteratorPromises(); + var createSharedExecutionContext_ts_1 = require_createSharedExecutionContext(); + var getStreamUsage_ts_1 = require_getStreamUsage(); + var hooks_ts_1 = require_hooks(); + var returnIteratorCatchingErrors_ts_1 = require_returnIteratorCatchingErrors(); + var values_ts_1 = require_values(); + exports.collectSubfields = (0, memoize3_ts_1.memoize3)((validatedExecutionArgs, returnType, fieldDetailsList) => { + const { schema, fragments, variableValues, hideSuggestions } = validatedExecutionArgs; + return (0, collectFields_ts_1.collectSubfields)(schema, fragments, variableValues, returnType, fieldDetailsList, hideSuggestions); + }); + exports.getStreamUsage = (0, memoize2_ts_1.memoize2)((validatedExecutionArgs, fieldDetailsList) => (0, getStreamUsage_ts_1.getStreamUsage)(validatedExecutionArgs, fieldDetailsList)); + + class CollectedErrors { + constructor() { + this._errorPositions = new Set; + this._errors = []; + } + get errors() { + return this._errors; + } + add(error, path) { + if (this.hasNulledPosition(path)) { + return; + } + this._errorPositions.add(path); + this._errors.push(error); + } + hasNulledPosition(startPath) { + let path = startPath; + while (path !== undefined) { + if (this._errorPositions.has(path)) { + return true; + } + path = path.prev; + } + return this._errorPositions.has(undefined); + } + } + var defaultAbortReason = new Error("This operation was aborted"); + + class Executor { + constructor(validatedExecutionArgs, sharedExecutionContext) { + this.validatedExecutionArgs = validatedExecutionArgs; + this.aborted = false; + this.abortReason = defaultAbortReason; + this.collectedErrors = new CollectedErrors; + if (sharedExecutionContext === undefined) { + this.resolverAbortController = new AbortController; + this.sharedExecutionContext = (0, createSharedExecutionContext_ts_1.createSharedExecutionContext)(this.resolverAbortController.signal); + } else { + this.sharedExecutionContext = sharedExecutionContext; + } + const { getAbortSignal, getAsyncHelpers, promiseAll } = this.sharedExecutionContext; + this.getAbortSignal = getAbortSignal; + this.getAsyncHelpers = getAsyncHelpers; + this.promiseAll = promiseAll; + } + executeRootSelectionSet(serially) { + if (!(0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.executeRootSelectionSetChannel)) { + return this.executeRootSelectionSetImpl(serially); + } + return (0, diagnostics_ts_1.traceMixed)(diagnostics_ts_1.executeRootSelectionSetChannel, this.buildExecuteContextFromValidatedArgs(this.validatedExecutionArgs), () => this.executeRootSelectionSetImpl(serially)); + } + buildExecuteContextFromValidatedArgs(args) { + return { + schema: args.schema, + document: args.document, + operation: args.operation, + rawVariableValues: args.rawVariableValues, + operationName: args.operation.name?.value, + operationType: args.operation.operation + }; + } + executeRootSelectionSetImpl(serially) { + const externalAbortSignal = this.validatedExecutionArgs.externalAbortSignal; + let removeExternalAbortListener; + if (externalAbortSignal) { + externalAbortSignal.throwIfAborted(); + const onExternalAbort = () => { + this.abort(externalAbortSignal.reason); + }; + removeExternalAbortListener = () => externalAbortSignal.removeEventListener("abort", onExternalAbort); + externalAbortSignal.addEventListener("abort", onExternalAbort); + } + const maybeRemoveExternalAbortListener = () => { + removeExternalAbortListener?.(); + }; + let result; + try { + const { schema, fragments, rootValue, operation, variableValues, hideSuggestions } = this.validatedExecutionArgs; + const { operation: operationType, selectionSet } = operation; + const rootType = schema.getRootType(operationType); + if (rootType == null) { + throw new GraphQLError_ts_1.GraphQLError(`Schema is not configured to execute ${operationType} operation.`, { nodes: operation }); + } + const { groupedFieldSet, newDeferUsages } = (0, collectFields_ts_1.collectFields)(schema, fragments, variableValues, rootType, selectionSet, hideSuggestions); + result = this.executeCollectedRootFields(rootType, rootValue, groupedFieldSet, serially ?? operationType === ast_ts_1.OperationTypeNode.MUTATION, newDeferUsages); + if ((0, isPromise_ts_1.isPromise)(result)) { + const promise = result.then((data) => { + maybeRemoveExternalAbortListener(); + return this.buildResponse(data); + }, (error) => { + maybeRemoveExternalAbortListener(); + this.collectedErrors.add((0, ensureGraphQLError_ts_1.ensureGraphQLError)(error), undefined); + return this.buildResponse(null); + }); + this.sharedExecutionContext.asyncWorkTracker.add(promise); + const { promise: cancellablePromise, abort: abortResultPromise } = (0, cancellablePromise_ts_1.withCancellation)(promise.then((resolved) => this.finish(resolved))); + this.abortResultPromise = () => { + abortResultPromise(this.createAbortedExecutionError(promise)); + }; + if (this.aborted) { + this.abortResultPromise(); + } + return cancellablePromise; + } + maybeRemoveExternalAbortListener(); + } catch (error) { + maybeRemoveExternalAbortListener(); + this.collectedErrors.add((0, ensureGraphQLError_ts_1.ensureGraphQLError)(error), undefined); + return this.finish(this.buildResponse(null)); + } + return this.finish(this.buildResponse(result)); + } + abort(reason) { + if (this.aborted) { + return; + } + this.aborted = true; + if (reason !== undefined) { + this.abortReason = reason; + } + this.abortResultPromise?.(); + this.resolverAbortController?.abort(this.abortReason); + } + finish(result) { + if (this.aborted) { + throw this.createAbortedExecutionError(result); + } + this.aborted = true; + return result; + } + createAbortedExecutionError(result) { + return new AbortedGraphQLExecutionError_ts_1.AbortedGraphQLExecutionError(this.abortReason, result); + } + getFinishSharedExecution() { + const resolverAbortController = this.resolverAbortController; + const asyncWorkFinishedHook = this.validatedExecutionArgs.hooks?.asyncWorkFinished; + if (asyncWorkFinishedHook === undefined) { + return () => resolverAbortController?.abort(); + } + const validatedExecutionArgs = this.validatedExecutionArgs; + const sharedExecutionContext = this.sharedExecutionContext; + return () => { + resolverAbortController?.abort(); + (0, hooks_ts_1.runAsyncWorkFinishedHook)(validatedExecutionArgs, sharedExecutionContext, asyncWorkFinishedHook); + }; + } + buildResponse(data) { + this.getFinishSharedExecution()(); + const errors = this.collectedErrors.errors; + return errors.length ? { errors, data } : { data }; + } + executeCollectedRootFields(rootType, rootValue, originalGroupedFieldSet, serially, _newDeferUsages) { + return this.executeRootGroupedFieldSet(rootType, rootValue, originalGroupedFieldSet, serially, undefined); + } + executeRootGroupedFieldSet(rootType, rootValue, groupedFieldSet, serially, positionContext) { + return serially ? this.executeFieldsSerially(rootType, rootValue, undefined, groupedFieldSet, positionContext) : this.executeFields(rootType, rootValue, undefined, groupedFieldSet, positionContext); + } + executeFieldsSerially(parentType, sourceValue, path, groupedFieldSet, positionContext) { + let tracingChannel = (0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.resolveChannel) ? diagnostics_ts_1.resolveChannel : undefined; + return (0, promiseReduce_ts_1.promiseReduce)(groupedFieldSet, (results, [responseName, fieldDetailsList]) => { + if (this.aborted) { + throw new Error("Aborted!"); + } + const fieldPath = (0, Path_ts_1.addPath)(path, responseName, parentType.name); + const result = this.executeField(parentType, sourceValue, fieldDetailsList, fieldPath, positionContext, tracingChannel); + if (result === undefined) { + return results; + } + if ((0, isPromise_ts_1.isPromise)(result)) { + return result.then((resolved) => { + results[responseName] = resolved; + tracingChannel = (0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.resolveChannel) ? diagnostics_ts_1.resolveChannel : undefined; + return results; + }); + } + results[responseName] = result; + return results; + }, Object.create(null)); + } + executeFields(parentType, sourceValue, path, groupedFieldSet, positionContext) { + const results = Object.create(null); + let containsPromise = false; + const tracingChannel = (0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.resolveChannel) ? diagnostics_ts_1.resolveChannel : undefined; + try { + for (const [responseName, fieldDetailsList] of groupedFieldSet) { + const fieldPath = (0, Path_ts_1.addPath)(path, responseName, parentType.name); + const result = this.executeField(parentType, sourceValue, fieldDetailsList, fieldPath, positionContext, tracingChannel); + if (result !== undefined) { + results[responseName] = result; + if ((0, isPromise_ts_1.isPromise)(result)) { + containsPromise = true; + } + } + } + } catch (error) { + if (containsPromise) { + this.sharedExecutionContext.asyncWorkTracker.addValues(Object.values(results)); + } + throw error; + } + if (!containsPromise) { + return results; + } + return (0, promiseForObject_ts_1.promiseForObject)(results, this.promiseAll); + } + executeField(parentType, source, fieldDetailsList, path, positionContext, tracingChannel) { + const validatedExecutionArgs = this.validatedExecutionArgs; + const { schema, contextValue, variableValues, hideSuggestions } = validatedExecutionArgs; + const firstFieldDetails = fieldDetailsList[0]; + const firstNode = firstFieldDetails.node; + const fieldName = firstNode.name.value; + const fieldDef = schema.getField(parentType, fieldName); + if (!fieldDef) { + return; + } + const returnType = fieldDef.type; + let resolveFn = fieldDef.resolve ?? validatedExecutionArgs.fieldResolver; + if (tracingChannel !== undefined) { + const originalResolveFn = resolveFn; + resolveFn = (s, args, c, info2) => (0, diagnostics_ts_1.traceMixed)(tracingChannel, this.buildResolveContext(args, info2, fieldDef.resolve === undefined), () => originalResolveFn(s, args, c, info2)); + } + const info = (0, buildResolveInfo_ts_1.buildResolveInfo)(validatedExecutionArgs, fieldDef, toNodes(fieldDetailsList), parentType, path, this.getAbortSignal, this.getAsyncHelpers); + try { + const args = (0, values_ts_1.getArgumentValues)(fieldDef, firstNode, variableValues, firstFieldDetails.fragmentVariableValues, hideSuggestions); + const result = resolveFn(source, args, contextValue, info); + if ((0, isPromise_ts_1.isPromiseLike)(result)) { + return this.completePromisedValue(returnType, fieldDetailsList, info, path, result, positionContext); + } + const completed = this.completeValue(returnType, fieldDetailsList, info, path, result, positionContext); + if ((0, isPromise_ts_1.isPromise)(completed)) { + return completed.then(undefined, (rawError) => { + this.handleFieldError(rawError, returnType, fieldDetailsList, path); + return null; + }); + } + return completed; + } catch (rawError) { + this.handleFieldError(rawError, returnType, fieldDetailsList, path); + return null; + } + } + buildResolveContext(args, info, isDefaultResolver) { + let cachedFieldPath; + return { + fieldName: info.fieldName, + alias: String(info.path.key), + parentType: info.parentType.name, + fieldType: String(info.returnType), + args, + isDefaultResolver, + get fieldPath() { + cachedFieldPath ??= (0, Path_ts_1.pathToArray)(info.path).join("."); + return cachedFieldPath; + } + }; + } + handleFieldError(rawError, returnType, fieldDetailsList, path) { + const error = (0, locatedError_ts_1.locatedError)(rawError, toNodes(fieldDetailsList), (0, Path_ts_1.pathToArray)(path)); + if (this.validatedExecutionArgs.errorPropagation && (0, definition_ts_1.isNonNullType)(returnType)) { + throw error; + } + this.collectedErrors.add(error, path); + } + completeValue(returnType, fieldDetailsList, info, path, result, positionContext) { + if (result instanceof Error) { + throw result; + } + if ((0, definition_ts_1.isNonNullType)(returnType)) { + const completed = this.completeValue(returnType.ofType, fieldDetailsList, info, path, result, positionContext); + if (completed === null) { + throw new Error(`Cannot return null for non-nullable field ${info.parentType}.${info.fieldName}.`); + } + return completed; + } + if (result == null) { + return null; + } + if ((0, definition_ts_1.isListType)(returnType)) { + return this.completeListValue(returnType, fieldDetailsList, info, path, result, positionContext); + } + if ((0, definition_ts_1.isLeafType)(returnType)) { + return this.completeLeafValue(returnType, result); + } + if ((0, definition_ts_1.isAbstractType)(returnType)) { + return this.completeAbstractValue(returnType, fieldDetailsList, info, path, result, positionContext); + } + if ((0, definition_ts_1.isObjectType)(returnType)) { + return this.completeObjectValue(returnType, fieldDetailsList, info, path, result, positionContext); + } + (0, invariant_ts_1.invariant)(false, "Cannot complete value of unexpected output type: " + (0, inspect_ts_1.inspect)(returnType)); + } + async completePromisedValue(returnType, fieldDetailsList, info, path, result, positionContext) { + try { + const resolved = await result; + if (this.aborted) { + throw new Error("Aborted!"); + } + let completed = this.completeValue(returnType, fieldDetailsList, info, path, resolved, positionContext); + if ((0, isPromise_ts_1.isPromise)(completed)) { + completed = await completed; + } + return completed; + } catch (rawError) { + this.handleFieldError(rawError, returnType, fieldDetailsList, path); + return null; + } + } + async completeAsyncIterableValue(itemType, fieldDetailsList, info, path, items, positionContext) { + const streamUsage = typeof path.key === "number" ? undefined : (0, exports.getStreamUsage)(this.validatedExecutionArgs, fieldDetailsList); + let containsPromise = false; + const completedResults = []; + const asyncIterator = items[Symbol.asyncIterator](); + let index = 0; + let iteration; + try { + while (true) { + if (streamUsage?.initialCount === index && this.handleStream(index, path, { handle: asyncIterator, isAsync: true }, streamUsage, info, itemType)) { + break; + } + const itemPath = (0, Path_ts_1.addPath)(path, index, undefined); + try { + iteration = await asyncIterator.next(); + } catch (rawError) { + throw (0, locatedError_ts_1.locatedError)(rawError, toNodes(fieldDetailsList), (0, Path_ts_1.pathToArray)(path)); + } + if (this.aborted || iteration.done) { + break; + } + const item = iteration.value; + if (this.completeMaybePromisedListItemValue(item, completedResults, itemType, fieldDetailsList, info, itemPath, positionContext)) { + containsPromise = true; + } + index++; + } + } catch (error) { + this.sharedExecutionContext.asyncWorkTracker.add((0, returnIteratorCatchingErrors_ts_1.returnIteratorCatchingErrors)(asyncIterator)); + if (containsPromise) { + this.sharedExecutionContext.asyncWorkTracker.addValues(completedResults); + } + throw error; + } + if (this.aborted) { + if (!iteration?.done) { + this.sharedExecutionContext.asyncWorkTracker.add((0, returnIteratorCatchingErrors_ts_1.returnIteratorCatchingErrors)(asyncIterator)); + } + throw new Error("Aborted!"); + } + return containsPromise ? this.promiseAll(completedResults) : completedResults; + } + handleStream(_index, _path, _iterator, _streamUsage, _info, _itemType) { + return false; + } + completeListValue(returnType, fieldDetailsList, info, path, result, positionContext) { + const itemType = returnType.ofType; + if ((0, isAsyncIterable_ts_1.isAsyncIterable)(result)) { + return this.completeAsyncIterableValue(itemType, fieldDetailsList, info, path, result, positionContext); + } + if (!(0, isIterableObject_ts_1.isIterableObject)(result)) { + throw new GraphQLError_ts_1.GraphQLError(`Expected Iterable, but did not find one for field "${info.parentType}.${info.fieldName}".`); + } + return this.completeIterableValue(itemType, fieldDetailsList, info, path, result, positionContext); + } + completeIterableValue(itemType, fieldDetailsList, info, path, items, positionContext) { + const streamUsage = typeof path.key === "number" ? undefined : (0, exports.getStreamUsage)(this.validatedExecutionArgs, fieldDetailsList); + let containsPromise = false; + const completedResults = []; + let index = 0; + const iterator = items[Symbol.iterator](); + try { + while (true) { + if (streamUsage?.initialCount === index && this.handleStream(index, path, { handle: iterator }, streamUsage, info, itemType)) { + break; + } + const iteration = iterator.next(); + if (iteration.done) { + break; + } + const item = iteration.value; + const itemPath = (0, Path_ts_1.addPath)(path, index, undefined); + if (this.completeMaybePromisedListItemValue(item, completedResults, itemType, fieldDetailsList, info, itemPath, positionContext)) { + containsPromise = true; + } + index++; + } + } catch (error) { + const asyncWorkTracker = this.sharedExecutionContext.asyncWorkTracker; + if (containsPromise) { + asyncWorkTracker.addValues(completedResults); + } + asyncWorkTracker.addValues((0, collectIteratorPromises_ts_1.collectIteratorPromises)(iterator)); + throw error; + } + return containsPromise ? this.promiseAll(completedResults) : completedResults; + } + completeMaybePromisedListItemValue(item, completedResults, itemType, fieldDetailsList, info, itemPath, positionContext) { + if ((0, isPromise_ts_1.isPromiseLike)(item)) { + completedResults.push(this.completePromisedListItemValue(item, itemType, fieldDetailsList, info, itemPath, positionContext)); + return true; + } else if (this.completeListItemValue(item, completedResults, itemType, fieldDetailsList, info, itemPath, positionContext)) { + return true; + } + return false; + } + completeListItemValue(item, completedResults, itemType, fieldDetailsList, info, itemPath, positionContext) { + try { + const completedItem = this.completeValue(itemType, fieldDetailsList, info, itemPath, item, positionContext); + if ((0, isPromise_ts_1.isPromise)(completedItem)) { + completedResults.push(completedItem.then(undefined, (rawError) => { + this.handleFieldError(rawError, itemType, fieldDetailsList, itemPath); + return null; + })); + return true; + } + completedResults.push(completedItem); + } catch (rawError) { + this.handleFieldError(rawError, itemType, fieldDetailsList, itemPath); + completedResults.push(null); + } + return false; + } + async completePromisedListItemValue(item, itemType, fieldDetailsList, info, itemPath, positionContext) { + try { + const resolved = await item; + if (this.aborted) { + throw new Error("Aborted!"); + } + let completed = this.completeValue(itemType, fieldDetailsList, info, itemPath, resolved, positionContext); + if ((0, isPromise_ts_1.isPromise)(completed)) { + completed = await completed; + } + return completed; + } catch (rawError) { + this.handleFieldError(rawError, itemType, fieldDetailsList, itemPath); + return null; + } + } + completeLeafValue(returnType, result) { + const coerced = returnType.coerceOutputValue(result); + if (coerced == null) { + throw new Error(`Expected \`${(0, inspect_ts_1.inspect)(returnType)}.coerceOutputValue(${(0, inspect_ts_1.inspect)(result)})\` to ` + `return non-nullable value, returned: ${(0, inspect_ts_1.inspect)(coerced)}`); + } + return coerced; + } + completeAbstractValue(returnType, fieldDetailsList, info, path, result, positionContext) { + const validatedExecutionArgs = this.validatedExecutionArgs; + const { schema, contextValue } = validatedExecutionArgs; + const resolveTypeFn = returnType.resolveType ?? validatedExecutionArgs.typeResolver; + const runtimeType = resolveTypeFn(result, contextValue, info, returnType); + if ((0, isPromise_ts_1.isPromiseLike)(runtimeType)) { + return runtimeType.then((resolvedRuntimeType) => { + if (this.aborted) { + throw new Error("Aborted!"); + } + return this.completeObjectValue(this.ensureValidRuntimeType(resolvedRuntimeType, schema, returnType, fieldDetailsList, info, result), fieldDetailsList, info, path, result, positionContext); + }); + } + return this.completeObjectValue(this.ensureValidRuntimeType(runtimeType, schema, returnType, fieldDetailsList, info, result), fieldDetailsList, info, path, result, positionContext); + } + ensureValidRuntimeType(runtimeTypeName, schema, returnType, fieldDetailsList, info, result) { + if (runtimeTypeName == null) { + throw new GraphQLError_ts_1.GraphQLError(`Abstract type "${returnType}" must resolve to an Object type at runtime for field "${info.parentType}.${info.fieldName}". Either the "${returnType}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`, { nodes: toNodes(fieldDetailsList) }); + } + if (typeof runtimeTypeName !== "string") { + throw new GraphQLError_ts_1.GraphQLError(`Abstract type "${returnType}" must resolve to an Object type at runtime for field "${info.parentType}.${info.fieldName}" with ` + `value ${(0, inspect_ts_1.inspect)(result)}, received "${(0, inspect_ts_1.inspect)(runtimeTypeName)}", which is not a valid Object type name.`); + } + const runtimeType = schema.getType(runtimeTypeName); + if (runtimeType == null) { + throw new GraphQLError_ts_1.GraphQLError(`Abstract type "${returnType}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, { nodes: toNodes(fieldDetailsList) }); + } + if (!(0, definition_ts_1.isObjectType)(runtimeType)) { + throw new GraphQLError_ts_1.GraphQLError(`Abstract type "${returnType}" was resolved to a non-object type "${runtimeTypeName}".`, { nodes: toNodes(fieldDetailsList) }); + } + if (!schema.isSubType(returnType, runtimeType)) { + throw new GraphQLError_ts_1.GraphQLError(`Runtime Object type "${runtimeType}" is not a possible type for "${returnType}".`, { nodes: toNodes(fieldDetailsList) }); + } + return runtimeType; + } + completeObjectValue(returnType, fieldDetailsList, info, path, result, positionContext) { + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, this.validatedExecutionArgs.contextValue, info); + if ((0, isPromise_ts_1.isPromiseLike)(isTypeOf)) { + return isTypeOf.then((resolvedIsTypeOf) => { + if (this.aborted) { + throw new Error("Aborted!"); + } + if (!resolvedIsTypeOf) { + throw this.invalidReturnTypeError(returnType, result, fieldDetailsList); + } + return this.collectAndExecuteSubfields(returnType, fieldDetailsList, path, result, positionContext); + }); + } + if (!isTypeOf) { + throw this.invalidReturnTypeError(returnType, result, fieldDetailsList); + } + } + return this.collectAndExecuteSubfields(returnType, fieldDetailsList, path, result, positionContext); + } + invalidReturnTypeError(returnType, result, fieldDetailsList) { + return new GraphQLError_ts_1.GraphQLError(`Expected value of type "${returnType}" but got: ${(0, inspect_ts_1.inspect)(result)}.`, { nodes: toNodes(fieldDetailsList) }); + } + collectAndExecuteSubfields(returnType, fieldDetailsList, path, result, positionContext) { + const { groupedFieldSet, newDeferUsages } = (0, exports.collectSubfields)(this.validatedExecutionArgs, returnType, fieldDetailsList); + return this.executeCollectedSubfields(returnType, result, path, groupedFieldSet, newDeferUsages, positionContext); + } + executeCollectedSubfields(parentType, sourceValue, path, originalGroupedFieldSet, _newDeferUsages, _positionContext) { + return this.executeFields(parentType, sourceValue, path, originalGroupedFieldSet, undefined); + } + } + exports.Executor = Executor; + function toNodes(fieldDetailsList) { + return fieldDetailsList.map((fieldDetails) => fieldDetails.node); + } +}); + +// node_modules/graphql/execution/ExecutorThrowingOnIncremental.js +var require_ExecutorThrowingOnIncremental = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExecutorThrowingOnIncremental = undefined; + var invariant_ts_1 = require_invariant(); + var ast_ts_1 = require_ast(); + var Executor_ts_1 = require_Executor(); + var UNEXPECTED_MULTIPLE_PAYLOADS = "Executing this GraphQL operation would unexpectedly produce multiple payloads (due to @defer or @stream directive)"; + + class ExecutorThrowingOnIncremental extends Executor_ts_1.Executor { + executeCollectedRootFields(rootType, rootValue, originalGroupedFieldSet, serially, newDeferUsages) { + if (newDeferUsages.length > 0) { + if (!(this.validatedExecutionArgs.operation.operation !== ast_ts_1.OperationTypeNode.SUBSCRIPTION)) + (0, invariant_ts_1.invariant)(false, "`@defer` directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`."); + const reason = new Error(UNEXPECTED_MULTIPLE_PAYLOADS); + this.abort(reason); + throw reason; + } + return this.executeRootGroupedFieldSet(rootType, rootValue, originalGroupedFieldSet, serially, undefined); + } + executeCollectedSubfields(parentType, sourceValue, path, originalGroupedFieldSet, newDeferUsages) { + if (newDeferUsages.length > 0) { + if (!(this.validatedExecutionArgs.operation.operation !== ast_ts_1.OperationTypeNode.SUBSCRIPTION)) + (0, invariant_ts_1.invariant)(false, "`@defer` directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`."); + const reason = new Error(UNEXPECTED_MULTIPLE_PAYLOADS); + this.abort(reason); + throw reason; + } + return this.executeFields(parentType, sourceValue, path, originalGroupedFieldSet, undefined); + } + completeListValue(returnType, fieldDetailsList, info, path, result, positionContext) { + const streamUsage = (0, Executor_ts_1.getStreamUsage)(this.validatedExecutionArgs, fieldDetailsList); + if (streamUsage !== undefined) { + if (!(this.validatedExecutionArgs.operation.operation !== ast_ts_1.OperationTypeNode.SUBSCRIPTION)) + (0, invariant_ts_1.invariant)(false, "`@stream` directive not supported on subscription operations. Disable `@stream` by setting the `if` argument to `false`."); + const reason = new Error(UNEXPECTED_MULTIPLE_PAYLOADS); + this.abort(reason); + throw reason; + } + return super.completeListValue(returnType, fieldDetailsList, info, path, result, positionContext); + } + } + exports.ExecutorThrowingOnIncremental = ExecutorThrowingOnIncremental; +}); + +// node_modules/graphql/jsutils/memoize1.js +var require_memoize1 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.memoize1 = memoize1; + function memoize1(fn) { + let cache0; + return function memoized(a1) { + cache0 ??= new WeakMap; + let fnResult = cache0.get(a1); + if (fnResult === undefined) { + fnResult = fn(a1); + cache0.set(a1, fnResult); + } + return fnResult; + }; + } +}); + +// node_modules/graphql/jsutils/isSameSet.js +var require_isSameSet = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isSameSet = isSameSet; + function isSameSet(setA, setB) { + if (setA.size !== setB.size) { + return false; + } + for (const item of setA) { + if (!setB.has(item)) { + return false; + } + } + return true; + } +}); + +// node_modules/graphql/jsutils/getBySet.js +var require_getBySet = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getBySet = getBySet; + var isSameSet_ts_1 = require_isSameSet(); + function getBySet(map, setToMatch) { + for (const set of map.keys()) { + if ((0, isSameSet_ts_1.isSameSet)(set, setToMatch)) { + return map.get(set); + } + } + return; + } +}); + +// node_modules/graphql/execution/incremental/buildExecutionPlan.js +var require_buildExecutionPlan = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildExecutionPlan = buildExecutionPlan; + var getBySet_ts_1 = require_getBySet(); + var isSameSet_ts_1 = require_isSameSet(); + function buildExecutionPlan(originalGroupedFieldSet, parentDeferUsages = new Set) { + const groupedFieldSet = new Map; + const newGroupedFieldSets = new Map; + for (const [responseKey, fieldDetailsList] of originalGroupedFieldSet) { + const filteredDeferUsageSet = getFilteredDeferUsageSet(fieldDetailsList); + if ((0, isSameSet_ts_1.isSameSet)(filteredDeferUsageSet, parentDeferUsages)) { + groupedFieldSet.set(responseKey, fieldDetailsList); + continue; + } + let newGroupedFieldSet = (0, getBySet_ts_1.getBySet)(newGroupedFieldSets, filteredDeferUsageSet); + if (newGroupedFieldSet === undefined) { + newGroupedFieldSet = new Map; + newGroupedFieldSets.set(filteredDeferUsageSet, newGroupedFieldSet); + } + newGroupedFieldSet.set(responseKey, fieldDetailsList); + } + return { + groupedFieldSet, + newGroupedFieldSets + }; + } + function getFilteredDeferUsageSet(fieldDetailsList) { + const filteredDeferUsageSet = new Set; + for (const fieldDetails of fieldDetailsList) { + const deferUsage = fieldDetails.deferUsage; + if (deferUsage === undefined) { + filteredDeferUsageSet.clear(); + return filteredDeferUsageSet; + } + filteredDeferUsageSet.add(deferUsage); + } + for (const deferUsage of filteredDeferUsageSet) { + let parentDeferUsage = deferUsage.parentDeferUsage; + while (parentDeferUsage !== undefined) { + if (filteredDeferUsageSet.has(parentDeferUsage)) { + filteredDeferUsageSet.delete(deferUsage); + break; + } + parentDeferUsage = parentDeferUsage.parentDeferUsage; + } + } + return filteredDeferUsageSet; + } +}); + +// node_modules/graphql/execution/incremental/Computation.js +var require_Computation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Computation = undefined; + var isPromise_ts_1 = require_isPromise(); + + class Computation { + constructor(fn, onAbort) { + this._fn = fn; + this._onAbort = onAbort; + } + prime() { + if (this._maybePromise) { + return this._maybePromise; + } + try { + const result = this._fn(); + if ((0, isPromise_ts_1.isPromise)(result)) { + this._maybePromise = { status: "pending", promise: result }; + result.then((value) => { + this._maybePromise = { status: "fulfilled", value }; + }, (reason) => { + this._maybePromise = { status: "rejected", reason }; + }); + } else { + this._maybePromise = { status: "fulfilled", value: result }; + } + } catch (reason) { + this._maybePromise = { status: "rejected", reason }; + } + return this._maybePromise; + } + result() { + const maybePromise = this.prime(); + switch (maybePromise.status) { + case "fulfilled": + return maybePromise.value; + case "rejected": + throw maybePromise.reason; + case "pending": { + return maybePromise.promise; + } + } + } + abort(reason) { + const maybePromise = this._maybePromise; + if (!maybePromise) { + this._maybePromise = { + status: "rejected", + reason + }; + return; + } + const status = maybePromise.status; + if (status === "pending") { + this._maybePromise = { + status: "rejected", + reason + }; + if (this._onAbort) { + return this._onAbort(reason); + } + } + } + } + exports.Computation = Computation; +}); + +// node_modules/graphql/execution/withConcurrentAbruptClose.js +var require_withConcurrentAbruptClose = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.withConcurrentAbruptClose = withConcurrentAbruptClose; + var isPromise_ts_1 = require_isPromise(); + var asyncDispose = Symbol.asyncDispose ?? Symbol.for("Symbol.asyncDispose"); + function withConcurrentAbruptClose(generator, beforeReturn, beforeThrow = beforeReturn) { + let completed = false; + let abruptCloseRequested = false; + const runAbruptCloseFn = (fn) => { + if (completed || abruptCloseRequested) { + return; + } + abruptCloseRequested = true; + return ignoreErrors(fn); + }; + return { + [Symbol.asyncIterator]() { + return this; + }, + next() { + const result = generator.next(); + result.then((iteration) => { + if (iteration.done) { + completed = true; + } + }).catch(() => { + return; + }); + return result; + }, + async return() { + await runAbruptCloseFn(beforeReturn); + return generator.return(); + }, + async throw(error) { + await runAbruptCloseFn(() => beforeThrow(error)); + return generator.throw(error); + }, + async[asyncDispose]() { + await runAbruptCloseFn(beforeReturn); + if (typeof generator[asyncDispose] === "function") { + await generator[asyncDispose](); + } + } + }; + } + function ignoreErrors(fn) { + try { + const result = fn(); + if ((0, isPromise_ts_1.isPromise)(result)) { + return result.catch(() => {}); + } + } catch {} + } +}); + +// node_modules/graphql/execution/mapAsyncIterable.js +var require_mapAsyncIterable = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.mapAsyncIterable = mapAsyncIterable; + var isPromise_ts_1 = require_isPromise(); + var withConcurrentAbruptClose_ts_1 = require_withConcurrentAbruptClose(); + function mapAsyncIterable(iterable, callback) { + const iterator = iterable[Symbol.asyncIterator](); + const returnFn = iterator.return?.bind(iterator); + const throwFn = iterator.throw?.bind(iterator); + const onReturn = returnFn ? () => callIgnoringErrors(returnFn) : () => Promise.resolve(); + const onThrow = throwFn ? (reason) => callIgnoringErrors(() => throwFn(reason)) : onReturn; + return (0, withConcurrentAbruptClose_ts_1.withConcurrentAbruptClose)(mapAsyncIterableImpl(iterable, callback), onReturn, onThrow); + } + async function callIgnoringErrors(fn) { + try { + await fn(); + } catch {} + } + async function* mapAsyncIterableImpl(iterable, mapFn) { + for await (const value of iterable) { + const result = mapFn(value); + if ((0, isPromise_ts_1.isPromise)(result)) { + yield await result; + continue; + } + yield result; + } + } +}); + +// node_modules/graphql/execution/incremental/Queue.js +var require_Queue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Queue = undefined; + var invariant_ts_1 = require_invariant(); + var isPromise_ts_1 = require_isPromise(); + var promiseWithResolvers_ts_1 = require_promiseWithResolvers(); + var withConcurrentAbruptClose_ts_1 = require_withConcurrentAbruptClose(); + + class Queue { + constructor(executor, initialCapacity = 1) { + this._backlog = 0; + this._waiters = []; + this._entries = []; + this._isStopped = false; + this._stopRequested = false; + this._stopCleanupCallbacks = []; + this._batchRequests = new Set; + this._capacity = this._normalizeCapacity(initialCapacity); + const { promise: started, resolve: resolveStarted } = (0, promiseWithResolvers_ts_1.promiseWithResolvers)(); + this._resolveStarted = resolveStarted; + try { + const result = executor({ + push: this._push.bind(this), + stop: this._stop.bind(this), + onStop: this._onStop.bind(this), + started + }); + if ((0, isPromise_ts_1.isPromise)(result)) { + result.catch(this._stop.bind(this)); + } + } catch (error) { + const stopped = this._stop(error); + if ((0, isPromise_ts_1.isPromise)(stopped)) { + stopped.catch(() => { + return; + }); + } + } + } + subscribe(reducer = (generator) => Array.from(generator)) { + const generator = this._iteratorLoop(reducer); + return (0, withConcurrentAbruptClose_ts_1.withConcurrentAbruptClose)(generator, () => this.cancel(), this.abort.bind(this)); + } + cancel() { + if (this._stopRequested) { + return this._stopCompletion; + } + return this._terminate(undefined, () => { + this._isStopped = true; + this._batchRequests.forEach((request) => request.resolve(undefined)); + this._batchRequests.clear(); + }); + } + abort(reason) { + if (this._stopRequested) { + return this._stopCompletion; + } + return this._terminate(reason, () => { + this._isStopped = true; + if (this._batchRequests.size) { + this._batchRequests.forEach((request) => request.reject(reason)); + this._batchRequests.clear(); + return; + } + this._entries.push({ + kind: "item", + settled: { status: "rejected", reason } + }); + }); + } + async forEachBatch(reducer) { + const sub = this.subscribe(async (generator) => { + const { promise: drained, resolve } = (0, promiseWithResolvers_ts_1.promiseWithResolvers)(); + const wrappedBatch = function* wrapper() { + yield* generator; + resolve(); + }(); + await Promise.all([reducer(wrappedBatch), drained]); + }); + for await (const _ of sub) {} + } + setCapacity(nextCapacity) { + this._capacity = this._normalizeCapacity(nextCapacity); + this._flush(); + } + getCapacity() { + return this._capacity; + } + isStopped() { + return this._isStopped; + } + _normalizeCapacity(capacity) { + return Math.max(1, Math.floor(capacity)); + } + _flush() { + while (this._waiters.length > 0 && this._backlog < this._capacity) { + this._waiters.shift()?.(); + } + } + _reserve() { + this._backlog += 1; + if (this._backlog < this._capacity) { + return; + } + const { promise, resolve } = (0, promiseWithResolvers_ts_1.promiseWithResolvers)(); + this._waiters.push(resolve); + return promise; + } + _release() { + if (this._backlog > 0) { + this._backlog -= 1; + } + this._flush(); + } + _onStop(cleanup) { + if (this._stopRequested) { + throw new Error("Cannot register onStop cleanup after stop has been requested."); + } + this._stopCleanupCallbacks.push(cleanup); + } + _runStopCleanup(reason, afterCleanup) { + this._stopRequested = true; + const cleanupPromises = this._stopCleanupCallbacks.flatMap((cleanupCallback) => { + try { + const result = cleanupCallback(reason); + return (0, isPromise_ts_1.isPromise)(result) ? [result] : []; + } catch { + return []; + } + }); + const cleanup = cleanupPromises.length > 0 ? Promise.allSettled(cleanupPromises).then(() => { + return; + }) : undefined; + if ((0, isPromise_ts_1.isPromise)(cleanup)) { + this._stopCompletion = cleanup.then(afterCleanup, afterCleanup).then(() => { + return; + }); + return this._stopCompletion; + } + afterCleanup(); + } + async* _iteratorLoop(reducer) { + this._resolveStarted(); + let nextBatch; + while (nextBatch = await this._waitForNextBatch()) { + let reduced = reducer(nextBatch); + if ((0, isPromise_ts_1.isPromise)(reduced)) { + reduced = await reduced; + } + if (reduced === undefined) { + continue; + } + yield reduced; + } + } + _waitForNextBatch() { + const { promise, resolve, reject } = (0, promiseWithResolvers_ts_1.promiseWithResolvers)(); + this._batchRequests.add({ resolve, reject }); + this._deliverBatchIfReady(); + return promise; + } + _push(item) { + if (this._stopRequested) { + return; + } + const maybePushPromise = this._reserve(); + if ((0, isPromise_ts_1.isPromise)(item)) { + const entry = { kind: "item" }; + this._entries.push(entry); + item.then((resolved) => { + entry.settled = { status: "fulfilled", value: resolved }; + this._deliverBatchIfReady(); + }, (reason) => { + entry.settled = { status: "rejected", reason }; + this._deliverBatchIfReady(); + }); + } else { + this._entries.push({ + kind: "item", + settled: { status: "fulfilled", value: item } + }); + this._deliverBatchIfReady(); + } + return maybePushPromise; + } + _terminate(reason, afterCleanup) { + for (const entry of this._entries) { + if (entry.kind === "item") { + this._release(); + } + } + this._entries.length = 0; + return this._runStopCleanup(reason, afterCleanup); + } + _stop(reason) { + if (this._stopRequested) { + return this._stopCompletion; + } + const stopCompletion = this._runStopCleanup(reason, () => { + if (reason === undefined) { + if (this._entries.length === 0) { + this._isStopped = true; + this._deliverBatchIfReady(); + return; + } + this._entries.push({ kind: "stop" }); + this._deliverBatchIfReady(); + return; + } + this._entries.push({ + kind: "item", + settled: { status: "rejected", reason } + }); + this._entries.push({ kind: "stop" }); + this._deliverBatchIfReady(); + }); + if ((0, isPromise_ts_1.isPromise)(stopCompletion)) { + stopCompletion.catch(() => { + return; + }); + } + return stopCompletion; + } + _deliverBatchIfReady() { + if (!this._batchRequests.size) { + return; + } + const headEntry = this._entries[0]; + const requests = this._batchRequests; + if (headEntry !== undefined) { + if (!(headEntry.kind !== "stop")) + (0, invariant_ts_1.invariant)(false); + const settled = headEntry.settled; + if (settled !== undefined) { + if (settled.status === "fulfilled") { + this._batchRequests = new Set; + requests.forEach((request) => request.resolve(this._drainBatch())); + return; + } + this._entries.shift(); + this._release(); + this._isStopped = true; + this._batchRequests = new Set; + requests.forEach((request) => request.reject(settled.reason)); + } + } else if (this._isStopped) { + this._batchRequests = new Set; + requests.forEach((request) => request.resolve(undefined)); + } + } + *_drainBatch() { + while (true) { + const entry = this._entries[0]; + if (entry === undefined) { + return; + } + if (entry.kind === "stop") { + this._isStopped = true; + this._entries.shift(); + return; + } + const settled = entry.settled; + if (settled === undefined || settled.status === "rejected") { + return; + } + this._entries.shift(); + this._release(); + yield settled.value; + } + } + } + exports.Queue = Queue; +}); + +// node_modules/graphql/execution/incremental/WorkQueue.js +var require_WorkQueue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createWorkQueue = createWorkQueue; + var isPromise_ts_1 = require_isPromise(); + var Queue_ts_1 = require_Queue(); + function createWorkQueue(initialWork) { + const rootGroups = new Set; + const rootStreams = new Set; + const groupNodes = new Map; + const taskNodes = new Map; + let pushGraphEvent; + let stopGraphEvents; + const { newGroups: initialRootGroups, newStreams: initialRootStreams } = maybeIntegrateWork(initialWork); + const nonEmptyInitialRootGroups = pruneEmptyGroups(initialRootGroups); + for (const group of nonEmptyInitialRootGroups) { + rootGroups.add(group); + } + for (const stream of initialRootStreams) { + rootStreams.add(stream); + } + const events = new Queue_ts_1.Queue(({ push: _push, stop: _stop, onStop, started }) => { + pushGraphEvent = _push; + stopGraphEvents = _stop; + started.then(() => { + for (const group of rootGroups) { + startGroup(group); + } + for (const stream of rootStreams) { + startStream(stream); + } + }); + onStop((reason) => cancel(reason)); + }, 1).subscribe((graphEvents) => handleGraphEvents(graphEvents)); + return { + initialGroups: nonEmptyInitialRootGroups, + initialStreams: initialRootStreams, + events + }; + function cancel(reason) { + const cancelPromises = []; + for (const group of rootGroups) { + cancelGroup(group, reason, cancelPromises); + } + for (const stream of rootStreams) { + cancelStream(stream, reason, cancelPromises); + } + if (cancelPromises.length > 0) { + return Promise.allSettled(cancelPromises).then(() => { + return; + }); + } + } + function cancelGroup(group, reason, cancelPromises) { + const groupNode = groupNodes.get(group); + if (groupNode) { + for (const task of groupNode.tasks) { + cancelTask(task, reason, cancelPromises); + } + for (const childGroup of groupNode.childGroups) { + cancelGroup(childGroup, reason, cancelPromises); + } + } + } + function cancelTask(task, reason, cancelPromises) { + const abortResult = task.computation.abort(reason); + if ((0, isPromise_ts_1.isPromise)(abortResult)) { + cancelPromises.push(abortResult); + } + const taskNode = taskNodes.get(task); + if (taskNode) { + for (const childStream of taskNode.childStreams) { + cancelStream(childStream, reason, cancelPromises); + } + } + } + function cancelStream(stream, reason, cancelPromises) { + const abortResult = stream.queue.abort(reason); + if ((0, isPromise_ts_1.isPromise)(abortResult)) { + cancelPromises.push(abortResult); + } + } + function maybeIntegrateWork(work, parentTask) { + if (!work) { + return { newGroups: [], newStreams: [] }; + } + const { groups, tasks, streams } = work; + const newGroups = groups ? addGroups(groups, parentTask) : []; + if (tasks) { + for (const task of tasks) { + addTask(task); + } + } + const newStreams = streams ? addStreams(streams, parentTask) : []; + return { newGroups, newStreams }; + } + function addGroups(originalGroups, parentTask) { + const groupSet = new Set(originalGroups); + const visited = new Set; + const newRootGroups = []; + for (const group of originalGroups) { + addGroup(group, groupSet, newRootGroups, visited, parentTask); + } + return newRootGroups; + } + function addGroup(group, groupSet, newRootGroups, visited, parentTask) { + if (visited.has(group)) { + return; + } + visited.add(group); + const parent = group.parent; + if (parent !== undefined && groupSet.has(parent)) { + addGroup(parent, groupSet, newRootGroups, visited, parentTask); + } + const groupNode = { + childGroups: [], + tasks: new Set, + pending: 0 + }; + groupNodes.set(group, groupNode); + if (parentTask === undefined && !parent) { + newRootGroups.push(group); + } else if (parent) { + groupNodes.get(parent)?.childGroups.push(group); + } + } + function addTask(task) { + for (const group of task.groups) { + const groupNode = groupNodes.get(group); + if (groupNode) { + groupNode.tasks.add(task); + groupNode.pending++; + if (rootGroups.has(group)) { + startTask(task); + } + } + } + } + function addStreams(streams, parentTask) { + if (!parentTask) { + return streams; + } + const taskNode = taskNodes.get(parentTask); + if (taskNode) { + taskNode.childStreams.push(...streams); + } + return []; + } + function pruneEmptyGroups(newGroups, nonEmptyNewGroups = []) { + for (const newGroup of newGroups) { + const newGroupState = groupNodes.get(newGroup); + if (newGroupState) { + if (newGroupState.pending === 0) { + groupNodes.delete(newGroup); + pruneEmptyGroups(newGroupState.childGroups, nonEmptyNewGroups); + } else { + nonEmptyNewGroups.push(newGroup); + } + } + } + return nonEmptyNewGroups; + } + function startNewWork(newGroups, newStreams) { + for (const group of newGroups) { + rootGroups.add(group); + startGroup(group); + } + for (const stream of newStreams) { + rootStreams.add(stream); + startStream(stream); + } + } + function startGroup(group) { + const groupNode = groupNodes.get(group); + if (groupNode) { + for (const task of groupNode.tasks) { + startTask(task); + } + } + } + function startTask(task) { + if (taskNodes.has(task)) { + return; + } + taskNodes.set(task, { + value: undefined, + childStreams: [] + }); + try { + const result = task.computation.result(); + if ((0, isPromise_ts_1.isPromise)(result)) { + result.then((resolved) => { + pushGraphEvent({ kind: "TASK_SUCCESS", task, result: resolved }); + }, (error) => { + pushGraphEvent({ kind: "TASK_FAILURE", task, error }); + }); + } else { + pushGraphEvent({ kind: "TASK_SUCCESS", task, result }); + } + } catch (error) { + pushGraphEvent({ kind: "TASK_FAILURE", task, error }); + } + } + async function startStream(stream) { + try { + await stream.queue.forEachBatch(async (items) => { + const pushed = pushGraphEvent({ + kind: "STREAM_ITEMS", + stream, + items + }); + if ((0, isPromise_ts_1.isPromise)(pushed)) { + await pushed; + } + }); + pushGraphEvent({ kind: "STREAM_SUCCESS", stream }); + } catch (error) { + pushGraphEvent({ kind: "STREAM_FAILURE", stream, error }); + } + } + function handleGraphEvents(graphEvents) { + const workQueueEvents = []; + for (const graphEvent of graphEvents) { + switch (graphEvent.kind) { + case "TASK_SUCCESS": + workQueueEvents.push(...taskSuccess(graphEvent)); + break; + case "TASK_FAILURE": + workQueueEvents.push(...taskFailure(graphEvent)); + break; + case "STREAM_ITEMS": + workQueueEvents.push(...streamItems(graphEvent)); + break; + case "STREAM_SUCCESS": + if (rootStreams.has(graphEvent.stream)) { + rootStreams.delete(graphEvent.stream); + workQueueEvents.push(graphEvent); + } + break; + case "STREAM_FAILURE": + rootStreams.delete(graphEvent.stream); + workQueueEvents.push(graphEvent); + break; + } + } + if (rootGroups.size === 0 && rootStreams.size === 0) { + stopGraphEvents(); + workQueueEvents.push({ kind: "WORK_QUEUE_TERMINATION" }); + } + return workQueueEvents.length > 0 ? workQueueEvents : undefined; + } + function taskSuccess(graphEvent) { + const { task, result } = graphEvent; + const { value, work } = result; + const taskNode = taskNodes.get(task); + if (taskNode) { + taskNode.value = value; + } + maybeIntegrateWork(work, task); + const groupEvents = []; + const newGroups = []; + const newStreams = []; + for (const group of task.groups) { + const groupNode = groupNodes.get(group); + if (groupNode) { + groupNode.pending--; + if (rootGroups.has(group) && groupNode.pending === 0) { + const { groupValuesEvent, groupSuccessEvent, newGroups: childNewGroups, newStreams: childNewStreams } = finishGroupSuccess(group, groupNode); + if (groupValuesEvent) { + groupEvents.push(groupValuesEvent); + } + groupEvents.push(groupSuccessEvent); + newGroups.push(...childNewGroups); + newStreams.push(...childNewStreams); + } + } + } + startNewWork(newGroups, newStreams); + return groupEvents; + } + function taskFailure(graphEvent) { + const { task, error } = graphEvent; + taskNodes.delete(task); + const groupFailureEvents = []; + for (const group of task.groups) { + const groupNode = groupNodes.get(group); + if (groupNode) { + groupFailureEvents.push(finishGroupFailure(group, groupNode, error)); + } + } + return groupFailureEvents; + } + function streamItems(graphEvent) { + const { stream, items } = graphEvent; + const values = []; + const newGroups = []; + const newStreams = []; + for (const { value, work } of items) { + const { newGroups: itemNewGroups, newStreams: itemNewStreams } = maybeIntegrateWork(work); + const nonEmptyNewGroups = pruneEmptyGroups(itemNewGroups); + startNewWork(nonEmptyNewGroups, itemNewStreams); + values.push(value); + newGroups.push(...nonEmptyNewGroups); + newStreams.push(...itemNewStreams); + } + const streamValuesEvent = { + kind: "STREAM_VALUES", + stream, + values, + newGroups, + newStreams + }; + if (stream.queue.isStopped()) { + rootStreams.delete(stream); + return [streamValuesEvent, { kind: "STREAM_SUCCESS", stream }]; + } + return [streamValuesEvent]; + } + function finishGroupSuccess(group, groupNode) { + groupNodes.delete(group); + const values = []; + const newStreams = []; + for (const task of groupNode.tasks) { + const taskNode = taskNodes.get(task); + if (taskNode) { + const { value, childStreams } = taskNode; + if (value !== undefined) { + values.push(value); + } + for (const childStream of childStreams) { + newStreams.push(childStream); + } + removeTask(task); + } + } + const newGroups = pruneEmptyGroups(groupNode.childGroups); + rootGroups.delete(group); + return { + groupValuesEvent: values.length ? { kind: "GROUP_VALUES", group, values } : undefined, + groupSuccessEvent: { + kind: "GROUP_SUCCESS", + group, + newGroups, + newStreams + }, + newGroups, + newStreams + }; + } + function finishGroupFailure(group, groupNode, error) { + removeGroup(group, groupNode); + rootGroups.delete(group); + return { kind: "GROUP_FAILURE", group, error }; + } + function removeGroup(group, groupNode) { + groupNodes.delete(group); + for (const task of groupNode.tasks) { + if (task.groups.every((taskGroup) => !groupNodes.has(taskGroup))) { + removeTask(task); + } + } + for (const childGroup of groupNode.childGroups) { + const childGroupState = groupNodes.get(childGroup); + if (childGroupState) { + removeGroup(childGroup, childGroupState); + } + } + } + function removeTask(task) { + for (const group of task.groups) { + const groupNode = groupNodes.get(group); + groupNode?.tasks.delete(task); + } + taskNodes.delete(task); + } + } +}); + +// node_modules/graphql/execution/incremental/IncrementalPublisher.js +var require_IncrementalPublisher = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.IncrementalPublisher = undefined; + var Path_ts_1 = require_Path(); + var ensureGraphQLError_ts_1 = require_ensureGraphQLError(); + var mapAsyncIterable_ts_1 = require_mapAsyncIterable(); + var withConcurrentAbruptClose_ts_1 = require_withConcurrentAbruptClose(); + var WorkQueue_ts_1 = require_WorkQueue(); + + class IncrementalPublisher { + constructor() { + this._ids = new Map; + this._nextId = 0; + } + buildResponse(data, errors, work, abortSignal, onFinished) { + const { initialGroups, initialStreams, events } = (0, WorkQueue_ts_1.createWorkQueue)(work); + function abort() { + subsequentResults.throw(abortSignal?.reason).catch(() => {}); + } + if (abortSignal) { + abortSignal.addEventListener("abort", abort); + } + const onWorkQueueFinished = () => { + onFinished(); + abortSignal?.removeEventListener("abort", abort); + }; + const pending = this._toPendingResults(initialGroups, initialStreams); + const initialResult = errors.length ? { errors, data, pending, hasNext: true } : { data, pending, hasNext: true }; + const subsequentResults = (0, withConcurrentAbruptClose_ts_1.withConcurrentAbruptClose)((0, mapAsyncIterable_ts_1.mapAsyncIterable)(events, (batch) => this._handleBatch(batch, onWorkQueueFinished)), () => onWorkQueueFinished()); + return { + initialResult, + subsequentResults + }; + } + _ensureId(deferredFragmentOrStream) { + let id = this._ids.get(deferredFragmentOrStream); + if (id !== undefined) { + return id; + } + id = String(this._nextId++); + this._ids.set(deferredFragmentOrStream, id); + return id; + } + _toPendingResults(newGroups, newStreams) { + const pendingResults = []; + for (const collection of [newGroups, newStreams]) { + for (const node of collection) { + const id = this._ensureId(node); + const pendingResult = { + id, + path: (0, Path_ts_1.pathToArray)(node.path) + }; + if (node.label !== undefined) { + pendingResult.label = node.label; + } + pendingResults.push(pendingResult); + } + } + return pendingResults; + } + _handleBatch(batch, onWorkQueueFinished) { + const context = { + pending: [], + incremental: [], + completed: [], + hasNext: true + }; + for (const event of batch) { + this._handleWorkQueueEvent(event, context, onWorkQueueFinished); + } + const { incremental, completed, pending, hasNext } = context; + const result = { hasNext }; + if (pending.length > 0) { + result.pending = pending; + } + if (incremental.length > 0) { + result.incremental = incremental; + } + if (completed.length > 0) { + result.completed = completed; + } + return result; + } + _handleWorkQueueEvent(event, context, onWorkQueueFinished) { + switch (event.kind) { + case "GROUP_VALUES": { + const group = event.group; + const id = this._ensureId(group); + for (const value of event.values) { + const { bestId, subPath } = this._getBestIdAndSubPath(id, group, value); + const incrementalEntry = { + id: bestId, + data: value.data + }; + if (value.errors !== undefined) { + incrementalEntry.errors = value.errors; + } + if (subPath !== undefined) { + incrementalEntry.subPath = subPath; + } + context.incremental.push(incrementalEntry); + } + break; + } + case "GROUP_SUCCESS": { + const group = event.group; + const id = this._ensureId(group); + context.completed.push({ id }); + this._ids.delete(group); + if (event.newGroups.length > 0 || event.newStreams.length > 0) { + context.pending.push(...this._toPendingResults(event.newGroups, event.newStreams)); + } + break; + } + case "GROUP_FAILURE": { + const { group, error } = event; + const id = this._ensureId(group); + context.completed.push({ + id, + errors: [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(error)] + }); + this._ids.delete(group); + break; + } + case "STREAM_VALUES": { + const stream = event.stream; + const id = this._ensureId(stream); + const { values, newGroups, newStreams } = event; + const items = []; + const errors = []; + for (const value of values) { + items.push(value.item); + if (value.errors !== undefined) { + errors.push(...value.errors); + } + } + context.incremental.push(errors.length > 0 ? { id, items, errors } : { id, items }); + if (newGroups.length > 0 || newStreams.length > 0) { + context.pending.push(...this._toPendingResults(newGroups, newStreams)); + } + break; + } + case "STREAM_SUCCESS": { + const stream = event.stream; + context.completed.push({ + id: this._ensureId(stream) + }); + this._ids.delete(stream); + break; + } + case "STREAM_FAILURE": { + const stream = event.stream; + context.completed.push({ + id: this._ensureId(stream), + errors: [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(event.error)] + }); + this._ids.delete(stream); + break; + } + case "WORK_QUEUE_TERMINATION": { + onWorkQueueFinished?.(); + context.hasNext = false; + break; + } + } + } + _getBestIdAndSubPath(initialId, initialDeferredFragmentRecord, executionGroupValue) { + let maxLength = (0, Path_ts_1.pathToArray)(initialDeferredFragmentRecord.path).length; + let bestId = initialId; + for (const deliveryGroup of executionGroupValue.deliveryGroups) { + if (deliveryGroup === initialDeferredFragmentRecord) { + continue; + } + const id = this._ids.get(deliveryGroup); + if (id === undefined) { + continue; + } + const path = (0, Path_ts_1.pathToArray)(deliveryGroup.path); + const length = path.length; + if (length > maxLength) { + maxLength = length; + bestId = id; + } + } + const subPath = executionGroupValue.path.slice(maxLength); + return { + bestId, + subPath: subPath.length > 0 ? subPath : undefined + }; + } + } + exports.IncrementalPublisher = IncrementalPublisher; +}); + +// node_modules/graphql/execution/incremental/IncrementalExecutor.js +var require_IncrementalExecutor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.IncrementalExecutor = undefined; + var invariant_ts_1 = require_invariant(); + var isPromise_ts_1 = require_isPromise(); + var memoize1_ts_1 = require_memoize1(); + var memoize2_ts_1 = require_memoize2(); + var Path_ts_1 = require_Path(); + var locatedError_ts_1 = require_locatedError(); + var ast_ts_1 = require_ast(); + var collectFields_ts_1 = require_collectFields(); + var collectIteratorPromises_ts_1 = require_collectIteratorPromises(); + var Executor_ts_1 = require_Executor(); + var returnIteratorCatchingErrors_ts_1 = require_returnIteratorCatchingErrors(); + var buildExecutionPlan_ts_1 = require_buildExecutionPlan(); + var Computation_ts_1 = require_Computation(); + var IncrementalPublisher_ts_1 = require_IncrementalPublisher(); + var Queue_ts_1 = require_Queue(); + var buildExecutionPlanFromInitial = (0, memoize1_ts_1.memoize1)((groupedFieldSet) => (0, buildExecutionPlan_ts_1.buildExecutionPlan)(groupedFieldSet)); + var buildExecutionPlanFromDeferred = (0, memoize2_ts_1.memoize2)((groupedFieldSet, deferUsageSet) => (0, buildExecutionPlan_ts_1.buildExecutionPlan)(groupedFieldSet, deferUsageSet)); + + class IncrementalExecutor extends Executor_ts_1.Executor { + constructor(validatedExecutionArgs, sharedExecutionContext, deferUsageSet) { + super(validatedExecutionArgs, sharedExecutionContext); + this.deferUsageSet = deferUsageSet; + this.groups = []; + this.tasks = []; + this.streams = []; + } + getCreateSubExecutor() { + const validatedExecutionArgs = this.validatedExecutionArgs; + const sharedExecutionContext = this.sharedExecutionContext; + return (deferUsageSet) => new IncrementalExecutor(validatedExecutionArgs, sharedExecutionContext, deferUsageSet); + } + abort(reason) { + super.abort(reason); + for (const task of this.tasks) { + const aborted = task.computation.abort(reason); + if (!!(0, isPromise_ts_1.isPromise)(aborted)) + (0, invariant_ts_1.invariant)(false); + } + for (const stream of this.streams) { + const aborted = stream.queue.abort(reason); + if (!!(0, isPromise_ts_1.isPromise)(aborted)) + (0, invariant_ts_1.invariant)(false); + } + } + buildResponse(data) { + const work = this.getIncrementalWork(); + const { tasks, streams } = work; + if (tasks?.length === 0 && streams?.length === 0) { + return super.buildResponse(data); + } + const errors = this.collectedErrors.errors; + if (!(data !== null)) + (0, invariant_ts_1.invariant)(false); + const incrementalPublisher = new IncrementalPublisher_ts_1.IncrementalPublisher; + return incrementalPublisher.buildResponse(data, errors, work, this.validatedExecutionArgs.externalAbortSignal, this.getFinishSharedExecution()); + } + executeCollectedRootFields(rootType, rootValue, originalGroupedFieldSet, serially, newDeferUsages) { + if (newDeferUsages.length === 0) { + return this.executeRootGroupedFieldSet(rootType, rootValue, originalGroupedFieldSet, serially, undefined); + } + if (!(this.validatedExecutionArgs.operation.operation !== ast_ts_1.OperationTypeNode.SUBSCRIPTION)) + (0, invariant_ts_1.invariant)(false, "`@defer` directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`."); + const { newDeliveryGroups, newDeliveryGroupMap } = this.getNewDeliveryGroupMap(newDeferUsages, undefined, undefined); + const { groupedFieldSet, newGroupedFieldSets } = this.buildRootExecutionPlan(originalGroupedFieldSet); + const data = this.executeRootGroupedFieldSet(rootType, rootValue, groupedFieldSet, serially, newDeliveryGroupMap); + this.groups.push(...newDeliveryGroups); + if (newGroupedFieldSets.size > 0) { + this.collectExecutionGroups(rootType, rootValue, undefined, newGroupedFieldSets, newDeliveryGroupMap); + } + return data; + } + buildRootExecutionPlan(originalGroupedFieldSet) { + return buildExecutionPlanFromInitial(originalGroupedFieldSet); + } + executeCollectedSubfields(parentType, sourceValue, path, originalGroupedFieldSet, newDeferUsages, deliveryGroupMap) { + if (newDeferUsages.length > 0) { + if (!(this.validatedExecutionArgs.operation.operation !== ast_ts_1.OperationTypeNode.SUBSCRIPTION)) + (0, invariant_ts_1.invariant)(false, "`@defer` directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`."); + } + if (deliveryGroupMap === undefined && newDeferUsages.length === 0) { + return this.executeFields(parentType, sourceValue, path, originalGroupedFieldSet, deliveryGroupMap); + } + const { newDeliveryGroups, newDeliveryGroupMap } = this.getNewDeliveryGroupMap(newDeferUsages, deliveryGroupMap, path); + const { groupedFieldSet, newGroupedFieldSets } = this.buildSubExecutionPlan(originalGroupedFieldSet); + const data = this.executeFields(parentType, sourceValue, path, groupedFieldSet, newDeliveryGroupMap); + this.groups.push(...newDeliveryGroups); + if (newGroupedFieldSets.size > 0) { + this.collectExecutionGroups(parentType, sourceValue, path, newGroupedFieldSets, newDeliveryGroupMap); + } + return data; + } + buildSubExecutionPlan(originalGroupedFieldSet) { + return this.deferUsageSet === undefined ? buildExecutionPlanFromInitial(originalGroupedFieldSet) : buildExecutionPlanFromDeferred(originalGroupedFieldSet, this.deferUsageSet); + } + collectExecutionGroups(parentType, sourceValue, path, newGroupedFieldSets, deliveryGroupMap) { + const createSubExecutor = this.getCreateSubExecutor(); + for (const [deferUsageSet, groupedFieldSet] of newGroupedFieldSets) { + const deliveryGroups = getDeliveryGroups(deferUsageSet, deliveryGroupMap); + const executor = createSubExecutor(deferUsageSet); + const executionGroup = { + groups: deliveryGroups, + path, + computation: new Computation_ts_1.Computation(() => executor.executeExecutionGroup(deliveryGroups, parentType, sourceValue, path, groupedFieldSet, deliveryGroupMap), (reason) => executor.abort(reason)) + }; + const parentDeferUsages = this.deferUsageSet; + if (this.validatedExecutionArgs.enableEarlyExecution) { + if (this.shouldDefer(parentDeferUsages, deferUsageSet)) { + Promise.resolve().then(() => executionGroup.computation.prime()); + } else { + executionGroup.computation.prime(); + } + } + this.tasks.push(executionGroup); + } + } + executeExecutionGroup(deliveryGroups, parentType, sourceValue, path, groupedFieldSet, deliveryGroupMap) { + let result; + try { + result = this.executeFields(parentType, sourceValue, path, groupedFieldSet, deliveryGroupMap); + } catch (error) { + this.abort(); + throw error; + } + if ((0, isPromise_ts_1.isPromise)(result)) { + return result.then((resolved) => this.buildExecutionGroupResult(deliveryGroups, path, resolved), (error) => { + this.abort(); + throw error; + }); + } + return this.buildExecutionGroupResult(deliveryGroups, path, result); + } + buildExecutionGroupResult(deliveryGroups, path, result) { + const data = result; + const errors = this.collectedErrors.errors; + return this.finish({ + value: errors.length ? { deliveryGroups, path: (0, Path_ts_1.pathToArray)(path), errors, data } : { deliveryGroups, path: (0, Path_ts_1.pathToArray)(path), data }, + work: this.getIncrementalWork() + }); + } + getIncrementalWork() { + const { groups, tasks, streams, collectedErrors } = this; + if (collectedErrors.errors.length === 0) { + return { groups, tasks, streams }; + } + const cancellationReason = new Error("Cancelled secondary to null within original result"); + const filteredTasks = []; + for (const task of tasks) { + if (collectedErrors.hasNulledPosition(task.path)) { + const aborted = task.computation.abort(cancellationReason); + if (!!(0, isPromise_ts_1.isPromise)(aborted)) + (0, invariant_ts_1.invariant)(false); + } else { + filteredTasks.push(task); + } + } + const filteredStreams = []; + for (const stream of streams) { + if (collectedErrors.hasNulledPosition(stream.path)) { + const aborted = stream.queue.abort(cancellationReason); + if (!!(0, isPromise_ts_1.isPromise)(aborted)) + (0, invariant_ts_1.invariant)(false); + } else { + filteredStreams.push(stream); + } + } + return { + groups, + tasks: filteredTasks, + streams: filteredStreams + }; + } + getNewDeliveryGroupMap(newDeferUsages, deliveryGroupMap, path) { + const newDeliveryGroups = []; + const newDeliveryGroupMap = new Map(deliveryGroupMap); + for (const newDeferUsage of newDeferUsages) { + const parentDeferUsage = newDeferUsage.parentDeferUsage; + const parent = parentDeferUsage === undefined ? undefined : deliveryGroupFromDeferUsage(parentDeferUsage, newDeliveryGroupMap); + const deliveryGroup = { + path, + label: newDeferUsage.label, + parent + }; + newDeliveryGroups.push(deliveryGroup); + newDeliveryGroupMap.set(newDeferUsage, deliveryGroup); + } + return { + newDeliveryGroups, + newDeliveryGroupMap + }; + } + shouldDefer(parentDeferUsages, deferUsages) { + return parentDeferUsages === undefined || !Array.from(deferUsages).every((deferUsage) => parentDeferUsages.has(deferUsage)); + } + handleStream(index, path, iterator, streamUsage, info, itemType) { + const { handle, isAsync } = iterator; + const queue = this.buildStreamItemQueue(index, path, handle, streamUsage.fieldDetailsList, info, itemType, isAsync); + const itemStream = { + label: streamUsage.label, + path, + queue, + initialCount: index + }; + this.streams.push(itemStream); + return true; + } + buildStreamItemQueue(initialIndex, streamPath, iterator, fieldDetailsList, info, itemType, isAsync) { + const createSubExecutor = this.getCreateSubExecutor(); + const { enableEarlyExecution } = this.validatedExecutionArgs; + const sharedExecutionContext = this.sharedExecutionContext; + const queue = new Queue_ts_1.Queue(async ({ push, stop, onStop, started }) => { + const abortStreamItems = new Set; + let finishedNormally = false; + let stopRequested = false; + onStop((reason) => { + stopRequested = true; + if (!finishedNormally) { + for (const abortStreamItem of abortStreamItems) { + abortStreamItem(reason); + } + if (isAsync) { + sharedExecutionContext.asyncWorkTracker.add((0, returnIteratorCatchingErrors_ts_1.returnIteratorCatchingErrors)(iterator)); + } else { + sharedExecutionContext.asyncWorkTracker.addValues((0, collectIteratorPromises_ts_1.collectIteratorPromises)(iterator)); + } + } + }); + await (enableEarlyExecution ? Promise.resolve() : started); + if (stopRequested) { + return; + } + let index = initialIndex; + while (true) { + let iteration; + try { + if (isAsync) { + iteration = await iterator.next(); + if (stopRequested) { + return; + } + } else { + iteration = iterator.next(); + } + } catch (rawError) { + throw (0, locatedError_ts_1.locatedError)(rawError, toNodes(fieldDetailsList), (0, Path_ts_1.pathToArray)(streamPath)); + } + if (iteration.done) { + finishedNormally = true; + const stopped = stop(); + if ((0, isPromise_ts_1.isPromise)(stopped)) { + stopped.catch(() => { + return; + }); + } + return; + } + const itemPath = (0, Path_ts_1.addPath)(streamPath, index, undefined); + const executor = createSubExecutor(); + let streamItemResult = executor.completeStreamItem(itemPath, iteration.value, fieldDetailsList, info, itemType); + if ((0, isPromise_ts_1.isPromise)(streamItemResult)) { + if (enableEarlyExecution) { + const abortStreamItem = (reason) => executor.abort(reason); + abortStreamItems.add(abortStreamItem); + streamItemResult = streamItemResult.finally(() => { + abortStreamItems.delete(abortStreamItem); + }); + } else { + streamItemResult = await streamItemResult; + if (stopRequested) { + return; + } + } + } + const pushResult = push(streamItemResult); + if ((0, isPromise_ts_1.isPromise)(pushResult)) { + await pushResult; + if (stopRequested) { + return; + } + } + index += 1; + } + }, 100); + return queue; + } + completeStreamItem(itemPath, item, fieldDetailsList, info, itemType) { + if ((0, isPromise_ts_1.isPromiseLike)(item)) { + return this.completePromisedValue(itemType, fieldDetailsList, info, itemPath, item, undefined).then((resolvedItem) => this.buildStreamItemResult(resolvedItem), (rawError) => { + this.handleFieldError(rawError, itemType, fieldDetailsList, itemPath); + return this.buildStreamItemResult(null); + }).then(undefined, (error) => { + this.abort(); + throw error; + }); + } + let result; + try { + try { + result = this.completeValue(itemType, fieldDetailsList, info, itemPath, item, undefined); + } catch (rawError) { + this.handleFieldError(rawError, itemType, fieldDetailsList, itemPath); + return this.buildStreamItemResult(null); + } + } catch (error) { + this.abort(); + throw error; + } + if ((0, isPromise_ts_1.isPromise)(result)) { + return result.then((resolved) => this.buildStreamItemResult(resolved), (rawError) => { + this.handleFieldError(rawError, itemType, fieldDetailsList, itemPath); + return this.buildStreamItemResult(null); + }).then(undefined, (error) => { + this.abort(); + throw error; + }); + } + return this.buildStreamItemResult(result); + } + buildStreamItemResult(result) { + const item = result; + const errors = this.collectedErrors.errors; + const work = this.getIncrementalWork(); + return this.finish(errors.length > 0 ? { value: { item, errors }, work } : { value: { item }, work }); + } + } + exports.IncrementalExecutor = IncrementalExecutor; + function toNodes(fieldDetailsList) { + return fieldDetailsList.map((fieldDetails) => fieldDetails.node); + } + function getDeliveryGroups(deferUsageSet, deliveryGroupMap) { + return Array.from(deferUsageSet).map((deferUsage) => deliveryGroupFromDeferUsage(deferUsage, deliveryGroupMap)); + } + function deliveryGroupFromDeferUsage(deferUsage, deliveryGroupMap) { + return deliveryGroupMap.get(deferUsage); + } +}); + +// node_modules/graphql/execution/execute.js +var require_execute = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultFieldResolver = exports.defaultTypeResolver = undefined; + exports.execute = execute; + exports.experimentalExecuteIncrementally = experimentalExecuteIncrementally; + exports.executeIgnoringIncremental = executeIgnoringIncremental; + exports.executeRootSelectionSet = executeRootSelectionSet; + exports.experimentalExecuteRootSelectionSet = experimentalExecuteRootSelectionSet; + exports.executeRootSelectionSetIgnoringIncremental = executeRootSelectionSetIgnoringIncremental; + exports.executeSync = executeSync; + exports.executeSubscriptionEvent = executeSubscriptionEvent; + exports.subscribe = subscribe; + exports.createSourceEventStream = createSourceEventStream; + exports.validateExecutionArgs = validateExecutionArgs; + exports.validateSubscriptionArgs = validateSubscriptionArgs; + exports.mapSourceToResponseEvent = mapSourceToResponseEvent; + var inspect_ts_1 = require_inspect(); + var isAsyncIterable_ts_1 = require_isAsyncIterable(); + var isObjectLike_ts_1 = require_isObjectLike(); + var isPromise_ts_1 = require_isPromise(); + var Path_ts_1 = require_Path(); + var ensureGraphQLError_ts_1 = require_ensureGraphQLError(); + var GraphQLError_ts_1 = require_GraphQLError(); + var locatedError_ts_1 = require_locatedError(); + var kinds_ts_1 = require_kinds(); + var predicates_ts_1 = require_predicates(); + var directives_ts_1 = require_directives(); + var index_ts_1 = require_type(); + var getOperationAST_ts_1 = require_getOperationAST(); + var diagnostics_ts_1 = require_diagnostics(); + var buildResolveInfo_ts_1 = require_buildResolveInfo(); + var cancellablePromise_ts_1 = require_cancellablePromise(); + var collectFields_ts_1 = require_collectFields(); + var createSharedExecutionContext_ts_1 = require_createSharedExecutionContext(); + var Executor_ts_1 = require_Executor(); + var ExecutorThrowingOnIncremental_ts_1 = require_ExecutorThrowingOnIncremental(); + var getVariableSignature_ts_1 = require_getVariableSignature(); + var IncrementalExecutor_ts_1 = require_IncrementalExecutor(); + var mapAsyncIterable_ts_1 = require_mapAsyncIterable(); + var values_ts_1 = require_values(); + var UNEXPECTED_EXPERIMENTAL_DIRECTIVES = "The provided schema unexpectedly contains experimental directives (@defer or @stream). These directives may only be utilized if experimental execution features are explicitly enabled."; + function execute(args) { + if (!(0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.executeChannel)) { + return executeImpl(args); + } + return (0, diagnostics_ts_1.traceMixed)(diagnostics_ts_1.executeChannel, buildOperationContextFromArgs(args), () => executeImpl(args)); + } + function buildOperationContextFromArgs(args) { + let operation; + const resolveOperation = () => { + if (operation === undefined) { + operation = (0, getOperationAST_ts_1.getOperationAST)(args.document, args.operationName); + } + return operation; + }; + return { + schema: args.schema, + document: args.document, + rawVariableValues: args.variableValues, + get operationName() { + return args.operationName ?? resolveOperation()?.name?.value; + }, + get operationType() { + return resolveOperation()?.operation; + } + }; + } + function executeImpl(args) { + if (args.schema.getDirective("defer") || args.schema.getDirective("stream")) { + throw new Error(UNEXPECTED_EXPERIMENTAL_DIRECTIVES); + } + const validatedExecutionArgs = validateExecutionArgs(args); + if (!("schema" in validatedExecutionArgs)) { + return { errors: validatedExecutionArgs }; + } + return executeRootSelectionSet(validatedExecutionArgs); + } + function experimentalExecuteIncrementally(args) { + if (!(0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.executeChannel)) { + return experimentalExecuteIncrementallyImpl(args); + } + return (0, diagnostics_ts_1.traceMixed)(diagnostics_ts_1.executeChannel, buildOperationContextFromArgs(args), () => experimentalExecuteIncrementallyImpl(args)); + } + function experimentalExecuteIncrementallyImpl(args) { + const validatedExecutionArgs = validateExecutionArgs(args); + if (!("schema" in validatedExecutionArgs)) { + return { errors: validatedExecutionArgs }; + } + return experimentalExecuteRootSelectionSet(validatedExecutionArgs); + } + function executeIgnoringIncremental(args) { + if (!(0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.executeChannel)) { + return executeIgnoringIncrementalImpl(args); + } + return (0, diagnostics_ts_1.traceMixed)(diagnostics_ts_1.executeChannel, buildOperationContextFromArgs(args), () => executeIgnoringIncrementalImpl(args)); + } + function executeIgnoringIncrementalImpl(args) { + const validatedExecutionArgs = validateExecutionArgs(args); + if (!("schema" in validatedExecutionArgs)) { + return { errors: validatedExecutionArgs }; + } + return executeRootSelectionSetIgnoringIncremental(validatedExecutionArgs); + } + function executeRootSelectionSet(validatedExecutionArgs) { + return new ExecutorThrowingOnIncremental_ts_1.ExecutorThrowingOnIncremental(validatedExecutionArgs).executeRootSelectionSet(); + } + function experimentalExecuteRootSelectionSet(validatedExecutionArgs) { + return new IncrementalExecutor_ts_1.IncrementalExecutor(validatedExecutionArgs).executeRootSelectionSet(); + } + function executeRootSelectionSetIgnoringIncremental(validatedExecutionArgs) { + return new Executor_ts_1.Executor(validatedExecutionArgs).executeRootSelectionSet(); + } + function executeSync(args) { + const result = experimentalExecuteIncrementally(args); + if ((0, isPromise_ts_1.isPromise)(result) || "initialResult" in result) { + throw new Error("GraphQL execution failed to complete synchronously."); + } + return result; + } + function executeSubscriptionEvent(validatedExecutionArgs) { + return new ExecutorThrowingOnIncremental_ts_1.ExecutorThrowingOnIncremental(validatedExecutionArgs).executeRootSelectionSet(false); + } + function subscribe(args) { + if (!(0, diagnostics_ts_1.shouldTrace)(diagnostics_ts_1.subscribeChannel)) { + return subscribeImpl(args); + } + return (0, diagnostics_ts_1.traceMixed)(diagnostics_ts_1.subscribeChannel, buildOperationContextFromArgs(args), () => subscribeImpl(args)); + } + function subscribeImpl(args) { + const validatedExecutionArgs = validateSubscriptionArgs(args); + if (!("schema" in validatedExecutionArgs)) { + return { errors: validatedExecutionArgs }; + } + const resultOrStream = createSourceEventStream(validatedExecutionArgs); + if ((0, isPromise_ts_1.isPromise)(resultOrStream)) { + return resultOrStream.then((resolvedResultOrStream) => (0, isAsyncIterable_ts_1.isAsyncIterable)(resolvedResultOrStream) ? mapSourceToResponseEvent(validatedExecutionArgs, resolvedResultOrStream) : resolvedResultOrStream); + } + return (0, isAsyncIterable_ts_1.isAsyncIterable)(resultOrStream) ? mapSourceToResponseEvent(validatedExecutionArgs, resultOrStream) : resultOrStream; + } + function createSourceEventStream(validatedExecutionArgs) { + if (!("operation" in validatedExecutionArgs)) { + throw new GraphQLError_ts_1.GraphQLError("Passing ExecutionArgs to createSourceEventStream() was removed in graphql-js@17.0.0; call validateSubscriptionArgs() first and pass the result instead, or use subscribe() for the full subscription pipeline."); + } + try { + const eventStream = executeSubscription(validatedExecutionArgs); + if ((0, isPromise_ts_1.isPromise)(eventStream)) { + return eventStream.then(undefined, (error) => ({ + errors: [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(error)] + })); + } + return eventStream; + } catch (error) { + return { errors: [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(error)] }; + } + } + function validateExecutionArgs(args) { + const { schema, document: document2, rootValue, contextValue, variableValues: rawVariableValues, operationName, fieldResolver, typeResolver, subscribeFieldResolver, abortSignal: externalAbortSignal, enableEarlyExecution, hooks, options } = args; + (0, index_ts_1.assertValidSchema)(schema); + let operation; + const fragmentDefinitions = Object.create(null); + const fragments = Object.create(null); + const fragmentVariableSignatureErrors = []; + for (const definition of document2.definitions) { + switch (definition.kind) { + case kinds_ts_1.Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [ + new GraphQLError_ts_1.GraphQLError("Must provide operation name if query contains multiple operations.") + ]; + } + operation = definition; + } else if (definition.name?.value === operationName) { + operation = definition; + } + break; + case kinds_ts_1.Kind.FRAGMENT_DEFINITION: { + fragmentDefinitions[definition.name.value] = definition; + let variableSignatures; + if (definition.variableDefinitions) { + const signatures = Object.create(null); + for (const varDef of definition.variableDefinitions) { + const signature = (0, getVariableSignature_ts_1.getVariableSignature)(schema, varDef); + if (signature instanceof GraphQLError_ts_1.GraphQLError) { + fragmentVariableSignatureErrors.push(signature); + continue; + } + signatures[signature.name] = signature; + } + variableSignatures = signatures; + } + fragments[definition.name.value] = { definition, variableSignatures }; + break; + } + default: + } + } + if (!operation) { + if (operationName != null) { + return [new GraphQLError_ts_1.GraphQLError(`Unknown operation named "${operationName}".`)]; + } + return [new GraphQLError_ts_1.GraphQLError("Must provide an operation.")]; + } + if (fragmentVariableSignatureErrors.length > 0) { + return fragmentVariableSignatureErrors; + } + const variableDefinitions = operation.variableDefinitions ?? []; + const hideSuggestions = args.hideSuggestions ?? false; + const coercionInput = rawVariableValues ?? {}; + const coercionOptions = { + maxErrors: options?.maxCoercionErrors ?? 50, + hideSuggestions + }; + const coercionChannel = diagnostics_ts_1.executeVariableCoercionChannel; + const variableValuesOrErrors = (0, diagnostics_ts_1.shouldTrace)(coercionChannel) ? (0, diagnostics_ts_1.traceMixed)(coercionChannel, { + schema, + document: document2, + operation, + rawVariableValues, + operationName: operation.name?.value, + operationType: operation.operation + }, () => (0, values_ts_1.getVariableValues)(schema, variableDefinitions, coercionInput, coercionOptions)) : (0, values_ts_1.getVariableValues)(schema, variableDefinitions, coercionInput, coercionOptions); + if (variableValuesOrErrors.errors) { + return variableValuesOrErrors.errors; + } + const errorPropagation = !operation.directives?.find((directive) => directive.name.value === directives_ts_1.GraphQLDisableErrorPropagationDirective.name); + return { + schema, + document: document2, + fragmentDefinitions, + fragments, + rootValue, + contextValue, + operation, + variableValues: variableValuesOrErrors.variableValues, + fieldResolver: fieldResolver ?? exports.defaultFieldResolver, + typeResolver: typeResolver ?? exports.defaultTypeResolver, + subscribeFieldResolver: subscribeFieldResolver ?? exports.defaultFieldResolver, + hideSuggestions, + errorPropagation, + externalAbortSignal: externalAbortSignal ?? undefined, + enableEarlyExecution: enableEarlyExecution === true, + hooks: hooks ?? undefined, + rawVariableValues + }; + } + function validateSubscriptionArgs(args) { + const validatedExecutionArgs = validateExecutionArgs(args); + if (!("schema" in validatedExecutionArgs)) { + return validatedExecutionArgs; + } + assertSubscriptionExecutionArgs(validatedExecutionArgs); + return validatedExecutionArgs; + } + function assertSubscriptionExecutionArgs(validatedExecutionArgs) { + if (!(0, predicates_ts_1.isSubscriptionOperationDefinitionNode)(validatedExecutionArgs.operation)) { + throw new GraphQLError_ts_1.GraphQLError("Expected subscription operation."); + } + } + var defaultTypeResolver = function(value, contextValue, info, abstractType) { + if ((0, isObjectLike_ts_1.isObjectLike)(value) && typeof value.__typename === "string") { + return value.__typename; + } + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + try { + for (let i = 0;i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + if ((0, isPromise_ts_1.isPromiseLike)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + if (promisedIsTypeOfResults.length) { + info.getAsyncHelpers().track(promisedIsTypeOfResults); + } + return type.name; + } + } + } + } catch (error) { + if (promisedIsTypeOfResults.length) { + info.getAsyncHelpers().track(promisedIsTypeOfResults); + } + throw error; + } + if (promisedIsTypeOfResults.length) { + return info.getAsyncHelpers().promiseAll(promisedIsTypeOfResults).then((isTypeOfResults) => { + for (let i = 0;i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i].name; + } + } + }); + } + }; + exports.defaultTypeResolver = defaultTypeResolver; + var defaultFieldResolver = function(source, args, contextValue, info) { + if ((0, isObjectLike_ts_1.isObjectLike)(source) || typeof source === "function") { + const property = source[info.fieldName]; + if (typeof property === "function") { + return source[info.fieldName](args, contextValue, info); + } + return property; + } + }; + exports.defaultFieldResolver = defaultFieldResolver; + function mapSourceToResponseEvent(validatedExecutionArgs, sourceEventStream, rootSelectionSetExecutor = executeSubscriptionEvent) { + function mapFn(payload) { + const perEventExecutionArgs = { + ...validatedExecutionArgs, + rootValue: payload + }; + return rootSelectionSetExecutor(perEventExecutionArgs); + } + const externalAbortSignal = validatedExecutionArgs.externalAbortSignal; + if (externalAbortSignal) { + const generator = (0, mapAsyncIterable_ts_1.mapAsyncIterable)(sourceEventStream, mapFn); + return { + ...generator, + next: () => (0, cancellablePromise_ts_1.cancellablePromise)(generator.next(), externalAbortSignal) + }; + } + return (0, mapAsyncIterable_ts_1.mapAsyncIterable)(sourceEventStream, mapFn); + } + function executeSubscription(validatedExecutionArgs) { + const { schema, fragments, rootValue, contextValue, operation, variableValues, hideSuggestions, externalAbortSignal } = validatedExecutionArgs; + const rootType = schema.getSubscriptionType(); + if (rootType == null) { + throw new GraphQLError_ts_1.GraphQLError("Schema is not configured to execute subscription operation.", { nodes: operation }); + } + const { groupedFieldSet } = (0, collectFields_ts_1.collectFields)(schema, fragments, variableValues, rootType, operation.selectionSet, hideSuggestions); + const firstRootField = groupedFieldSet.entries().next().value; + const [responseName, fieldDetailsList] = firstRootField; + const firstFieldDetails = fieldDetailsList[0]; + const firstNode = firstFieldDetails.node; + const fieldName = firstNode.name.value; + const fieldDef = schema.getField(rootType, fieldName); + const fieldNodes = fieldDetailsList.map((fieldDetails) => fieldDetails.node); + if (!fieldDef) { + throw new GraphQLError_ts_1.GraphQLError(`The subscription field "${fieldName}" is not defined.`, { nodes: fieldNodes }); + } + const sharedExecutionContext = (0, createSharedExecutionContext_ts_1.createSharedExecutionContext)(externalAbortSignal); + const path = (0, Path_ts_1.addPath)(undefined, responseName, rootType.name); + const info = (0, buildResolveInfo_ts_1.buildResolveInfo)(validatedExecutionArgs, fieldDef, fieldNodes, rootType, path, sharedExecutionContext.getAbortSignal, sharedExecutionContext.getAsyncHelpers); + try { + const args = (0, values_ts_1.getArgumentValues)(fieldDef, firstNode, variableValues, firstFieldDetails.fragmentVariableValues, hideSuggestions); + const resolveFn = fieldDef.subscribe ?? validatedExecutionArgs.subscribeFieldResolver; + const result = resolveFn(rootValue, args, contextValue, info); + if ((0, isPromise_ts_1.isPromiseLike)(result)) { + const promisedResult = Promise.resolve(result); + const promise = externalAbortSignal ? (0, cancellablePromise_ts_1.cancellablePromise)(promisedResult, externalAbortSignal) : promisedResult; + return promise.then(assertEventStream).then(undefined, (error) => { + throw (0, locatedError_ts_1.locatedError)(error, toNodes(fieldDetailsList), (0, Path_ts_1.pathToArray)(path)); + }); + } + return assertEventStream(result); + } catch (error) { + throw (0, locatedError_ts_1.locatedError)(error, fieldNodes, (0, Path_ts_1.pathToArray)(path)); + } + } + function assertEventStream(result) { + if (result instanceof Error) { + throw result; + } + if (!(0, isAsyncIterable_ts_1.isAsyncIterable)(result)) { + throw new GraphQLError_ts_1.GraphQLError("Subscription field must return Async Iterable. " + `Received: ${(0, inspect_ts_1.inspect)(result)}.`); + } + return result; + } + function toNodes(fieldDetailsList) { + return fieldDetailsList.map((fieldDetails) => fieldDetails.node); + } +}); + +// node_modules/graphql/harness.js +var require_harness = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultHarness = undefined; + var parser_ts_1 = require_parser(); + var validate_ts_1 = require_validate2(); + var execute_ts_1 = require_execute(); + exports.defaultHarness = { + parse: parser_ts_1.parse, + validate: validate_ts_1.validate, + execute: execute_ts_1.execute, + subscribe: execute_ts_1.subscribe + }; +}); + +// node_modules/graphql/graphql.js +var require_graphql = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.graphql = graphql; + exports.graphqlSync = graphqlSync; + var isPromise_ts_1 = require_isPromise(); + var ensureGraphQLError_ts_1 = require_ensureGraphQLError(); + var validate_ts_1 = require_validate(); + var harness_ts_1 = require_harness(); + function graphql(args) { + return new Promise((resolve) => resolve(graphqlImpl(args))); + } + function graphqlSync(args) { + const result = graphqlImpl(args); + if ((0, isPromise_ts_1.isPromise)(result)) { + throw new Error("GraphQL execution failed to complete synchronously."); + } + return result; + } + function graphqlImpl(args) { + const harness = args.harness ?? harness_ts_1.defaultHarness; + const { schema, source } = args; + const schemaValidationErrors = (0, validate_ts_1.validateSchema)(schema); + if (schemaValidationErrors.length > 0) { + return { errors: schemaValidationErrors }; + } + let document2; + try { + document2 = harness.parse(source, args); + } catch (syntaxError) { + return { errors: [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(syntaxError)] }; + } + if ((0, isPromise_ts_1.isPromise)(document2)) { + return document2.then((resolvedDocument) => validateAndExecute(harness, args, schema, resolvedDocument), (syntaxError) => ({ errors: [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(syntaxError)] })); + } + return validateAndExecute(harness, args, schema, document2); + } + function validateAndExecute(harness, args, schema, document2) { + const validationResult = harness.validate(schema, document2, args.rules, args); + if ((0, isPromise_ts_1.isPromise)(validationResult)) { + return validationResult.then((resolvedValidationResult) => checkValidationAndExecute(harness, args, resolvedValidationResult, document2)); + } + return checkValidationAndExecute(harness, args, validationResult, document2); + } + function checkValidationAndExecute(harness, args, validationResult, document2) { + if (validationResult.length > 0) { + return { errors: validationResult }; + } + return harness.execute({ ...args, document: document2 }); + } +}); + +// node_modules/graphql/language/index.js +var require_language = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DirectiveLocation = exports.isSubscriptionOperationDefinitionNode = exports.isSchemaCoordinateNode = exports.isTypeExtensionNode = exports.isTypeSystemExtensionNode = exports.isTypeDefinitionNode = exports.isTypeSystemDefinitionNode = exports.isTypeNode = exports.isConstValueNode = exports.isValueNode = exports.isSelectionNode = exports.isExecutableDefinitionNode = exports.isDefinitionNode = exports.OperationTypeNode = exports.Token = exports.Location = exports.BREAK = exports.getEnterLeaveForKind = exports.visitInParallel = exports.visit = exports.print = exports.parseSchemaCoordinate = exports.parseType = exports.parseConstValue = exports.parseValue = exports.parse = exports.Lexer = exports.TokenKind = exports.Kind = exports.printSourceLocation = exports.printLocation = exports.getLocation = exports.Source = undefined; + var source_ts_1 = require_source(); + Object.defineProperty(exports, "Source", { enumerable: true, get: function() { + return source_ts_1.Source; + } }); + var location_ts_1 = require_location(); + Object.defineProperty(exports, "getLocation", { enumerable: true, get: function() { + return location_ts_1.getLocation; + } }); + var printLocation_ts_1 = require_printLocation(); + Object.defineProperty(exports, "printLocation", { enumerable: true, get: function() { + return printLocation_ts_1.printLocation; + } }); + Object.defineProperty(exports, "printSourceLocation", { enumerable: true, get: function() { + return printLocation_ts_1.printSourceLocation; + } }); + var kinds_ts_1 = require_kinds(); + Object.defineProperty(exports, "Kind", { enumerable: true, get: function() { + return kinds_ts_1.Kind; + } }); + var tokenKind_ts_1 = require_tokenKind(); + Object.defineProperty(exports, "TokenKind", { enumerable: true, get: function() { + return tokenKind_ts_1.TokenKind; + } }); + var lexer_ts_1 = require_lexer(); + Object.defineProperty(exports, "Lexer", { enumerable: true, get: function() { + return lexer_ts_1.Lexer; + } }); + var parser_ts_1 = require_parser(); + Object.defineProperty(exports, "parse", { enumerable: true, get: function() { + return parser_ts_1.parse; + } }); + Object.defineProperty(exports, "parseValue", { enumerable: true, get: function() { + return parser_ts_1.parseValue; + } }); + Object.defineProperty(exports, "parseConstValue", { enumerable: true, get: function() { + return parser_ts_1.parseConstValue; + } }); + Object.defineProperty(exports, "parseType", { enumerable: true, get: function() { + return parser_ts_1.parseType; + } }); + Object.defineProperty(exports, "parseSchemaCoordinate", { enumerable: true, get: function() { + return parser_ts_1.parseSchemaCoordinate; + } }); + var printer_ts_1 = require_printer(); + Object.defineProperty(exports, "print", { enumerable: true, get: function() { + return printer_ts_1.print; + } }); + var visitor_ts_1 = require_visitor(); + Object.defineProperty(exports, "visit", { enumerable: true, get: function() { + return visitor_ts_1.visit; + } }); + Object.defineProperty(exports, "visitInParallel", { enumerable: true, get: function() { + return visitor_ts_1.visitInParallel; + } }); + Object.defineProperty(exports, "getEnterLeaveForKind", { enumerable: true, get: function() { + return visitor_ts_1.getEnterLeaveForKind; + } }); + Object.defineProperty(exports, "BREAK", { enumerable: true, get: function() { + return visitor_ts_1.BREAK; + } }); + var ast_ts_1 = require_ast(); + Object.defineProperty(exports, "Location", { enumerable: true, get: function() { + return ast_ts_1.Location; + } }); + Object.defineProperty(exports, "Token", { enumerable: true, get: function() { + return ast_ts_1.Token; + } }); + Object.defineProperty(exports, "OperationTypeNode", { enumerable: true, get: function() { + return ast_ts_1.OperationTypeNode; + } }); + var predicates_ts_1 = require_predicates(); + Object.defineProperty(exports, "isDefinitionNode", { enumerable: true, get: function() { + return predicates_ts_1.isDefinitionNode; + } }); + Object.defineProperty(exports, "isExecutableDefinitionNode", { enumerable: true, get: function() { + return predicates_ts_1.isExecutableDefinitionNode; + } }); + Object.defineProperty(exports, "isSelectionNode", { enumerable: true, get: function() { + return predicates_ts_1.isSelectionNode; + } }); + Object.defineProperty(exports, "isValueNode", { enumerable: true, get: function() { + return predicates_ts_1.isValueNode; + } }); + Object.defineProperty(exports, "isConstValueNode", { enumerable: true, get: function() { + return predicates_ts_1.isConstValueNode; + } }); + Object.defineProperty(exports, "isTypeNode", { enumerable: true, get: function() { + return predicates_ts_1.isTypeNode; + } }); + Object.defineProperty(exports, "isTypeSystemDefinitionNode", { enumerable: true, get: function() { + return predicates_ts_1.isTypeSystemDefinitionNode; + } }); + Object.defineProperty(exports, "isTypeDefinitionNode", { enumerable: true, get: function() { + return predicates_ts_1.isTypeDefinitionNode; + } }); + Object.defineProperty(exports, "isTypeSystemExtensionNode", { enumerable: true, get: function() { + return predicates_ts_1.isTypeSystemExtensionNode; + } }); + Object.defineProperty(exports, "isTypeExtensionNode", { enumerable: true, get: function() { + return predicates_ts_1.isTypeExtensionNode; + } }); + Object.defineProperty(exports, "isSchemaCoordinateNode", { enumerable: true, get: function() { + return predicates_ts_1.isSchemaCoordinateNode; + } }); + Object.defineProperty(exports, "isSubscriptionOperationDefinitionNode", { enumerable: true, get: function() { + return predicates_ts_1.isSubscriptionOperationDefinitionNode; + } }); + var directiveLocation_ts_1 = require_directiveLocation(); + Object.defineProperty(exports, "DirectiveLocation", { enumerable: true, get: function() { + return directiveLocation_ts_1.DirectiveLocation; + } }); +}); + +// node_modules/graphql/execution/legacyIncremental/BranchingIncrementalPublisher.js +var require_BranchingIncrementalPublisher = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BranchingIncrementalPublisher = undefined; + var Path_ts_1 = require_Path(); + var ensureGraphQLError_ts_1 = require_ensureGraphQLError(); + var WorkQueue_ts_1 = require_WorkQueue(); + var mapAsyncIterable_ts_1 = require_mapAsyncIterable(); + var withConcurrentAbruptClose_ts_1 = require_withConcurrentAbruptClose(); + + class BranchingIncrementalPublisher { + constructor() { + this._indices = new Map; + } + buildResponse(data, errors, work, abortSignal, onFinished) { + const { initialStreams, events } = (0, WorkQueue_ts_1.createWorkQueue)(work); + for (const stream of initialStreams) { + this._indices.set(stream, stream.initialCount); + } + function abort() { + subsequentResults.throw(abortSignal?.reason).catch(() => {}); + } + if (abortSignal) { + abortSignal.addEventListener("abort", abort); + } + const onWorkQueueFinished = () => { + onFinished(); + abortSignal?.removeEventListener("abort", abort); + }; + const initialResult = errors.length ? { errors, data, hasNext: true } : { data, hasNext: true }; + const subsequentResults = (0, withConcurrentAbruptClose_ts_1.withConcurrentAbruptClose)((0, mapAsyncIterable_ts_1.mapAsyncIterable)(events, (batch) => this._handleBatch(batch, onWorkQueueFinished)), () => onWorkQueueFinished()); + return { + initialResult, + subsequentResults + }; + } + _handleBatch(batch, onWorkQueueFinished) { + const context = { + incremental: [], + hasNext: true + }; + for (const event of batch) { + this._handleWorkQueueEvent(event, context, onWorkQueueFinished); + } + const { incremental, hasNext } = context; + const result = { hasNext }; + if (incremental.length > 0) { + result.incremental = incremental; + } + return result; + } + _handleWorkQueueEvent(event, context, onWorkQueueFinished) { + switch (event.kind) { + case "GROUP_VALUES": { + const group = event.group; + for (const value of event.values) { + context.incremental.push(buildIncrementalResult({ + data: value.data, + path: (0, Path_ts_1.pathToArray)(group.path) + }, group.label, value.errors)); + } + break; + } + case "GROUP_SUCCESS": { + break; + } + case "GROUP_FAILURE": { + const group = event.group; + context.incremental.push(buildIncrementalResult({ + data: null, + path: (0, Path_ts_1.pathToArray)(group.path) + }, group.label, [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(event.error)])); + break; + } + case "STREAM_VALUES": { + const stream = event.stream; + const { values } = event; + const items = []; + const errors = []; + for (const value of values) { + items.push(value.item); + if (value.errors !== undefined) { + errors.push(...value.errors); + } + } + let index = this._indices.get(stream); + if (index === undefined) { + index = stream.initialCount; + this._indices.set(stream, index); + } + this._indices.set(stream, index + items.length); + context.incremental.push(buildIncrementalResult({ + items, + path: (0, Path_ts_1.pathToArray)((0, Path_ts_1.addPath)(stream.path, index, undefined)) + }, stream.label, errors.length > 0 ? errors : undefined)); + break; + } + case "STREAM_SUCCESS": { + this._indices.delete(event.stream); + break; + } + case "STREAM_FAILURE": { + this._indices.delete(event.stream); + const stream = event.stream; + context.incremental.push(buildIncrementalResult({ + items: null, + path: (0, Path_ts_1.pathToArray)(stream.path) + }, stream.label, [(0, ensureGraphQLError_ts_1.ensureGraphQLError)(event.error)])); + break; + } + case "WORK_QUEUE_TERMINATION": { + onWorkQueueFinished?.(); + context.hasNext = false; + break; + } + } + } + } + exports.BranchingIncrementalPublisher = BranchingIncrementalPublisher; + function buildIncrementalResult(originalIncrementalResult, label, errors) { + const incrementalResult = originalIncrementalResult; + if (errors !== undefined) { + incrementalResult.errors = errors; + } + if (label !== undefined) { + incrementalResult.label = label; + } + return incrementalResult; + } +}); + +// node_modules/graphql/execution/legacyIncremental/BranchingIncrementalExecutor.js +var require_BranchingIncrementalExecutor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BranchingIncrementalExecutor = undefined; + var AccumulatorMap_ts_1 = require_AccumulatorMap(); + var getBySet_ts_1 = require_getBySet(); + var invariant_ts_1 = require_invariant(); + var isSameSet_ts_1 = require_isSameSet(); + var memoize1_ts_1 = require_memoize1(); + var memoize2_ts_1 = require_memoize2(); + var IncrementalExecutor_ts_1 = require_IncrementalExecutor(); + var BranchingIncrementalPublisher_ts_1 = require_BranchingIncrementalPublisher(); + var buildBranchingExecutionPlanFromInitial = (0, memoize1_ts_1.memoize1)((groupedFieldSet) => buildBranchingExecutionPlan(groupedFieldSet)); + var buildBranchingExecutionPlanFromDeferred = (0, memoize2_ts_1.memoize2)((groupedFieldSet, deferUsageSet) => buildBranchingExecutionPlan(groupedFieldSet, deferUsageSet)); + + class BranchingIncrementalExecutor extends IncrementalExecutor_ts_1.IncrementalExecutor { + getCreateSubExecutor() { + const validatedExecutionArgs = this.validatedExecutionArgs; + const sharedExecutionContext = this.sharedExecutionContext; + return (deferUsageSet) => new BranchingIncrementalExecutor(validatedExecutionArgs, sharedExecutionContext, deferUsageSet); + } + buildResponse(data) { + const work = this.getIncrementalWork(); + const { tasks, streams } = work; + if (tasks?.length === 0 && streams?.length === 0) { + return super.buildResponse(data); + } + const errors = this.collectedErrors.errors; + if (!(data !== null)) + (0, invariant_ts_1.invariant)(false); + const incrementalPublisher = new BranchingIncrementalPublisher_ts_1.BranchingIncrementalPublisher; + return incrementalPublisher.buildResponse(data, errors, work, this.validatedExecutionArgs.externalAbortSignal, this.getFinishSharedExecution()); + } + buildRootExecutionPlan(originalGroupedFieldSet) { + return buildBranchingExecutionPlanFromInitial(originalGroupedFieldSet); + } + buildSubExecutionPlan(originalGroupedFieldSet) { + return this.deferUsageSet === undefined ? buildBranchingExecutionPlanFromInitial(originalGroupedFieldSet) : buildBranchingExecutionPlanFromDeferred(originalGroupedFieldSet, this.deferUsageSet); + } + } + exports.BranchingIncrementalExecutor = BranchingIncrementalExecutor; + function buildBranchingExecutionPlan(originalGroupedFieldSet, parentDeferUsages = new Set) { + const groupedFieldSet = new AccumulatorMap_ts_1.AccumulatorMap; + const newGroupedFieldSets = new Map; + for (const [responseKey, fieldGroup] of originalGroupedFieldSet) { + for (const fieldDetails of fieldGroup) { + const deferUsage = fieldDetails.deferUsage; + const deferUsageSet = deferUsage === undefined ? new Set : new Set([deferUsage]); + if ((0, isSameSet_ts_1.isSameSet)(parentDeferUsages, deferUsageSet)) { + groupedFieldSet.add(responseKey, fieldDetails); + } else { + let newGroupedFieldSet = (0, getBySet_ts_1.getBySet)(newGroupedFieldSets, deferUsageSet); + if (newGroupedFieldSet === undefined) { + newGroupedFieldSet = new AccumulatorMap_ts_1.AccumulatorMap; + newGroupedFieldSets.set(deferUsageSet, newGroupedFieldSet); + } + newGroupedFieldSet.add(responseKey, fieldDetails); + } + } + } + return { + groupedFieldSet, + newGroupedFieldSets + }; + } +}); + +// node_modules/graphql/execution/legacyIncremental/legacyExecuteIncrementally.js +var require_legacyExecuteIncrementally = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.legacyExecuteIncrementally = legacyExecuteIncrementally; + exports.legacyExecuteRootSelectionSet = legacyExecuteRootSelectionSet; + var execute_ts_1 = require_execute(); + var BranchingIncrementalExecutor_ts_1 = require_BranchingIncrementalExecutor(); + function legacyExecuteIncrementally(args) { + const validatedExecutionArgs = (0, execute_ts_1.validateExecutionArgs)(args); + if (!("schema" in validatedExecutionArgs)) { + return { errors: validatedExecutionArgs }; + } + return legacyExecuteRootSelectionSet(validatedExecutionArgs); + } + function legacyExecuteRootSelectionSet(validatedExecutionArgs) { + return new BranchingIncrementalExecutor_ts_1.BranchingIncrementalExecutor(validatedExecutionArgs).executeRootSelectionSet(); + } +}); + +// node_modules/graphql/execution/index.js +var require_execution = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getDirectiveValues = exports.getVariableValues = exports.getArgumentValues = exports.AbortedGraphQLExecutionError = exports.legacyExecuteRootSelectionSet = exports.legacyExecuteIncrementally = exports.validateSubscriptionArgs = exports.validateExecutionArgs = exports.subscribe = exports.mapSourceToResponseEvent = exports.defaultTypeResolver = exports.defaultFieldResolver = exports.experimentalExecuteRootSelectionSet = exports.experimentalExecuteIncrementally = exports.executeSync = exports.executeSubscriptionEvent = exports.executeRootSelectionSet = exports.execute = exports.createSourceEventStream = exports.responsePathAsArray = undefined; + var Path_ts_1 = require_Path(); + Object.defineProperty(exports, "responsePathAsArray", { enumerable: true, get: function() { + return Path_ts_1.pathToArray; + } }); + var execute_ts_1 = require_execute(); + Object.defineProperty(exports, "createSourceEventStream", { enumerable: true, get: function() { + return execute_ts_1.createSourceEventStream; + } }); + Object.defineProperty(exports, "execute", { enumerable: true, get: function() { + return execute_ts_1.execute; + } }); + Object.defineProperty(exports, "executeRootSelectionSet", { enumerable: true, get: function() { + return execute_ts_1.executeRootSelectionSet; + } }); + Object.defineProperty(exports, "executeSubscriptionEvent", { enumerable: true, get: function() { + return execute_ts_1.executeSubscriptionEvent; + } }); + Object.defineProperty(exports, "executeSync", { enumerable: true, get: function() { + return execute_ts_1.executeSync; + } }); + Object.defineProperty(exports, "experimentalExecuteIncrementally", { enumerable: true, get: function() { + return execute_ts_1.experimentalExecuteIncrementally; + } }); + Object.defineProperty(exports, "experimentalExecuteRootSelectionSet", { enumerable: true, get: function() { + return execute_ts_1.experimentalExecuteRootSelectionSet; + } }); + Object.defineProperty(exports, "defaultFieldResolver", { enumerable: true, get: function() { + return execute_ts_1.defaultFieldResolver; + } }); + Object.defineProperty(exports, "defaultTypeResolver", { enumerable: true, get: function() { + return execute_ts_1.defaultTypeResolver; + } }); + Object.defineProperty(exports, "mapSourceToResponseEvent", { enumerable: true, get: function() { + return execute_ts_1.mapSourceToResponseEvent; + } }); + Object.defineProperty(exports, "subscribe", { enumerable: true, get: function() { + return execute_ts_1.subscribe; + } }); + Object.defineProperty(exports, "validateExecutionArgs", { enumerable: true, get: function() { + return execute_ts_1.validateExecutionArgs; + } }); + Object.defineProperty(exports, "validateSubscriptionArgs", { enumerable: true, get: function() { + return execute_ts_1.validateSubscriptionArgs; + } }); + var legacyExecuteIncrementally_ts_1 = require_legacyExecuteIncrementally(); + Object.defineProperty(exports, "legacyExecuteIncrementally", { enumerable: true, get: function() { + return legacyExecuteIncrementally_ts_1.legacyExecuteIncrementally; + } }); + Object.defineProperty(exports, "legacyExecuteRootSelectionSet", { enumerable: true, get: function() { + return legacyExecuteIncrementally_ts_1.legacyExecuteRootSelectionSet; + } }); + var AbortedGraphQLExecutionError_ts_1 = require_AbortedGraphQLExecutionError(); + Object.defineProperty(exports, "AbortedGraphQLExecutionError", { enumerable: true, get: function() { + return AbortedGraphQLExecutionError_ts_1.AbortedGraphQLExecutionError; + } }); + var values_ts_1 = require_values(); + Object.defineProperty(exports, "getArgumentValues", { enumerable: true, get: function() { + return values_ts_1.getArgumentValues; + } }); + Object.defineProperty(exports, "getVariableValues", { enumerable: true, get: function() { + return values_ts_1.getVariableValues; + } }); + Object.defineProperty(exports, "getDirectiveValues", { enumerable: true, get: function() { + return values_ts_1.getDirectiveValues; + } }); +}); + +// node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js +var require_NoDeprecatedCustomRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + function NoDeprecatedCustomRule(context) { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = fieldDef?.deprecationReason; + if (fieldDef && deprecationReason != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`The field ${fieldDef} is deprecated. ${deprecationReason}`, { nodes: node })); + } + }, + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = argDef?.deprecationReason; + if (argDef && deprecationReason != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`The argument "${argDef}" is deprecated. ${deprecationReason}`, { nodes: node })); + } + }, + ObjectField(node) { + const inputObjectDef = (0, definition_ts_1.getNamedType)(context.getParentInputType()); + if ((0, definition_ts_1.isInputObjectType)(inputObjectDef)) { + const inputFieldDef = inputObjectDef.getFields()[node.name.value]; + const deprecationReason = inputFieldDef?.deprecationReason; + if (deprecationReason != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`The input field ${inputFieldDef} is deprecated. ${deprecationReason}`, { nodes: node })); + } + } + }, + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = enumValueDef?.deprecationReason; + if (enumValueDef && deprecationReason != null) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`The enum value "${enumValueDef}" is deprecated. ${deprecationReason}`, { nodes: node })); + } + } + }; + } +}); + +// node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js +var require_NoSchemaIntrospectionCustomRule = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; + var GraphQLError_ts_1 = require_GraphQLError(); + var definition_ts_1 = require_definition(); + var introspection_ts_1 = require_introspection(); + function NoSchemaIntrospectionCustomRule(context) { + return { + Field(node) { + const type = (0, definition_ts_1.getNamedType)(context.getType()); + if (type && (0, introspection_ts_1.isIntrospectionType)(type)) { + context.reportError(new GraphQLError_ts_1.GraphQLError(`GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, { nodes: node })); + } + } + }; + } +}); + +// node_modules/graphql/validation/index.js +var require_validation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoSchemaIntrospectionCustomRule = exports.NoDeprecatedCustomRule = exports.PossibleTypeExtensionsRule = exports.UniqueDirectiveNamesRule = exports.UniqueArgumentDefinitionNamesRule = exports.UniqueFieldDefinitionNamesRule = exports.UniqueEnumValueNamesRule = exports.UniqueTypeNamesRule = exports.UniqueOperationTypesRule = exports.LoneSchemaDefinitionRule = exports.MaxIntrospectionDepthRule = exports.VariablesInAllowedPositionRule = exports.VariablesAreInputTypesRule = exports.ValuesOfCorrectTypeRule = exports.UniqueVariableNamesRule = exports.UniqueOperationNamesRule = exports.UniqueInputFieldNamesRule = exports.UniqueFragmentNamesRule = exports.UniqueDirectivesPerLocationRule = exports.UniqueArgumentNamesRule = exports.StreamDirectiveOnListFieldRule = exports.SingleFieldSubscriptionsRule = exports.ScalarLeafsRule = exports.ProvidedRequiredArgumentsRule = exports.PossibleFragmentSpreadsRule = exports.OverlappingFieldsCanBeMergedRule = exports.NoUnusedVariablesRule = exports.NoUnusedFragmentsRule = exports.NoUndefinedVariablesRule = exports.NoFragmentCyclesRule = exports.LoneAnonymousOperationRule = exports.KnownTypeNamesRule = exports.KnownOperationTypesRule = exports.KnownFragmentNamesRule = exports.KnownDirectivesRule = exports.KnownArgumentNamesRule = exports.FragmentsOnCompositeTypesRule = exports.FieldsOnCorrectTypeRule = exports.ExecutableDefinitionsRule = exports.DeferStreamDirectiveOnValidOperationsRule = exports.DeferStreamDirectiveOnRootFieldRule = exports.DeferStreamDirectiveLabelRule = exports.recommendedRules = exports.specifiedRules = exports.ValidationContext = exports.validate = undefined; + var validate_ts_1 = require_validate2(); + Object.defineProperty(exports, "validate", { enumerable: true, get: function() { + return validate_ts_1.validate; + } }); + var ValidationContext_ts_1 = require_ValidationContext(); + Object.defineProperty(exports, "ValidationContext", { enumerable: true, get: function() { + return ValidationContext_ts_1.ValidationContext; + } }); + var specifiedRules_ts_1 = require_specifiedRules(); + Object.defineProperty(exports, "specifiedRules", { enumerable: true, get: function() { + return specifiedRules_ts_1.specifiedRules; + } }); + Object.defineProperty(exports, "recommendedRules", { enumerable: true, get: function() { + return specifiedRules_ts_1.recommendedRules; + } }); + var DeferStreamDirectiveLabelRule_ts_1 = require_DeferStreamDirectiveLabelRule(); + Object.defineProperty(exports, "DeferStreamDirectiveLabelRule", { enumerable: true, get: function() { + return DeferStreamDirectiveLabelRule_ts_1.DeferStreamDirectiveLabelRule; + } }); + var DeferStreamDirectiveOnRootFieldRule_ts_1 = require_DeferStreamDirectiveOnRootFieldRule(); + Object.defineProperty(exports, "DeferStreamDirectiveOnRootFieldRule", { enumerable: true, get: function() { + return DeferStreamDirectiveOnRootFieldRule_ts_1.DeferStreamDirectiveOnRootFieldRule; + } }); + var DeferStreamDirectiveOnValidOperationsRule_ts_1 = require_DeferStreamDirectiveOnValidOperationsRule(); + Object.defineProperty(exports, "DeferStreamDirectiveOnValidOperationsRule", { enumerable: true, get: function() { + return DeferStreamDirectiveOnValidOperationsRule_ts_1.DeferStreamDirectiveOnValidOperationsRule; + } }); + var ExecutableDefinitionsRule_ts_1 = require_ExecutableDefinitionsRule(); + Object.defineProperty(exports, "ExecutableDefinitionsRule", { enumerable: true, get: function() { + return ExecutableDefinitionsRule_ts_1.ExecutableDefinitionsRule; + } }); + var FieldsOnCorrectTypeRule_ts_1 = require_FieldsOnCorrectTypeRule(); + Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { enumerable: true, get: function() { + return FieldsOnCorrectTypeRule_ts_1.FieldsOnCorrectTypeRule; + } }); + var FragmentsOnCompositeTypesRule_ts_1 = require_FragmentsOnCompositeTypesRule(); + Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { enumerable: true, get: function() { + return FragmentsOnCompositeTypesRule_ts_1.FragmentsOnCompositeTypesRule; + } }); + var KnownArgumentNamesRule_ts_1 = require_KnownArgumentNamesRule(); + Object.defineProperty(exports, "KnownArgumentNamesRule", { enumerable: true, get: function() { + return KnownArgumentNamesRule_ts_1.KnownArgumentNamesRule; + } }); + var KnownDirectivesRule_ts_1 = require_KnownDirectivesRule(); + Object.defineProperty(exports, "KnownDirectivesRule", { enumerable: true, get: function() { + return KnownDirectivesRule_ts_1.KnownDirectivesRule; + } }); + var KnownFragmentNamesRule_ts_1 = require_KnownFragmentNamesRule(); + Object.defineProperty(exports, "KnownFragmentNamesRule", { enumerable: true, get: function() { + return KnownFragmentNamesRule_ts_1.KnownFragmentNamesRule; + } }); + var KnownOperationTypesRule_ts_1 = require_KnownOperationTypesRule(); + Object.defineProperty(exports, "KnownOperationTypesRule", { enumerable: true, get: function() { + return KnownOperationTypesRule_ts_1.KnownOperationTypesRule; + } }); + var KnownTypeNamesRule_ts_1 = require_KnownTypeNamesRule(); + Object.defineProperty(exports, "KnownTypeNamesRule", { enumerable: true, get: function() { + return KnownTypeNamesRule_ts_1.KnownTypeNamesRule; + } }); + var LoneAnonymousOperationRule_ts_1 = require_LoneAnonymousOperationRule(); + Object.defineProperty(exports, "LoneAnonymousOperationRule", { enumerable: true, get: function() { + return LoneAnonymousOperationRule_ts_1.LoneAnonymousOperationRule; + } }); + var NoFragmentCyclesRule_ts_1 = require_NoFragmentCyclesRule(); + Object.defineProperty(exports, "NoFragmentCyclesRule", { enumerable: true, get: function() { + return NoFragmentCyclesRule_ts_1.NoFragmentCyclesRule; + } }); + var NoUndefinedVariablesRule_ts_1 = require_NoUndefinedVariablesRule(); + Object.defineProperty(exports, "NoUndefinedVariablesRule", { enumerable: true, get: function() { + return NoUndefinedVariablesRule_ts_1.NoUndefinedVariablesRule; + } }); + var NoUnusedFragmentsRule_ts_1 = require_NoUnusedFragmentsRule(); + Object.defineProperty(exports, "NoUnusedFragmentsRule", { enumerable: true, get: function() { + return NoUnusedFragmentsRule_ts_1.NoUnusedFragmentsRule; + } }); + var NoUnusedVariablesRule_ts_1 = require_NoUnusedVariablesRule(); + Object.defineProperty(exports, "NoUnusedVariablesRule", { enumerable: true, get: function() { + return NoUnusedVariablesRule_ts_1.NoUnusedVariablesRule; + } }); + var OverlappingFieldsCanBeMergedRule_ts_1 = require_OverlappingFieldsCanBeMergedRule(); + Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { enumerable: true, get: function() { + return OverlappingFieldsCanBeMergedRule_ts_1.OverlappingFieldsCanBeMergedRule; + } }); + var PossibleFragmentSpreadsRule_ts_1 = require_PossibleFragmentSpreadsRule(); + Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { enumerable: true, get: function() { + return PossibleFragmentSpreadsRule_ts_1.PossibleFragmentSpreadsRule; + } }); + var ProvidedRequiredArgumentsRule_ts_1 = require_ProvidedRequiredArgumentsRule(); + Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { enumerable: true, get: function() { + return ProvidedRequiredArgumentsRule_ts_1.ProvidedRequiredArgumentsRule; + } }); + var ScalarLeafsRule_ts_1 = require_ScalarLeafsRule(); + Object.defineProperty(exports, "ScalarLeafsRule", { enumerable: true, get: function() { + return ScalarLeafsRule_ts_1.ScalarLeafsRule; + } }); + var SingleFieldSubscriptionsRule_ts_1 = require_SingleFieldSubscriptionsRule(); + Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { enumerable: true, get: function() { + return SingleFieldSubscriptionsRule_ts_1.SingleFieldSubscriptionsRule; + } }); + var StreamDirectiveOnListFieldRule_ts_1 = require_StreamDirectiveOnListFieldRule(); + Object.defineProperty(exports, "StreamDirectiveOnListFieldRule", { enumerable: true, get: function() { + return StreamDirectiveOnListFieldRule_ts_1.StreamDirectiveOnListFieldRule; + } }); + var UniqueArgumentNamesRule_ts_1 = require_UniqueArgumentNamesRule(); + Object.defineProperty(exports, "UniqueArgumentNamesRule", { enumerable: true, get: function() { + return UniqueArgumentNamesRule_ts_1.UniqueArgumentNamesRule; + } }); + var UniqueDirectivesPerLocationRule_ts_1 = require_UniqueDirectivesPerLocationRule(); + Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { enumerable: true, get: function() { + return UniqueDirectivesPerLocationRule_ts_1.UniqueDirectivesPerLocationRule; + } }); + var UniqueFragmentNamesRule_ts_1 = require_UniqueFragmentNamesRule(); + Object.defineProperty(exports, "UniqueFragmentNamesRule", { enumerable: true, get: function() { + return UniqueFragmentNamesRule_ts_1.UniqueFragmentNamesRule; + } }); + var UniqueInputFieldNamesRule_ts_1 = require_UniqueInputFieldNamesRule(); + Object.defineProperty(exports, "UniqueInputFieldNamesRule", { enumerable: true, get: function() { + return UniqueInputFieldNamesRule_ts_1.UniqueInputFieldNamesRule; + } }); + var UniqueOperationNamesRule_ts_1 = require_UniqueOperationNamesRule(); + Object.defineProperty(exports, "UniqueOperationNamesRule", { enumerable: true, get: function() { + return UniqueOperationNamesRule_ts_1.UniqueOperationNamesRule; + } }); + var UniqueVariableNamesRule_ts_1 = require_UniqueVariableNamesRule(); + Object.defineProperty(exports, "UniqueVariableNamesRule", { enumerable: true, get: function() { + return UniqueVariableNamesRule_ts_1.UniqueVariableNamesRule; + } }); + var ValuesOfCorrectTypeRule_ts_1 = require_ValuesOfCorrectTypeRule(); + Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { enumerable: true, get: function() { + return ValuesOfCorrectTypeRule_ts_1.ValuesOfCorrectTypeRule; + } }); + var VariablesAreInputTypesRule_ts_1 = require_VariablesAreInputTypesRule(); + Object.defineProperty(exports, "VariablesAreInputTypesRule", { enumerable: true, get: function() { + return VariablesAreInputTypesRule_ts_1.VariablesAreInputTypesRule; + } }); + var VariablesInAllowedPositionRule_ts_1 = require_VariablesInAllowedPositionRule(); + Object.defineProperty(exports, "VariablesInAllowedPositionRule", { enumerable: true, get: function() { + return VariablesInAllowedPositionRule_ts_1.VariablesInAllowedPositionRule; + } }); + var MaxIntrospectionDepthRule_ts_1 = require_MaxIntrospectionDepthRule(); + Object.defineProperty(exports, "MaxIntrospectionDepthRule", { enumerable: true, get: function() { + return MaxIntrospectionDepthRule_ts_1.MaxIntrospectionDepthRule; + } }); + var LoneSchemaDefinitionRule_ts_1 = require_LoneSchemaDefinitionRule(); + Object.defineProperty(exports, "LoneSchemaDefinitionRule", { enumerable: true, get: function() { + return LoneSchemaDefinitionRule_ts_1.LoneSchemaDefinitionRule; + } }); + var UniqueOperationTypesRule_ts_1 = require_UniqueOperationTypesRule(); + Object.defineProperty(exports, "UniqueOperationTypesRule", { enumerable: true, get: function() { + return UniqueOperationTypesRule_ts_1.UniqueOperationTypesRule; + } }); + var UniqueTypeNamesRule_ts_1 = require_UniqueTypeNamesRule(); + Object.defineProperty(exports, "UniqueTypeNamesRule", { enumerable: true, get: function() { + return UniqueTypeNamesRule_ts_1.UniqueTypeNamesRule; + } }); + var UniqueEnumValueNamesRule_ts_1 = require_UniqueEnumValueNamesRule(); + Object.defineProperty(exports, "UniqueEnumValueNamesRule", { enumerable: true, get: function() { + return UniqueEnumValueNamesRule_ts_1.UniqueEnumValueNamesRule; + } }); + var UniqueFieldDefinitionNamesRule_ts_1 = require_UniqueFieldDefinitionNamesRule(); + Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", { enumerable: true, get: function() { + return UniqueFieldDefinitionNamesRule_ts_1.UniqueFieldDefinitionNamesRule; + } }); + var UniqueArgumentDefinitionNamesRule_ts_1 = require_UniqueArgumentDefinitionNamesRule(); + Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", { enumerable: true, get: function() { + return UniqueArgumentDefinitionNamesRule_ts_1.UniqueArgumentDefinitionNamesRule; + } }); + var UniqueDirectiveNamesRule_ts_1 = require_UniqueDirectiveNamesRule(); + Object.defineProperty(exports, "UniqueDirectiveNamesRule", { enumerable: true, get: function() { + return UniqueDirectiveNamesRule_ts_1.UniqueDirectiveNamesRule; + } }); + var PossibleTypeExtensionsRule_ts_1 = require_PossibleTypeExtensionsRule(); + Object.defineProperty(exports, "PossibleTypeExtensionsRule", { enumerable: true, get: function() { + return PossibleTypeExtensionsRule_ts_1.PossibleTypeExtensionsRule; + } }); + var NoDeprecatedCustomRule_ts_1 = require_NoDeprecatedCustomRule(); + Object.defineProperty(exports, "NoDeprecatedCustomRule", { enumerable: true, get: function() { + return NoDeprecatedCustomRule_ts_1.NoDeprecatedCustomRule; + } }); + var NoSchemaIntrospectionCustomRule_ts_1 = require_NoSchemaIntrospectionCustomRule(); + Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", { enumerable: true, get: function() { + return NoSchemaIntrospectionCustomRule_ts_1.NoSchemaIntrospectionCustomRule; + } }); +}); + +// node_modules/graphql/error/index.js +var require_error = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.locatedError = exports.syntaxError = exports.GraphQLError = undefined; + var GraphQLError_ts_1 = require_GraphQLError(); + Object.defineProperty(exports, "GraphQLError", { enumerable: true, get: function() { + return GraphQLError_ts_1.GraphQLError; + } }); + var syntaxError_ts_1 = require_syntaxError(); + Object.defineProperty(exports, "syntaxError", { enumerable: true, get: function() { + return syntaxError_ts_1.syntaxError; + } }); + var locatedError_ts_1 = require_locatedError(); + Object.defineProperty(exports, "locatedError", { enumerable: true, get: function() { + return locatedError_ts_1.locatedError; + } }); +}); + +// node_modules/graphql/utilities/getIntrospectionQuery.js +var require_getIntrospectionQuery = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getIntrospectionQuery = getIntrospectionQuery; + function getIntrospectionQuery(options) { + const optionsWithDefault = { + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false, + experimentalDirectiveDeprecation: false, + oneOf: false, + typeDepth: 9, + ...options + }; + const descriptions = optionsWithDefault.descriptions ? "description" : ""; + const specifiedByUrl = optionsWithDefault.specifiedByUrl ? "specifiedByURL" : ""; + const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable ? "isRepeatable" : ""; + const schemaDescription = optionsWithDefault.schemaDescription ? descriptions : ""; + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ""; + } + function experimentalDirectiveDeprecation(str) { + return optionsWithDefault.experimentalDirectiveDeprecation ? str : ""; + } + const oneOf = optionsWithDefault.oneOf ? "isOneOf" : ""; + function ofType(level, indent) { + if (level <= 0) { + return ""; + } + if (level > 100) { + throw new Error("Please set typeDepth to a reasonable value between 0 and 100; the default is 9."); + } + return ` +${indent}ofType { +${indent} name +${indent} kind${ofType(level - 1, indent + " ")} +${indent}}`; + } + return ` + query IntrospectionQuery { + __schema { + ${schemaDescription} + queryType { name kind } + mutationType { name kind } + subscriptionType { name kind } + types { + ...FullType + } + directives${experimentalDirectiveDeprecation("(includeDeprecated: true)")} { + name + ${descriptions} + ${directiveIsRepeatable} + ${experimentalDirectiveDeprecation("isDeprecated")} + ${experimentalDirectiveDeprecation("deprecationReason")} + locations + args${inputDeprecation("(includeDeprecated: true)")} { + ...InputValue + } + } + } + } + + fragment FullType on __Type { + kind + name + ${descriptions} + ${specifiedByUrl} + ${oneOf} + fields(includeDeprecated: true) { + name + ${descriptions} + args${inputDeprecation("(includeDeprecated: true)")} { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields${inputDeprecation("(includeDeprecated: true)")} { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + ${descriptions} + type { ...TypeRef } + defaultValue + ${inputDeprecation("isDeprecated")} + ${inputDeprecation("deprecationReason")} + } + + fragment TypeRef on __Type { + kind + name${ofType(optionsWithDefault.typeDepth, " ")} + } + `; + } +}); + +// node_modules/graphql/utilities/introspectionFromSchema.js +var require_introspectionFromSchema = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.introspectionFromSchema = introspectionFromSchema; + var invariant_ts_1 = require_invariant(); + var parser_ts_1 = require_parser(); + var execute_ts_1 = require_execute(); + var getIntrospectionQuery_ts_1 = require_getIntrospectionQuery(); + function introspectionFromSchema(schema, options) { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + experimentalDirectiveDeprecation: true, + oneOf: true, + ...options + }; + const document2 = (0, parser_ts_1.parse)((0, getIntrospectionQuery_ts_1.getIntrospectionQuery)(optionsWithDefaults)); + const result = (0, execute_ts_1.executeSync)({ schema, document: document2 }); + if (!(result.errors == null && result.data != null)) + (0, invariant_ts_1.invariant)(false); + return result.data; + } +}); + +// node_modules/graphql/utilities/buildClientSchema.js +var require_buildClientSchema = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildClientSchema = buildClientSchema; + var devAssert_ts_1 = require_devAssert(); + var inspect_ts_1 = require_inspect(); + var isObjectLike_ts_1 = require_isObjectLike(); + var keyValMap_ts_1 = require_keyValMap(); + var parser_ts_1 = require_parser(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var introspection_ts_1 = require_introspection(); + var scalars_ts_1 = require_scalars(); + var schema_ts_1 = require_schema(); + function buildClientSchema(introspection, options) { + if (!((0, isObjectLike_ts_1.isObjectLike)(introspection) && (0, isObjectLike_ts_1.isObjectLike)(introspection.__schema))) + (0, devAssert_ts_1.devAssert)(false, `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, inspect_ts_1.inspect)(introspection)}.`); + const schemaIntrospection = introspection.__schema; + const typeMap = new Map(schemaIntrospection.types.map((typeIntrospection) => [ + typeIntrospection.name, + buildType(typeIntrospection) + ])); + for (const stdType of [...scalars_ts_1.specifiedScalarTypes, ...introspection_ts_1.introspectionTypes]) { + if (typeMap.has(stdType.name)) { + typeMap.set(stdType.name, stdType); + } + } + const queryType = schemaIntrospection.queryType != null ? getObjectType(schemaIntrospection.queryType) : null; + const mutationType = schemaIntrospection.mutationType != null ? getObjectType(schemaIntrospection.mutationType) : null; + const subscriptionType = schemaIntrospection.subscriptionType != null ? getObjectType(schemaIntrospection.subscriptionType) : null; + const directives = schemaIntrospection.directives != null ? schemaIntrospection.directives.map(buildDirective) : []; + return new schema_ts_1.GraphQLSchema({ + description: schemaIntrospection.description, + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: [...typeMap.values()], + directives, + assumeValid: options?.assumeValid + }); + function getType(typeRef) { + if (typeRef.kind === introspection_ts_1.TypeKind.LIST) { + const itemRef = typeRef.ofType; + if (itemRef == null) { + throw new Error("Decorated type deeper than introspection query."); + } + return new definition_ts_1.GraphQLList(getType(itemRef)); + } + if (typeRef.kind === introspection_ts_1.TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + if (nullableRef == null) { + throw new Error("Decorated type deeper than introspection query."); + } + const nullableType = getType(nullableRef); + return new definition_ts_1.GraphQLNonNull((0, definition_ts_1.assertNullableType)(nullableType)); + } + return getNamedType(typeRef); + } + function getNamedType(typeRef) { + const typeName = typeRef.name; + if (!typeName) { + throw new Error(`Unknown type reference: ${(0, inspect_ts_1.inspect)(typeRef)}.`); + } + const type = typeMap.get(typeName); + if (type == null) { + throw new Error(`Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`); + } + return type; + } + function getObjectType(typeRef) { + return (0, definition_ts_1.assertObjectType)(getNamedType(typeRef)); + } + function getInterfaceType(typeRef) { + return (0, definition_ts_1.assertInterfaceType)(getNamedType(typeRef)); + } + function buildType(type) { + switch (type.kind) { + case introspection_ts_1.TypeKind.SCALAR: + return buildScalarDef(type); + case introspection_ts_1.TypeKind.OBJECT: + return buildObjectDef(type); + case introspection_ts_1.TypeKind.INTERFACE: + return buildInterfaceDef(type); + case introspection_ts_1.TypeKind.UNION: + return buildUnionDef(type); + case introspection_ts_1.TypeKind.ENUM: + return buildEnumDef(type); + case introspection_ts_1.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + default: + throw new Error(`Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${(0, inspect_ts_1.inspect)(type)}.`); + } + } + function buildScalarDef(scalarIntrospection) { + return new definition_ts_1.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByURL: scalarIntrospection.specifiedByURL + }); + } + function buildImplementationsList(implementingIntrospection) { + if (implementingIntrospection.interfaces === null && implementingIntrospection.kind === introspection_ts_1.TypeKind.INTERFACE) { + return []; + } + if (implementingIntrospection.interfaces == null) { + const implementingIntrospectionStr = (0, inspect_ts_1.inspect)(implementingIntrospection); + throw new Error(`Introspection result missing interfaces: ${implementingIntrospectionStr}.`); + } + return implementingIntrospection.interfaces.map(getInterfaceType); + } + function buildObjectDef(objectIntrospection) { + return new definition_ts_1.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection) + }); + } + function buildInterfaceDef(interfaceIntrospection) { + return new definition_ts_1.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection) + }); + } + function buildUnionDef(unionIntrospection) { + if (unionIntrospection.possibleTypes == null) { + const unionIntrospectionStr = (0, inspect_ts_1.inspect)(unionIntrospection); + throw new Error(`Introspection result missing possibleTypes: ${unionIntrospectionStr}.`); + } + return new definition_ts_1.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType) + }); + } + function buildEnumDef(enumIntrospection) { + if (enumIntrospection.enumValues == null) { + const enumIntrospectionStr = (0, inspect_ts_1.inspect)(enumIntrospection); + throw new Error(`Introspection result missing enumValues: ${enumIntrospectionStr}.`); + } + return new definition_ts_1.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, keyValMap_ts_1.keyValMap)(enumIntrospection.enumValues, (valueIntrospection) => valueIntrospection.name, (valueIntrospection) => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + })) + }); + } + function buildInputObjectDef(inputObjectIntrospection) { + if (inputObjectIntrospection.inputFields == null) { + const inputObjectIntrospectionStr = (0, inspect_ts_1.inspect)(inputObjectIntrospection); + throw new Error(`Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`); + } + return new definition_ts_1.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields), + isOneOf: inputObjectIntrospection.isOneOf + }); + } + function buildFieldDefMap(typeIntrospection) { + if (typeIntrospection.fields == null) { + throw new Error(`Introspection result missing fields: ${(0, inspect_ts_1.inspect)(typeIntrospection)}.`); + } + return (0, keyValMap_ts_1.keyValMap)(typeIntrospection.fields, (fieldIntrospection) => fieldIntrospection.name, buildField); + } + function buildField(fieldIntrospection) { + const type = getType(fieldIntrospection.type); + if (!(0, definition_ts_1.isOutputType)(type)) { + const typeStr = (0, inspect_ts_1.inspect)(type); + throw new Error(`Introspection must provide output type for fields, but received: ${typeStr}.`); + } + if (fieldIntrospection.args == null) { + const fieldIntrospectionStr = (0, inspect_ts_1.inspect)(fieldIntrospection); + throw new Error(`Introspection result missing field args: ${fieldIntrospectionStr}.`); + } + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type, + args: buildInputValueDefMap(fieldIntrospection.args) + }; + } + function buildInputValueDefMap(inputValueIntrospections) { + return (0, keyValMap_ts_1.keyValMap)(inputValueIntrospections, (inputValue) => inputValue.name, buildInputValue); + } + function buildInputValue(inputValueIntrospection) { + const type = getType(inputValueIntrospection.type); + if (!(0, definition_ts_1.isInputType)(type)) { + const typeStr = (0, inspect_ts_1.inspect)(type); + throw new Error(`Introspection must provide input type for arguments, but received: ${typeStr}.`); + } + return { + description: inputValueIntrospection.description, + type, + default: inputValueIntrospection.defaultValue != null ? { literal: (0, parser_ts_1.parseConstValue)(inputValueIntrospection.defaultValue) } : undefined, + deprecationReason: inputValueIntrospection.deprecationReason + }; + } + function buildDirective(directiveIntrospection) { + if (directiveIntrospection.args == null) { + const directiveIntrospectionStr = (0, inspect_ts_1.inspect)(directiveIntrospection); + throw new Error(`Introspection result missing directive args: ${directiveIntrospectionStr}.`); + } + if (directiveIntrospection.locations == null) { + const directiveIntrospectionStr = (0, inspect_ts_1.inspect)(directiveIntrospection); + throw new Error(`Introspection result missing directive locations: ${directiveIntrospectionStr}.`); + } + return new directives_ts_1.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + deprecationReason: directiveIntrospection.deprecationReason, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } + } +}); + +// node_modules/graphql/utilities/mapSchemaConfig.js +var require_mapSchemaConfig = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SchemaElementKind = undefined; + exports.mapSchemaConfig = mapSchemaConfig; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var introspection_ts_1 = require_introspection(); + var scalars_ts_1 = require_scalars(); + exports.SchemaElementKind = { + SCHEMA: "SCHEMA", + SCALAR: "SCALAR", + OBJECT: "OBJECT", + FIELD: "FIELD", + ARGUMENT: "ARGUMENT", + INTERFACE: "INTERFACE", + UNION: "UNION", + ENUM: "ENUM", + ENUM_VALUE: "ENUM_VALUE", + INPUT_OBJECT: "INPUT_OBJECT", + INPUT_FIELD: "INPUT_FIELD", + DIRECTIVE: "DIRECTIVE" + }; + function mapSchemaConfig(schemaConfig, configMapperMapFn) { + const configMapperMap = configMapperMapFn({ + getNamedType, + setNamedType, + getNamedTypes + }); + const mappedTypeMap = new Map; + for (const type of schemaConfig.types) { + const typeName = type.name; + const mappedNamedType = mapNamedType(type); + if (mappedNamedType) { + mappedTypeMap.set(typeName, mappedNamedType); + } + } + const mappedDirectives = []; + for (const directive of schemaConfig.directives) { + if ((0, directives_ts_1.isSpecifiedDirective)(directive)) { + mappedDirectives.push(directive); + continue; + } + const mappedDirectiveConfig = mapDirective(directive.toConfig()); + if (mappedDirectiveConfig) { + mappedDirectives.push(new directives_ts_1.GraphQLDirective(mappedDirectiveConfig)); + } + } + const mappedSchemaConfig = { + ...schemaConfig, + query: schemaConfig.query && getNamedType(schemaConfig.query.name), + mutation: schemaConfig.mutation && getNamedType(schemaConfig.mutation.name), + subscription: schemaConfig.subscription && getNamedType(schemaConfig.subscription.name), + types: Array.from(mappedTypeMap.values()), + directives: mappedDirectives + }; + const schemaMapper = configMapperMap[exports.SchemaElementKind.SCHEMA]; + return schemaMapper == null ? mappedSchemaConfig : schemaMapper(mappedSchemaConfig); + function getType(type) { + if ((0, definition_ts_1.isListType)(type)) { + return new definition_ts_1.GraphQLList(getType(type.ofType)); + } + if ((0, definition_ts_1.isNonNullType)(type)) { + return new definition_ts_1.GraphQLNonNull(getType(type.ofType)); + } + return getNamedType(type.name); + } + function getNamedType(typeName) { + const type = stdTypeMap.get(typeName) ?? mappedTypeMap.get(typeName); + if (!(type !== undefined)) + (0, invariant_ts_1.invariant)(false, `Unknown type: "${typeName}".`); + return type; + } + function setNamedType(type) { + mappedTypeMap.set(type.name, type); + } + function getNamedTypes() { + return Array.from(mappedTypeMap.values()); + } + function mapNamedType(type) { + if ((0, introspection_ts_1.isIntrospectionType)(type) || (0, scalars_ts_1.isSpecifiedScalarType)(type)) { + return type; + } + if ((0, definition_ts_1.isScalarType)(type)) { + return mapScalarType(type); + } + if ((0, definition_ts_1.isObjectType)(type)) { + return mapObjectType(type); + } + if ((0, definition_ts_1.isInterfaceType)(type)) { + return mapInterfaceType(type); + } + if ((0, definition_ts_1.isUnionType)(type)) { + return mapUnionType(type); + } + if ((0, definition_ts_1.isEnumType)(type)) { + return mapEnumType(type); + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + return mapInputObjectType(type); + } + (0, invariant_ts_1.invariant)(false, "Unexpected type: " + (0, inspect_ts_1.inspect)(type)); + } + function mapScalarType(type) { + let mappedConfig = type.toConfig(); + const mapper = configMapperMap[exports.SchemaElementKind.SCALAR]; + mappedConfig = mapper == null ? mappedConfig : mapper(mappedConfig); + return new definition_ts_1.GraphQLScalarType(mappedConfig); + } + function mapObjectType(type) { + const config = type.toConfig(); + let mappedConfig = { + ...config, + interfaces: () => config.interfaces.map((iface) => getNamedType(iface.name)), + fields: () => mapFields(config.fields, type.name) + }; + const mapper = configMapperMap[exports.SchemaElementKind.OBJECT]; + mappedConfig = mapper == null ? mappedConfig : mapper(mappedConfig); + return new definition_ts_1.GraphQLObjectType(mappedConfig); + } + function mapFields(fieldMap, parentTypeName) { + const newFieldMap = Object.create(null); + for (const [fieldName, field] of Object.entries(fieldMap)) { + let mappedField = { + ...field, + type: getType(field.type), + args: mapArgs(field.args, parentTypeName, fieldName) + }; + const mapper = configMapperMap[exports.SchemaElementKind.FIELD]; + if (mapper) { + mappedField = mapper(mappedField, parentTypeName); + } + newFieldMap[fieldName] = mappedField; + } + return newFieldMap; + } + function mapArgs(argumentMap, fieldOrDirectiveName, parentTypeName) { + const newArgumentMap = Object.create(null); + for (const [argName, arg] of Object.entries(argumentMap)) { + let mappedArg = { + ...arg, + type: getType(arg.type) + }; + const mapper = configMapperMap[exports.SchemaElementKind.ARGUMENT]; + if (mapper) { + mappedArg = mapper(mappedArg, fieldOrDirectiveName, parentTypeName); + } + newArgumentMap[argName] = mappedArg; + } + return newArgumentMap; + } + function mapInterfaceType(type) { + const config = type.toConfig(); + let mappedConfig = { + ...config, + interfaces: () => config.interfaces.map((iface) => getNamedType(iface.name)), + fields: () => mapFields(config.fields, type.name) + }; + const mapper = configMapperMap[exports.SchemaElementKind.INTERFACE]; + mappedConfig = mapper == null ? mappedConfig : mapper(mappedConfig); + return new definition_ts_1.GraphQLInterfaceType(mappedConfig); + } + function mapUnionType(type) { + const config = type.toConfig(); + let mappedConfig = { + ...config, + types: () => config.types.map((memberType) => getNamedType(memberType.name)) + }; + const mapper = configMapperMap[exports.SchemaElementKind.UNION]; + mappedConfig = mapper == null ? mappedConfig : mapper(mappedConfig); + return new definition_ts_1.GraphQLUnionType(mappedConfig); + } + function mapEnumType(type) { + const config = type.toConfig(); + let mappedConfig = { + ...config, + values: () => { + const newEnumValues = Object.create(null); + for (const [valueName, value] of Object.entries(config.values)) { + const mappedValue = mapEnumValue(value, valueName, type.name); + newEnumValues[valueName] = mappedValue; + } + return newEnumValues; + } + }; + const mapper = configMapperMap[exports.SchemaElementKind.ENUM]; + mappedConfig = mapper == null ? mappedConfig : mapper(mappedConfig); + return new definition_ts_1.GraphQLEnumType(mappedConfig); + } + function mapEnumValue(valueConfig, valueName, enumName) { + const mappedConfig = { ...valueConfig }; + const mapper = configMapperMap[exports.SchemaElementKind.ENUM_VALUE]; + return mapper == null ? mappedConfig : mapper(mappedConfig, valueName, enumName); + } + function mapInputObjectType(type) { + const config = type.toConfig(); + let mappedConfig = { + ...config, + fields: () => { + const newInputFieldMap = Object.create(null); + for (const [fieldName, field] of Object.entries(config.fields)) { + const mappedField = mapInputField(field, fieldName, type.name); + newInputFieldMap[fieldName] = mappedField; + } + return newInputFieldMap; + } + }; + const mapper = configMapperMap[exports.SchemaElementKind.INPUT_OBJECT]; + mappedConfig = mapper == null ? mappedConfig : mapper(mappedConfig); + return new definition_ts_1.GraphQLInputObjectType(mappedConfig); + } + function mapInputField(inputFieldConfig, inputFieldName, inputObjectTypeName) { + const mappedConfig = { + ...inputFieldConfig, + type: getType(inputFieldConfig.type) + }; + const mapper = configMapperMap[exports.SchemaElementKind.INPUT_FIELD]; + return mapper == null ? mappedConfig : mapper(mappedConfig, inputFieldName, inputObjectTypeName); + } + function mapDirective(config) { + const mappedConfig = { + ...config, + args: mapArgs(config.args, config.name, undefined) + }; + const mapper = configMapperMap[exports.SchemaElementKind.DIRECTIVE]; + return mapper == null ? mappedConfig : mapper(mappedConfig); + } + } + var stdTypeMap = new Map([...scalars_ts_1.specifiedScalarTypes, ...introspection_ts_1.introspectionTypes].map((type) => [ + type.name, + type + ])); +}); + +// node_modules/graphql/utilities/extendSchema.js +var require_extendSchema = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSchema = extendSchema; + exports.extendSchemaImpl = extendSchemaImpl; + var AccumulatorMap_ts_1 = require_AccumulatorMap(); + var invariant_ts_1 = require_invariant(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var introspection_ts_1 = require_introspection(); + var scalars_ts_1 = require_scalars(); + var schema_ts_1 = require_schema(); + var validate_ts_1 = require_validate2(); + var values_ts_1 = require_values(); + var mapSchemaConfig_ts_1 = require_mapSchemaConfig(); + function extendSchema(schema, documentAST, options) { + (0, schema_ts_1.assertSchema)(schema); + if (options?.assumeValid !== true && options?.assumeValidSDL !== true) { + (0, validate_ts_1.assertValidSDLExtension)(documentAST, schema); + } + const schemaConfig = schema.toConfig(); + const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); + return schemaConfig === extendedConfig ? schema : new schema_ts_1.GraphQLSchema(extendedConfig); + } + function extendSchemaImpl(schemaConfig, documentAST, options) { + const typeDefs = []; + const scalarExtensions = new AccumulatorMap_ts_1.AccumulatorMap; + const objectExtensions = new AccumulatorMap_ts_1.AccumulatorMap; + const interfaceExtensions = new AccumulatorMap_ts_1.AccumulatorMap; + const unionExtensions = new AccumulatorMap_ts_1.AccumulatorMap; + const enumExtensions = new AccumulatorMap_ts_1.AccumulatorMap; + const inputObjectExtensions = new AccumulatorMap_ts_1.AccumulatorMap; + const directiveExtensions = new AccumulatorMap_ts_1.AccumulatorMap; + const directiveDefs = []; + let schemaDef; + const schemaExtensions = []; + let isSchemaChanged = false; + for (const def of documentAST.definitions) { + switch (def.kind) { + case kinds_ts_1.Kind.SCHEMA_DEFINITION: + schemaDef = def; + break; + case kinds_ts_1.Kind.SCHEMA_EXTENSION: + schemaExtensions.push(def); + break; + case kinds_ts_1.Kind.DIRECTIVE_DEFINITION: + directiveDefs.push(def); + break; + case kinds_ts_1.Kind.DIRECTIVE_EXTENSION: + directiveExtensions.add(def.name.value, def); + break; + case kinds_ts_1.Kind.SCALAR_TYPE_DEFINITION: + case kinds_ts_1.Kind.OBJECT_TYPE_DEFINITION: + case kinds_ts_1.Kind.INTERFACE_TYPE_DEFINITION: + case kinds_ts_1.Kind.UNION_TYPE_DEFINITION: + case kinds_ts_1.Kind.ENUM_TYPE_DEFINITION: + case kinds_ts_1.Kind.INPUT_OBJECT_TYPE_DEFINITION: + typeDefs.push(def); + break; + case kinds_ts_1.Kind.SCALAR_TYPE_EXTENSION: + scalarExtensions.add(def.name.value, def); + break; + case kinds_ts_1.Kind.OBJECT_TYPE_EXTENSION: + objectExtensions.add(def.name.value, def); + break; + case kinds_ts_1.Kind.INTERFACE_TYPE_EXTENSION: + interfaceExtensions.add(def.name.value, def); + break; + case kinds_ts_1.Kind.UNION_TYPE_EXTENSION: + unionExtensions.add(def.name.value, def); + break; + case kinds_ts_1.Kind.ENUM_TYPE_EXTENSION: + enumExtensions.add(def.name.value, def); + break; + case kinds_ts_1.Kind.INPUT_OBJECT_TYPE_EXTENSION: + inputObjectExtensions.add(def.name.value, def); + break; + default: + continue; + } + isSchemaChanged = true; + } + if (!isSchemaChanged) { + return schemaConfig; + } + return (0, mapSchemaConfig_ts_1.mapSchemaConfig)(schemaConfig, (context) => { + const { getNamedType, setNamedType, getNamedTypes } = context; + return { + [mapSchemaConfig_ts_1.SchemaElementKind.SCHEMA]: (config) => { + for (const typeNode of typeDefs) { + const type = stdTypeMap.get(typeNode.name.value) ?? buildNamedType(typeNode); + setNamedType(type); + } + const operationTypes = { + query: config.query && getNamedType(config.query.name), + mutation: config.mutation && getNamedType(config.mutation.name), + subscription: config.subscription && getNamedType(config.subscription.name), + ...schemaDef && getOperationTypes([schemaDef]), + ...getOperationTypes(schemaExtensions) + }; + return { + description: schemaDef?.description?.value ?? config.description, + ...operationTypes, + types: getNamedTypes(), + directives: [ + ...config.directives.map(extendDirective), + ...directiveDefs.map(buildDirective) + ], + extensions: config.extensions, + astNode: schemaDef ?? config.astNode, + extensionASTNodes: config.extensionASTNodes.concat(schemaExtensions), + assumeValid: options?.assumeValid ?? false + }; + }, + [mapSchemaConfig_ts_1.SchemaElementKind.INPUT_OBJECT]: (config) => { + const extensions = inputObjectExtensions.get(config.name) ?? []; + return { + ...config, + fields: () => ({ + ...config.fields(), + ...buildInputFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }; + }, + [mapSchemaConfig_ts_1.SchemaElementKind.ENUM]: (config) => { + const extensions = enumExtensions.get(config.name) ?? []; + return { + ...config, + values: () => ({ + ...config.values(), + ...buildEnumValueMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }; + }, + [mapSchemaConfig_ts_1.SchemaElementKind.SCALAR]: (config) => { + const extensions = scalarExtensions.get(config.name) ?? []; + let specifiedByURL = config.specifiedByURL; + for (const extensionNode of extensions) { + specifiedByURL = getSpecifiedByURL(extensionNode) ?? specifiedByURL; + } + return { + ...config, + specifiedByURL, + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }; + }, + [mapSchemaConfig_ts_1.SchemaElementKind.OBJECT]: (config) => { + const extensions = objectExtensions.get(config.name) ?? []; + return { + ...config, + interfaces: () => [ + ...config.interfaces(), + ...buildInterfaces(extensions) + ], + fields: () => ({ + ...config.fields(), + ...buildFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }; + }, + [mapSchemaConfig_ts_1.SchemaElementKind.INTERFACE]: (config) => { + const extensions = interfaceExtensions.get(config.name) ?? []; + return { + ...config, + interfaces: () => [ + ...config.interfaces(), + ...buildInterfaces(extensions) + ], + fields: () => ({ + ...config.fields(), + ...buildFieldMap(extensions) + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }; + }, + [mapSchemaConfig_ts_1.SchemaElementKind.UNION]: (config) => { + const extensions = unionExtensions.get(config.name) ?? []; + return { + ...config, + types: () => [...config.types(), ...buildUnionTypes(extensions)], + extensionASTNodes: config.extensionASTNodes.concat(extensions) + }; + } + }; + function getOperationTypes(nodes) { + const opTypes = {}; + for (const node of nodes) { + const operationTypesNodes = node.operationTypes ?? []; + for (const operationType of operationTypesNodes) { + opTypes[operationType.operation] = namedTypeFromAST(operationType.type); + } + } + return opTypes; + } + function namedTypeFromAST(node) { + const name = node.name.value; + const type = getNamedType(name); + if (!(type !== undefined)) + (0, invariant_ts_1.invariant)(false, `Unknown type: "${name}".`); + return type; + } + function typeFromAST(node) { + if (node.kind === kinds_ts_1.Kind.LIST_TYPE) { + return new definition_ts_1.GraphQLList(typeFromAST(node.type)); + } + if (node.kind === kinds_ts_1.Kind.NON_NULL_TYPE) { + return new definition_ts_1.GraphQLNonNull(typeFromAST(node.type)); + } + return namedTypeFromAST(node); + } + function buildDirective(node) { + const extensionASTNodes = directiveExtensions.get(node.name.value) ?? []; + const deprecationReason = getDeprecationReason(node) ?? extensionASTNodes.map((extensionNode) => getDeprecationReason(extensionNode)).find((reason) => reason != null); + return new directives_ts_1.GraphQLDirective({ + name: node.name.value, + description: node.description?.value, + locations: node.locations.map(({ value }) => value), + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + deprecationReason, + astNode: node, + extensionASTNodes + }); + } + function extendDirective(directive) { + const extensionASTNodes = directiveExtensions.get(directive.name) ?? []; + if (extensionASTNodes.length === 0) { + return directive; + } + const deprecationReason = directive.deprecationReason ?? extensionASTNodes.map((extensionNode) => getDeprecationReason(extensionNode)).find((reason) => reason != null); + return new directives_ts_1.GraphQLDirective({ + ...directive.toConfig(), + deprecationReason, + extensionASTNodes: directive.extensionASTNodes.concat(extensionASTNodes) + }); + } + function buildFieldMap(nodes) { + const fieldConfigMap = Object.create(null); + for (const node of nodes) { + const nodeFields = node.fields ?? []; + for (const field of nodeFields) { + fieldConfigMap[field.name.value] = { + type: typeFromAST(field.type), + description: field.description?.value, + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + return fieldConfigMap; + } + function buildArgumentMap(args) { + const argsNodes = args ?? []; + const argConfigMap = Object.create(null); + for (const arg of argsNodes) { + const type = typeFromAST(arg.type); + argConfigMap[arg.name.value] = { + type, + description: arg.description?.value, + default: arg.defaultValue && { literal: arg.defaultValue }, + deprecationReason: getDeprecationReason(arg), + astNode: arg + }; + } + return argConfigMap; + } + function buildInputFieldMap(nodes) { + const inputFieldMap = Object.create(null); + for (const node of nodes) { + const fieldsNodes = node.fields ?? []; + for (const field of fieldsNodes) { + const type = typeFromAST(field.type); + inputFieldMap[field.name.value] = { + type, + description: field.description?.value, + default: field.defaultValue && { literal: field.defaultValue }, + deprecationReason: getDeprecationReason(field), + astNode: field + }; + } + } + return inputFieldMap; + } + function buildEnumValueMap(nodes) { + const enumValueMap = Object.create(null); + for (const node of nodes) { + const valuesNodes = node.values ?? []; + for (const value of valuesNodes) { + enumValueMap[value.name.value] = { + description: value.description?.value, + deprecationReason: getDeprecationReason(value), + astNode: value + }; + } + } + return enumValueMap; + } + function buildInterfaces(nodes) { + return nodes.flatMap((node) => node.interfaces?.map(namedTypeFromAST) ?? []); + } + function buildUnionTypes(nodes) { + return nodes.flatMap((node) => node.types?.map(namedTypeFromAST) ?? []); + } + function buildNamedType(astNode) { + const name = astNode.name.value; + switch (astNode.kind) { + case kinds_ts_1.Kind.OBJECT_TYPE_DEFINITION: { + const extensionASTNodes = objectExtensions.get(name) ?? []; + const allNodes = [astNode, ...extensionASTNodes]; + return new definition_ts_1.GraphQLObjectType({ + name, + description: astNode.description?.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes + }); + } + case kinds_ts_1.Kind.INTERFACE_TYPE_DEFINITION: { + const extensionASTNodes = interfaceExtensions.get(name) ?? []; + const allNodes = [astNode, ...extensionASTNodes]; + return new definition_ts_1.GraphQLInterfaceType({ + name, + description: astNode.description?.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes + }); + } + case kinds_ts_1.Kind.ENUM_TYPE_DEFINITION: { + const extensionASTNodes = enumExtensions.get(name) ?? []; + const allNodes = [astNode, ...extensionASTNodes]; + return new definition_ts_1.GraphQLEnumType({ + name, + description: astNode.description?.value, + values: () => buildEnumValueMap(allNodes), + astNode, + extensionASTNodes + }); + } + case kinds_ts_1.Kind.UNION_TYPE_DEFINITION: { + const extensionASTNodes = unionExtensions.get(name) ?? []; + const allNodes = [astNode, ...extensionASTNodes]; + return new definition_ts_1.GraphQLUnionType({ + name, + description: astNode.description?.value, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes + }); + } + case kinds_ts_1.Kind.SCALAR_TYPE_DEFINITION: { + const extensionASTNodes = scalarExtensions.get(name) ?? []; + let specifiedByURL = getSpecifiedByURL(astNode); + for (const extensionNode of extensionASTNodes) { + specifiedByURL = getSpecifiedByURL(extensionNode) ?? specifiedByURL; + } + return new definition_ts_1.GraphQLScalarType({ + name, + description: astNode.description?.value, + specifiedByURL, + astNode, + extensionASTNodes + }); + } + case kinds_ts_1.Kind.INPUT_OBJECT_TYPE_DEFINITION: { + const extensionASTNodes = inputObjectExtensions.get(name) ?? []; + const allNodes = [astNode, ...extensionASTNodes]; + return new definition_ts_1.GraphQLInputObjectType({ + name, + description: astNode.description?.value, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes, + isOneOf: isOneOf(astNode) + }); + } + } + } + }); + } + var stdTypeMap = new Map([...scalars_ts_1.specifiedScalarTypes, ...introspection_ts_1.introspectionTypes].map((type) => [ + type.name, + type + ])); + function getDeprecationReason(node) { + const deprecated = (0, values_ts_1.getDirectiveValues)(directives_ts_1.GraphQLDeprecatedDirective, node); + return deprecated?.reason; + } + function getSpecifiedByURL(node) { + const specifiedBy = (0, values_ts_1.getDirectiveValues)(directives_ts_1.GraphQLSpecifiedByDirective, node); + return specifiedBy?.url; + } + function isOneOf(node) { + return Boolean((0, values_ts_1.getDirectiveValues)(directives_ts_1.GraphQLOneOfDirective, node)); + } +}); + +// node_modules/graphql/utilities/buildASTSchema.js +var require_buildASTSchema = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildASTSchema = buildASTSchema; + exports.buildSchema = buildSchema; + var parser_ts_1 = require_parser(); + var directives_ts_1 = require_directives(); + var schema_ts_1 = require_schema(); + var validate_ts_1 = require_validate2(); + var extendSchema_ts_1 = require_extendSchema(); + function buildASTSchema(documentAST, options) { + if (options?.assumeValid !== true && options?.assumeValidSDL !== true) { + (0, validate_ts_1.assertValidSDL)(documentAST); + } + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: Object.create(null), + extensionASTNodes: [], + assumeValid: false + }; + const config = (0, extendSchema_ts_1.extendSchemaImpl)(emptySchemaConfig, documentAST, options); + if (config.astNode == null) { + for (const type of config.types) { + switch (type.name) { + case "Query": + config.query = type; + break; + case "Mutation": + config.mutation = type; + break; + case "Subscription": + config.subscription = type; + break; + } + } + } + const directives = [ + ...config.directives, + ...directives_ts_1.specifiedDirectives.filter((stdDirective) => config.directives.every((directive) => directive.name !== stdDirective.name)) + ]; + return new schema_ts_1.GraphQLSchema({ ...config, directives }); + } + function buildSchema(source, options) { + const document2 = (0, parser_ts_1.parse)(source, { + noLocation: options?.noLocation, + experimentalFragmentArguments: options?.experimentalFragmentArguments + }); + return buildASTSchema(document2, { + assumeValidSDL: options?.assumeValidSDL, + assumeValid: options?.assumeValid + }); + } +}); + +// node_modules/graphql/utilities/lexicographicSortSchema.js +var require_lexicographicSortSchema = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.lexicographicSortSchema = lexicographicSortSchema; + var naturalCompare_ts_1 = require_naturalCompare(); + var schema_ts_1 = require_schema(); + var mapSchemaConfig_ts_1 = require_mapSchemaConfig(); + function lexicographicSortSchema(schema) { + return new schema_ts_1.GraphQLSchema((0, mapSchemaConfig_ts_1.mapSchemaConfig)(schema.toConfig(), () => ({ + [mapSchemaConfig_ts_1.SchemaElementKind.OBJECT]: (config) => ({ + ...config, + interfaces: () => sortByName(config.interfaces()), + fields: () => sortObjMap(config.fields()) + }), + [mapSchemaConfig_ts_1.SchemaElementKind.FIELD]: (config) => ({ + ...config, + args: sortObjMap(config.args) + }), + [mapSchemaConfig_ts_1.SchemaElementKind.INTERFACE]: (config) => ({ + ...config, + interfaces: () => sortByName(config.interfaces()), + fields: () => sortObjMap(config.fields()) + }), + [mapSchemaConfig_ts_1.SchemaElementKind.UNION]: (config) => ({ + ...config, + types: () => sortByName(config.types()) + }), + [mapSchemaConfig_ts_1.SchemaElementKind.ENUM]: (config) => ({ + ...config, + values: () => sortObjMap(config.values()) + }), + [mapSchemaConfig_ts_1.SchemaElementKind.INPUT_OBJECT]: (config) => ({ + ...config, + fields: () => sortObjMap(config.fields()) + }), + [mapSchemaConfig_ts_1.SchemaElementKind.DIRECTIVE]: (config) => ({ + ...config, + locations: sortBy(config.locations, (x) => x), + args: sortObjMap(config.args) + }), + [mapSchemaConfig_ts_1.SchemaElementKind.SCHEMA]: (config) => ({ + ...config, + types: sortByName(config.types), + directives: sortByName(config.directives) + }) + }))); + } + function sortObjMap(map) { + const sortedMap = Object.create(null); + for (const key of Object.keys(map).sort(naturalCompare_ts_1.naturalCompare)) { + sortedMap[key] = map[key]; + } + return sortedMap; + } + function sortByName(array) { + return sortBy(array, (obj) => obj.name); + } + function sortBy(array, mapToKey) { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return (0, naturalCompare_ts_1.naturalCompare)(key1, key2); + }); + } +}); + +// node_modules/graphql/utilities/printSchema.js +var require_printSchema = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.printSchema = printSchema; + exports.printIntrospectionSchema = printIntrospectionSchema; + exports.printType = printType; + exports.printDirective = printDirective; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var blockString_ts_1 = require_blockString(); + var kinds_ts_1 = require_kinds(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var directives_ts_1 = require_directives(); + var introspection_ts_1 = require_introspection(); + var scalars_ts_1 = require_scalars(); + var getDefaultValueAST_ts_1 = require_getDefaultValueAST(); + function printSchema(schema) { + return printFilteredSchema(schema, (n) => !(0, directives_ts_1.isSpecifiedDirective)(n), isDefinedType); + } + function printIntrospectionSchema(schema) { + return printFilteredSchema(schema, directives_ts_1.isSpecifiedDirective, introspection_ts_1.isIntrospectionType); + } + function isDefinedType(type) { + return !(0, scalars_ts_1.isSpecifiedScalarType)(type) && !(0, introspection_ts_1.isIntrospectionType)(type); + } + function printFilteredSchema(schema, directiveFilter, typeFilter) { + const directives = schema.getDirectives().filter(directiveFilter); + const types = Object.values(schema.getTypeMap()).filter(typeFilter); + return [ + printSchemaDefinition(schema), + ...directives.map((directive) => printDirective(directive)), + ...types.map((type) => printType(type)) + ].filter(Boolean).join(` + +`); + } + function printSchemaDefinition(schema) { + const queryType = schema.getQueryType(); + const mutationType = schema.getMutationType(); + const subscriptionType = schema.getSubscriptionType(); + if (!queryType && !mutationType && !subscriptionType) { + return; + } + if (schema.description != null || !hasDefaultRootOperationTypes(schema)) { + return printDescription(schema) + `schema { +` + (queryType ? ` query: ${queryType} +` : "") + (mutationType ? ` mutation: ${mutationType} +` : "") + (subscriptionType ? ` subscription: ${subscriptionType} +` : "") + "}"; + } + } + function hasDefaultRootOperationTypes(schema) { + return schema.getQueryType() == schema.getType("Query") && schema.getMutationType() == schema.getType("Mutation") && schema.getSubscriptionType() == schema.getType("Subscription"); + } + function printType(type) { + if ((0, definition_ts_1.isScalarType)(type)) { + return printScalar(type); + } + if ((0, definition_ts_1.isObjectType)(type)) { + return printObject(type); + } + if ((0, definition_ts_1.isInterfaceType)(type)) { + return printInterface(type); + } + if ((0, definition_ts_1.isUnionType)(type)) { + return printUnion(type); + } + if ((0, definition_ts_1.isEnumType)(type)) { + return printEnum(type); + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + return printInputObject(type); + } + (0, invariant_ts_1.invariant)(false, "Unexpected type: " + (0, inspect_ts_1.inspect)(type)); + } + function printScalar(type) { + return printDescription(type) + `scalar ${type}` + printSpecifiedByURL(type); + } + function printImplementedInterfaces(type) { + const interfaces = type.getInterfaces(); + return interfaces.length ? " implements " + interfaces.map((i) => i.name).join(" & ") : ""; + } + function printObject(type) { + return printDescription(type) + `type ${type}` + printImplementedInterfaces(type) + printFields(type); + } + function printInterface(type) { + return printDescription(type) + `interface ${type}` + printImplementedInterfaces(type) + printFields(type); + } + function printUnion(type) { + const types = type.getTypes(); + const possibleTypes = types.length ? " = " + types.join(" | ") : ""; + return printDescription(type) + `union ${type.name}` + possibleTypes; + } + function printEnum(type) { + const values = type.getValues().map((value, i) => printDescription(value, " ", !i) + " " + value.name + printDeprecated(value.deprecationReason)); + return printDescription(type) + `enum ${type}` + printBlock(values); + } + function printInputObject(type) { + const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, " ", !i) + " " + printInputValue(f)); + return printDescription(type) + `input ${type}` + (type.isOneOf ? " @oneOf" : "") + printBlock(fields); + } + function printFields(type) { + const fields = Object.values(type.getFields()).map((f, i) => printDescription(f, " ", !i) + " " + f.name + printArgs(f.args, " ") + ": " + String(f.type) + printDeprecated(f.deprecationReason)); + return printBlock(fields); + } + function printBlock(items) { + return items.length !== 0 ? ` { +` + items.join(` +`) + ` +}` : ""; + } + function printArgs(args, indentation = "") { + if (args.length === 0) { + return ""; + } + if (args.every((arg) => arg.description == null)) { + return "(" + args.map(printInputValue).join(", ") + ")"; + } + return `( +` + args.map((arg, i) => printDescription(arg, " " + indentation, !i) + " " + indentation + printInputValue(arg)).join(` +`) + ` +` + indentation + ")"; + } + function printInputValue(argOrInputField) { + let argDecl = argOrInputField.name + ": " + String(argOrInputField.type); + const defaultValueAST = (0, getDefaultValueAST_ts_1.getDefaultValueAST)(argOrInputField); + if (defaultValueAST) { + argDecl += ` = ${(0, printer_ts_1.print)(defaultValueAST)}`; + } + return argDecl + printDeprecated(argOrInputField.deprecationReason); + } + function printDirective(directive) { + return printDescription(directive) + `directive ${directive}` + printArgs(directive.args) + printDeprecated(directive.deprecationReason) + (directive.isRepeatable ? " repeatable" : "") + " on " + directive.locations.join(" | "); + } + function printDeprecated(reason) { + if (reason == null) { + return ""; + } + if (reason !== directives_ts_1.DEFAULT_DEPRECATION_REASON) { + const astValue = (0, printer_ts_1.print)({ kind: kinds_ts_1.Kind.STRING, value: reason }); + return ` @deprecated(reason: ${astValue})`; + } + return " @deprecated"; + } + function printSpecifiedByURL(scalar) { + if (scalar.specifiedByURL == null) { + return ""; + } + const astValue = (0, printer_ts_1.print)({ + kind: kinds_ts_1.Kind.STRING, + value: scalar.specifiedByURL + }); + return ` @specifiedBy(url: ${astValue})`; + } + function printDescription(def, indentation = "", firstInBlock = true) { + const { description } = def; + if (description == null) { + return ""; + } + const blockString = (0, printer_ts_1.print)({ + kind: kinds_ts_1.Kind.STRING, + value: description, + block: (0, blockString_ts_1.isPrintableAsBlockString)(description) + }); + const prefix = indentation && !firstInBlock ? ` +` + indentation : indentation; + return prefix + blockString.replaceAll(` +`, ` +` + indentation) + ` +`; + } +}); + +// node_modules/graphql/utilities/valueFromAST.js +var require_valueFromAST = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.valueFromAST = valueFromAST; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var kinds_ts_1 = require_kinds(); + var definition_ts_1 = require_definition(); + function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + return; + } + if (valueNode.kind === kinds_ts_1.Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (variables == null || !Object.hasOwn(variables, variableName)) { + return; + } + const variableValue = variables[variableName]; + if (variableValue === undefined) { + return; + } + if (variableValue === null && (0, definition_ts_1.isNonNullType)(type)) { + return; + } + return variableValue; + } + if ((0, definition_ts_1.isNonNullType)(type)) { + if (valueNode.kind === kinds_ts_1.Kind.NULL) { + return; + } + return valueFromAST(valueNode, type.ofType, variables); + } + if (valueNode.kind === kinds_ts_1.Kind.NULL) { + return null; + } + if ((0, definition_ts_1.isListType)(type)) { + const itemType = type.ofType; + if (valueNode.kind === kinds_ts_1.Kind.LIST) { + const coercedValues = []; + for (const itemNode of valueNode.values) { + if (isMissingVariable(itemNode, variables)) { + if ((0, definition_ts_1.isNonNullType)(itemType)) { + return; + } + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNode, itemType, variables); + if (itemValue === undefined) { + return; + } + coercedValues.push(itemValue); + } + } + return coercedValues; + } + const coercedValue = valueFromAST(valueNode, itemType, variables); + if (coercedValue === undefined) { + return; + } + return [coercedValue]; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + if (valueNode.kind !== kinds_ts_1.Kind.OBJECT) { + return; + } + const coercedObj = Object.create(null); + const fieldDefs = type.getFields(); + const hasUnknownField = valueNode.fields.some((field) => !Object.hasOwn(fieldDefs, field.name.value)); + if (hasUnknownField) { + return; + } + const fieldNodes = new Map(valueNode.fields.map((field) => [field.name.value, field])); + for (const field of Object.values(fieldDefs)) { + const fieldNode = fieldNodes.get(field.name); + if (fieldNode == null || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, definition_ts_1.isNonNullType)(field.type)) { + return; + } + continue; + } + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); + if (fieldValue === undefined) { + return; + } + coercedObj[field.name] = fieldValue; + } + if (type.isOneOf) { + const coercedKeys = Object.keys(coercedObj); + if (fieldNodes.size !== 1 || coercedKeys.length !== 1) { + return; + } + for (const [fieldName, fieldNode] of fieldNodes) { + if (fieldNode.value.kind === kinds_ts_1.Kind.NULL || coercedObj[fieldName] === null) { + return; + } + } + } + return coercedObj; + } + if ((0, definition_ts_1.isLeafType)(type)) { + let result; + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; + } + if (result === undefined) { + return; + } + return result; + } + (0, invariant_ts_1.invariant)(false, "Unexpected input type: " + (0, inspect_ts_1.inspect)(type)); + } + function isMissingVariable(valueNode, variables) { + return valueNode.kind === kinds_ts_1.Kind.VARIABLE && (variables?.[valueNode.name.value] === undefined || !Object.hasOwn(variables, valueNode.name.value)); + } +}); + +// node_modules/graphql/utilities/concatAST.js +var require_concatAST = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.concatAST = concatAST; + var kinds_ts_1 = require_kinds(); + function concatAST(documents) { + const definitions = []; + for (const doc of documents) { + definitions.push(...doc.definitions); + } + return { kind: kinds_ts_1.Kind.DOCUMENT, definitions }; + } +}); + +// node_modules/graphql/utilities/separateOperations.js +var require_separateOperations = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.separateOperations = separateOperations; + var kinds_ts_1 = require_kinds(); + var visitor_ts_1 = require_visitor(); + function separateOperations(documentAST) { + const operations = []; + const depGraph = Object.create(null); + for (const definitionNode of documentAST.definitions) { + switch (definitionNode.kind) { + case kinds_ts_1.Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + case kinds_ts_1.Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies(definitionNode.selectionSet); + break; + default: + } + } + const separatedDocumentASTs = Object.create(null); + for (const operation of operations) { + const dependencies = new Set; + for (const fragmentName of collectDependencies(operation.selectionSet)) { + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } + const operationName = operation.name ? operation.name.value : ""; + separatedDocumentASTs[operationName] = { + kind: kinds_ts_1.Kind.DOCUMENT, + definitions: documentAST.definitions.filter((node) => node === operation || node.kind === kinds_ts_1.Kind.FRAGMENT_DEFINITION && dependencies.has(node.name.value)) + }; + } + return separatedDocumentASTs; + } + function collectTransitiveDependencies(collected, depGraph, fromName) { + if (!collected.has(fromName)) { + collected.add(fromName); + const immediateDeps = depGraph[fromName]; + if (immediateDeps !== undefined) { + for (const toName of immediateDeps) { + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } + } + function collectDependencies(selectionSet) { + const dependencies = []; + (0, visitor_ts_1.visit)(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); + } + }); + return dependencies; + } +}); + +// node_modules/graphql/utilities/stripIgnoredCharacters.js +var require_stripIgnoredCharacters = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.stripIgnoredCharacters = stripIgnoredCharacters; + var blockString_ts_1 = require_blockString(); + var lexer_ts_1 = require_lexer(); + var source_ts_1 = require_source(); + var tokenKind_ts_1 = require_tokenKind(); + function stripIgnoredCharacters(source) { + const sourceObj = (0, source_ts_1.isSource)(source) ? source : new source_ts_1.Source(source); + const body = sourceObj.body; + const lexer = new lexer_ts_1.Lexer(sourceObj); + let strippedBody = ""; + let wasLastAddedTokenNonPunctuator = false; + while (lexer.advance().kind !== tokenKind_ts_1.TokenKind.EOF) { + const currentToken = lexer.token; + const tokenKind = currentToken.kind; + const isNonPunctuator = !(0, lexer_ts_1.isPunctuatorTokenKind)(currentToken.kind); + if (wasLastAddedTokenNonPunctuator) { + if (isNonPunctuator || currentToken.kind === tokenKind_ts_1.TokenKind.SPREAD) { + strippedBody += " "; + } + } + const tokenBody = body.slice(currentToken.start, currentToken.end); + if (tokenKind === tokenKind_ts_1.TokenKind.BLOCK_STRING) { + strippedBody += (0, blockString_ts_1.printBlockString)(currentToken.value, { minimize: true }); + } else { + strippedBody += tokenBody; + } + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + return strippedBody; + } +}); + +// node_modules/graphql/utilities/findSchemaChanges.js +var require_findSchemaChanges = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SafeChangeType = exports.DangerousChangeType = exports.BreakingChangeType = undefined; + exports.findBreakingChanges = findBreakingChanges; + exports.findDangerousChanges = findDangerousChanges; + exports.findSchemaChanges = findSchemaChanges; + var inspect_ts_1 = require_inspect(); + var invariant_ts_1 = require_invariant(); + var keyMap_ts_1 = require_keyMap(); + var printer_ts_1 = require_printer(); + var definition_ts_1 = require_definition(); + var scalars_ts_1 = require_scalars(); + var getDefaultValueAST_ts_1 = require_getDefaultValueAST(); + var sortValueNode_ts_1 = require_sortValueNode(); + exports.BreakingChangeType = { + TYPE_REMOVED: "TYPE_REMOVED", + TYPE_CHANGED_KIND: "TYPE_CHANGED_KIND", + TYPE_REMOVED_FROM_UNION: "TYPE_REMOVED_FROM_UNION", + VALUE_REMOVED_FROM_ENUM: "VALUE_REMOVED_FROM_ENUM", + REQUIRED_INPUT_FIELD_ADDED: "REQUIRED_INPUT_FIELD_ADDED", + IMPLEMENTED_INTERFACE_REMOVED: "IMPLEMENTED_INTERFACE_REMOVED", + FIELD_REMOVED: "FIELD_REMOVED", + FIELD_CHANGED_KIND: "FIELD_CHANGED_KIND", + REQUIRED_ARG_ADDED: "REQUIRED_ARG_ADDED", + ARG_REMOVED: "ARG_REMOVED", + ARG_CHANGED_KIND: "ARG_CHANGED_KIND", + DIRECTIVE_REMOVED: "DIRECTIVE_REMOVED", + DIRECTIVE_ARG_REMOVED: "DIRECTIVE_ARG_REMOVED", + REQUIRED_DIRECTIVE_ARG_ADDED: "REQUIRED_DIRECTIVE_ARG_ADDED", + DIRECTIVE_REPEATABLE_REMOVED: "DIRECTIVE_REPEATABLE_REMOVED", + DIRECTIVE_LOCATION_REMOVED: "DIRECTIVE_LOCATION_REMOVED" + }; + exports.DangerousChangeType = { + VALUE_ADDED_TO_ENUM: "VALUE_ADDED_TO_ENUM", + TYPE_ADDED_TO_UNION: "TYPE_ADDED_TO_UNION", + OPTIONAL_INPUT_FIELD_ADDED: "OPTIONAL_INPUT_FIELD_ADDED", + OPTIONAL_ARG_ADDED: "OPTIONAL_ARG_ADDED", + IMPLEMENTED_INTERFACE_ADDED: "IMPLEMENTED_INTERFACE_ADDED", + ARG_DEFAULT_VALUE_CHANGE: "ARG_DEFAULT_VALUE_CHANGE" + }; + exports.SafeChangeType = { + DESCRIPTION_CHANGED: "DESCRIPTION_CHANGED", + TYPE_ADDED: "TYPE_ADDED", + OPTIONAL_INPUT_FIELD_ADDED: "OPTIONAL_INPUT_FIELD_ADDED", + OPTIONAL_ARG_ADDED: "OPTIONAL_ARG_ADDED", + DIRECTIVE_ADDED: "DIRECTIVE_ADDED", + FIELD_ADDED: "FIELD_ADDED", + DIRECTIVE_REPEATABLE_ADDED: "DIRECTIVE_REPEATABLE_ADDED", + DIRECTIVE_LOCATION_ADDED: "DIRECTIVE_LOCATION_ADDED", + OPTIONAL_DIRECTIVE_ARG_ADDED: "OPTIONAL_DIRECTIVE_ARG_ADDED", + FIELD_CHANGED_KIND_SAFE: "FIELD_CHANGED_KIND_SAFE", + ARG_CHANGED_KIND_SAFE: "ARG_CHANGED_KIND_SAFE", + ARG_DEFAULT_VALUE_ADDED: "ARG_DEFAULT_VALUE_ADDED" + }; + function findBreakingChanges(oldSchema, newSchema) { + return findSchemaChanges(oldSchema, newSchema).filter((change) => (change.type in exports.BreakingChangeType)); + } + function findDangerousChanges(oldSchema, newSchema) { + return findSchemaChanges(oldSchema, newSchema).filter((change) => (change.type in exports.DangerousChangeType)); + } + function findSchemaChanges(oldSchema, newSchema) { + return [ + ...findTypeChanges(oldSchema, newSchema), + ...findDirectiveChanges(oldSchema, newSchema) + ]; + } + function findDirectiveChanges(oldSchema, newSchema) { + const schemaChanges = []; + const directivesDiff = diff(oldSchema.getDirectives(), newSchema.getDirectives()); + for (const oldDirective of directivesDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.DIRECTIVE_REMOVED, + description: `Directive ${oldDirective} was removed.` + }); + } + for (const newDirective of directivesDiff.added) { + schemaChanges.push({ + type: exports.SafeChangeType.DIRECTIVE_ADDED, + description: `Directive @${newDirective.name} was added.` + }); + } + for (const [oldDirective, newDirective] of directivesDiff.persisted) { + const argsDiff = diff(oldDirective.args, newDirective.args); + for (const newArg of argsDiff.added) { + if ((0, definition_ts_1.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: exports.BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: `A required argument ${newArg} was added.` + }); + } else { + schemaChanges.push({ + type: exports.SafeChangeType.OPTIONAL_DIRECTIVE_ARG_ADDED, + description: `An optional argument @${oldDirective.name}(${newArg.name}:) was added.` + }); + } + } + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `Argument ${oldArg} was removed.` + }); + } + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArg.type, newArg.type); + const oldDefaultValueStr = getDefaultValue(oldArg); + const newDefaultValueStr = getDefaultValue(newArg); + if (!isSafe) { + schemaChanges.push({ + type: exports.BreakingChangeType.ARG_CHANGED_KIND, + description: `Argument @${oldDirective.name}(${oldArg.name}:) has changed type from ` + `${String(oldArg.type)} to ${String(newArg.type)}.` + }); + } else if (oldDefaultValueStr !== undefined) { + if (newDefaultValueStr === undefined) { + schemaChanges.push({ + type: exports.DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `@${oldDirective.name}(${oldArg.name}:) defaultValue was removed.` + }); + } else if (oldDefaultValueStr !== newDefaultValueStr) { + schemaChanges.push({ + type: exports.DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `@${oldDirective.name}(${oldArg.name}:) has changed defaultValue from ${oldDefaultValueStr} to ${newDefaultValueStr}.` + }); + } + } else if (newDefaultValueStr !== undefined && oldDefaultValueStr === undefined) { + schemaChanges.push({ + type: exports.SafeChangeType.ARG_DEFAULT_VALUE_ADDED, + description: `@${oldDirective.name}(${oldArg.name}:) added a defaultValue ${newDefaultValueStr}.` + }); + } else if (oldArg.type.toString() !== newArg.type.toString()) { + schemaChanges.push({ + type: exports.SafeChangeType.ARG_CHANGED_KIND_SAFE, + description: `Argument @${oldDirective.name}(${oldArg.name}:) has changed type from ` + `${String(oldArg.type)} to ${String(newArg.type)}.` + }); + } + if (oldArg.description !== newArg.description) { + schemaChanges.push({ + type: exports.SafeChangeType.DESCRIPTION_CHANGED, + description: `Description of @${oldDirective.name}(${oldDirective.name}) has changed to "${newArg.description}".` + }); + } + } + if (oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: exports.BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: `Repeatable flag was removed from ${oldDirective}.` + }); + } else if (newDirective.isRepeatable && !oldDirective.isRepeatable) { + schemaChanges.push({ + type: exports.SafeChangeType.DIRECTIVE_REPEATABLE_ADDED, + description: `Repeatable flag was added to @${oldDirective.name}.` + }); + } + if (oldDirective.description !== newDirective.description) { + schemaChanges.push({ + type: exports.SafeChangeType.DESCRIPTION_CHANGED, + description: `Description of @${oldDirective.name} has changed to "${newDirective.description}".` + }); + } + for (const location of oldDirective.locations) { + if (!newDirective.locations.includes(location)) { + schemaChanges.push({ + type: exports.BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective}.` + }); + } + } + for (const location of newDirective.locations) { + if (!oldDirective.locations.includes(location)) { + schemaChanges.push({ + type: exports.SafeChangeType.DIRECTIVE_LOCATION_ADDED, + description: `${location} was added to @${oldDirective.name}.` + }); + } + } + } + return schemaChanges; + } + function findTypeChanges(oldSchema, newSchema) { + const schemaChanges = []; + const typesDiff = diff(Object.values(oldSchema.getTypeMap()), Object.values(newSchema.getTypeMap())); + for (const oldType of typesDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.TYPE_REMOVED, + description: (0, scalars_ts_1.isSpecifiedScalarType)(oldType) ? `Standard scalar ${oldType} was removed because it is not referenced anymore.` : `${oldType} was removed.` + }); + } + for (const newType of typesDiff.added) { + schemaChanges.push({ + type: exports.SafeChangeType.TYPE_ADDED, + description: `${newType} was added.` + }); + } + for (const [oldType, newType] of typesDiff.persisted) { + if (oldType.description !== newType.description) { + schemaChanges.push({ + type: exports.SafeChangeType.DESCRIPTION_CHANGED, + description: `Description of ${oldType.name} has changed to "${newType.description}".` + }); + } + if ((0, definition_ts_1.isEnumType)(oldType) && (0, definition_ts_1.isEnumType)(newType)) { + schemaChanges.push(...findEnumTypeChanges(oldType, newType)); + } else if ((0, definition_ts_1.isUnionType)(oldType) && (0, definition_ts_1.isUnionType)(newType)) { + schemaChanges.push(...findUnionTypeChanges(oldType, newType)); + } else if ((0, definition_ts_1.isInputObjectType)(oldType) && (0, definition_ts_1.isInputObjectType)(newType)) { + schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); + } else if ((0, definition_ts_1.isObjectType)(oldType) && (0, definition_ts_1.isObjectType)(newType)) { + schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); + } else if ((0, definition_ts_1.isInterfaceType)(oldType) && (0, definition_ts_1.isInterfaceType)(newType)) { + schemaChanges.push(...findFieldChanges(oldType, newType), ...findImplementedInterfacesChanges(oldType, newType)); + } else if (oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: exports.BreakingChangeType.TYPE_CHANGED_KIND, + description: `${oldType} changed from ${typeKindName(oldType)} to ${typeKindName(newType)}.` + }); + } + } + return schemaChanges; + } + function findInputObjectTypeChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); + for (const newField of fieldsDiff.added) { + if ((0, definition_ts_1.isRequiredInputField)(newField)) { + schemaChanges.push({ + type: exports.BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: `A required field ${newField} was added.` + }); + } else { + schemaChanges.push({ + type: exports.DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: `An optional field ${newField} was added.` + }); + } + } + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.FIELD_REMOVED, + description: `Field ${oldField} was removed.` + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldField.type, newField.type); + if (!isSafe) { + schemaChanges.push({ + type: exports.BreakingChangeType.FIELD_CHANGED_KIND, + description: `Field ${newField} changed type from ${oldField.type} to ${newField.type}.` + }); + } else if (oldField.type.toString() !== newField.type.toString()) { + schemaChanges.push({ + type: exports.SafeChangeType.FIELD_CHANGED_KIND_SAFE, + description: `Field ${oldType}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` + }); + } + if (oldField.description !== newField.description) { + schemaChanges.push({ + type: exports.SafeChangeType.DESCRIPTION_CHANGED, + description: `Description of input-field ${newType}.${newField.name} has changed to "${newField.description}".` + }); + } + } + return schemaChanges; + } + function findUnionTypeChanges(oldType, newType) { + const schemaChanges = []; + const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + for (const newPossibleType of possibleTypesDiff.added) { + schemaChanges.push({ + type: exports.DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${newPossibleType} was added to union type ${oldType}.` + }); + } + for (const oldPossibleType of possibleTypesDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${oldPossibleType} was removed from union type ${oldType}.` + }); + } + return schemaChanges; + } + function findEnumTypeChanges(oldType, newType) { + const schemaChanges = []; + const valuesDiff = diff(oldType.getValues(), newType.getValues()); + for (const newValue of valuesDiff.added) { + schemaChanges.push({ + type: exports.DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `Enum value ${newValue} was added.` + }); + } + for (const oldValue of valuesDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `Enum value ${oldValue} was removed.` + }); + } + for (const [oldValue, newValue] of valuesDiff.persisted) { + if (oldValue.description !== newValue.description) { + schemaChanges.push({ + type: exports.SafeChangeType.DESCRIPTION_CHANGED, + description: `Description of enum value ${oldType}.${oldValue.name} has changed to "${newValue.description}".` + }); + } + } + return schemaChanges; + } + function findImplementedInterfacesChanges(oldType, newType) { + const schemaChanges = []; + const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + for (const newInterface of interfacesDiff.added) { + schemaChanges.push({ + type: exports.DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: `${newInterface} added to interfaces implemented by ${oldType}.` + }); + } + for (const oldInterface of interfacesDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: `${oldType} no longer implements interface ${oldInterface}.` + }); + } + return schemaChanges; + } + function findFieldChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff(Object.values(oldType.getFields()), Object.values(newType.getFields())); + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.FIELD_REMOVED, + description: `Field ${oldField} was removed.` + }); + } + for (const newField of fieldsDiff.added) { + schemaChanges.push({ + type: exports.SafeChangeType.FIELD_ADDED, + description: `Field ${oldType}.${newField.name} was added.` + }); + } + for (const [oldField, newField] of fieldsDiff.persisted) { + schemaChanges.push(...findArgChanges(oldField, newField)); + const isSafe = isChangeSafeForObjectOrInterfaceField(oldField.type, newField.type); + if (!isSafe) { + schemaChanges.push({ + type: exports.BreakingChangeType.FIELD_CHANGED_KIND, + description: `Field ${newField} changed type from ${oldField.type} to ${newField.type}.` + }); + } else if (oldField.type.toString() !== newField.type.toString()) { + schemaChanges.push({ + type: exports.SafeChangeType.FIELD_CHANGED_KIND_SAFE, + description: `Field ${oldType}.${oldField.name} changed type from ` + `${String(oldField.type)} to ${String(newField.type)}.` + }); + } + if (oldField.description !== newField.description) { + schemaChanges.push({ + type: exports.SafeChangeType.DESCRIPTION_CHANGED, + description: `Description of field ${oldType}.${oldField.name} has changed to "${newField.description}".` + }); + } + } + return schemaChanges; + } + function findArgChanges(oldField, newField) { + const schemaChanges = []; + const argsDiff = diff(oldField.args, newField.args); + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: exports.BreakingChangeType.ARG_REMOVED, + description: `Argument ${oldArg} was removed.` + }); + } + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArg.type, newArg.type); + const oldDefaultValueStr = getDefaultValue(oldArg); + const newDefaultValueStr = getDefaultValue(newArg); + if (!isSafe) { + schemaChanges.push({ + type: exports.BreakingChangeType.ARG_CHANGED_KIND, + description: `Argument ${newArg} has changed type from ${oldArg.type} to ${newArg.type}.` + }); + } else if (oldDefaultValueStr !== undefined) { + if (newDefaultValueStr === undefined) { + schemaChanges.push({ + type: exports.DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldArg} defaultValue was removed.` + }); + } else if (oldDefaultValueStr !== newDefaultValueStr) { + schemaChanges.push({ + type: exports.DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldArg} has changed defaultValue from ${oldDefaultValueStr} to ${newDefaultValueStr}.` + }); + } + } else if (newDefaultValueStr !== undefined && oldDefaultValueStr === undefined) { + schemaChanges.push({ + type: exports.SafeChangeType.ARG_DEFAULT_VALUE_ADDED, + description: `${oldArg} added a defaultValue ${newDefaultValueStr}.` + }); + } else if (oldArg.type.toString() !== newArg.type.toString()) { + schemaChanges.push({ + type: exports.SafeChangeType.ARG_CHANGED_KIND_SAFE, + description: `Argument ${oldArg} has changed type from ` + `${String(oldArg.type)} to ${String(newArg.type)}.` + }); + } + if (oldArg.description !== newArg.description) { + schemaChanges.push({ + type: exports.SafeChangeType.DESCRIPTION_CHANGED, + description: `Description of argument ${oldArg} has changed to "${newArg.description}".` + }); + } + } + for (const newArg of argsDiff.added) { + if ((0, definition_ts_1.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: exports.BreakingChangeType.REQUIRED_ARG_ADDED, + description: `A required argument ${newArg} was added.` + }); + } else { + schemaChanges.push({ + type: exports.DangerousChangeType.OPTIONAL_ARG_ADDED, + description: `An optional argument ${newArg} was added.` + }); + } + } + return schemaChanges; + } + function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, definition_ts_1.isListType)(oldType)) { + return (0, definition_ts_1.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || (0, definition_ts_1.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType); + } + if ((0, definition_ts_1.isNonNullType)(oldType)) { + return (0, definition_ts_1.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); + } + return (0, definition_ts_1.isNamedType)(newType) && oldType.name === newType.name || (0, definition_ts_1.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType); + } + function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, definition_ts_1.isListType)(oldType)) { + return (0, definition_ts_1.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } + if ((0, definition_ts_1.isNonNullType)(oldType)) { + return (0, definition_ts_1.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || !(0, definition_ts_1.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType); + } + return (0, definition_ts_1.isNamedType)(newType) && oldType.name === newType.name; + } + function typeKindName(type) { + if ((0, definition_ts_1.isScalarType)(type)) { + return "a Scalar type"; + } + if ((0, definition_ts_1.isObjectType)(type)) { + return "an Object type"; + } + if ((0, definition_ts_1.isInterfaceType)(type)) { + return "an Interface type"; + } + if ((0, definition_ts_1.isUnionType)(type)) { + return "a Union type"; + } + if ((0, definition_ts_1.isEnumType)(type)) { + return "an Enum type"; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + return "an Input type"; + } + (0, invariant_ts_1.invariant)(false, "Unexpected type: " + (0, inspect_ts_1.inspect)(type)); + } + function getDefaultValue(argOrInputField) { + const ast = (0, getDefaultValueAST_ts_1.getDefaultValueAST)(argOrInputField); + if (ast) { + return (0, printer_ts_1.print)((0, sortValueNode_ts_1.sortValueNode)(ast)); + } + } + function diff(oldArray, newArray) { + const added = []; + const removed = []; + const persisted = []; + const oldMap = (0, keyMap_ts_1.keyMap)(oldArray, ({ name }) => name); + const newMap = (0, keyMap_ts_1.keyMap)(newArray, ({ name }) => name); + for (const oldItem of oldArray) { + const newItem = newMap[oldItem.name]; + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } + } + for (const newItem of newArray) { + if (oldMap[newItem.name] === undefined) { + added.push(newItem); + } + } + return { added, persisted, removed }; + } +}); + +// node_modules/graphql/utilities/resolveSchemaCoordinate.js +var require_resolveSchemaCoordinate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchemaCoordinate = resolveSchemaCoordinate; + exports.resolveASTSchemaCoordinate = resolveASTSchemaCoordinate; + var inspect_ts_1 = require_inspect(); + var kinds_ts_1 = require_kinds(); + var parser_ts_1 = require_parser(); + var definition_ts_1 = require_definition(); + function resolveSchemaCoordinate(schema, schemaCoordinate) { + return resolveASTSchemaCoordinate(schema, (0, parser_ts_1.parseSchemaCoordinate)(schemaCoordinate)); + } + function resolveTypeCoordinate(schema, schemaCoordinate) { + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); + if (type == null) { + return; + } + return { kind: "NamedType", type }; + } + function resolveMemberCoordinate(schema, schemaCoordinate) { + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); + if (!type) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(typeName)} to be defined as a type in the schema.`); + } + if (!(0, definition_ts_1.isEnumType)(type) && !(0, definition_ts_1.isInputObjectType)(type) && !(0, definition_ts_1.isObjectType)(type) && !(0, definition_ts_1.isInterfaceType)(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(typeName)} to be an Enum, Input Object, Object or Interface type.`); + } + if ((0, definition_ts_1.isEnumType)(type)) { + const enumValueName = schemaCoordinate.memberName.value; + const enumValue = type.getValue(enumValueName); + if (enumValue == null) { + return; + } + return { kind: "EnumValue", type, enumValue }; + } + if ((0, definition_ts_1.isInputObjectType)(type)) { + const inputFieldName = schemaCoordinate.memberName.value; + const inputField = type.getFields()[inputFieldName]; + if (inputField == null) { + return; + } + return { kind: "InputField", type, inputField }; + } + const fieldName = schemaCoordinate.memberName.value; + const field = schema.getField(type, fieldName); + if (field == null) { + return; + } + return { kind: "Field", type, field }; + } + function resolveArgumentCoordinate(schema, schemaCoordinate) { + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); + if (type == null) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(typeName)} to be defined as a type in the schema.`); + } + if (!(0, definition_ts_1.isObjectType)(type) && !(0, definition_ts_1.isInterfaceType)(type)) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(typeName)} to be an object type or interface type.`); + } + const fieldName = schemaCoordinate.fieldName.value; + const field = schema.getField(type, fieldName); + if (field == null) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(fieldName)} to exist as a field of type ${(0, inspect_ts_1.inspect)(typeName)} in the schema.`); + } + const fieldArgumentName = schemaCoordinate.argumentName.value; + const fieldArgument = field.args.find((arg) => arg.name === fieldArgumentName); + if (fieldArgument == null) { + return; + } + return { kind: "FieldArgument", type, field, fieldArgument }; + } + function resolveDirectiveCoordinate(schema, schemaCoordinate) { + const directiveName = schemaCoordinate.name.value; + const directive = schema.getDirective(directiveName); + if (!directive) { + return; + } + return { kind: "Directive", directive }; + } + function resolveDirectiveArgumentCoordinate(schema, schemaCoordinate) { + const directiveName = schemaCoordinate.name.value; + const directive = schema.getDirective(directiveName); + if (!directive) { + throw new Error(`Expected ${(0, inspect_ts_1.inspect)(directiveName)} to be defined as a directive in the schema.`); + } + const { argumentName: { value: directiveArgumentName } } = schemaCoordinate; + const directiveArgument = directive.args.find((arg) => arg.name === directiveArgumentName); + if (!directiveArgument) { + return; + } + return { kind: "DirectiveArgument", directive, directiveArgument }; + } + function resolveASTSchemaCoordinate(schema, schemaCoordinate) { + switch (schemaCoordinate.kind) { + case kinds_ts_1.Kind.TYPE_COORDINATE: + return resolveTypeCoordinate(schema, schemaCoordinate); + case kinds_ts_1.Kind.MEMBER_COORDINATE: + return resolveMemberCoordinate(schema, schemaCoordinate); + case kinds_ts_1.Kind.ARGUMENT_COORDINATE: + return resolveArgumentCoordinate(schema, schemaCoordinate); + case kinds_ts_1.Kind.DIRECTIVE_COORDINATE: + return resolveDirectiveCoordinate(schema, schemaCoordinate); + case kinds_ts_1.Kind.DIRECTIVE_ARGUMENT_COORDINATE: + return resolveDirectiveArgumentCoordinate(schema, schemaCoordinate); + } + } +}); + +// node_modules/graphql/utilities/index.js +var require_utilities = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveASTSchemaCoordinate = exports.resolveSchemaCoordinate = exports.findSchemaChanges = exports.findDangerousChanges = exports.findBreakingChanges = exports.SafeChangeType = exports.DangerousChangeType = exports.BreakingChangeType = exports.doTypesOverlap = exports.isTypeSubTypeOf = exports.isEqualType = exports.stripIgnoredCharacters = exports.separateOperations = exports.concatAST = exports.validateInputLiteral = exports.validateInputValue = exports.coerceInputLiteral = exports.coerceInputValue = exports.valueToLiteral = exports.replaceVariables = exports.visitWithTypeInfo = exports.TypeInfo = exports.astFromValue = exports.valueFromASTUntyped = exports.valueFromAST = exports.typeFromAST = exports.printIntrospectionSchema = exports.printDirective = exports.printType = exports.printSchema = exports.lexicographicSortSchema = exports.extendSchema = exports.buildSchema = exports.buildASTSchema = exports.buildClientSchema = exports.introspectionFromSchema = exports.getOperationAST = exports.getIntrospectionQuery = undefined; + var getIntrospectionQuery_ts_1 = require_getIntrospectionQuery(); + Object.defineProperty(exports, "getIntrospectionQuery", { enumerable: true, get: function() { + return getIntrospectionQuery_ts_1.getIntrospectionQuery; + } }); + var getOperationAST_ts_1 = require_getOperationAST(); + Object.defineProperty(exports, "getOperationAST", { enumerable: true, get: function() { + return getOperationAST_ts_1.getOperationAST; + } }); + var introspectionFromSchema_ts_1 = require_introspectionFromSchema(); + Object.defineProperty(exports, "introspectionFromSchema", { enumerable: true, get: function() { + return introspectionFromSchema_ts_1.introspectionFromSchema; + } }); + var buildClientSchema_ts_1 = require_buildClientSchema(); + Object.defineProperty(exports, "buildClientSchema", { enumerable: true, get: function() { + return buildClientSchema_ts_1.buildClientSchema; + } }); + var buildASTSchema_ts_1 = require_buildASTSchema(); + Object.defineProperty(exports, "buildASTSchema", { enumerable: true, get: function() { + return buildASTSchema_ts_1.buildASTSchema; + } }); + Object.defineProperty(exports, "buildSchema", { enumerable: true, get: function() { + return buildASTSchema_ts_1.buildSchema; + } }); + var extendSchema_ts_1 = require_extendSchema(); + Object.defineProperty(exports, "extendSchema", { enumerable: true, get: function() { + return extendSchema_ts_1.extendSchema; + } }); + var lexicographicSortSchema_ts_1 = require_lexicographicSortSchema(); + Object.defineProperty(exports, "lexicographicSortSchema", { enumerable: true, get: function() { + return lexicographicSortSchema_ts_1.lexicographicSortSchema; + } }); + var printSchema_ts_1 = require_printSchema(); + Object.defineProperty(exports, "printSchema", { enumerable: true, get: function() { + return printSchema_ts_1.printSchema; + } }); + Object.defineProperty(exports, "printType", { enumerable: true, get: function() { + return printSchema_ts_1.printType; + } }); + Object.defineProperty(exports, "printDirective", { enumerable: true, get: function() { + return printSchema_ts_1.printDirective; + } }); + Object.defineProperty(exports, "printIntrospectionSchema", { enumerable: true, get: function() { + return printSchema_ts_1.printIntrospectionSchema; + } }); + var typeFromAST_ts_1 = require_typeFromAST(); + Object.defineProperty(exports, "typeFromAST", { enumerable: true, get: function() { + return typeFromAST_ts_1.typeFromAST; + } }); + var valueFromAST_ts_1 = require_valueFromAST(); + Object.defineProperty(exports, "valueFromAST", { enumerable: true, get: function() { + return valueFromAST_ts_1.valueFromAST; + } }); + var valueFromASTUntyped_ts_1 = require_valueFromASTUntyped(); + Object.defineProperty(exports, "valueFromASTUntyped", { enumerable: true, get: function() { + return valueFromASTUntyped_ts_1.valueFromASTUntyped; + } }); + var astFromValue_ts_1 = require_astFromValue(); + Object.defineProperty(exports, "astFromValue", { enumerable: true, get: function() { + return astFromValue_ts_1.astFromValue; + } }); + var TypeInfo_ts_1 = require_TypeInfo(); + Object.defineProperty(exports, "TypeInfo", { enumerable: true, get: function() { + return TypeInfo_ts_1.TypeInfo; + } }); + Object.defineProperty(exports, "visitWithTypeInfo", { enumerable: true, get: function() { + return TypeInfo_ts_1.visitWithTypeInfo; + } }); + var replaceVariables_ts_1 = require_replaceVariables(); + Object.defineProperty(exports, "replaceVariables", { enumerable: true, get: function() { + return replaceVariables_ts_1.replaceVariables; + } }); + var valueToLiteral_ts_1 = require_valueToLiteral(); + Object.defineProperty(exports, "valueToLiteral", { enumerable: true, get: function() { + return valueToLiteral_ts_1.valueToLiteral; + } }); + var coerceInputValue_ts_1 = require_coerceInputValue(); + Object.defineProperty(exports, "coerceInputValue", { enumerable: true, get: function() { + return coerceInputValue_ts_1.coerceInputValue; + } }); + Object.defineProperty(exports, "coerceInputLiteral", { enumerable: true, get: function() { + return coerceInputValue_ts_1.coerceInputLiteral; + } }); + var validateInputValue_ts_1 = require_validateInputValue(); + Object.defineProperty(exports, "validateInputValue", { enumerable: true, get: function() { + return validateInputValue_ts_1.validateInputValue; + } }); + Object.defineProperty(exports, "validateInputLiteral", { enumerable: true, get: function() { + return validateInputValue_ts_1.validateInputLiteral; + } }); + var concatAST_ts_1 = require_concatAST(); + Object.defineProperty(exports, "concatAST", { enumerable: true, get: function() { + return concatAST_ts_1.concatAST; + } }); + var separateOperations_ts_1 = require_separateOperations(); + Object.defineProperty(exports, "separateOperations", { enumerable: true, get: function() { + return separateOperations_ts_1.separateOperations; + } }); + var stripIgnoredCharacters_ts_1 = require_stripIgnoredCharacters(); + Object.defineProperty(exports, "stripIgnoredCharacters", { enumerable: true, get: function() { + return stripIgnoredCharacters_ts_1.stripIgnoredCharacters; + } }); + var typeComparators_ts_1 = require_typeComparators(); + Object.defineProperty(exports, "isEqualType", { enumerable: true, get: function() { + return typeComparators_ts_1.isEqualType; + } }); + Object.defineProperty(exports, "isTypeSubTypeOf", { enumerable: true, get: function() { + return typeComparators_ts_1.isTypeSubTypeOf; + } }); + Object.defineProperty(exports, "doTypesOverlap", { enumerable: true, get: function() { + return typeComparators_ts_1.doTypesOverlap; + } }); + var findSchemaChanges_ts_1 = require_findSchemaChanges(); + Object.defineProperty(exports, "BreakingChangeType", { enumerable: true, get: function() { + return findSchemaChanges_ts_1.BreakingChangeType; + } }); + Object.defineProperty(exports, "DangerousChangeType", { enumerable: true, get: function() { + return findSchemaChanges_ts_1.DangerousChangeType; + } }); + Object.defineProperty(exports, "SafeChangeType", { enumerable: true, get: function() { + return findSchemaChanges_ts_1.SafeChangeType; + } }); + Object.defineProperty(exports, "findBreakingChanges", { enumerable: true, get: function() { + return findSchemaChanges_ts_1.findBreakingChanges; + } }); + Object.defineProperty(exports, "findDangerousChanges", { enumerable: true, get: function() { + return findSchemaChanges_ts_1.findDangerousChanges; + } }); + Object.defineProperty(exports, "findSchemaChanges", { enumerable: true, get: function() { + return findSchemaChanges_ts_1.findSchemaChanges; + } }); + var resolveSchemaCoordinate_ts_1 = require_resolveSchemaCoordinate(); + Object.defineProperty(exports, "resolveSchemaCoordinate", { enumerable: true, get: function() { + return resolveSchemaCoordinate_ts_1.resolveSchemaCoordinate; + } }); + Object.defineProperty(exports, "resolveASTSchemaCoordinate", { enumerable: true, get: function() { + return resolveSchemaCoordinate_ts_1.resolveASTSchemaCoordinate; + } }); +}); + +// node_modules/graphql/index.js +var require_graphql2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isSchema = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = exports.introspectionTypes = exports.DEFAULT_DEPRECATION_REASON = exports.TypeKind = exports.GraphQLOneOfDirective = exports.GraphQLSpecifiedByDirective = exports.GraphQLDeprecatedDirective = exports.GraphQLStreamDirective = exports.GraphQLDeferDirective = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.specifiedDirectives = exports.GRAPHQL_MIN_INT = exports.GRAPHQL_MAX_INT = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = exports.specifiedScalarTypes = exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = exports.GraphQLDirective = exports.GraphQLSchema = exports.resolveReadonlyArrayThunk = exports.resolveObjMapThunk = exports.defaultHarness = exports.graphqlSync = exports.graphql = exports.isDevModeEnabled = exports.enableDevMode = exports.versionInfo = exports.version = undefined; + exports.assertNamedType = exports.assertNullableType = exports.assertWrappingType = exports.assertAbstractType = exports.assertCompositeType = exports.assertLeafType = exports.assertOutputType = exports.assertInputType = exports.assertNonNullType = exports.assertListType = exports.assertInputField = exports.assertInputObjectType = exports.assertEnumValue = exports.assertEnumType = exports.assertUnionType = exports.assertInterfaceType = exports.assertArgument = exports.assertField = exports.assertObjectType = exports.assertScalarType = exports.assertType = exports.assertDirective = exports.assertSchema = exports.isSpecifiedDirective = exports.isIntrospectionType = exports.isSpecifiedScalarType = exports.isRequiredInputField = exports.isRequiredArgument = exports.isNamedType = exports.isNullableType = exports.isWrappingType = exports.isAbstractType = exports.isCompositeType = exports.isLeafType = exports.isOutputType = exports.isInputType = exports.isNonNullType = exports.isListType = exports.isInputField = exports.isInputObjectType = exports.isEnumValue = exports.isEnumType = exports.isUnionType = exports.isInterfaceType = exports.isArgument = exports.isField = exports.isObjectType = exports.isScalarType = exports.isType = exports.isDirective = undefined; + exports.defaultTypeResolver = exports.defaultFieldResolver = exports.executeSync = exports.legacyExecuteRootSelectionSet = exports.legacyExecuteIncrementally = exports.experimentalExecuteRootSelectionSet = exports.experimentalExecuteIncrementally = exports.executeSubscriptionEvent = exports.executeRootSelectionSet = exports.execute = exports.AbortedGraphQLExecutionError = exports.isSubscriptionOperationDefinitionNode = exports.isSchemaCoordinateNode = exports.isTypeExtensionNode = exports.isTypeSystemExtensionNode = exports.isTypeDefinitionNode = exports.isTypeSystemDefinitionNode = exports.isTypeNode = exports.isConstValueNode = exports.isValueNode = exports.isSelectionNode = exports.isExecutableDefinitionNode = exports.isDefinitionNode = exports.DirectiveLocation = exports.BREAK = exports.getEnterLeaveForKind = exports.visitInParallel = exports.visit = exports.print = exports.parseSchemaCoordinate = exports.parseType = exports.parseConstValue = exports.parseValue = exports.parse = exports.TokenKind = exports.Lexer = exports.printSourceLocation = exports.printLocation = exports.getLocation = exports.OperationTypeNode = exports.Location = exports.Source = exports.Token = exports.Kind = exports.assertEnumValueName = exports.assertName = exports.assertValidSchema = exports.validateSchema = exports.getNamedType = exports.getNullableType = undefined; + exports.UniqueFieldDefinitionNamesRule = exports.UniqueEnumValueNamesRule = exports.UniqueTypeNamesRule = exports.UniqueOperationTypesRule = exports.LoneSchemaDefinitionRule = exports.MaxIntrospectionDepthRule = exports.VariablesInAllowedPositionRule = exports.VariablesAreInputTypesRule = exports.ValuesOfCorrectTypeRule = exports.UniqueVariableNamesRule = exports.UniqueOperationNamesRule = exports.UniqueInputFieldNamesRule = exports.UniqueFragmentNamesRule = exports.UniqueDirectivesPerLocationRule = exports.UniqueArgumentNamesRule = exports.StreamDirectiveOnListFieldRule = exports.SingleFieldSubscriptionsRule = exports.ScalarLeafsRule = exports.ProvidedRequiredArgumentsRule = exports.PossibleFragmentSpreadsRule = exports.OverlappingFieldsCanBeMergedRule = exports.NoUnusedVariablesRule = exports.NoUnusedFragmentsRule = exports.NoUndefinedVariablesRule = exports.NoFragmentCyclesRule = exports.LoneAnonymousOperationRule = exports.KnownTypeNamesRule = exports.KnownOperationTypesRule = exports.KnownFragmentNamesRule = exports.KnownDirectivesRule = exports.KnownArgumentNamesRule = exports.FragmentsOnCompositeTypesRule = exports.FieldsOnCorrectTypeRule = exports.ExecutableDefinitionsRule = exports.DeferStreamDirectiveOnValidOperationsRule = exports.DeferStreamDirectiveOnRootFieldRule = exports.DeferStreamDirectiveLabelRule = exports.recommendedRules = exports.specifiedRules = exports.ValidationContext = exports.validate = exports.validateSubscriptionArgs = exports.validateExecutionArgs = exports.mapSourceToResponseEvent = exports.createSourceEventStream = exports.subscribe = exports.getDirectiveValues = exports.getVariableValues = exports.getArgumentValues = exports.responsePathAsArray = undefined; + exports.resolveASTSchemaCoordinate = exports.resolveSchemaCoordinate = exports.findSchemaChanges = exports.findDangerousChanges = exports.findBreakingChanges = exports.SafeChangeType = exports.DangerousChangeType = exports.BreakingChangeType = exports.doTypesOverlap = exports.isTypeSubTypeOf = exports.isEqualType = exports.stripIgnoredCharacters = exports.separateOperations = exports.concatAST = exports.validateInputLiteral = exports.validateInputValue = exports.coerceInputLiteral = exports.coerceInputValue = exports.valueToLiteral = exports.replaceVariables = exports.visitWithTypeInfo = exports.TypeInfo = exports.astFromValue = exports.valueFromASTUntyped = exports.valueFromAST = exports.typeFromAST = exports.printIntrospectionSchema = exports.printDirective = exports.printType = exports.printSchema = exports.lexicographicSortSchema = exports.extendSchema = exports.buildSchema = exports.buildASTSchema = exports.buildClientSchema = exports.introspectionFromSchema = exports.getOperationAST = exports.getIntrospectionQuery = exports.locatedError = exports.syntaxError = exports.GraphQLError = exports.NoSchemaIntrospectionCustomRule = exports.NoDeprecatedCustomRule = exports.PossibleTypeExtensionsRule = exports.UniqueDirectiveNamesRule = exports.UniqueArgumentDefinitionNamesRule = undefined; + var version_ts_1 = require_version(); + Object.defineProperty(exports, "version", { enumerable: true, get: function() { + return version_ts_1.version; + } }); + Object.defineProperty(exports, "versionInfo", { enumerable: true, get: function() { + return version_ts_1.versionInfo; + } }); + var devMode_ts_1 = require_devMode(); + Object.defineProperty(exports, "enableDevMode", { enumerable: true, get: function() { + return devMode_ts_1.enableDevMode; + } }); + Object.defineProperty(exports, "isDevModeEnabled", { enumerable: true, get: function() { + return devMode_ts_1.isDevModeEnabled; + } }); + var graphql_ts_1 = require_graphql(); + Object.defineProperty(exports, "graphql", { enumerable: true, get: function() { + return graphql_ts_1.graphql; + } }); + Object.defineProperty(exports, "graphqlSync", { enumerable: true, get: function() { + return graphql_ts_1.graphqlSync; + } }); + var harness_ts_1 = require_harness(); + Object.defineProperty(exports, "defaultHarness", { enumerable: true, get: function() { + return harness_ts_1.defaultHarness; + } }); + var index_ts_1 = require_type(); + Object.defineProperty(exports, "resolveObjMapThunk", { enumerable: true, get: function() { + return index_ts_1.resolveObjMapThunk; + } }); + Object.defineProperty(exports, "resolveReadonlyArrayThunk", { enumerable: true, get: function() { + return index_ts_1.resolveReadonlyArrayThunk; + } }); + Object.defineProperty(exports, "GraphQLSchema", { enumerable: true, get: function() { + return index_ts_1.GraphQLSchema; + } }); + Object.defineProperty(exports, "GraphQLDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLDirective; + } }); + Object.defineProperty(exports, "GraphQLScalarType", { enumerable: true, get: function() { + return index_ts_1.GraphQLScalarType; + } }); + Object.defineProperty(exports, "GraphQLObjectType", { enumerable: true, get: function() { + return index_ts_1.GraphQLObjectType; + } }); + Object.defineProperty(exports, "GraphQLInterfaceType", { enumerable: true, get: function() { + return index_ts_1.GraphQLInterfaceType; + } }); + Object.defineProperty(exports, "GraphQLUnionType", { enumerable: true, get: function() { + return index_ts_1.GraphQLUnionType; + } }); + Object.defineProperty(exports, "GraphQLEnumType", { enumerable: true, get: function() { + return index_ts_1.GraphQLEnumType; + } }); + Object.defineProperty(exports, "GraphQLInputObjectType", { enumerable: true, get: function() { + return index_ts_1.GraphQLInputObjectType; + } }); + Object.defineProperty(exports, "GraphQLList", { enumerable: true, get: function() { + return index_ts_1.GraphQLList; + } }); + Object.defineProperty(exports, "GraphQLNonNull", { enumerable: true, get: function() { + return index_ts_1.GraphQLNonNull; + } }); + Object.defineProperty(exports, "specifiedScalarTypes", { enumerable: true, get: function() { + return index_ts_1.specifiedScalarTypes; + } }); + Object.defineProperty(exports, "GraphQLInt", { enumerable: true, get: function() { + return index_ts_1.GraphQLInt; + } }); + Object.defineProperty(exports, "GraphQLFloat", { enumerable: true, get: function() { + return index_ts_1.GraphQLFloat; + } }); + Object.defineProperty(exports, "GraphQLString", { enumerable: true, get: function() { + return index_ts_1.GraphQLString; + } }); + Object.defineProperty(exports, "GraphQLBoolean", { enumerable: true, get: function() { + return index_ts_1.GraphQLBoolean; + } }); + Object.defineProperty(exports, "GraphQLID", { enumerable: true, get: function() { + return index_ts_1.GraphQLID; + } }); + Object.defineProperty(exports, "GRAPHQL_MAX_INT", { enumerable: true, get: function() { + return index_ts_1.GRAPHQL_MAX_INT; + } }); + Object.defineProperty(exports, "GRAPHQL_MIN_INT", { enumerable: true, get: function() { + return index_ts_1.GRAPHQL_MIN_INT; + } }); + Object.defineProperty(exports, "specifiedDirectives", { enumerable: true, get: function() { + return index_ts_1.specifiedDirectives; + } }); + Object.defineProperty(exports, "GraphQLIncludeDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLIncludeDirective; + } }); + Object.defineProperty(exports, "GraphQLSkipDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLSkipDirective; + } }); + Object.defineProperty(exports, "GraphQLDeferDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLDeferDirective; + } }); + Object.defineProperty(exports, "GraphQLStreamDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLStreamDirective; + } }); + Object.defineProperty(exports, "GraphQLDeprecatedDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLDeprecatedDirective; + } }); + Object.defineProperty(exports, "GraphQLSpecifiedByDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLSpecifiedByDirective; + } }); + Object.defineProperty(exports, "GraphQLOneOfDirective", { enumerable: true, get: function() { + return index_ts_1.GraphQLOneOfDirective; + } }); + Object.defineProperty(exports, "TypeKind", { enumerable: true, get: function() { + return index_ts_1.TypeKind; + } }); + Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { enumerable: true, get: function() { + return index_ts_1.DEFAULT_DEPRECATION_REASON; + } }); + Object.defineProperty(exports, "introspectionTypes", { enumerable: true, get: function() { + return index_ts_1.introspectionTypes; + } }); + Object.defineProperty(exports, "__Schema", { enumerable: true, get: function() { + return index_ts_1.__Schema; + } }); + Object.defineProperty(exports, "__Directive", { enumerable: true, get: function() { + return index_ts_1.__Directive; + } }); + Object.defineProperty(exports, "__DirectiveLocation", { enumerable: true, get: function() { + return index_ts_1.__DirectiveLocation; + } }); + Object.defineProperty(exports, "__Type", { enumerable: true, get: function() { + return index_ts_1.__Type; + } }); + Object.defineProperty(exports, "__Field", { enumerable: true, get: function() { + return index_ts_1.__Field; + } }); + Object.defineProperty(exports, "__InputValue", { enumerable: true, get: function() { + return index_ts_1.__InputValue; + } }); + Object.defineProperty(exports, "__EnumValue", { enumerable: true, get: function() { + return index_ts_1.__EnumValue; + } }); + Object.defineProperty(exports, "__TypeKind", { enumerable: true, get: function() { + return index_ts_1.__TypeKind; + } }); + Object.defineProperty(exports, "SchemaMetaFieldDef", { enumerable: true, get: function() { + return index_ts_1.SchemaMetaFieldDef; + } }); + Object.defineProperty(exports, "TypeMetaFieldDef", { enumerable: true, get: function() { + return index_ts_1.TypeMetaFieldDef; + } }); + Object.defineProperty(exports, "TypeNameMetaFieldDef", { enumerable: true, get: function() { + return index_ts_1.TypeNameMetaFieldDef; + } }); + Object.defineProperty(exports, "isSchema", { enumerable: true, get: function() { + return index_ts_1.isSchema; + } }); + Object.defineProperty(exports, "isDirective", { enumerable: true, get: function() { + return index_ts_1.isDirective; + } }); + Object.defineProperty(exports, "isType", { enumerable: true, get: function() { + return index_ts_1.isType; + } }); + Object.defineProperty(exports, "isScalarType", { enumerable: true, get: function() { + return index_ts_1.isScalarType; + } }); + Object.defineProperty(exports, "isObjectType", { enumerable: true, get: function() { + return index_ts_1.isObjectType; + } }); + Object.defineProperty(exports, "isField", { enumerable: true, get: function() { + return index_ts_1.isField; + } }); + Object.defineProperty(exports, "isArgument", { enumerable: true, get: function() { + return index_ts_1.isArgument; + } }); + Object.defineProperty(exports, "isInterfaceType", { enumerable: true, get: function() { + return index_ts_1.isInterfaceType; + } }); + Object.defineProperty(exports, "isUnionType", { enumerable: true, get: function() { + return index_ts_1.isUnionType; + } }); + Object.defineProperty(exports, "isEnumType", { enumerable: true, get: function() { + return index_ts_1.isEnumType; + } }); + Object.defineProperty(exports, "isEnumValue", { enumerable: true, get: function() { + return index_ts_1.isEnumValue; + } }); + Object.defineProperty(exports, "isInputObjectType", { enumerable: true, get: function() { + return index_ts_1.isInputObjectType; + } }); + Object.defineProperty(exports, "isInputField", { enumerable: true, get: function() { + return index_ts_1.isInputField; + } }); + Object.defineProperty(exports, "isListType", { enumerable: true, get: function() { + return index_ts_1.isListType; + } }); + Object.defineProperty(exports, "isNonNullType", { enumerable: true, get: function() { + return index_ts_1.isNonNullType; + } }); + Object.defineProperty(exports, "isInputType", { enumerable: true, get: function() { + return index_ts_1.isInputType; + } }); + Object.defineProperty(exports, "isOutputType", { enumerable: true, get: function() { + return index_ts_1.isOutputType; + } }); + Object.defineProperty(exports, "isLeafType", { enumerable: true, get: function() { + return index_ts_1.isLeafType; + } }); + Object.defineProperty(exports, "isCompositeType", { enumerable: true, get: function() { + return index_ts_1.isCompositeType; + } }); + Object.defineProperty(exports, "isAbstractType", { enumerable: true, get: function() { + return index_ts_1.isAbstractType; + } }); + Object.defineProperty(exports, "isWrappingType", { enumerable: true, get: function() { + return index_ts_1.isWrappingType; + } }); + Object.defineProperty(exports, "isNullableType", { enumerable: true, get: function() { + return index_ts_1.isNullableType; + } }); + Object.defineProperty(exports, "isNamedType", { enumerable: true, get: function() { + return index_ts_1.isNamedType; + } }); + Object.defineProperty(exports, "isRequiredArgument", { enumerable: true, get: function() { + return index_ts_1.isRequiredArgument; + } }); + Object.defineProperty(exports, "isRequiredInputField", { enumerable: true, get: function() { + return index_ts_1.isRequiredInputField; + } }); + Object.defineProperty(exports, "isSpecifiedScalarType", { enumerable: true, get: function() { + return index_ts_1.isSpecifiedScalarType; + } }); + Object.defineProperty(exports, "isIntrospectionType", { enumerable: true, get: function() { + return index_ts_1.isIntrospectionType; + } }); + Object.defineProperty(exports, "isSpecifiedDirective", { enumerable: true, get: function() { + return index_ts_1.isSpecifiedDirective; + } }); + Object.defineProperty(exports, "assertSchema", { enumerable: true, get: function() { + return index_ts_1.assertSchema; + } }); + Object.defineProperty(exports, "assertDirective", { enumerable: true, get: function() { + return index_ts_1.assertDirective; + } }); + Object.defineProperty(exports, "assertType", { enumerable: true, get: function() { + return index_ts_1.assertType; + } }); + Object.defineProperty(exports, "assertScalarType", { enumerable: true, get: function() { + return index_ts_1.assertScalarType; + } }); + Object.defineProperty(exports, "assertObjectType", { enumerable: true, get: function() { + return index_ts_1.assertObjectType; + } }); + Object.defineProperty(exports, "assertField", { enumerable: true, get: function() { + return index_ts_1.assertField; + } }); + Object.defineProperty(exports, "assertArgument", { enumerable: true, get: function() { + return index_ts_1.assertArgument; + } }); + Object.defineProperty(exports, "assertInterfaceType", { enumerable: true, get: function() { + return index_ts_1.assertInterfaceType; + } }); + Object.defineProperty(exports, "assertUnionType", { enumerable: true, get: function() { + return index_ts_1.assertUnionType; + } }); + Object.defineProperty(exports, "assertEnumType", { enumerable: true, get: function() { + return index_ts_1.assertEnumType; + } }); + Object.defineProperty(exports, "assertEnumValue", { enumerable: true, get: function() { + return index_ts_1.assertEnumValue; + } }); + Object.defineProperty(exports, "assertInputObjectType", { enumerable: true, get: function() { + return index_ts_1.assertInputObjectType; + } }); + Object.defineProperty(exports, "assertInputField", { enumerable: true, get: function() { + return index_ts_1.assertInputField; + } }); + Object.defineProperty(exports, "assertListType", { enumerable: true, get: function() { + return index_ts_1.assertListType; + } }); + Object.defineProperty(exports, "assertNonNullType", { enumerable: true, get: function() { + return index_ts_1.assertNonNullType; + } }); + Object.defineProperty(exports, "assertInputType", { enumerable: true, get: function() { + return index_ts_1.assertInputType; + } }); + Object.defineProperty(exports, "assertOutputType", { enumerable: true, get: function() { + return index_ts_1.assertOutputType; + } }); + Object.defineProperty(exports, "assertLeafType", { enumerable: true, get: function() { + return index_ts_1.assertLeafType; + } }); + Object.defineProperty(exports, "assertCompositeType", { enumerable: true, get: function() { + return index_ts_1.assertCompositeType; + } }); + Object.defineProperty(exports, "assertAbstractType", { enumerable: true, get: function() { + return index_ts_1.assertAbstractType; + } }); + Object.defineProperty(exports, "assertWrappingType", { enumerable: true, get: function() { + return index_ts_1.assertWrappingType; + } }); + Object.defineProperty(exports, "assertNullableType", { enumerable: true, get: function() { + return index_ts_1.assertNullableType; + } }); + Object.defineProperty(exports, "assertNamedType", { enumerable: true, get: function() { + return index_ts_1.assertNamedType; + } }); + Object.defineProperty(exports, "getNullableType", { enumerable: true, get: function() { + return index_ts_1.getNullableType; + } }); + Object.defineProperty(exports, "getNamedType", { enumerable: true, get: function() { + return index_ts_1.getNamedType; + } }); + Object.defineProperty(exports, "validateSchema", { enumerable: true, get: function() { + return index_ts_1.validateSchema; + } }); + Object.defineProperty(exports, "assertValidSchema", { enumerable: true, get: function() { + return index_ts_1.assertValidSchema; + } }); + Object.defineProperty(exports, "assertName", { enumerable: true, get: function() { + return index_ts_1.assertName; + } }); + Object.defineProperty(exports, "assertEnumValueName", { enumerable: true, get: function() { + return index_ts_1.assertEnumValueName; + } }); + var kinds_ts_1 = require_kinds(); + Object.defineProperty(exports, "Kind", { enumerable: true, get: function() { + return kinds_ts_1.Kind; + } }); + var index_ts_2 = require_language(); + Object.defineProperty(exports, "Token", { enumerable: true, get: function() { + return index_ts_2.Token; + } }); + Object.defineProperty(exports, "Source", { enumerable: true, get: function() { + return index_ts_2.Source; + } }); + Object.defineProperty(exports, "Location", { enumerable: true, get: function() { + return index_ts_2.Location; + } }); + Object.defineProperty(exports, "OperationTypeNode", { enumerable: true, get: function() { + return index_ts_2.OperationTypeNode; + } }); + Object.defineProperty(exports, "getLocation", { enumerable: true, get: function() { + return index_ts_2.getLocation; + } }); + Object.defineProperty(exports, "printLocation", { enumerable: true, get: function() { + return index_ts_2.printLocation; + } }); + Object.defineProperty(exports, "printSourceLocation", { enumerable: true, get: function() { + return index_ts_2.printSourceLocation; + } }); + Object.defineProperty(exports, "Lexer", { enumerable: true, get: function() { + return index_ts_2.Lexer; + } }); + Object.defineProperty(exports, "TokenKind", { enumerable: true, get: function() { + return index_ts_2.TokenKind; + } }); + Object.defineProperty(exports, "parse", { enumerable: true, get: function() { + return index_ts_2.parse; + } }); + Object.defineProperty(exports, "parseValue", { enumerable: true, get: function() { + return index_ts_2.parseValue; + } }); + Object.defineProperty(exports, "parseConstValue", { enumerable: true, get: function() { + return index_ts_2.parseConstValue; + } }); + Object.defineProperty(exports, "parseType", { enumerable: true, get: function() { + return index_ts_2.parseType; + } }); + Object.defineProperty(exports, "parseSchemaCoordinate", { enumerable: true, get: function() { + return index_ts_2.parseSchemaCoordinate; + } }); + Object.defineProperty(exports, "print", { enumerable: true, get: function() { + return index_ts_2.print; + } }); + Object.defineProperty(exports, "visit", { enumerable: true, get: function() { + return index_ts_2.visit; + } }); + Object.defineProperty(exports, "visitInParallel", { enumerable: true, get: function() { + return index_ts_2.visitInParallel; + } }); + Object.defineProperty(exports, "getEnterLeaveForKind", { enumerable: true, get: function() { + return index_ts_2.getEnterLeaveForKind; + } }); + Object.defineProperty(exports, "BREAK", { enumerable: true, get: function() { + return index_ts_2.BREAK; + } }); + Object.defineProperty(exports, "DirectiveLocation", { enumerable: true, get: function() { + return index_ts_2.DirectiveLocation; + } }); + Object.defineProperty(exports, "isDefinitionNode", { enumerable: true, get: function() { + return index_ts_2.isDefinitionNode; + } }); + Object.defineProperty(exports, "isExecutableDefinitionNode", { enumerable: true, get: function() { + return index_ts_2.isExecutableDefinitionNode; + } }); + Object.defineProperty(exports, "isSelectionNode", { enumerable: true, get: function() { + return index_ts_2.isSelectionNode; + } }); + Object.defineProperty(exports, "isValueNode", { enumerable: true, get: function() { + return index_ts_2.isValueNode; + } }); + Object.defineProperty(exports, "isConstValueNode", { enumerable: true, get: function() { + return index_ts_2.isConstValueNode; + } }); + Object.defineProperty(exports, "isTypeNode", { enumerable: true, get: function() { + return index_ts_2.isTypeNode; + } }); + Object.defineProperty(exports, "isTypeSystemDefinitionNode", { enumerable: true, get: function() { + return index_ts_2.isTypeSystemDefinitionNode; + } }); + Object.defineProperty(exports, "isTypeDefinitionNode", { enumerable: true, get: function() { + return index_ts_2.isTypeDefinitionNode; + } }); + Object.defineProperty(exports, "isTypeSystemExtensionNode", { enumerable: true, get: function() { + return index_ts_2.isTypeSystemExtensionNode; + } }); + Object.defineProperty(exports, "isTypeExtensionNode", { enumerable: true, get: function() { + return index_ts_2.isTypeExtensionNode; + } }); + Object.defineProperty(exports, "isSchemaCoordinateNode", { enumerable: true, get: function() { + return index_ts_2.isSchemaCoordinateNode; + } }); + Object.defineProperty(exports, "isSubscriptionOperationDefinitionNode", { enumerable: true, get: function() { + return index_ts_2.isSubscriptionOperationDefinitionNode; + } }); + var index_ts_3 = require_execution(); + Object.defineProperty(exports, "AbortedGraphQLExecutionError", { enumerable: true, get: function() { + return index_ts_3.AbortedGraphQLExecutionError; + } }); + Object.defineProperty(exports, "execute", { enumerable: true, get: function() { + return index_ts_3.execute; + } }); + Object.defineProperty(exports, "executeRootSelectionSet", { enumerable: true, get: function() { + return index_ts_3.executeRootSelectionSet; + } }); + Object.defineProperty(exports, "executeSubscriptionEvent", { enumerable: true, get: function() { + return index_ts_3.executeSubscriptionEvent; + } }); + Object.defineProperty(exports, "experimentalExecuteIncrementally", { enumerable: true, get: function() { + return index_ts_3.experimentalExecuteIncrementally; + } }); + Object.defineProperty(exports, "experimentalExecuteRootSelectionSet", { enumerable: true, get: function() { + return index_ts_3.experimentalExecuteRootSelectionSet; + } }); + Object.defineProperty(exports, "legacyExecuteIncrementally", { enumerable: true, get: function() { + return index_ts_3.legacyExecuteIncrementally; + } }); + Object.defineProperty(exports, "legacyExecuteRootSelectionSet", { enumerable: true, get: function() { + return index_ts_3.legacyExecuteRootSelectionSet; + } }); + Object.defineProperty(exports, "executeSync", { enumerable: true, get: function() { + return index_ts_3.executeSync; + } }); + Object.defineProperty(exports, "defaultFieldResolver", { enumerable: true, get: function() { + return index_ts_3.defaultFieldResolver; + } }); + Object.defineProperty(exports, "defaultTypeResolver", { enumerable: true, get: function() { + return index_ts_3.defaultTypeResolver; + } }); + Object.defineProperty(exports, "responsePathAsArray", { enumerable: true, get: function() { + return index_ts_3.responsePathAsArray; + } }); + Object.defineProperty(exports, "getArgumentValues", { enumerable: true, get: function() { + return index_ts_3.getArgumentValues; + } }); + Object.defineProperty(exports, "getVariableValues", { enumerable: true, get: function() { + return index_ts_3.getVariableValues; + } }); + Object.defineProperty(exports, "getDirectiveValues", { enumerable: true, get: function() { + return index_ts_3.getDirectiveValues; + } }); + Object.defineProperty(exports, "subscribe", { enumerable: true, get: function() { + return index_ts_3.subscribe; + } }); + Object.defineProperty(exports, "createSourceEventStream", { enumerable: true, get: function() { + return index_ts_3.createSourceEventStream; + } }); + Object.defineProperty(exports, "mapSourceToResponseEvent", { enumerable: true, get: function() { + return index_ts_3.mapSourceToResponseEvent; + } }); + Object.defineProperty(exports, "validateExecutionArgs", { enumerable: true, get: function() { + return index_ts_3.validateExecutionArgs; + } }); + Object.defineProperty(exports, "validateSubscriptionArgs", { enumerable: true, get: function() { + return index_ts_3.validateSubscriptionArgs; + } }); + var index_ts_4 = require_validation(); + Object.defineProperty(exports, "validate", { enumerable: true, get: function() { + return index_ts_4.validate; + } }); + Object.defineProperty(exports, "ValidationContext", { enumerable: true, get: function() { + return index_ts_4.ValidationContext; + } }); + Object.defineProperty(exports, "specifiedRules", { enumerable: true, get: function() { + return index_ts_4.specifiedRules; + } }); + Object.defineProperty(exports, "recommendedRules", { enumerable: true, get: function() { + return index_ts_4.recommendedRules; + } }); + Object.defineProperty(exports, "DeferStreamDirectiveLabelRule", { enumerable: true, get: function() { + return index_ts_4.DeferStreamDirectiveLabelRule; + } }); + Object.defineProperty(exports, "DeferStreamDirectiveOnRootFieldRule", { enumerable: true, get: function() { + return index_ts_4.DeferStreamDirectiveOnRootFieldRule; + } }); + Object.defineProperty(exports, "DeferStreamDirectiveOnValidOperationsRule", { enumerable: true, get: function() { + return index_ts_4.DeferStreamDirectiveOnValidOperationsRule; + } }); + Object.defineProperty(exports, "ExecutableDefinitionsRule", { enumerable: true, get: function() { + return index_ts_4.ExecutableDefinitionsRule; + } }); + Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { enumerable: true, get: function() { + return index_ts_4.FieldsOnCorrectTypeRule; + } }); + Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { enumerable: true, get: function() { + return index_ts_4.FragmentsOnCompositeTypesRule; + } }); + Object.defineProperty(exports, "KnownArgumentNamesRule", { enumerable: true, get: function() { + return index_ts_4.KnownArgumentNamesRule; + } }); + Object.defineProperty(exports, "KnownDirectivesRule", { enumerable: true, get: function() { + return index_ts_4.KnownDirectivesRule; + } }); + Object.defineProperty(exports, "KnownFragmentNamesRule", { enumerable: true, get: function() { + return index_ts_4.KnownFragmentNamesRule; + } }); + Object.defineProperty(exports, "KnownOperationTypesRule", { enumerable: true, get: function() { + return index_ts_4.KnownOperationTypesRule; + } }); + Object.defineProperty(exports, "KnownTypeNamesRule", { enumerable: true, get: function() { + return index_ts_4.KnownTypeNamesRule; + } }); + Object.defineProperty(exports, "LoneAnonymousOperationRule", { enumerable: true, get: function() { + return index_ts_4.LoneAnonymousOperationRule; + } }); + Object.defineProperty(exports, "NoFragmentCyclesRule", { enumerable: true, get: function() { + return index_ts_4.NoFragmentCyclesRule; + } }); + Object.defineProperty(exports, "NoUndefinedVariablesRule", { enumerable: true, get: function() { + return index_ts_4.NoUndefinedVariablesRule; + } }); + Object.defineProperty(exports, "NoUnusedFragmentsRule", { enumerable: true, get: function() { + return index_ts_4.NoUnusedFragmentsRule; + } }); + Object.defineProperty(exports, "NoUnusedVariablesRule", { enumerable: true, get: function() { + return index_ts_4.NoUnusedVariablesRule; + } }); + Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { enumerable: true, get: function() { + return index_ts_4.OverlappingFieldsCanBeMergedRule; + } }); + Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { enumerable: true, get: function() { + return index_ts_4.PossibleFragmentSpreadsRule; + } }); + Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { enumerable: true, get: function() { + return index_ts_4.ProvidedRequiredArgumentsRule; + } }); + Object.defineProperty(exports, "ScalarLeafsRule", { enumerable: true, get: function() { + return index_ts_4.ScalarLeafsRule; + } }); + Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { enumerable: true, get: function() { + return index_ts_4.SingleFieldSubscriptionsRule; + } }); + Object.defineProperty(exports, "StreamDirectiveOnListFieldRule", { enumerable: true, get: function() { + return index_ts_4.StreamDirectiveOnListFieldRule; + } }); + Object.defineProperty(exports, "UniqueArgumentNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueArgumentNamesRule; + } }); + Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { enumerable: true, get: function() { + return index_ts_4.UniqueDirectivesPerLocationRule; + } }); + Object.defineProperty(exports, "UniqueFragmentNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueFragmentNamesRule; + } }); + Object.defineProperty(exports, "UniqueInputFieldNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueInputFieldNamesRule; + } }); + Object.defineProperty(exports, "UniqueOperationNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueOperationNamesRule; + } }); + Object.defineProperty(exports, "UniqueVariableNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueVariableNamesRule; + } }); + Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { enumerable: true, get: function() { + return index_ts_4.ValuesOfCorrectTypeRule; + } }); + Object.defineProperty(exports, "VariablesAreInputTypesRule", { enumerable: true, get: function() { + return index_ts_4.VariablesAreInputTypesRule; + } }); + Object.defineProperty(exports, "VariablesInAllowedPositionRule", { enumerable: true, get: function() { + return index_ts_4.VariablesInAllowedPositionRule; + } }); + Object.defineProperty(exports, "MaxIntrospectionDepthRule", { enumerable: true, get: function() { + return index_ts_4.MaxIntrospectionDepthRule; + } }); + Object.defineProperty(exports, "LoneSchemaDefinitionRule", { enumerable: true, get: function() { + return index_ts_4.LoneSchemaDefinitionRule; + } }); + Object.defineProperty(exports, "UniqueOperationTypesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueOperationTypesRule; + } }); + Object.defineProperty(exports, "UniqueTypeNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueTypeNamesRule; + } }); + Object.defineProperty(exports, "UniqueEnumValueNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueEnumValueNamesRule; + } }); + Object.defineProperty(exports, "UniqueFieldDefinitionNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueFieldDefinitionNamesRule; + } }); + Object.defineProperty(exports, "UniqueArgumentDefinitionNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueArgumentDefinitionNamesRule; + } }); + Object.defineProperty(exports, "UniqueDirectiveNamesRule", { enumerable: true, get: function() { + return index_ts_4.UniqueDirectiveNamesRule; + } }); + Object.defineProperty(exports, "PossibleTypeExtensionsRule", { enumerable: true, get: function() { + return index_ts_4.PossibleTypeExtensionsRule; + } }); + Object.defineProperty(exports, "NoDeprecatedCustomRule", { enumerable: true, get: function() { + return index_ts_4.NoDeprecatedCustomRule; + } }); + Object.defineProperty(exports, "NoSchemaIntrospectionCustomRule", { enumerable: true, get: function() { + return index_ts_4.NoSchemaIntrospectionCustomRule; + } }); + var index_ts_5 = require_error(); + Object.defineProperty(exports, "GraphQLError", { enumerable: true, get: function() { + return index_ts_5.GraphQLError; + } }); + Object.defineProperty(exports, "syntaxError", { enumerable: true, get: function() { + return index_ts_5.syntaxError; + } }); + Object.defineProperty(exports, "locatedError", { enumerable: true, get: function() { + return index_ts_5.locatedError; + } }); + var index_ts_6 = require_utilities(); + Object.defineProperty(exports, "getIntrospectionQuery", { enumerable: true, get: function() { + return index_ts_6.getIntrospectionQuery; + } }); + Object.defineProperty(exports, "getOperationAST", { enumerable: true, get: function() { + return index_ts_6.getOperationAST; + } }); + Object.defineProperty(exports, "introspectionFromSchema", { enumerable: true, get: function() { + return index_ts_6.introspectionFromSchema; + } }); + Object.defineProperty(exports, "buildClientSchema", { enumerable: true, get: function() { + return index_ts_6.buildClientSchema; + } }); + Object.defineProperty(exports, "buildASTSchema", { enumerable: true, get: function() { + return index_ts_6.buildASTSchema; + } }); + Object.defineProperty(exports, "buildSchema", { enumerable: true, get: function() { + return index_ts_6.buildSchema; + } }); + Object.defineProperty(exports, "extendSchema", { enumerable: true, get: function() { + return index_ts_6.extendSchema; + } }); + Object.defineProperty(exports, "lexicographicSortSchema", { enumerable: true, get: function() { + return index_ts_6.lexicographicSortSchema; + } }); + Object.defineProperty(exports, "printSchema", { enumerable: true, get: function() { + return index_ts_6.printSchema; + } }); + Object.defineProperty(exports, "printType", { enumerable: true, get: function() { + return index_ts_6.printType; + } }); + Object.defineProperty(exports, "printDirective", { enumerable: true, get: function() { + return index_ts_6.printDirective; + } }); + Object.defineProperty(exports, "printIntrospectionSchema", { enumerable: true, get: function() { + return index_ts_6.printIntrospectionSchema; + } }); + Object.defineProperty(exports, "typeFromAST", { enumerable: true, get: function() { + return index_ts_6.typeFromAST; + } }); + Object.defineProperty(exports, "valueFromAST", { enumerable: true, get: function() { + return index_ts_6.valueFromAST; + } }); + Object.defineProperty(exports, "valueFromASTUntyped", { enumerable: true, get: function() { + return index_ts_6.valueFromASTUntyped; + } }); + Object.defineProperty(exports, "astFromValue", { enumerable: true, get: function() { + return index_ts_6.astFromValue; + } }); + Object.defineProperty(exports, "TypeInfo", { enumerable: true, get: function() { + return index_ts_6.TypeInfo; + } }); + Object.defineProperty(exports, "visitWithTypeInfo", { enumerable: true, get: function() { + return index_ts_6.visitWithTypeInfo; + } }); + Object.defineProperty(exports, "replaceVariables", { enumerable: true, get: function() { + return index_ts_6.replaceVariables; + } }); + Object.defineProperty(exports, "valueToLiteral", { enumerable: true, get: function() { + return index_ts_6.valueToLiteral; + } }); + Object.defineProperty(exports, "coerceInputValue", { enumerable: true, get: function() { + return index_ts_6.coerceInputValue; + } }); + Object.defineProperty(exports, "coerceInputLiteral", { enumerable: true, get: function() { + return index_ts_6.coerceInputLiteral; + } }); + Object.defineProperty(exports, "validateInputValue", { enumerable: true, get: function() { + return index_ts_6.validateInputValue; + } }); + Object.defineProperty(exports, "validateInputLiteral", { enumerable: true, get: function() { + return index_ts_6.validateInputLiteral; + } }); + Object.defineProperty(exports, "concatAST", { enumerable: true, get: function() { + return index_ts_6.concatAST; + } }); + Object.defineProperty(exports, "separateOperations", { enumerable: true, get: function() { + return index_ts_6.separateOperations; + } }); + Object.defineProperty(exports, "stripIgnoredCharacters", { enumerable: true, get: function() { + return index_ts_6.stripIgnoredCharacters; + } }); + Object.defineProperty(exports, "isEqualType", { enumerable: true, get: function() { + return index_ts_6.isEqualType; + } }); + Object.defineProperty(exports, "isTypeSubTypeOf", { enumerable: true, get: function() { + return index_ts_6.isTypeSubTypeOf; + } }); + Object.defineProperty(exports, "doTypesOverlap", { enumerable: true, get: function() { + return index_ts_6.doTypesOverlap; + } }); + Object.defineProperty(exports, "BreakingChangeType", { enumerable: true, get: function() { + return index_ts_6.BreakingChangeType; + } }); + Object.defineProperty(exports, "DangerousChangeType", { enumerable: true, get: function() { + return index_ts_6.DangerousChangeType; + } }); + Object.defineProperty(exports, "SafeChangeType", { enumerable: true, get: function() { + return index_ts_6.SafeChangeType; + } }); + Object.defineProperty(exports, "findBreakingChanges", { enumerable: true, get: function() { + return index_ts_6.findBreakingChanges; + } }); + Object.defineProperty(exports, "findDangerousChanges", { enumerable: true, get: function() { + return index_ts_6.findDangerousChanges; + } }); + Object.defineProperty(exports, "findSchemaChanges", { enumerable: true, get: function() { + return index_ts_6.findSchemaChanges; + } }); + Object.defineProperty(exports, "resolveSchemaCoordinate", { enumerable: true, get: function() { + return index_ts_6.resolveSchemaCoordinate; + } }); + Object.defineProperty(exports, "resolveASTSchemaCoordinate", { enumerable: true, get: function() { + return index_ts_6.resolveASTSchemaCoordinate; + } }); +}); + +// node_modules/graphql/__dev__/index.js +var require___dev__ = __commonJS((exports, module) => { + var { enableDevMode } = require_devMode(); + enableDevMode(); + module.exports = require_graphql2(); +}); + +// node_modules/graphql-request/build/lib/http.js +var ACCEPT_HEADER = `Accept`, CONTENT_TYPE_HEADER = `Content-Type`, CONTENT_TYPE_JSON = `application/json`, CONTENT_TYPE_GQL = `application/graphql-response+json`; +var init_http = () => {}; + +// node_modules/graphql-request/build/legacy/lib/graphql.js +var import_graphql, cleanQuery = (str) => str.replace(/([\s,]|#[^\n\r]+)+/g, ` `).trim(), isGraphQLContentType = (contentType) => { + const contentTypeLower = contentType.toLowerCase(); + return contentTypeLower.includes(CONTENT_TYPE_GQL) || contentTypeLower.includes(CONTENT_TYPE_JSON); +}, parseGraphQLExecutionResult = (result) => { + try { + if (Array.isArray(result)) { + return { + _tag: `Batch`, + executionResults: result.map(parseExecutionResult) + }; + } else if (isPlainObject(result)) { + return { + _tag: `Single`, + executionResult: parseExecutionResult(result) + }; + } else { + throw new Error(`Invalid execution result: result is not object or array. +Got: +${String(result)}`); + } + } catch (e) { + return e; + } +}, parseExecutionResult = (result) => { + if (typeof result !== `object` || result === null) { + throw new Error(`Invalid execution result: result is not object`); + } + let errors = undefined; + let data = undefined; + let extensions = undefined; + if (`errors` in result) { + if (!isPlainObject(result.errors) && !Array.isArray(result.errors)) { + throw new Error(`Invalid execution result: errors is not plain object OR array`); + } + errors = result.errors; + } + if (`data` in result) { + if (!isPlainObject(result.data) && result.data !== null) { + throw new Error(`Invalid execution result: data is not plain object`); + } + data = result.data; + } + if (`extensions` in result) { + if (!isPlainObject(result.extensions)) + throw new Error(`Invalid execution result: extensions is not plain object`); + extensions = result.extensions; + } + return { + data, + errors, + extensions + }; +}, isRequestResultHaveErrors = (result) => result._tag === `Batch` ? result.executionResults.some(isExecutionResultHaveErrors) : isExecutionResultHaveErrors(result.executionResult), isExecutionResultHaveErrors = (result) => Array.isArray(result.errors) ? result.errors.length > 0 : Boolean(result.errors), isOperationDefinitionNode = (definition) => { + return typeof definition === `object` && definition !== null && `kind` in definition && definition.kind === import_graphql.Kind.OPERATION_DEFINITION; +}; +var init_graphql = __esm(() => { + init_http(); + import_graphql = __toESM(require___dev__(), 1); +}); + +// node_modules/graphql-request/build/legacy/helpers/analyzeDocument.js +var import_graphql3, import_graphql4, extractOperationName = (document2) => { + let operationName = undefined; + const defs = document2.definitions.filter(isOperationDefinitionNode); + if (defs.length === 1) { + operationName = defs[0].name?.value; + } + return operationName; +}, extractIsMutation = (document2) => { + let isMutation = false; + const defs = document2.definitions.filter(isOperationDefinitionNode); + if (defs.length === 1) { + isMutation = defs[0].operation === `mutation`; + } + return isMutation; +}, analyzeDocument = (document2, excludeOperationName) => { + const normalizedDocument = typeof document2 === `string` || `kind` in document2 ? document2 : String(document2); + const expression2 = typeof normalizedDocument === `string` ? normalizedDocument : import_graphql4.print(normalizedDocument); + let isMutation = false; + let operationName = undefined; + if (excludeOperationName) { + return { expression: expression2, isMutation, operationName }; + } + const docNode = tryCatch(() => typeof normalizedDocument === `string` ? import_graphql3.parse(normalizedDocument) : normalizedDocument); + if (docNode instanceof Error) { + return { expression: expression2, isMutation, operationName }; + } + operationName = extractOperationName(docNode); + isMutation = extractIsMutation(docNode); + return { expression: expression2, operationName, isMutation }; +}; +var init_analyzeDocument = __esm(() => { + init_graphql(); + import_graphql3 = __toESM(require___dev__(), 1); + import_graphql4 = __toESM(require___dev__(), 1); +}); + +// node_modules/graphql-request/build/legacy/helpers/defaultJsonSerializer.js +var defaultJsonSerializer; +var init_defaultJsonSerializer = __esm(() => { + defaultJsonSerializer = JSON; +}); + +// node_modules/graphql-request/build/legacy/helpers/runRequest.js +var runRequest = async (input) => { + const config = { + ...input, + method: input.request._tag === `Single` ? input.request.document.isMutation ? `POST` : uppercase(input.method ?? `post`) : input.request.hasMutations ? `POST` : uppercase(input.method ?? `post`), + fetchOptions: { + ...input.fetchOptions, + errorPolicy: input.fetchOptions.errorPolicy ?? `none` + } + }; + const fetcher = createFetcher(config.method); + const fetchResponse = await fetcher(config); + const body = await fetchResponse.text(); + let result; + try { + result = parseResultFromText(body, fetchResponse.headers.get(CONTENT_TYPE_HEADER), input.fetchOptions.jsonSerializer ?? defaultJsonSerializer); + } catch (error) { + result = error; + } + const clientResponseBase = { + status: fetchResponse.status, + headers: fetchResponse.headers, + body + }; + if (!fetchResponse.ok) { + if (result instanceof Error) { + return new ClientError({ ...clientResponseBase }, { + query: input.request._tag === `Single` ? input.request.document.expression : input.request.query, + variables: input.request.variables + }); + } + const clientResponse = result._tag === `Batch` ? { ...result.executionResults, ...clientResponseBase } : { + ...result.executionResult, + ...clientResponseBase + }; + return new ClientError(clientResponse, { + query: input.request._tag === `Single` ? input.request.document.expression : input.request.query, + variables: input.request.variables + }); + } + if (result instanceof Error) + throw result; + if (isRequestResultHaveErrors(result) && config.fetchOptions.errorPolicy === `none`) { + const clientResponse = result._tag === `Batch` ? { ...result.executionResults, ...clientResponseBase } : { + ...result.executionResult, + ...clientResponseBase + }; + return new ClientError(clientResponse, { + query: input.request._tag === `Single` ? input.request.document.expression : input.request.query, + variables: input.request.variables + }); + } + switch (result._tag) { + case `Single`: + return { + ...clientResponseBase, + ...executionResultClientResponseFields(config)(result.executionResult) + }; + case `Batch`: + return { + ...clientResponseBase, + data: result.executionResults.map(executionResultClientResponseFields(config)) + }; + default: + casesExhausted(result); + } +}, executionResultClientResponseFields = ($params) => (executionResult) => { + return { + extensions: executionResult.extensions, + data: executionResult.data, + errors: $params.fetchOptions.errorPolicy === `all` ? executionResult.errors : undefined + }; +}, parseResultFromText = (text, contentType, jsonSerializer) => { + if (contentType && isGraphQLContentType(contentType)) { + return parseGraphQLExecutionResult(jsonSerializer.parse(text)); + } else { + return parseGraphQLExecutionResult(text); + } +}, createFetcher = (method) => async (params) => { + const headers = new Headers(params.headers); + let searchParams = null; + let body = undefined; + if (!headers.has(ACCEPT_HEADER)) { + headers.set(ACCEPT_HEADER, [CONTENT_TYPE_GQL, CONTENT_TYPE_JSON].join(`, `)); + } + if (method === `POST`) { + const $jsonSerializer = params.fetchOptions.jsonSerializer ?? defaultJsonSerializer; + body = $jsonSerializer.stringify(buildBody(params)); + if (typeof body === `string` && !headers.has(CONTENT_TYPE_HEADER)) { + headers.set(CONTENT_TYPE_HEADER, CONTENT_TYPE_JSON); + } + } else { + searchParams = buildQueryParams(params); + } + const init = { method, headers, body, ...params.fetchOptions }; + let url = new URL(params.url); + let initResolved = init; + if (params.middleware) { + const result = await Promise.resolve(params.middleware({ + ...init, + url: params.url, + operationName: params.request._tag === `Single` ? params.request.document.operationName : undefined, + variables: params.request.variables + })); + const { url: urlNew, ...initNew } = result; + url = new URL(urlNew); + initResolved = initNew; + } + if (searchParams) { + searchParams.forEach((value, name) => { + url.searchParams.append(name, value); + }); + } + const $fetch = params.fetch ?? fetch; + return await $fetch(url, initResolved); +}, buildBody = (params) => { + switch (params.request._tag) { + case `Single`: + return { + query: params.request.document.expression, + variables: params.request.variables, + operationName: params.request.document.operationName + }; + case `Batch`: + return zip(params.request.query, params.request.variables ?? []).map(([query, variables]) => ({ + query, + variables + })); + default: + throw casesExhausted(params.request); + } +}, buildQueryParams = (params) => { + const $jsonSerializer = params.fetchOptions.jsonSerializer ?? defaultJsonSerializer; + const searchParams = new URLSearchParams; + switch (params.request._tag) { + case `Single`: { + searchParams.append(`query`, cleanQuery(params.request.document.expression)); + if (params.request.variables) { + searchParams.append(`variables`, $jsonSerializer.stringify(params.request.variables)); + } + if (params.request.document.operationName) { + searchParams.append(`operationName`, params.request.document.operationName); + } + return searchParams; + } + case `Batch`: { + const variablesSerialized = params.request.variables?.map((v) => $jsonSerializer.stringify(v)) ?? []; + const queriesCleaned = params.request.query.map(cleanQuery); + const payload = zip(queriesCleaned, variablesSerialized).map(([query, variables]) => ({ + query, + variables + })); + searchParams.append(`query`, $jsonSerializer.stringify(payload)); + return searchParams; + } + default: + throw casesExhausted(params.request); + } +}; +var init_runRequest = __esm(() => { + init_http(); + init_ClientError(); + init_graphql(); + init_defaultJsonSerializer(); +}); + +// node_modules/graphql-request/build/legacy/classes/GraphQLClient.js +class GraphQLClient { + url; + requestConfig; + constructor(url, requestConfig = {}) { + this.url = url; + this.requestConfig = requestConfig; + } + rawRequest = async (...args) => { + const [queryOrOptions, variables, requestHeaders] = args; + const rawRequestOptions = parseRawRequestArgs(queryOrOptions, variables, requestHeaders); + const { headers, fetch: fetch2 = globalThis.fetch, method = `POST`, requestMiddleware, responseMiddleware, excludeOperationName, ...fetchOptions } = this.requestConfig; + const { url } = this; + if (rawRequestOptions.signal !== undefined) { + fetchOptions.signal = rawRequestOptions.signal; + } + const document2 = analyzeDocument(rawRequestOptions.query, excludeOperationName); + const response = await runRequest({ + url, + request: { + _tag: `Single`, + document: document2, + variables: rawRequestOptions.variables + }, + headers: { + ...HeadersInitToPlainObject(callOrIdentity(headers)), + ...HeadersInitToPlainObject(rawRequestOptions.requestHeaders) + }, + fetch: fetch2, + method, + fetchOptions, + middleware: requestMiddleware + }); + if (responseMiddleware) { + await responseMiddleware(response, { + operationName: document2.operationName, + variables, + url: this.url + }); + } + if (response instanceof Error) { + throw response; + } + return response; + }; + async request(documentOrOptions, ...variablesAndRequestHeaders) { + const [variables, requestHeaders] = variablesAndRequestHeaders; + const requestOptions = parseRequestArgs(documentOrOptions, variables, requestHeaders); + const { headers, fetch: fetch2 = globalThis.fetch, method = `POST`, requestMiddleware, responseMiddleware, excludeOperationName, ...fetchOptions } = this.requestConfig; + const { url } = this; + if (requestOptions.signal !== undefined) { + fetchOptions.signal = requestOptions.signal; + } + const analyzedDocument = analyzeDocument(requestOptions.document, excludeOperationName); + const response = await runRequest({ + url, + request: { + _tag: `Single`, + document: analyzedDocument, + variables: requestOptions.variables + }, + headers: { + ...HeadersInitToPlainObject(callOrIdentity(headers)), + ...HeadersInitToPlainObject(requestOptions.requestHeaders) + }, + fetch: fetch2, + method, + fetchOptions, + middleware: requestMiddleware + }); + if (responseMiddleware) { + await responseMiddleware(response, { + operationName: analyzedDocument.operationName, + variables: requestOptions.variables, + url: this.url + }); + } + if (response instanceof Error) { + throw response; + } + return response.data; + } + async batchRequests(documentsOrOptions, requestHeaders) { + const batchRequestOptions = parseBatchRequestArgs(documentsOrOptions, requestHeaders); + const { headers, excludeOperationName, ...fetchOptions } = this.requestConfig; + if (batchRequestOptions.signal !== undefined) { + fetchOptions.signal = batchRequestOptions.signal; + } + const analyzedDocuments = batchRequestOptions.documents.map(({ document: document2 }) => analyzeDocument(document2, excludeOperationName)); + const expressions = analyzedDocuments.map(({ expression: expression2 }) => expression2); + const hasMutations = analyzedDocuments.some(({ isMutation }) => isMutation); + const variables = batchRequestOptions.documents.map(({ variables: variables2 }) => variables2); + const response = await runRequest({ + url: this.url, + request: { + _tag: `Batch`, + operationName: undefined, + query: expressions, + hasMutations, + variables + }, + headers: { + ...HeadersInitToPlainObject(callOrIdentity(headers)), + ...HeadersInitToPlainObject(batchRequestOptions.requestHeaders) + }, + fetch: this.requestConfig.fetch ?? globalThis.fetch, + method: this.requestConfig.method || `POST`, + fetchOptions, + middleware: this.requestConfig.requestMiddleware + }); + if (this.requestConfig.responseMiddleware) { + await this.requestConfig.responseMiddleware(response, { + operationName: undefined, + variables, + url: this.url + }); + } + if (response instanceof Error) { + throw response; + } + return response.data; + } + setHeaders(headers) { + this.requestConfig.headers = headers; + return this; + } + setHeader(key, value) { + const { headers } = this.requestConfig; + if (headers) { + headers[key] = value; + } else { + this.requestConfig.headers = { [key]: value }; + } + return this; + } + setEndpoint(value) { + this.url = value; + return this; + } +} +var init_GraphQLClient = __esm(() => { + init_batchRequests(); + init_rawRequest(); + init_request(); + init_analyzeDocument(); + init_runRequest(); +}); + +// node_modules/graphql-request/build/legacy/functions/request.js +var parseRequestArgs = (documentOrOptions, variables, requestHeaders) => { + return documentOrOptions.document ? documentOrOptions : { + document: documentOrOptions, + variables, + requestHeaders, + signal: undefined + }; +}; +var init_request = __esm(() => { + init_GraphQLClient(); +}); + +// node_modules/graphql-request/build/legacy/functions/gql.js +var gql = (chunks, ...variables) => { + return chunks.reduce((acc, chunk, index) => `${acc}${chunk}${index in variables ? String(variables[index]) : ``}`, ``); +}; + +// node_modules/graphql-request/build/entrypoints/main.js +var init_main = __esm(() => { + init_ClientError(); + init_request(); + init_GraphQLClient(); + init_batchRequests(); + init_rawRequest(); + init_analyzeDocument(); +}); + +// node_modules/@opentelemetry/api/build/src/version.js +var require_version2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = undefined; + exports.VERSION = "1.9.1"; +}); + +// node_modules/@opentelemetry/api/build/src/internal/semver.js +var require_semver = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isCompatible = exports._makeCompatibilityCheck = undefined; + var version_1 = require_version2(); + var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; + function _makeCompatibilityCheck(ownVersion) { + const acceptedVersions = new Set([ownVersion]); + const rejectedVersions = new Set; + const myVersionMatch = ownVersion.match(re); + if (!myVersionMatch) { + return () => false; + } + const ownVersionParsed = { + major: +myVersionMatch[1], + minor: +myVersionMatch[2], + patch: +myVersionMatch[3], + prerelease: myVersionMatch[4] + }; + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } + function _reject(v) { + rejectedVersions.add(v); + return false; + } + function _accept(v) { + acceptedVersions.add(v); + return true; + } + return function isCompatible(globalVersion) { + if (acceptedVersions.has(globalVersion)) { + return true; + } + if (rejectedVersions.has(globalVersion)) { + return false; + } + const globalVersionMatch = globalVersion.match(re); + if (!globalVersionMatch) { + return _reject(globalVersion); + } + const globalVersionParsed = { + major: +globalVersionMatch[1], + minor: +globalVersionMatch[2], + patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4] + }; + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } + if (ownVersionParsed.major !== globalVersionParsed.major) { + return _reject(globalVersion); + } + if (ownVersionParsed.major === 0) { + if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { + return _accept(globalVersion); + } + return _reject(globalVersion); + } + if (ownVersionParsed.minor <= globalVersionParsed.minor) { + return _accept(globalVersion); + } + return _reject(globalVersion); + }; + } + exports._makeCompatibilityCheck = _makeCompatibilityCheck; + exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); +}); + +// node_modules/@opentelemetry/api/build/src/internal/global-utils.js +var require_global_utils = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = undefined; + var version_1 = require_version2(); + var semver_1 = require_semver(); + var major = version_1.VERSION.split(".")[0]; + var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); + var _global = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {}; + function registerGlobal(type, instance, diag, allowOverride = false) { + var _a; + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== undefined ? _a : { + version: version_1.VERSION + }; + if (!allowOverride && api[type]) { + const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); + diag.error(err.stack || err.message); + return false; + } + if (api.version !== version_1.VERSION) { + const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); + diag.error(err.stack || err.message); + return false; + } + api[type] = instance; + diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); + return true; + } + exports.registerGlobal = registerGlobal; + function getGlobal(type) { + var _a, _b; + const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === undefined ? undefined : _a.version; + if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { + return; + } + return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === undefined ? undefined : _b[type]; + } + exports.getGlobal = getGlobal; + function unregisterGlobal(type, diag) { + diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); + const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + if (api) { + delete api[type]; + } + } + exports.unregisterGlobal = unregisterGlobal; +}); + +// node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js +var require_ComponentLogger = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagComponentLogger = undefined; + var global_utils_1 = require_global_utils(); + + class DiagComponentLogger { + constructor(props) { + this._namespace = props.namespace || "DiagComponentLogger"; + } + debug(...args) { + return logProxy("debug", this._namespace, args); + } + error(...args) { + return logProxy("error", this._namespace, args); + } + info(...args) { + return logProxy("info", this._namespace, args); + } + warn(...args) { + return logProxy("warn", this._namespace, args); + } + verbose(...args) { + return logProxy("verbose", this._namespace, args); + } + } + exports.DiagComponentLogger = DiagComponentLogger; + function logProxy(funcName, namespace, args) { + const logger = (0, global_utils_1.getGlobal)("diag"); + if (!logger) { + return; + } + return logger[funcName](namespace, ...args); + } +}); + +// node_modules/@opentelemetry/api/build/src/diag/types.js +var require_types = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagLogLevel = undefined; + var DiagLogLevel; + (function(DiagLogLevel2) { + DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE"; + DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR"; + DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN"; + DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO"; + DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG"; + DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE"; + DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL"; + })(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); +}); + +// node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js +var require_logLevelLogger = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createLogLevelDiagLogger = undefined; + var types_1 = require_types(); + function createLogLevelDiagLogger(maxLevel, logger) { + if (maxLevel < types_1.DiagLogLevel.NONE) { + maxLevel = types_1.DiagLogLevel.NONE; + } else if (maxLevel > types_1.DiagLogLevel.ALL) { + maxLevel = types_1.DiagLogLevel.ALL; + } + logger = logger || {}; + function _filterFunc(funcName, theLevel) { + const theFunc = logger[funcName]; + if (typeof theFunc === "function" && maxLevel >= theLevel) { + return theFunc.bind(logger); + } + return function() {}; + } + return { + error: _filterFunc("error", types_1.DiagLogLevel.ERROR), + warn: _filterFunc("warn", types_1.DiagLogLevel.WARN), + info: _filterFunc("info", types_1.DiagLogLevel.INFO), + debug: _filterFunc("debug", types_1.DiagLogLevel.DEBUG), + verbose: _filterFunc("verbose", types_1.DiagLogLevel.VERBOSE) + }; + } + exports.createLogLevelDiagLogger = createLogLevelDiagLogger; +}); + +// node_modules/@opentelemetry/api/build/src/api/diag.js +var require_diag = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagAPI = undefined; + var ComponentLogger_1 = require_ComponentLogger(); + var logLevelLogger_1 = require_logLevelLogger(); + var types_1 = require_types(); + var global_utils_1 = require_global_utils(); + var API_NAME = "diag"; + + class DiagAPI { + static instance() { + if (!this._instance) { + this._instance = new DiagAPI; + } + return this._instance; + } + constructor() { + function _logProxy(funcName) { + return function(...args) { + const logger = (0, global_utils_1.getGlobal)("diag"); + if (!logger) + return; + return logger[funcName](...args); + }; + } + const self2 = this; + const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { + var _a, _b, _c; + if (logger === self2) { + const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); + self2.error((_a = err.stack) !== null && _a !== undefined ? _a : err.message); + return false; + } + if (typeof optionsOrLogLevel === "number") { + optionsOrLogLevel = { + logLevel: optionsOrLogLevel + }; + } + const oldLogger = (0, global_utils_1.getGlobal)("diag"); + const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== undefined ? _b : types_1.DiagLogLevel.INFO, logger); + if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { + const stack = (_c = new Error().stack) !== null && _c !== undefined ? _c : ""; + oldLogger.warn(`Current logger will be overwritten from ${stack}`); + newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); + } + return (0, global_utils_1.registerGlobal)("diag", newLogger, self2, true); + }; + self2.setLogger = setLogger; + self2.disable = () => { + (0, global_utils_1.unregisterGlobal)(API_NAME, self2); + }; + self2.createComponentLogger = (options) => { + return new ComponentLogger_1.DiagComponentLogger(options); + }; + self2.verbose = _logProxy("verbose"); + self2.debug = _logProxy("debug"); + self2.info = _logProxy("info"); + self2.warn = _logProxy("warn"); + self2.error = _logProxy("error"); + } + } + exports.DiagAPI = DiagAPI; +}); + +// node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js +var require_baggage_impl = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaggageImpl = undefined; + + class BaggageImpl { + constructor(entries) { + this._entries = entries ? new Map(entries) : new Map; + } + getEntry(key) { + const entry = this._entries.get(key); + if (!entry) { + return; + } + return Object.assign({}, entry); + } + getAllEntries() { + return Array.from(this._entries.entries()); + } + setEntry(key, entry) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + } + removeEntry(key) { + const newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + } + removeEntries(...keys) { + const newBaggage = new BaggageImpl(this._entries); + for (const key of keys) { + newBaggage._entries.delete(key); + } + return newBaggage; + } + clear() { + return new BaggageImpl; + } + } + exports.BaggageImpl = BaggageImpl; +}); + +// node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js +var require_symbol = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.baggageEntryMetadataSymbol = undefined; + exports.baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata"); +}); + +// node_modules/@opentelemetry/api/build/src/baggage/utils.js +var require_utils = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.baggageEntryMetadataFromString = exports.createBaggage = undefined; + var diag_1 = require_diag(); + var baggage_impl_1 = require_baggage_impl(); + var symbol_1 = require_symbol(); + var diag = diag_1.DiagAPI.instance(); + function createBaggage(entries = {}) { + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); + } + exports.createBaggage = createBaggage; + function baggageEntryMetadataFromString(str) { + if (typeof str !== "string") { + diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); + str = ""; + } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString() { + return str; + } + }; + } + exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; +}); + +// node_modules/@opentelemetry/api/build/src/context/context.js +var require_context = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ROOT_CONTEXT = exports.createContextKey = undefined; + function createContextKey(description) { + return Symbol.for(description); + } + exports.createContextKey = createContextKey; + + class BaseContext { + constructor(parentContext) { + const self2 = this; + self2._currentContext = parentContext ? new Map(parentContext) : new Map; + self2.getValue = (key) => self2._currentContext.get(key); + self2.setValue = (key, value) => { + const context = new BaseContext(self2._currentContext); + context._currentContext.set(key, value); + return context; + }; + self2.deleteValue = (key) => { + const context = new BaseContext(self2._currentContext); + context._currentContext.delete(key); + return context; + }; + } + } + exports.ROOT_CONTEXT = new BaseContext; +}); + +// node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js +var require_consoleLogger = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiagConsoleLogger = exports._originalConsoleMethods = undefined; + var consoleMap = [ + { n: "error", c: "error" }, + { n: "warn", c: "warn" }, + { n: "info", c: "info" }, + { n: "debug", c: "debug" }, + { n: "verbose", c: "trace" } + ]; + exports._originalConsoleMethods = {}; + if (typeof console !== "undefined") { + const keys = [ + "error", + "warn", + "info", + "debug", + "trace", + "log" + ]; + for (const key of keys) { + if (typeof console[key] === "function") { + exports._originalConsoleMethods[key] = console[key]; + } + } + } + + class DiagConsoleLogger { + constructor() { + function _consoleFunc(funcName) { + return function(...args) { + let theFunc = exports._originalConsoleMethods[funcName]; + if (typeof theFunc !== "function") { + theFunc = exports._originalConsoleMethods["log"]; + } + if (typeof theFunc !== "function" && console) { + theFunc = console[funcName]; + if (typeof theFunc !== "function") { + theFunc = console.log; + } + } + if (typeof theFunc === "function") { + return theFunc.apply(console, args); + } + }; + } + for (let i = 0;i < consoleMap.length; i++) { + this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); + } + } + } + exports.DiagConsoleLogger = DiagConsoleLogger; +}); + +// node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js +var require_NoopMeter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = undefined; + + class NoopMeter { + constructor() {} + createGauge(_name, _options) { + return exports.NOOP_GAUGE_METRIC; + } + createHistogram(_name, _options) { + return exports.NOOP_HISTOGRAM_METRIC; + } + createCounter(_name, _options) { + return exports.NOOP_COUNTER_METRIC; + } + createUpDownCounter(_name, _options) { + return exports.NOOP_UP_DOWN_COUNTER_METRIC; + } + createObservableGauge(_name, _options) { + return exports.NOOP_OBSERVABLE_GAUGE_METRIC; + } + createObservableCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_COUNTER_METRIC; + } + createObservableUpDownCounter(_name, _options) { + return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; + } + addBatchObservableCallback(_callback, _observables) {} + removeBatchObservableCallback(_callback) {} + } + exports.NoopMeter = NoopMeter; + + class NoopMetric { + } + exports.NoopMetric = NoopMetric; + + class NoopCounterMetric extends NoopMetric { + add(_value, _attributes) {} + } + exports.NoopCounterMetric = NoopCounterMetric; + + class NoopUpDownCounterMetric extends NoopMetric { + add(_value, _attributes) {} + } + exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; + + class NoopGaugeMetric extends NoopMetric { + record(_value, _attributes) {} + } + exports.NoopGaugeMetric = NoopGaugeMetric; + + class NoopHistogramMetric extends NoopMetric { + record(_value, _attributes) {} + } + exports.NoopHistogramMetric = NoopHistogramMetric; + + class NoopObservableMetric { + addCallback(_callback) {} + removeCallback(_callback) {} + } + exports.NoopObservableMetric = NoopObservableMetric; + + class NoopObservableCounterMetric extends NoopObservableMetric { + } + exports.NoopObservableCounterMetric = NoopObservableCounterMetric; + + class NoopObservableGaugeMetric extends NoopObservableMetric { + } + exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; + + class NoopObservableUpDownCounterMetric extends NoopObservableMetric { + } + exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; + exports.NOOP_METER = new NoopMeter; + exports.NOOP_COUNTER_METRIC = new NoopCounterMetric; + exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric; + exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric; + exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric; + exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric; + exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric; + exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric; + function createNoopMeter() { + return exports.NOOP_METER; + } + exports.createNoopMeter = createNoopMeter; +}); + +// node_modules/@opentelemetry/api/build/src/metrics/Metric.js +var require_Metric = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueType = undefined; + var ValueType; + (function(ValueType2) { + ValueType2[ValueType2["INT"] = 0] = "INT"; + ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE"; + })(ValueType = exports.ValueType || (exports.ValueType = {})); +}); + +// node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js +var require_TextMapPropagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultTextMapSetter = exports.defaultTextMapGetter = undefined; + exports.defaultTextMapGetter = { + get(carrier, key) { + if (carrier == null) { + return; + } + return carrier[key]; + }, + keys(carrier) { + if (carrier == null) { + return []; + } + return Object.keys(carrier); + } + }; + exports.defaultTextMapSetter = { + set(carrier, key, value) { + if (carrier == null) { + return; + } + carrier[key] = value; + } + }; +}); + +// node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js +var require_NoopContextManager = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopContextManager = undefined; + var context_1 = require_context(); + + class NoopContextManager { + active() { + return context_1.ROOT_CONTEXT; + } + with(_context, fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + bind(_context, target) { + return target; + } + enable() { + return this; + } + disable() { + return this; + } + } + exports.NoopContextManager = NoopContextManager; +}); + +// node_modules/@opentelemetry/api/build/src/api/context.js +var require_context2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ContextAPI = undefined; + var NoopContextManager_1 = require_NoopContextManager(); + var global_utils_1 = require_global_utils(); + var diag_1 = require_diag(); + var API_NAME = "context"; + var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager; + + class ContextAPI { + constructor() {} + static getInstance() { + if (!this._instance) { + this._instance = new ContextAPI; + } + return this._instance; + } + setGlobalContextManager(contextManager) { + return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); + } + active() { + return this._getContextManager().active(); + } + with(context, fn, thisArg, ...args) { + return this._getContextManager().with(context, fn, thisArg, ...args); + } + bind(context, target) { + return this._getContextManager().bind(context, target); + } + _getContextManager() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; + } + disable() { + this._getContextManager().disable(); + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + } + exports.ContextAPI = ContextAPI; +}); + +// node_modules/@opentelemetry/api/build/src/trace/trace_flags.js +var require_trace_flags = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceFlags = undefined; + var TraceFlags; + (function(TraceFlags2) { + TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE"; + TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED"; + })(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); +}); + +// node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js +var require_invalid_span_constants = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = undefined; + var trace_flags_1 = require_trace_flags(); + exports.INVALID_SPANID = "0000000000000000"; + exports.INVALID_TRACEID = "00000000000000000000000000000000"; + exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE + }; +}); + +// node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js +var require_NonRecordingSpan = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NonRecordingSpan = undefined; + var invalid_span_constants_1 = require_invalid_span_constants(); + + class NonRecordingSpan { + constructor(spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { + this._spanContext = spanContext; + } + spanContext() { + return this._spanContext; + } + setAttribute(_key, _value) { + return this; + } + setAttributes(_attributes) { + return this; + } + addEvent(_name, _attributes) { + return this; + } + addLink(_link) { + return this; + } + addLinks(_links) { + return this; + } + setStatus(_status) { + return this; + } + updateName(_name) { + return this; + } + end(_endTime) {} + isRecording() { + return false; + } + recordException(_exception, _time) {} + } + exports.NonRecordingSpan = NonRecordingSpan; +}); + +// node_modules/@opentelemetry/api/build/src/trace/context-utils.js +var require_context_utils = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = undefined; + var context_1 = require_context(); + var NonRecordingSpan_1 = require_NonRecordingSpan(); + var context_2 = require_context2(); + var SPAN_KEY = (0, context_1.createContextKey)("OpenTelemetry Context Key SPAN"); + function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; + } + exports.getSpan = getSpan; + function getActiveSpan() { + return getSpan(context_2.ContextAPI.getInstance().active()); + } + exports.getActiveSpan = getActiveSpan; + function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); + } + exports.setSpan = setSpan; + function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); + } + exports.deleteSpan = deleteSpan; + function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); + } + exports.setSpanContext = setSpanContext; + function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === undefined ? undefined : _a.spanContext(); + } + exports.getSpanContext = getSpanContext; +}); + +// node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js +var require_spancontext_utils = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = undefined; + var invalid_span_constants_1 = require_invalid_span_constants(); + var NonRecordingSpan_1 = require_NonRecordingSpan(); + var isHex = new Uint8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1 + ]); + function isValidHex(id, length) { + if (typeof id !== "string" || id.length !== length) + return false; + let r = 0; + for (let i = 0;i < id.length; i += 4) { + r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0); + } + return r === length; + } + function isValidTraceId(traceId) { + return isValidHex(traceId, 32) && traceId !== invalid_span_constants_1.INVALID_TRACEID; + } + exports.isValidTraceId = isValidTraceId; + function isValidSpanId(spanId) { + return isValidHex(spanId, 16) && spanId !== invalid_span_constants_1.INVALID_SPANID; + } + exports.isValidSpanId = isValidSpanId; + function isSpanContextValid(spanContext) { + return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); + } + exports.isSpanContextValid = isSpanContextValid; + function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); + } + exports.wrapSpanContext = wrapSpanContext; +}); + +// node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js +var require_NoopTracer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopTracer = undefined; + var context_1 = require_context2(); + var context_utils_1 = require_context_utils(); + var NonRecordingSpan_1 = require_NonRecordingSpan(); + var spancontext_utils_1 = require_spancontext_utils(); + var contextApi = context_1.ContextAPI.getInstance(); + + class NoopTracer { + startSpan(name, options, context = contextApi.active()) { + const root = Boolean(options === null || options === undefined ? undefined : options.root); + if (root) { + return new NonRecordingSpan_1.NonRecordingSpan; + } + const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); + if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); + } else { + return new NonRecordingSpan_1.NonRecordingSpan; + } + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } else if (arguments.length === 2) { + fn = arg2; + } else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx !== null && ctx !== undefined ? ctx : contextApi.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); + return contextApi.with(contextWithSpanSet, fn, undefined, span); + } + } + exports.NoopTracer = NoopTracer; + function isSpanContext(spanContext) { + return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number"; + } +}); + +// node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js +var require_ProxyTracer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyTracer = undefined; + var NoopTracer_1 = require_NoopTracer(); + var NOOP_TRACER = new NoopTracer_1.NoopTracer; + + class ProxyTracer { + constructor(provider, name, version, options) { + this._provider = provider; + this.name = name; + this.version = version; + this.options = options; + } + startSpan(name, options, context) { + return this._getTracer().startSpan(name, options, context); + } + startActiveSpan(_name, _options, _context, _fn) { + const tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + } + _getTracer() { + if (this._delegate) { + return this._delegate; + } + const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); + if (!tracer) { + return NOOP_TRACER; + } + this._delegate = tracer; + return this._delegate; + } + } + exports.ProxyTracer = ProxyTracer; +}); + +// node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js +var require_NoopTracerProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopTracerProvider = undefined; + var NoopTracer_1 = require_NoopTracer(); + + class NoopTracerProvider { + getTracer(_name, _version, _options) { + return new NoopTracer_1.NoopTracer; + } + } + exports.NoopTracerProvider = NoopTracerProvider; +}); + +// node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js +var require_ProxyTracerProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyTracerProvider = undefined; + var ProxyTracer_1 = require_ProxyTracer(); + var NoopTracerProvider_1 = require_NoopTracerProvider(); + var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider; + + class ProxyTracerProvider { + getTracer(name, version, options) { + var _a; + return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== undefined ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options); + } + getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== undefined ? _a : NOOP_TRACER_PROVIDER; + } + setDelegate(delegate) { + this._delegate = delegate; + } + getDelegateTracer(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === undefined ? undefined : _a.getTracer(name, version, options); + } + } + exports.ProxyTracerProvider = ProxyTracerProvider; +}); + +// node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js +var require_SamplingResult = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SamplingDecision = undefined; + var SamplingDecision; + (function(SamplingDecision2) { + SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD"; + SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD"; + SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +}); + +// node_modules/@opentelemetry/api/build/src/trace/span_kind.js +var require_span_kind = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanKind = undefined; + var SpanKind; + (function(SpanKind2) { + SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL"; + SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER"; + SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT"; + SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER"; + SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER"; + })(SpanKind = exports.SpanKind || (exports.SpanKind = {})); +}); + +// node_modules/@opentelemetry/api/build/src/trace/status.js +var require_status = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanStatusCode = undefined; + var SpanStatusCode; + (function(SpanStatusCode2) { + SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET"; + SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK"; + SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR"; + })(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); +}); + +// node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js +var require_tracestate_validators = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateValue = exports.validateKey = undefined; + var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]"; + var VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; + var VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; + var VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); + var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; + var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; + function validateKey(key) { + return VALID_KEY_REGEX.test(key); + } + exports.validateKey = validateKey; + function validateValue(value) { + return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value); + } + exports.validateValue = validateValue; +}); + +// node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js +var require_tracestate_impl = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceStateImpl = undefined; + var tracestate_validators_1 = require_tracestate_validators(); + var MAX_TRACE_STATE_ITEMS = 32; + var MAX_TRACE_STATE_LEN = 512; + var LIST_MEMBERS_SEPARATOR = ","; + var LIST_MEMBER_KEY_VALUE_SPLITTER = "="; + + class TraceStateImpl { + constructor(rawTraceState) { + this._internalState = new Map; + if (rawTraceState) + this._parse(rawTraceState); + } + set(key, value) { + const traceState = this._clone(); + if (traceState._internalState.has(key)) { + traceState._internalState.delete(key); + } + traceState._internalState.set(key, value); + return traceState; + } + unset(key) { + const traceState = this._clone(); + traceState._internalState.delete(key); + return traceState; + } + get(key) { + return this._internalState.get(key); + } + serialize() { + return Array.from(this._internalState.keys()).reduceRight((agg, key) => { + agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); + return agg; + }, []).join(LIST_MEMBERS_SEPARATOR); + } + _parse(rawTraceState) { + if (rawTraceState.length > MAX_TRACE_STATE_LEN) + return; + this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reduceRight((agg, part) => { + const listMember = part.trim(); + const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (i !== -1) { + const key = listMember.slice(0, i); + const value = listMember.slice(i + 1, part.length); + if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { + agg.set(key, value); + } else {} + } + return agg; + }, new Map); + if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { + this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS)); + } + } + _keys() { + return Array.from(this._internalState.keys()).reverse(); + } + _clone() { + const traceState = new TraceStateImpl; + traceState._internalState = new Map(this._internalState); + return traceState; + } + } + exports.TraceStateImpl = TraceStateImpl; +}); + +// node_modules/@opentelemetry/api/build/src/trace/internal/utils.js +var require_utils2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createTraceState = undefined; + var tracestate_impl_1 = require_tracestate_impl(); + function createTraceState(rawTraceState) { + return new tracestate_impl_1.TraceStateImpl(rawTraceState); + } + exports.createTraceState = createTraceState; +}); + +// node_modules/@opentelemetry/api/build/src/context-api.js +var require_context_api = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.context = undefined; + var context_1 = require_context2(); + exports.context = context_1.ContextAPI.getInstance(); +}); + +// node_modules/@opentelemetry/api/build/src/diag-api.js +var require_diag_api = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.diag = undefined; + var diag_1 = require_diag(); + exports.diag = diag_1.DiagAPI.instance(); +}); + +// node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js +var require_NoopMeterProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = undefined; + var NoopMeter_1 = require_NoopMeter(); + + class NoopMeterProvider { + getMeter(_name, _version, _options) { + return NoopMeter_1.NOOP_METER; + } + } + exports.NoopMeterProvider = NoopMeterProvider; + exports.NOOP_METER_PROVIDER = new NoopMeterProvider; +}); + +// node_modules/@opentelemetry/api/build/src/api/metrics.js +var require_metrics = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricsAPI = undefined; + var NoopMeterProvider_1 = require_NoopMeterProvider(); + var global_utils_1 = require_global_utils(); + var diag_1 = require_diag(); + var API_NAME = "metrics"; + + class MetricsAPI { + constructor() {} + static getInstance() { + if (!this._instance) { + this._instance = new MetricsAPI; + } + return this._instance; + } + setGlobalMeterProvider(provider) { + return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); + } + getMeterProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; + } + getMeter(name, version, options) { + return this.getMeterProvider().getMeter(name, version, options); + } + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + } + exports.MetricsAPI = MetricsAPI; +}); + +// node_modules/@opentelemetry/api/build/src/metrics-api.js +var require_metrics_api = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.metrics = undefined; + var metrics_1 = require_metrics(); + exports.metrics = metrics_1.MetricsAPI.getInstance(); +}); + +// node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js +var require_NoopTextMapPropagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopTextMapPropagator = undefined; + + class NoopTextMapPropagator { + inject(_context, _carrier) {} + extract(context, _carrier) { + return context; + } + fields() { + return []; + } + } + exports.NoopTextMapPropagator = NoopTextMapPropagator; +}); + +// node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js +var require_context_helpers = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = undefined; + var context_1 = require_context2(); + var context_2 = require_context(); + var BAGGAGE_KEY = (0, context_2.createContextKey)("OpenTelemetry Baggage Key"); + function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; + } + exports.getBaggage = getBaggage; + function getActiveBaggage() { + return getBaggage(context_1.ContextAPI.getInstance().active()); + } + exports.getActiveBaggage = getActiveBaggage; + function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); + } + exports.setBaggage = setBaggage; + function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); + } + exports.deleteBaggage = deleteBaggage; +}); + +// node_modules/@opentelemetry/api/build/src/api/propagation.js +var require_propagation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PropagationAPI = undefined; + var global_utils_1 = require_global_utils(); + var NoopTextMapPropagator_1 = require_NoopTextMapPropagator(); + var TextMapPropagator_1 = require_TextMapPropagator(); + var context_helpers_1 = require_context_helpers(); + var utils_1 = require_utils(); + var diag_1 = require_diag(); + var API_NAME = "propagation"; + var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator; + + class PropagationAPI { + constructor() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.getActiveBaggage = context_helpers_1.getActiveBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; + } + static getInstance() { + if (!this._instance) { + this._instance = new PropagationAPI; + } + return this._instance; + } + setGlobalPropagator(propagator) { + return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); + } + inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { + return this._getGlobalPropagator().inject(context, carrier, setter); + } + extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { + return this._getGlobalPropagator().extract(context, carrier, getter); + } + fields() { + return this._getGlobalPropagator().fields(); + } + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + } + _getGlobalPropagator() { + return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; + } + } + exports.PropagationAPI = PropagationAPI; +}); + +// node_modules/@opentelemetry/api/build/src/propagation-api.js +var require_propagation_api = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.propagation = undefined; + var propagation_1 = require_propagation(); + exports.propagation = propagation_1.PropagationAPI.getInstance(); +}); + +// node_modules/@opentelemetry/api/build/src/api/trace.js +var require_trace = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceAPI = undefined; + var global_utils_1 = require_global_utils(); + var ProxyTracerProvider_1 = require_ProxyTracerProvider(); + var spancontext_utils_1 = require_spancontext_utils(); + var context_utils_1 = require_context_utils(); + var diag_1 = require_diag(); + var API_NAME = "trace"; + + class TraceAPI { + constructor() { + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider; + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; + this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getActiveSpan = context_utils_1.getActiveSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; + } + static getInstance() { + if (!this._instance) { + this._instance = new TraceAPI; + } + return this._instance; + } + setGlobalTracerProvider(provider) { + const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; + } + getTracerProvider() { + return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; + } + getTracer(name, version) { + return this.getTracerProvider().getTracer(name, version); + } + disable() { + (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); + this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider; + } + } + exports.TraceAPI = TraceAPI; +}); + +// node_modules/@opentelemetry/api/build/src/trace-api.js +var require_trace_api = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.trace = undefined; + var trace_1 = require_trace(); + exports.trace = trace_1.TraceAPI.getInstance(); +}); + +// node_modules/@opentelemetry/api/build/src/index.js +var require_src = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = undefined; + var utils_1 = require_utils(); + Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function() { + return utils_1.baggageEntryMetadataFromString; + } }); + var context_1 = require_context(); + Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function() { + return context_1.createContextKey; + } }); + Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function() { + return context_1.ROOT_CONTEXT; + } }); + var consoleLogger_1 = require_consoleLogger(); + Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function() { + return consoleLogger_1.DiagConsoleLogger; + } }); + var types_1 = require_types(); + Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function() { + return types_1.DiagLogLevel; + } }); + var NoopMeter_1 = require_NoopMeter(); + Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function() { + return NoopMeter_1.createNoopMeter; + } }); + var Metric_1 = require_Metric(); + Object.defineProperty(exports, "ValueType", { enumerable: true, get: function() { + return Metric_1.ValueType; + } }); + var TextMapPropagator_1 = require_TextMapPropagator(); + Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function() { + return TextMapPropagator_1.defaultTextMapGetter; + } }); + Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function() { + return TextMapPropagator_1.defaultTextMapSetter; + } }); + var ProxyTracer_1 = require_ProxyTracer(); + Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function() { + return ProxyTracer_1.ProxyTracer; + } }); + var ProxyTracerProvider_1 = require_ProxyTracerProvider(); + Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function() { + return ProxyTracerProvider_1.ProxyTracerProvider; + } }); + var SamplingResult_1 = require_SamplingResult(); + Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function() { + return SamplingResult_1.SamplingDecision; + } }); + var span_kind_1 = require_span_kind(); + Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function() { + return span_kind_1.SpanKind; + } }); + var status_1 = require_status(); + Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function() { + return status_1.SpanStatusCode; + } }); + var trace_flags_1 = require_trace_flags(); + Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function() { + return trace_flags_1.TraceFlags; + } }); + var utils_2 = require_utils2(); + Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function() { + return utils_2.createTraceState; + } }); + var spancontext_utils_1 = require_spancontext_utils(); + Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function() { + return spancontext_utils_1.isSpanContextValid; + } }); + Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function() { + return spancontext_utils_1.isValidTraceId; + } }); + Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function() { + return spancontext_utils_1.isValidSpanId; + } }); + var invalid_span_constants_1 = require_invalid_span_constants(); + Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_SPANID; + } }); + Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_TRACEID; + } }); + Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function() { + return invalid_span_constants_1.INVALID_SPAN_CONTEXT; + } }); + var context_api_1 = require_context_api(); + Object.defineProperty(exports, "context", { enumerable: true, get: function() { + return context_api_1.context; + } }); + var diag_api_1 = require_diag_api(); + Object.defineProperty(exports, "diag", { enumerable: true, get: function() { + return diag_api_1.diag; + } }); + var metrics_api_1 = require_metrics_api(); + Object.defineProperty(exports, "metrics", { enumerable: true, get: function() { + return metrics_api_1.metrics; + } }); + var propagation_api_1 = require_propagation_api(); + Object.defineProperty(exports, "propagation", { enumerable: true, get: function() { + return propagation_api_1.propagation; + } }); + var trace_api_1 = require_trace_api(); + Object.defineProperty(exports, "trace", { enumerable: true, get: function() { + return trace_api_1.trace; + } }); + exports.default = { + context: context_api_1.context, + diag: diag_api_1.diag, + metrics: metrics_api_1.metrics, + propagation: propagation_api_1.propagation, + trace: trace_api_1.trace + }; +}); + +// node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js +var require_suppress_tracing = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = undefined; + var api_1 = require_src(); + var SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key SUPPRESS_TRACING"); + function suppressTracing(context) { + return context.setValue(SUPPRESS_TRACING_KEY, true); + } + exports.suppressTracing = suppressTracing; + function unsuppressTracing(context) { + return context.deleteValue(SUPPRESS_TRACING_KEY); + } + exports.unsuppressTracing = unsuppressTracing; + function isTracingSuppressed(context) { + return context.getValue(SUPPRESS_TRACING_KEY) === true; + } + exports.isTracingSuppressed = isTracingSuppressed; +}); + +// node_modules/@opentelemetry/core/build/src/baggage/constants.js +var require_constants = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BAGGAGE_MAX_TOTAL_LENGTH = exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = exports.BAGGAGE_HEADER = exports.BAGGAGE_ITEMS_SEPARATOR = exports.BAGGAGE_PROPERTIES_SEPARATOR = exports.BAGGAGE_KEY_PAIR_SEPARATOR = undefined; + exports.BAGGAGE_KEY_PAIR_SEPARATOR = "="; + exports.BAGGAGE_PROPERTIES_SEPARATOR = ";"; + exports.BAGGAGE_ITEMS_SEPARATOR = ","; + exports.BAGGAGE_HEADER = "baggage"; + exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = 180; + exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096; + exports.BAGGAGE_MAX_TOTAL_LENGTH = 8192; +}); + +// node_modules/@opentelemetry/core/build/src/baggage/utils.js +var require_utils3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseKeyPairsIntoRecord = exports.parseBaggageHeaderString = exports.parsePairKeyValue = exports.getKeyPairs = exports.serializeKeyPairs = undefined; + var api_1 = require_src(); + var constants_1 = require_constants(); + function serializeKeyPairs(keyPairs) { + return keyPairs.reduce((hValue, current) => { + const value = `${hValue}${hValue !== "" ? constants_1.BAGGAGE_ITEMS_SEPARATOR : ""}${current}`; + return value.length > constants_1.BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value; + }, ""); + } + exports.serializeKeyPairs = serializeKeyPairs; + function getKeyPairs(baggage) { + return baggage.getAllEntries().map(([key, value]) => { + let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`; + if (value.metadata !== undefined) { + entry += constants_1.BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString(); + } + return entry; + }); + } + exports.getKeyPairs = getKeyPairs; + function parsePairKeyValue(entry) { + if (!entry) + return; + const metadataSeparatorIndex = entry.indexOf(constants_1.BAGGAGE_PROPERTIES_SEPARATOR); + const keyPairPart = metadataSeparatorIndex === -1 ? entry : entry.substring(0, metadataSeparatorIndex); + const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR); + if (separatorIndex <= 0) + return; + const rawKey = keyPairPart.substring(0, separatorIndex).trim(); + const rawValue = keyPairPart.substring(separatorIndex + 1).trim(); + if (!rawKey || !rawValue) + return; + let key; + let value; + try { + key = decodeURIComponent(rawKey); + value = decodeURIComponent(rawValue); + } catch { + return; + } + let metadata; + if (metadataSeparatorIndex !== -1 && metadataSeparatorIndex < entry.length - 1) { + const metadataString = entry.substring(metadataSeparatorIndex + 1); + metadata = (0, api_1.baggageEntryMetadataFromString)(metadataString); + } + return { key, value, metadata }; + } + exports.parsePairKeyValue = parsePairKeyValue; + function parseBaggageHeaderString(value, baggage, count, totalSize) { + let start = 0; + while (start < value.length && count < constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS) { + const end = value.indexOf(constants_1.BAGGAGE_ITEMS_SEPARATOR, start); + const entryEnd = end === -1 ? value.length : end; + const entryLength = entryEnd - start; + if (entryLength <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS) { + const keyPair = parsePairKeyValue(value.substring(start, entryEnd)); + if (keyPair) { + const entrySize = (count === 0 ? 0 : 1) + entryLength; + if (totalSize + entrySize > constants_1.BAGGAGE_MAX_TOTAL_LENGTH) + break; + baggage[keyPair.key] = keyPair.metadata ? { value: keyPair.value, metadata: keyPair.metadata } : { value: keyPair.value }; + count++; + totalSize += entrySize; + } + } + if (end === -1) + break; + start = end + 1; + } + return [count, totalSize]; + } + exports.parseBaggageHeaderString = parseBaggageHeaderString; + function parseKeyPairsIntoRecord(value) { + const result = {}; + if (typeof value === "string" && value.length > 0) { + value.split(constants_1.BAGGAGE_ITEMS_SEPARATOR).forEach((entry) => { + const keyPair = parsePairKeyValue(entry); + if (keyPair !== undefined && keyPair.value.length > 0) { + result[keyPair.key] = keyPair.value; + } + }); + } + return result; + } + exports.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord; +}); + +// node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js +var require_W3CBaggagePropagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.W3CBaggagePropagator = undefined; + var api_1 = require_src(); + var suppress_tracing_1 = require_suppress_tracing(); + var constants_1 = require_constants(); + var utils_1 = require_utils3(); + + class W3CBaggagePropagator { + inject(context, carrier, setter) { + const baggage = api_1.propagation.getBaggage(context); + if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context)) + return; + const keyPairs = (0, utils_1.getKeyPairs)(baggage).filter((pair) => { + return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS; + }).slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS); + const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs); + if (headerValue.length > 0) { + setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue); + } + } + extract(context, carrier, getter) { + const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER); + if (!headerValue) { + return context; + } + const baggage = {}; + let count = 0; + let totalSize = 0; + if (Array.isArray(headerValue)) { + for (let i = 0;i < headerValue.length; i++) { + [count, totalSize] = (0, utils_1.parseBaggageHeaderString)(headerValue[i], baggage, count, totalSize); + } + } else { + [count] = (0, utils_1.parseBaggageHeaderString)(headerValue, baggage, count, totalSize); + } + if (count === 0) { + return context; + } + return api_1.propagation.setBaggage(context, api_1.propagation.createBaggage(baggage)); + } + fields() { + return [constants_1.BAGGAGE_HEADER]; + } + } + exports.W3CBaggagePropagator = W3CBaggagePropagator; +}); + +// node_modules/@opentelemetry/core/build/src/common/anchored-clock.js +var require_anchored_clock = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AnchoredClock = undefined; + + class AnchoredClock { + _monotonicClock; + _epochMillis; + _performanceMillis; + constructor(systemClock, monotonicClock) { + this._monotonicClock = monotonicClock; + this._epochMillis = systemClock.now(); + this._performanceMillis = monotonicClock.now(); + } + now() { + const delta = this._monotonicClock.now() - this._performanceMillis; + return this._epochMillis + delta; + } + } + exports.AnchoredClock = AnchoredClock; +}); + +// node_modules/@opentelemetry/core/build/src/common/attributes.js +var require_attributes = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isAttributeValue = exports.isAttributeKey = exports.sanitizeAttributes = undefined; + var api_1 = require_src(); + function sanitizeAttributes(attributes) { + const out = {}; + if (typeof attributes !== "object" || attributes == null) { + return out; + } + for (const key in attributes) { + if (!Object.prototype.hasOwnProperty.call(attributes, key)) { + continue; + } + if (!isAttributeKey(key)) { + api_1.diag.warn(`Invalid attribute key: ${key}`); + continue; + } + const val = attributes[key]; + if (!isAttributeValue(val)) { + api_1.diag.warn(`Invalid attribute value set for key: ${key}`); + continue; + } + if (Array.isArray(val)) { + out[key] = val.slice(); + } else { + out[key] = val; + } + } + return out; + } + exports.sanitizeAttributes = sanitizeAttributes; + function isAttributeKey(key) { + return typeof key === "string" && key !== ""; + } + exports.isAttributeKey = isAttributeKey; + function isAttributeValue(val) { + if (val == null) { + return true; + } + if (Array.isArray(val)) { + return isHomogeneousAttributeValueArray(val); + } + return isValidPrimitiveAttributeValueType(typeof val); + } + exports.isAttributeValue = isAttributeValue; + function isHomogeneousAttributeValueArray(arr) { + let type; + for (const element of arr) { + if (element == null) + continue; + const elementType = typeof element; + if (elementType === type) { + continue; + } + if (!type) { + if (isValidPrimitiveAttributeValueType(elementType)) { + type = elementType; + continue; + } + return false; + } + return false; + } + return true; + } + function isValidPrimitiveAttributeValueType(valType) { + switch (valType) { + case "number": + case "boolean": + case "string": + return true; + } + return false; + } +}); + +// node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js +var require_logging_error_handler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.loggingErrorHandler = undefined; + var api_1 = require_src(); + function loggingErrorHandler() { + return (ex) => { + api_1.diag.error(stringifyException(ex)); + }; + } + exports.loggingErrorHandler = loggingErrorHandler; + function stringifyException(ex) { + if (typeof ex === "string") { + return ex; + } else { + return JSON.stringify(flattenException(ex)); + } + } + function flattenException(ex) { + const result = {}; + let current = ex; + while (current !== null) { + Object.getOwnPropertyNames(current).forEach((propertyName) => { + if (result[propertyName]) + return; + const value = current[propertyName]; + if (value) { + result[propertyName] = String(value); + } + }); + current = Object.getPrototypeOf(current); + } + return result; + } +}); + +// node_modules/@opentelemetry/core/build/src/common/global-error-handler.js +var require_global_error_handler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.globalErrorHandler = exports.setGlobalErrorHandler = undefined; + var logging_error_handler_1 = require_logging_error_handler(); + var delegateHandler = (0, logging_error_handler_1.loggingErrorHandler)(); + function setGlobalErrorHandler(handler) { + delegateHandler = handler; + } + exports.setGlobalErrorHandler = setGlobalErrorHandler; + function globalErrorHandler(ex) { + try { + delegateHandler(ex); + } catch {} + } + exports.globalErrorHandler = globalErrorHandler; +}); + +// node_modules/@opentelemetry/core/build/src/platform/node/environment.js +var require_environment = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getStringListFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports.getNumberFromEnv = undefined; + var api_1 = require_src(); + var util_1 = __require("util"); + function getNumberFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === "") { + return; + } + const value = Number(raw); + if (isNaN(value)) { + api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected a number, using defaults`); + return; + } + return value; + } + exports.getNumberFromEnv = getNumberFromEnv; + function getStringFromEnv(key) { + const raw = process.env[key]; + if (raw == null || raw.trim() === "") { + return; + } + return raw; + } + exports.getStringFromEnv = getStringFromEnv; + function getBooleanFromEnv(key) { + const raw = process.env[key]?.trim().toLowerCase(); + if (raw == null || raw === "") { + return false; + } + if (raw === "true") { + return true; + } else if (raw === "false") { + return false; + } else { + api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`); + return false; + } + } + exports.getBooleanFromEnv = getBooleanFromEnv; + function getStringListFromEnv(key) { + return getStringFromEnv(key)?.split(",").map((v) => v.trim()).filter((s) => s !== ""); + } + exports.getStringListFromEnv = getStringListFromEnv; +}); + +// node_modules/@opentelemetry/core/build/src/common/globalThis.js +var require_globalThis = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports._globalThis = undefined; + exports._globalThis = globalThis; +}); + +// node_modules/@opentelemetry/core/build/src/version.js +var require_version3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = undefined; + exports.VERSION = "2.8.0"; +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js +var require_utils4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createConstMap = undefined; + function createConstMap(values) { + let res = {}; + const len = values.length; + for (let lp = 0;lp < len; lp++) { + const val = values[lp]; + if (val) { + res[String(val).toUpperCase().replace(/[-.]/g, "_")] = val; + } + } + return res; + } + exports.createConstMap = createConstMap; +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js +var require_SemanticAttributes = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = undefined; + exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = undefined; + exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = undefined; + exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = undefined; + exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = undefined; + exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = undefined; + var utils_1 = require_utils4(); + var TMP_AWS_LAMBDA_INVOKED_ARN = "aws.lambda.invoked_arn"; + var TMP_DB_SYSTEM = "db.system"; + var TMP_DB_CONNECTION_STRING = "db.connection_string"; + var TMP_DB_USER = "db.user"; + var TMP_DB_JDBC_DRIVER_CLASSNAME = "db.jdbc.driver_classname"; + var TMP_DB_NAME = "db.name"; + var TMP_DB_STATEMENT = "db.statement"; + var TMP_DB_OPERATION = "db.operation"; + var TMP_DB_MSSQL_INSTANCE_NAME = "db.mssql.instance_name"; + var TMP_DB_CASSANDRA_KEYSPACE = "db.cassandra.keyspace"; + var TMP_DB_CASSANDRA_PAGE_SIZE = "db.cassandra.page_size"; + var TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = "db.cassandra.consistency_level"; + var TMP_DB_CASSANDRA_TABLE = "db.cassandra.table"; + var TMP_DB_CASSANDRA_IDEMPOTENCE = "db.cassandra.idempotence"; + var TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = "db.cassandra.speculative_execution_count"; + var TMP_DB_CASSANDRA_COORDINATOR_ID = "db.cassandra.coordinator.id"; + var TMP_DB_CASSANDRA_COORDINATOR_DC = "db.cassandra.coordinator.dc"; + var TMP_DB_HBASE_NAMESPACE = "db.hbase.namespace"; + var TMP_DB_REDIS_DATABASE_INDEX = "db.redis.database_index"; + var TMP_DB_MONGODB_COLLECTION = "db.mongodb.collection"; + var TMP_DB_SQL_TABLE = "db.sql.table"; + var TMP_EXCEPTION_TYPE = "exception.type"; + var TMP_EXCEPTION_MESSAGE = "exception.message"; + var TMP_EXCEPTION_STACKTRACE = "exception.stacktrace"; + var TMP_EXCEPTION_ESCAPED = "exception.escaped"; + var TMP_FAAS_TRIGGER = "faas.trigger"; + var TMP_FAAS_EXECUTION = "faas.execution"; + var TMP_FAAS_DOCUMENT_COLLECTION = "faas.document.collection"; + var TMP_FAAS_DOCUMENT_OPERATION = "faas.document.operation"; + var TMP_FAAS_DOCUMENT_TIME = "faas.document.time"; + var TMP_FAAS_DOCUMENT_NAME = "faas.document.name"; + var TMP_FAAS_TIME = "faas.time"; + var TMP_FAAS_CRON = "faas.cron"; + var TMP_FAAS_COLDSTART = "faas.coldstart"; + var TMP_FAAS_INVOKED_NAME = "faas.invoked_name"; + var TMP_FAAS_INVOKED_PROVIDER = "faas.invoked_provider"; + var TMP_FAAS_INVOKED_REGION = "faas.invoked_region"; + var TMP_NET_TRANSPORT = "net.transport"; + var TMP_NET_PEER_IP = "net.peer.ip"; + var TMP_NET_PEER_PORT = "net.peer.port"; + var TMP_NET_PEER_NAME = "net.peer.name"; + var TMP_NET_HOST_IP = "net.host.ip"; + var TMP_NET_HOST_PORT = "net.host.port"; + var TMP_NET_HOST_NAME = "net.host.name"; + var TMP_NET_HOST_CONNECTION_TYPE = "net.host.connection.type"; + var TMP_NET_HOST_CONNECTION_SUBTYPE = "net.host.connection.subtype"; + var TMP_NET_HOST_CARRIER_NAME = "net.host.carrier.name"; + var TMP_NET_HOST_CARRIER_MCC = "net.host.carrier.mcc"; + var TMP_NET_HOST_CARRIER_MNC = "net.host.carrier.mnc"; + var TMP_NET_HOST_CARRIER_ICC = "net.host.carrier.icc"; + var TMP_PEER_SERVICE = "peer.service"; + var TMP_ENDUSER_ID = "enduser.id"; + var TMP_ENDUSER_ROLE = "enduser.role"; + var TMP_ENDUSER_SCOPE = "enduser.scope"; + var TMP_THREAD_ID = "thread.id"; + var TMP_THREAD_NAME = "thread.name"; + var TMP_CODE_FUNCTION = "code.function"; + var TMP_CODE_NAMESPACE = "code.namespace"; + var TMP_CODE_FILEPATH = "code.filepath"; + var TMP_CODE_LINENO = "code.lineno"; + var TMP_HTTP_METHOD = "http.method"; + var TMP_HTTP_URL = "http.url"; + var TMP_HTTP_TARGET = "http.target"; + var TMP_HTTP_HOST = "http.host"; + var TMP_HTTP_SCHEME = "http.scheme"; + var TMP_HTTP_STATUS_CODE = "http.status_code"; + var TMP_HTTP_FLAVOR = "http.flavor"; + var TMP_HTTP_USER_AGENT = "http.user_agent"; + var TMP_HTTP_REQUEST_CONTENT_LENGTH = "http.request_content_length"; + var TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = "http.request_content_length_uncompressed"; + var TMP_HTTP_RESPONSE_CONTENT_LENGTH = "http.response_content_length"; + var TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = "http.response_content_length_uncompressed"; + var TMP_HTTP_SERVER_NAME = "http.server_name"; + var TMP_HTTP_ROUTE = "http.route"; + var TMP_HTTP_CLIENT_IP = "http.client_ip"; + var TMP_AWS_DYNAMODB_TABLE_NAMES = "aws.dynamodb.table_names"; + var TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = "aws.dynamodb.consumed_capacity"; + var TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = "aws.dynamodb.item_collection_metrics"; + var TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = "aws.dynamodb.provisioned_read_capacity"; + var TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = "aws.dynamodb.provisioned_write_capacity"; + var TMP_AWS_DYNAMODB_CONSISTENT_READ = "aws.dynamodb.consistent_read"; + var TMP_AWS_DYNAMODB_PROJECTION = "aws.dynamodb.projection"; + var TMP_AWS_DYNAMODB_LIMIT = "aws.dynamodb.limit"; + var TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = "aws.dynamodb.attributes_to_get"; + var TMP_AWS_DYNAMODB_INDEX_NAME = "aws.dynamodb.index_name"; + var TMP_AWS_DYNAMODB_SELECT = "aws.dynamodb.select"; + var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = "aws.dynamodb.global_secondary_indexes"; + var TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = "aws.dynamodb.local_secondary_indexes"; + var TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = "aws.dynamodb.exclusive_start_table"; + var TMP_AWS_DYNAMODB_TABLE_COUNT = "aws.dynamodb.table_count"; + var TMP_AWS_DYNAMODB_SCAN_FORWARD = "aws.dynamodb.scan_forward"; + var TMP_AWS_DYNAMODB_SEGMENT = "aws.dynamodb.segment"; + var TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = "aws.dynamodb.total_segments"; + var TMP_AWS_DYNAMODB_COUNT = "aws.dynamodb.count"; + var TMP_AWS_DYNAMODB_SCANNED_COUNT = "aws.dynamodb.scanned_count"; + var TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = "aws.dynamodb.attribute_definitions"; + var TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = "aws.dynamodb.global_secondary_index_updates"; + var TMP_MESSAGING_SYSTEM = "messaging.system"; + var TMP_MESSAGING_DESTINATION = "messaging.destination"; + var TMP_MESSAGING_DESTINATION_KIND = "messaging.destination_kind"; + var TMP_MESSAGING_TEMP_DESTINATION = "messaging.temp_destination"; + var TMP_MESSAGING_PROTOCOL = "messaging.protocol"; + var TMP_MESSAGING_PROTOCOL_VERSION = "messaging.protocol_version"; + var TMP_MESSAGING_URL = "messaging.url"; + var TMP_MESSAGING_MESSAGE_ID = "messaging.message_id"; + var TMP_MESSAGING_CONVERSATION_ID = "messaging.conversation_id"; + var TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = "messaging.message_payload_size_bytes"; + var TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = "messaging.message_payload_compressed_size_bytes"; + var TMP_MESSAGING_OPERATION = "messaging.operation"; + var TMP_MESSAGING_CONSUMER_ID = "messaging.consumer_id"; + var TMP_MESSAGING_RABBITMQ_ROUTING_KEY = "messaging.rabbitmq.routing_key"; + var TMP_MESSAGING_KAFKA_MESSAGE_KEY = "messaging.kafka.message_key"; + var TMP_MESSAGING_KAFKA_CONSUMER_GROUP = "messaging.kafka.consumer_group"; + var TMP_MESSAGING_KAFKA_CLIENT_ID = "messaging.kafka.client_id"; + var TMP_MESSAGING_KAFKA_PARTITION = "messaging.kafka.partition"; + var TMP_MESSAGING_KAFKA_TOMBSTONE = "messaging.kafka.tombstone"; + var TMP_RPC_SYSTEM = "rpc.system"; + var TMP_RPC_SERVICE = "rpc.service"; + var TMP_RPC_METHOD = "rpc.method"; + var TMP_RPC_GRPC_STATUS_CODE = "rpc.grpc.status_code"; + var TMP_RPC_JSONRPC_VERSION = "rpc.jsonrpc.version"; + var TMP_RPC_JSONRPC_REQUEST_ID = "rpc.jsonrpc.request_id"; + var TMP_RPC_JSONRPC_ERROR_CODE = "rpc.jsonrpc.error_code"; + var TMP_RPC_JSONRPC_ERROR_MESSAGE = "rpc.jsonrpc.error_message"; + var TMP_MESSAGE_TYPE = "message.type"; + var TMP_MESSAGE_ID = "message.id"; + var TMP_MESSAGE_COMPRESSED_SIZE = "message.compressed_size"; + var TMP_MESSAGE_UNCOMPRESSED_SIZE = "message.uncompressed_size"; + exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; + exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; + exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; + exports.SEMATTRS_DB_USER = TMP_DB_USER; + exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; + exports.SEMATTRS_DB_NAME = TMP_DB_NAME; + exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; + exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; + exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; + exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; + exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; + exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; + exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; + exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; + exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; + exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; + exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; + exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; + exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; + exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; + exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; + exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; + exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; + exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; + exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; + exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; + exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; + exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; + exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; + exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; + exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; + exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; + exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; + exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; + exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; + exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; + exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; + exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; + exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; + exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; + exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; + exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; + exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; + exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; + exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; + exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; + exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; + exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; + exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; + exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; + exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; + exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; + exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; + exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; + exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID; + exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; + exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; + exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; + exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; + exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; + exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; + exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL; + exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; + exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; + exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; + exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; + exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; + exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; + exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; + exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; + exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; + exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; + exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; + exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; + exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; + exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; + exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; + exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; + exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; + exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; + exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; + exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; + exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; + exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; + exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; + exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; + exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; + exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; + exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; + exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; + exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; + exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; + exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; + exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; + exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; + exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; + exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; + exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; + exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; + exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; + exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; + exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; + exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; + exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; + exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; + exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; + exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; + exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; + exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; + exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; + exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; + exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; + exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; + exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; + exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; + exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; + exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; + exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; + exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; + exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; + exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; + exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; + exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; + exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; + exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; + exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; + exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; + exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; + exports.SemanticAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_AWS_LAMBDA_INVOKED_ARN, + TMP_DB_SYSTEM, + TMP_DB_CONNECTION_STRING, + TMP_DB_USER, + TMP_DB_JDBC_DRIVER_CLASSNAME, + TMP_DB_NAME, + TMP_DB_STATEMENT, + TMP_DB_OPERATION, + TMP_DB_MSSQL_INSTANCE_NAME, + TMP_DB_CASSANDRA_KEYSPACE, + TMP_DB_CASSANDRA_PAGE_SIZE, + TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, + TMP_DB_CASSANDRA_TABLE, + TMP_DB_CASSANDRA_IDEMPOTENCE, + TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, + TMP_DB_CASSANDRA_COORDINATOR_ID, + TMP_DB_CASSANDRA_COORDINATOR_DC, + TMP_DB_HBASE_NAMESPACE, + TMP_DB_REDIS_DATABASE_INDEX, + TMP_DB_MONGODB_COLLECTION, + TMP_DB_SQL_TABLE, + TMP_EXCEPTION_TYPE, + TMP_EXCEPTION_MESSAGE, + TMP_EXCEPTION_STACKTRACE, + TMP_EXCEPTION_ESCAPED, + TMP_FAAS_TRIGGER, + TMP_FAAS_EXECUTION, + TMP_FAAS_DOCUMENT_COLLECTION, + TMP_FAAS_DOCUMENT_OPERATION, + TMP_FAAS_DOCUMENT_TIME, + TMP_FAAS_DOCUMENT_NAME, + TMP_FAAS_TIME, + TMP_FAAS_CRON, + TMP_FAAS_COLDSTART, + TMP_FAAS_INVOKED_NAME, + TMP_FAAS_INVOKED_PROVIDER, + TMP_FAAS_INVOKED_REGION, + TMP_NET_TRANSPORT, + TMP_NET_PEER_IP, + TMP_NET_PEER_PORT, + TMP_NET_PEER_NAME, + TMP_NET_HOST_IP, + TMP_NET_HOST_PORT, + TMP_NET_HOST_NAME, + TMP_NET_HOST_CONNECTION_TYPE, + TMP_NET_HOST_CONNECTION_SUBTYPE, + TMP_NET_HOST_CARRIER_NAME, + TMP_NET_HOST_CARRIER_MCC, + TMP_NET_HOST_CARRIER_MNC, + TMP_NET_HOST_CARRIER_ICC, + TMP_PEER_SERVICE, + TMP_ENDUSER_ID, + TMP_ENDUSER_ROLE, + TMP_ENDUSER_SCOPE, + TMP_THREAD_ID, + TMP_THREAD_NAME, + TMP_CODE_FUNCTION, + TMP_CODE_NAMESPACE, + TMP_CODE_FILEPATH, + TMP_CODE_LINENO, + TMP_HTTP_METHOD, + TMP_HTTP_URL, + TMP_HTTP_TARGET, + TMP_HTTP_HOST, + TMP_HTTP_SCHEME, + TMP_HTTP_STATUS_CODE, + TMP_HTTP_FLAVOR, + TMP_HTTP_USER_AGENT, + TMP_HTTP_REQUEST_CONTENT_LENGTH, + TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_RESPONSE_CONTENT_LENGTH, + TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, + TMP_HTTP_SERVER_NAME, + TMP_HTTP_ROUTE, + TMP_HTTP_CLIENT_IP, + TMP_AWS_DYNAMODB_TABLE_NAMES, + TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, + TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, + TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, + TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, + TMP_AWS_DYNAMODB_CONSISTENT_READ, + TMP_AWS_DYNAMODB_PROJECTION, + TMP_AWS_DYNAMODB_LIMIT, + TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, + TMP_AWS_DYNAMODB_INDEX_NAME, + TMP_AWS_DYNAMODB_SELECT, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, + TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, + TMP_AWS_DYNAMODB_TABLE_COUNT, + TMP_AWS_DYNAMODB_SCAN_FORWARD, + TMP_AWS_DYNAMODB_SEGMENT, + TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, + TMP_AWS_DYNAMODB_COUNT, + TMP_AWS_DYNAMODB_SCANNED_COUNT, + TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, + TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, + TMP_MESSAGING_SYSTEM, + TMP_MESSAGING_DESTINATION, + TMP_MESSAGING_DESTINATION_KIND, + TMP_MESSAGING_TEMP_DESTINATION, + TMP_MESSAGING_PROTOCOL, + TMP_MESSAGING_PROTOCOL_VERSION, + TMP_MESSAGING_URL, + TMP_MESSAGING_MESSAGE_ID, + TMP_MESSAGING_CONVERSATION_ID, + TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, + TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, + TMP_MESSAGING_OPERATION, + TMP_MESSAGING_CONSUMER_ID, + TMP_MESSAGING_RABBITMQ_ROUTING_KEY, + TMP_MESSAGING_KAFKA_MESSAGE_KEY, + TMP_MESSAGING_KAFKA_CONSUMER_GROUP, + TMP_MESSAGING_KAFKA_CLIENT_ID, + TMP_MESSAGING_KAFKA_PARTITION, + TMP_MESSAGING_KAFKA_TOMBSTONE, + TMP_RPC_SYSTEM, + TMP_RPC_SERVICE, + TMP_RPC_METHOD, + TMP_RPC_GRPC_STATUS_CODE, + TMP_RPC_JSONRPC_VERSION, + TMP_RPC_JSONRPC_REQUEST_ID, + TMP_RPC_JSONRPC_ERROR_CODE, + TMP_RPC_JSONRPC_ERROR_MESSAGE, + TMP_MESSAGE_TYPE, + TMP_MESSAGE_ID, + TMP_MESSAGE_COMPRESSED_SIZE, + TMP_MESSAGE_UNCOMPRESSED_SIZE + ]); + var TMP_DBSYSTEMVALUES_OTHER_SQL = "other_sql"; + var TMP_DBSYSTEMVALUES_MSSQL = "mssql"; + var TMP_DBSYSTEMVALUES_MYSQL = "mysql"; + var TMP_DBSYSTEMVALUES_ORACLE = "oracle"; + var TMP_DBSYSTEMVALUES_DB2 = "db2"; + var TMP_DBSYSTEMVALUES_POSTGRESQL = "postgresql"; + var TMP_DBSYSTEMVALUES_REDSHIFT = "redshift"; + var TMP_DBSYSTEMVALUES_HIVE = "hive"; + var TMP_DBSYSTEMVALUES_CLOUDSCAPE = "cloudscape"; + var TMP_DBSYSTEMVALUES_HSQLDB = "hsqldb"; + var TMP_DBSYSTEMVALUES_PROGRESS = "progress"; + var TMP_DBSYSTEMVALUES_MAXDB = "maxdb"; + var TMP_DBSYSTEMVALUES_HANADB = "hanadb"; + var TMP_DBSYSTEMVALUES_INGRES = "ingres"; + var TMP_DBSYSTEMVALUES_FIRSTSQL = "firstsql"; + var TMP_DBSYSTEMVALUES_EDB = "edb"; + var TMP_DBSYSTEMVALUES_CACHE = "cache"; + var TMP_DBSYSTEMVALUES_ADABAS = "adabas"; + var TMP_DBSYSTEMVALUES_FIREBIRD = "firebird"; + var TMP_DBSYSTEMVALUES_DERBY = "derby"; + var TMP_DBSYSTEMVALUES_FILEMAKER = "filemaker"; + var TMP_DBSYSTEMVALUES_INFORMIX = "informix"; + var TMP_DBSYSTEMVALUES_INSTANTDB = "instantdb"; + var TMP_DBSYSTEMVALUES_INTERBASE = "interbase"; + var TMP_DBSYSTEMVALUES_MARIADB = "mariadb"; + var TMP_DBSYSTEMVALUES_NETEZZA = "netezza"; + var TMP_DBSYSTEMVALUES_PERVASIVE = "pervasive"; + var TMP_DBSYSTEMVALUES_POINTBASE = "pointbase"; + var TMP_DBSYSTEMVALUES_SQLITE = "sqlite"; + var TMP_DBSYSTEMVALUES_SYBASE = "sybase"; + var TMP_DBSYSTEMVALUES_TERADATA = "teradata"; + var TMP_DBSYSTEMVALUES_VERTICA = "vertica"; + var TMP_DBSYSTEMVALUES_H2 = "h2"; + var TMP_DBSYSTEMVALUES_COLDFUSION = "coldfusion"; + var TMP_DBSYSTEMVALUES_CASSANDRA = "cassandra"; + var TMP_DBSYSTEMVALUES_HBASE = "hbase"; + var TMP_DBSYSTEMVALUES_MONGODB = "mongodb"; + var TMP_DBSYSTEMVALUES_REDIS = "redis"; + var TMP_DBSYSTEMVALUES_COUCHBASE = "couchbase"; + var TMP_DBSYSTEMVALUES_COUCHDB = "couchdb"; + var TMP_DBSYSTEMVALUES_COSMOSDB = "cosmosdb"; + var TMP_DBSYSTEMVALUES_DYNAMODB = "dynamodb"; + var TMP_DBSYSTEMVALUES_NEO4J = "neo4j"; + var TMP_DBSYSTEMVALUES_GEODE = "geode"; + var TMP_DBSYSTEMVALUES_ELASTICSEARCH = "elasticsearch"; + var TMP_DBSYSTEMVALUES_MEMCACHED = "memcached"; + var TMP_DBSYSTEMVALUES_COCKROACHDB = "cockroachdb"; + exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; + exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; + exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; + exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; + exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; + exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; + exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; + exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; + exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; + exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; + exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; + exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; + exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; + exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; + exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; + exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; + exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; + exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; + exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; + exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; + exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; + exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; + exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; + exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; + exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; + exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; + exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; + exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; + exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; + exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; + exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; + exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; + exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; + exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; + exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; + exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; + exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; + exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; + exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; + exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; + exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; + exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; + exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; + exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; + exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; + exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; + exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; + exports.DbSystemValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_DBSYSTEMVALUES_OTHER_SQL, + TMP_DBSYSTEMVALUES_MSSQL, + TMP_DBSYSTEMVALUES_MYSQL, + TMP_DBSYSTEMVALUES_ORACLE, + TMP_DBSYSTEMVALUES_DB2, + TMP_DBSYSTEMVALUES_POSTGRESQL, + TMP_DBSYSTEMVALUES_REDSHIFT, + TMP_DBSYSTEMVALUES_HIVE, + TMP_DBSYSTEMVALUES_CLOUDSCAPE, + TMP_DBSYSTEMVALUES_HSQLDB, + TMP_DBSYSTEMVALUES_PROGRESS, + TMP_DBSYSTEMVALUES_MAXDB, + TMP_DBSYSTEMVALUES_HANADB, + TMP_DBSYSTEMVALUES_INGRES, + TMP_DBSYSTEMVALUES_FIRSTSQL, + TMP_DBSYSTEMVALUES_EDB, + TMP_DBSYSTEMVALUES_CACHE, + TMP_DBSYSTEMVALUES_ADABAS, + TMP_DBSYSTEMVALUES_FIREBIRD, + TMP_DBSYSTEMVALUES_DERBY, + TMP_DBSYSTEMVALUES_FILEMAKER, + TMP_DBSYSTEMVALUES_INFORMIX, + TMP_DBSYSTEMVALUES_INSTANTDB, + TMP_DBSYSTEMVALUES_INTERBASE, + TMP_DBSYSTEMVALUES_MARIADB, + TMP_DBSYSTEMVALUES_NETEZZA, + TMP_DBSYSTEMVALUES_PERVASIVE, + TMP_DBSYSTEMVALUES_POINTBASE, + TMP_DBSYSTEMVALUES_SQLITE, + TMP_DBSYSTEMVALUES_SYBASE, + TMP_DBSYSTEMVALUES_TERADATA, + TMP_DBSYSTEMVALUES_VERTICA, + TMP_DBSYSTEMVALUES_H2, + TMP_DBSYSTEMVALUES_COLDFUSION, + TMP_DBSYSTEMVALUES_CASSANDRA, + TMP_DBSYSTEMVALUES_HBASE, + TMP_DBSYSTEMVALUES_MONGODB, + TMP_DBSYSTEMVALUES_REDIS, + TMP_DBSYSTEMVALUES_COUCHBASE, + TMP_DBSYSTEMVALUES_COUCHDB, + TMP_DBSYSTEMVALUES_COSMOSDB, + TMP_DBSYSTEMVALUES_DYNAMODB, + TMP_DBSYSTEMVALUES_NEO4J, + TMP_DBSYSTEMVALUES_GEODE, + TMP_DBSYSTEMVALUES_ELASTICSEARCH, + TMP_DBSYSTEMVALUES_MEMCACHED, + TMP_DBSYSTEMVALUES_COCKROACHDB + ]); + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = "all"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = "each_quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = "quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = "local_quorum"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = "one"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = "two"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = "three"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = "local_one"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = "any"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = "serial"; + var TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = "local_serial"; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; + exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; + exports.DbCassandraConsistencyLevelValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, + TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL + ]); + var TMP_FAASTRIGGERVALUES_DATASOURCE = "datasource"; + var TMP_FAASTRIGGERVALUES_HTTP = "http"; + var TMP_FAASTRIGGERVALUES_PUBSUB = "pubsub"; + var TMP_FAASTRIGGERVALUES_TIMER = "timer"; + var TMP_FAASTRIGGERVALUES_OTHER = "other"; + exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; + exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; + exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; + exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; + exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; + exports.FaasTriggerValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASTRIGGERVALUES_DATASOURCE, + TMP_FAASTRIGGERVALUES_HTTP, + TMP_FAASTRIGGERVALUES_PUBSUB, + TMP_FAASTRIGGERVALUES_TIMER, + TMP_FAASTRIGGERVALUES_OTHER + ]); + var TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = "insert"; + var TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = "edit"; + var TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = "delete"; + exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; + exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; + exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; + exports.FaasDocumentOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, + TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, + TMP_FAASDOCUMENTOPERATIONVALUES_DELETE + ]); + var TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + var TMP_FAASINVOKEDPROVIDERVALUES_AWS = "aws"; + var TMP_FAASINVOKEDPROVIDERVALUES_AZURE = "azure"; + var TMP_FAASINVOKEDPROVIDERVALUES_GCP = "gcp"; + exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; + exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; + exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; + exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; + exports.FaasInvokedProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_FAASINVOKEDPROVIDERVALUES_AWS, + TMP_FAASINVOKEDPROVIDERVALUES_AZURE, + TMP_FAASINVOKEDPROVIDERVALUES_GCP + ]); + var TMP_NETTRANSPORTVALUES_IP_TCP = "ip_tcp"; + var TMP_NETTRANSPORTVALUES_IP_UDP = "ip_udp"; + var TMP_NETTRANSPORTVALUES_IP = "ip"; + var TMP_NETTRANSPORTVALUES_UNIX = "unix"; + var TMP_NETTRANSPORTVALUES_PIPE = "pipe"; + var TMP_NETTRANSPORTVALUES_INPROC = "inproc"; + var TMP_NETTRANSPORTVALUES_OTHER = "other"; + exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; + exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; + exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; + exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; + exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; + exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; + exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; + exports.NetTransportValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETTRANSPORTVALUES_IP_TCP, + TMP_NETTRANSPORTVALUES_IP_UDP, + TMP_NETTRANSPORTVALUES_IP, + TMP_NETTRANSPORTVALUES_UNIX, + TMP_NETTRANSPORTVALUES_PIPE, + TMP_NETTRANSPORTVALUES_INPROC, + TMP_NETTRANSPORTVALUES_OTHER + ]); + var TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = "wifi"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = "wired"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = "cell"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = "unavailable"; + var TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = "unknown"; + exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; + exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; + exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; + exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; + exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; + exports.NetHostConnectionTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, + TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, + TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, + TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN + ]); + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = "gprs"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = "edge"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = "umts"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = "cdma"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = "evdo_0"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = "evdo_a"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = "cdma2000_1xrtt"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = "hsdpa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = "hsupa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = "hspa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = "iden"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = "evdo_b"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = "lte"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = "ehrpd"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = "hspap"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = "gsm"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = "td_scdma"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = "iwlan"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = "nr"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = "nrnsa"; + var TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = "lte_ca"; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; + exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; + exports.NetHostConnectionSubtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, + TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA + ]); + var TMP_HTTPFLAVORVALUES_HTTP_1_0 = "1.0"; + var TMP_HTTPFLAVORVALUES_HTTP_1_1 = "1.1"; + var TMP_HTTPFLAVORVALUES_HTTP_2_0 = "2.0"; + var TMP_HTTPFLAVORVALUES_SPDY = "SPDY"; + var TMP_HTTPFLAVORVALUES_QUIC = "QUIC"; + exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; + exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; + exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; + exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; + exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; + exports.HttpFlavorValues = { + HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, + HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, + HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, + SPDY: TMP_HTTPFLAVORVALUES_SPDY, + QUIC: TMP_HTTPFLAVORVALUES_QUIC + }; + var TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = "queue"; + var TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = "topic"; + exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; + exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; + exports.MessagingDestinationKindValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, + TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC + ]); + var TMP_MESSAGINGOPERATIONVALUES_RECEIVE = "receive"; + var TMP_MESSAGINGOPERATIONVALUES_PROCESS = "process"; + exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; + exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; + exports.MessagingOperationValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGINGOPERATIONVALUES_RECEIVE, + TMP_MESSAGINGOPERATIONVALUES_PROCESS + ]); + var TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; + var TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; + var TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; + var TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; + var TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; + var TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; + var TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; + var TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; + var TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; + var TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; + var TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; + var TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; + var TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; + var TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; + var TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; + var TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; + var TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; + exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; + exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; + exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; + exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; + exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; + exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; + exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; + exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; + exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; + exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; + exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; + exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; + exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; + exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; + exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; + exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; + exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; + exports.RpcGrpcStatusCodeValues = { + OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, + CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, + UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, + INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, + DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, + NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, + ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, + PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, + RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, + FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, + ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, + OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, + UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, + INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, + UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, + DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, + UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED + }; + var TMP_MESSAGETYPEVALUES_SENT = "SENT"; + var TMP_MESSAGETYPEVALUES_RECEIVED = "RECEIVED"; + exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; + exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; + exports.MessageTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_MESSAGETYPEVALUES_SENT, + TMP_MESSAGETYPEVALUES_RECEIVED + ]); +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js +var require_trace2 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_SemanticAttributes(), exports); +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js +var require_SemanticResourceAttributes = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = undefined; + exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = undefined; + exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = undefined; + var utils_1 = require_utils4(); + var TMP_CLOUD_PROVIDER = "cloud.provider"; + var TMP_CLOUD_ACCOUNT_ID = "cloud.account.id"; + var TMP_CLOUD_REGION = "cloud.region"; + var TMP_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; + var TMP_CLOUD_PLATFORM = "cloud.platform"; + var TMP_AWS_ECS_CONTAINER_ARN = "aws.ecs.container.arn"; + var TMP_AWS_ECS_CLUSTER_ARN = "aws.ecs.cluster.arn"; + var TMP_AWS_ECS_LAUNCHTYPE = "aws.ecs.launchtype"; + var TMP_AWS_ECS_TASK_ARN = "aws.ecs.task.arn"; + var TMP_AWS_ECS_TASK_FAMILY = "aws.ecs.task.family"; + var TMP_AWS_ECS_TASK_REVISION = "aws.ecs.task.revision"; + var TMP_AWS_EKS_CLUSTER_ARN = "aws.eks.cluster.arn"; + var TMP_AWS_LOG_GROUP_NAMES = "aws.log.group.names"; + var TMP_AWS_LOG_GROUP_ARNS = "aws.log.group.arns"; + var TMP_AWS_LOG_STREAM_NAMES = "aws.log.stream.names"; + var TMP_AWS_LOG_STREAM_ARNS = "aws.log.stream.arns"; + var TMP_CONTAINER_NAME = "container.name"; + var TMP_CONTAINER_ID = "container.id"; + var TMP_CONTAINER_RUNTIME = "container.runtime"; + var TMP_CONTAINER_IMAGE_NAME = "container.image.name"; + var TMP_CONTAINER_IMAGE_TAG = "container.image.tag"; + var TMP_DEPLOYMENT_ENVIRONMENT = "deployment.environment"; + var TMP_DEVICE_ID = "device.id"; + var TMP_DEVICE_MODEL_IDENTIFIER = "device.model.identifier"; + var TMP_DEVICE_MODEL_NAME = "device.model.name"; + var TMP_FAAS_NAME = "faas.name"; + var TMP_FAAS_ID = "faas.id"; + var TMP_FAAS_VERSION = "faas.version"; + var TMP_FAAS_INSTANCE = "faas.instance"; + var TMP_FAAS_MAX_MEMORY = "faas.max_memory"; + var TMP_HOST_ID = "host.id"; + var TMP_HOST_NAME = "host.name"; + var TMP_HOST_TYPE = "host.type"; + var TMP_HOST_ARCH = "host.arch"; + var TMP_HOST_IMAGE_NAME = "host.image.name"; + var TMP_HOST_IMAGE_ID = "host.image.id"; + var TMP_HOST_IMAGE_VERSION = "host.image.version"; + var TMP_K8S_CLUSTER_NAME = "k8s.cluster.name"; + var TMP_K8S_NODE_NAME = "k8s.node.name"; + var TMP_K8S_NODE_UID = "k8s.node.uid"; + var TMP_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + var TMP_K8S_POD_UID = "k8s.pod.uid"; + var TMP_K8S_POD_NAME = "k8s.pod.name"; + var TMP_K8S_CONTAINER_NAME = "k8s.container.name"; + var TMP_K8S_REPLICASET_UID = "k8s.replicaset.uid"; + var TMP_K8S_REPLICASET_NAME = "k8s.replicaset.name"; + var TMP_K8S_DEPLOYMENT_UID = "k8s.deployment.uid"; + var TMP_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + var TMP_K8S_STATEFULSET_UID = "k8s.statefulset.uid"; + var TMP_K8S_STATEFULSET_NAME = "k8s.statefulset.name"; + var TMP_K8S_DAEMONSET_UID = "k8s.daemonset.uid"; + var TMP_K8S_DAEMONSET_NAME = "k8s.daemonset.name"; + var TMP_K8S_JOB_UID = "k8s.job.uid"; + var TMP_K8S_JOB_NAME = "k8s.job.name"; + var TMP_K8S_CRONJOB_UID = "k8s.cronjob.uid"; + var TMP_K8S_CRONJOB_NAME = "k8s.cronjob.name"; + var TMP_OS_TYPE = "os.type"; + var TMP_OS_DESCRIPTION = "os.description"; + var TMP_OS_NAME = "os.name"; + var TMP_OS_VERSION = "os.version"; + var TMP_PROCESS_PID = "process.pid"; + var TMP_PROCESS_EXECUTABLE_NAME = "process.executable.name"; + var TMP_PROCESS_EXECUTABLE_PATH = "process.executable.path"; + var TMP_PROCESS_COMMAND = "process.command"; + var TMP_PROCESS_COMMAND_LINE = "process.command_line"; + var TMP_PROCESS_COMMAND_ARGS = "process.command_args"; + var TMP_PROCESS_OWNER = "process.owner"; + var TMP_PROCESS_RUNTIME_NAME = "process.runtime.name"; + var TMP_PROCESS_RUNTIME_VERSION = "process.runtime.version"; + var TMP_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; + var TMP_SERVICE_NAME = "service.name"; + var TMP_SERVICE_NAMESPACE = "service.namespace"; + var TMP_SERVICE_INSTANCE_ID = "service.instance.id"; + var TMP_SERVICE_VERSION = "service.version"; + var TMP_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + var TMP_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + var TMP_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + var TMP_TELEMETRY_AUTO_VERSION = "telemetry.auto.version"; + var TMP_WEBENGINE_NAME = "webengine.name"; + var TMP_WEBENGINE_VERSION = "webengine.version"; + var TMP_WEBENGINE_DESCRIPTION = "webengine.description"; + exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; + exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; + exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; + exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; + exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; + exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; + exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; + exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; + exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; + exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; + exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; + exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; + exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; + exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; + exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; + exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; + exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; + exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; + exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; + exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; + exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; + exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; + exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; + exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; + exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; + exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; + exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; + exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; + exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; + exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; + exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID; + exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; + exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; + exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; + exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; + exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; + exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; + exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; + exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; + exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; + exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; + exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; + exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; + exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; + exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; + exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; + exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; + exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; + exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; + exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; + exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; + exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; + exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; + exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; + exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; + exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; + exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; + exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; + exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME; + exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; + exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; + exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; + exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; + exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; + exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; + exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; + exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; + exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; + exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; + exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; + exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; + exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; + exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; + exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; + exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; + exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; + exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; + exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; + exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; + exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; + exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; + exports.SemanticResourceAttributes = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUD_PROVIDER, + TMP_CLOUD_ACCOUNT_ID, + TMP_CLOUD_REGION, + TMP_CLOUD_AVAILABILITY_ZONE, + TMP_CLOUD_PLATFORM, + TMP_AWS_ECS_CONTAINER_ARN, + TMP_AWS_ECS_CLUSTER_ARN, + TMP_AWS_ECS_LAUNCHTYPE, + TMP_AWS_ECS_TASK_ARN, + TMP_AWS_ECS_TASK_FAMILY, + TMP_AWS_ECS_TASK_REVISION, + TMP_AWS_EKS_CLUSTER_ARN, + TMP_AWS_LOG_GROUP_NAMES, + TMP_AWS_LOG_GROUP_ARNS, + TMP_AWS_LOG_STREAM_NAMES, + TMP_AWS_LOG_STREAM_ARNS, + TMP_CONTAINER_NAME, + TMP_CONTAINER_ID, + TMP_CONTAINER_RUNTIME, + TMP_CONTAINER_IMAGE_NAME, + TMP_CONTAINER_IMAGE_TAG, + TMP_DEPLOYMENT_ENVIRONMENT, + TMP_DEVICE_ID, + TMP_DEVICE_MODEL_IDENTIFIER, + TMP_DEVICE_MODEL_NAME, + TMP_FAAS_NAME, + TMP_FAAS_ID, + TMP_FAAS_VERSION, + TMP_FAAS_INSTANCE, + TMP_FAAS_MAX_MEMORY, + TMP_HOST_ID, + TMP_HOST_NAME, + TMP_HOST_TYPE, + TMP_HOST_ARCH, + TMP_HOST_IMAGE_NAME, + TMP_HOST_IMAGE_ID, + TMP_HOST_IMAGE_VERSION, + TMP_K8S_CLUSTER_NAME, + TMP_K8S_NODE_NAME, + TMP_K8S_NODE_UID, + TMP_K8S_NAMESPACE_NAME, + TMP_K8S_POD_UID, + TMP_K8S_POD_NAME, + TMP_K8S_CONTAINER_NAME, + TMP_K8S_REPLICASET_UID, + TMP_K8S_REPLICASET_NAME, + TMP_K8S_DEPLOYMENT_UID, + TMP_K8S_DEPLOYMENT_NAME, + TMP_K8S_STATEFULSET_UID, + TMP_K8S_STATEFULSET_NAME, + TMP_K8S_DAEMONSET_UID, + TMP_K8S_DAEMONSET_NAME, + TMP_K8S_JOB_UID, + TMP_K8S_JOB_NAME, + TMP_K8S_CRONJOB_UID, + TMP_K8S_CRONJOB_NAME, + TMP_OS_TYPE, + TMP_OS_DESCRIPTION, + TMP_OS_NAME, + TMP_OS_VERSION, + TMP_PROCESS_PID, + TMP_PROCESS_EXECUTABLE_NAME, + TMP_PROCESS_EXECUTABLE_PATH, + TMP_PROCESS_COMMAND, + TMP_PROCESS_COMMAND_LINE, + TMP_PROCESS_COMMAND_ARGS, + TMP_PROCESS_OWNER, + TMP_PROCESS_RUNTIME_NAME, + TMP_PROCESS_RUNTIME_VERSION, + TMP_PROCESS_RUNTIME_DESCRIPTION, + TMP_SERVICE_NAME, + TMP_SERVICE_NAMESPACE, + TMP_SERVICE_INSTANCE_ID, + TMP_SERVICE_VERSION, + TMP_TELEMETRY_SDK_NAME, + TMP_TELEMETRY_SDK_LANGUAGE, + TMP_TELEMETRY_SDK_VERSION, + TMP_TELEMETRY_AUTO_VERSION, + TMP_WEBENGINE_NAME, + TMP_WEBENGINE_VERSION, + TMP_WEBENGINE_DESCRIPTION + ]); + var TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = "alibaba_cloud"; + var TMP_CLOUDPROVIDERVALUES_AWS = "aws"; + var TMP_CLOUDPROVIDERVALUES_AZURE = "azure"; + var TMP_CLOUDPROVIDERVALUES_GCP = "gcp"; + exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; + exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; + exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; + exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; + exports.CloudProviderValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, + TMP_CLOUDPROVIDERVALUES_AWS, + TMP_CLOUDPROVIDERVALUES_AZURE, + TMP_CLOUDPROVIDERVALUES_GCP + ]); + var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; + var TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; + var TMP_CLOUDPLATFORMVALUES_AWS_EC2 = "aws_ec2"; + var TMP_CLOUDPLATFORMVALUES_AWS_ECS = "aws_ecs"; + var TMP_CLOUDPLATFORMVALUES_AWS_EKS = "aws_eks"; + var TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = "aws_lambda"; + var TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; + var TMP_CLOUDPLATFORMVALUES_AZURE_VM = "azure_vm"; + var TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = "azure_container_instances"; + var TMP_CLOUDPLATFORMVALUES_AZURE_AKS = "azure_aks"; + var TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = "azure_functions"; + var TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = "azure_app_service"; + var TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = "gcp_compute_engine"; + var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = "gcp_cloud_run"; + var TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; + var TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; + var TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = "gcp_app_engine"; + exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; + exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; + exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; + exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; + exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; + exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; + exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; + exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; + exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; + exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; + exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; + exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; + exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; + exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; + exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; + exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; + exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; + exports.CloudPlatformValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, + TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, + TMP_CLOUDPLATFORMVALUES_AWS_EC2, + TMP_CLOUDPLATFORMVALUES_AWS_ECS, + TMP_CLOUDPLATFORMVALUES_AWS_EKS, + TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, + TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, + TMP_CLOUDPLATFORMVALUES_AZURE_VM, + TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, + TMP_CLOUDPLATFORMVALUES_AZURE_AKS, + TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, + TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, + TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, + TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, + TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE + ]); + var TMP_AWSECSLAUNCHTYPEVALUES_EC2 = "ec2"; + var TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = "fargate"; + exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; + exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; + exports.AwsEcsLaunchtypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_AWSECSLAUNCHTYPEVALUES_EC2, + TMP_AWSECSLAUNCHTYPEVALUES_FARGATE + ]); + var TMP_HOSTARCHVALUES_AMD64 = "amd64"; + var TMP_HOSTARCHVALUES_ARM32 = "arm32"; + var TMP_HOSTARCHVALUES_ARM64 = "arm64"; + var TMP_HOSTARCHVALUES_IA64 = "ia64"; + var TMP_HOSTARCHVALUES_PPC32 = "ppc32"; + var TMP_HOSTARCHVALUES_PPC64 = "ppc64"; + var TMP_HOSTARCHVALUES_X86 = "x86"; + exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; + exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; + exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; + exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; + exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; + exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; + exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; + exports.HostArchValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_HOSTARCHVALUES_AMD64, + TMP_HOSTARCHVALUES_ARM32, + TMP_HOSTARCHVALUES_ARM64, + TMP_HOSTARCHVALUES_IA64, + TMP_HOSTARCHVALUES_PPC32, + TMP_HOSTARCHVALUES_PPC64, + TMP_HOSTARCHVALUES_X86 + ]); + var TMP_OSTYPEVALUES_WINDOWS = "windows"; + var TMP_OSTYPEVALUES_LINUX = "linux"; + var TMP_OSTYPEVALUES_DARWIN = "darwin"; + var TMP_OSTYPEVALUES_FREEBSD = "freebsd"; + var TMP_OSTYPEVALUES_NETBSD = "netbsd"; + var TMP_OSTYPEVALUES_OPENBSD = "openbsd"; + var TMP_OSTYPEVALUES_DRAGONFLYBSD = "dragonflybsd"; + var TMP_OSTYPEVALUES_HPUX = "hpux"; + var TMP_OSTYPEVALUES_AIX = "aix"; + var TMP_OSTYPEVALUES_SOLARIS = "solaris"; + var TMP_OSTYPEVALUES_Z_OS = "z_os"; + exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; + exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; + exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; + exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; + exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; + exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; + exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; + exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; + exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; + exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; + exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; + exports.OsTypeValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_OSTYPEVALUES_WINDOWS, + TMP_OSTYPEVALUES_LINUX, + TMP_OSTYPEVALUES_DARWIN, + TMP_OSTYPEVALUES_FREEBSD, + TMP_OSTYPEVALUES_NETBSD, + TMP_OSTYPEVALUES_OPENBSD, + TMP_OSTYPEVALUES_DRAGONFLYBSD, + TMP_OSTYPEVALUES_HPUX, + TMP_OSTYPEVALUES_AIX, + TMP_OSTYPEVALUES_SOLARIS, + TMP_OSTYPEVALUES_Z_OS + ]); + var TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = "cpp"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = "dotnet"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = "erlang"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_GO = "go"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = "java"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = "nodejs"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = "php"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = "python"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = "ruby"; + var TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = "webjs"; + exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; + exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; + exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; + exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; + exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; + exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; + exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; + exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; + exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; + exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; + exports.TelemetrySdkLanguageValues = /* @__PURE__ */ (0, utils_1.createConstMap)([ + TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, + TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, + TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, + TMP_TELEMETRYSDKLANGUAGEVALUES_GO, + TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, + TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, + TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, + TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, + TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, + TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS + ]); +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js +var require_resource = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_SemanticResourceAttributes(), exports); +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js +var require_stable_attributes = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_ERROR_TYPE = exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = exports.ATTR_DOTNET_GC_HEAP_GENERATION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = exports.DB_SYSTEM_NAME_VALUE_MYSQL = exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = exports.DB_SYSTEM_NAME_VALUE_MARIADB = exports.ATTR_DB_SYSTEM_NAME = exports.ATTR_DB_STORED_PROCEDURE_NAME = exports.ATTR_DB_RESPONSE_STATUS_CODE = exports.ATTR_DB_QUERY_TEXT = exports.ATTR_DB_QUERY_SUMMARY = exports.ATTR_DB_OPERATION_NAME = exports.ATTR_DB_OPERATION_BATCH_SIZE = exports.ATTR_DB_NAMESPACE = exports.ATTR_DB_COLLECTION_NAME = exports.ATTR_CODE_STACKTRACE = exports.ATTR_CODE_LINE_NUMBER = exports.ATTR_CODE_FUNCTION_NAME = exports.ATTR_CODE_FILE_PATH = exports.ATTR_CODE_COLUMN_NUMBER = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = undefined; + exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = undefined; + exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.ATTR_TELEMETRY_DISTRO_VERSION = exports.ATTR_TELEMETRY_DISTRO_NAME = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.ATTR_OTEL_EVENT_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = undefined; + exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = "aspnetcore.diagnostics.exception.result"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; + exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; + exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = "aspnetcore.diagnostics.handler.type"; + exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = "aspnetcore.rate_limiting.policy"; + exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = "aspnetcore.rate_limiting.result"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; + exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; + exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = "aspnetcore.request.is_unhandled"; + exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = "aspnetcore.routing.is_fallback"; + exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = "aspnetcore.routing.match_status"; + exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; + exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; + exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = "aspnetcore.user.is_authenticated"; + exports.ATTR_CLIENT_ADDRESS = "client.address"; + exports.ATTR_CLIENT_PORT = "client.port"; + exports.ATTR_CODE_COLUMN_NUMBER = "code.column.number"; + exports.ATTR_CODE_FILE_PATH = "code.file.path"; + exports.ATTR_CODE_FUNCTION_NAME = "code.function.name"; + exports.ATTR_CODE_LINE_NUMBER = "code.line.number"; + exports.ATTR_CODE_STACKTRACE = "code.stacktrace"; + exports.ATTR_DB_COLLECTION_NAME = "db.collection.name"; + exports.ATTR_DB_NAMESPACE = "db.namespace"; + exports.ATTR_DB_OPERATION_BATCH_SIZE = "db.operation.batch.size"; + exports.ATTR_DB_OPERATION_NAME = "db.operation.name"; + exports.ATTR_DB_QUERY_SUMMARY = "db.query.summary"; + exports.ATTR_DB_QUERY_TEXT = "db.query.text"; + exports.ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code"; + exports.ATTR_DB_STORED_PROCEDURE_NAME = "db.stored_procedure.name"; + exports.ATTR_DB_SYSTEM_NAME = "db.system.name"; + exports.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; + exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; + exports.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; + exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; + exports.ATTR_DEPLOYMENT_ENVIRONMENT_NAME = "deployment.environment.name"; + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_DEVELOPMENT = "development"; + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_PRODUCTION = "production"; + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_STAGING = "staging"; + exports.DEPLOYMENT_ENVIRONMENT_NAME_VALUE_TEST = "test"; + exports.ATTR_DOTNET_GC_HEAP_GENERATION = "dotnet.gc.heap.generation"; + exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; + exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; + exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; + exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; + exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; + exports.ATTR_ERROR_TYPE = "error.type"; + exports.ERROR_TYPE_VALUE_OTHER = "_OTHER"; + exports.ATTR_EXCEPTION_ESCAPED = "exception.escaped"; + exports.ATTR_EXCEPTION_MESSAGE = "exception.message"; + exports.ATTR_EXCEPTION_STACKTRACE = "exception.stacktrace"; + exports.ATTR_EXCEPTION_TYPE = "exception.type"; + var ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; + exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; + exports.ATTR_HTTP_REQUEST_METHOD = "http.request.method"; + exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; + exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; + exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; + exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; + exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; + exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; + exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; + exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; + exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; + exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; + exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original"; + exports.ATTR_HTTP_REQUEST_RESEND_COUNT = "http.request.resend_count"; + var ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; + exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; + exports.ATTR_HTTP_RESPONSE_STATUS_CODE = "http.response.status_code"; + exports.ATTR_HTTP_ROUTE = "http.route"; + exports.ATTR_JVM_GC_ACTION = "jvm.gc.action"; + exports.ATTR_JVM_GC_NAME = "jvm.gc.name"; + exports.ATTR_JVM_MEMORY_POOL_NAME = "jvm.memory.pool.name"; + exports.ATTR_JVM_MEMORY_TYPE = "jvm.memory.type"; + exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; + exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; + exports.ATTR_JVM_THREAD_DAEMON = "jvm.thread.daemon"; + exports.ATTR_JVM_THREAD_STATE = "jvm.thread.state"; + exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; + exports.JVM_THREAD_STATE_VALUE_NEW = "new"; + exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; + exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; + exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; + exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; + exports.ATTR_NETWORK_LOCAL_ADDRESS = "network.local.address"; + exports.ATTR_NETWORK_LOCAL_PORT = "network.local.port"; + exports.ATTR_NETWORK_PEER_ADDRESS = "network.peer.address"; + exports.ATTR_NETWORK_PEER_PORT = "network.peer.port"; + exports.ATTR_NETWORK_PROTOCOL_NAME = "network.protocol.name"; + exports.ATTR_NETWORK_PROTOCOL_VERSION = "network.protocol.version"; + exports.ATTR_NETWORK_TRANSPORT = "network.transport"; + exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; + exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; + exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; + exports.NETWORK_TRANSPORT_VALUE_UDP = "udp"; + exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; + exports.ATTR_NETWORK_TYPE = "network.type"; + exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; + exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; + exports.ATTR_OTEL_EVENT_NAME = "otel.event.name"; + exports.ATTR_OTEL_SCOPE_NAME = "otel.scope.name"; + exports.ATTR_OTEL_SCOPE_VERSION = "otel.scope.version"; + exports.ATTR_OTEL_STATUS_CODE = "otel.status_code"; + exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; + exports.OTEL_STATUS_CODE_VALUE_OK = "OK"; + exports.ATTR_OTEL_STATUS_DESCRIPTION = "otel.status_description"; + exports.ATTR_SERVER_ADDRESS = "server.address"; + exports.ATTR_SERVER_PORT = "server.port"; + exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; + exports.ATTR_SERVICE_NAME = "service.name"; + exports.ATTR_SERVICE_NAMESPACE = "service.namespace"; + exports.ATTR_SERVICE_VERSION = "service.version"; + exports.ATTR_SIGNALR_CONNECTION_STATUS = "signalr.connection.status"; + exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; + exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; + exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; + exports.ATTR_SIGNALR_TRANSPORT = "signalr.transport"; + exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; + exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; + exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; + exports.ATTR_TELEMETRY_DISTRO_NAME = "telemetry.distro.name"; + exports.ATTR_TELEMETRY_DISTRO_VERSION = "telemetry.distro.version"; + exports.ATTR_TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; + exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; + exports.ATTR_TELEMETRY_SDK_NAME = "telemetry.sdk.name"; + exports.ATTR_TELEMETRY_SDK_VERSION = "telemetry.sdk.version"; + exports.ATTR_URL_FRAGMENT = "url.fragment"; + exports.ATTR_URL_FULL = "url.full"; + exports.ATTR_URL_PATH = "url.path"; + exports.ATTR_URL_QUERY = "url.query"; + exports.ATTR_URL_SCHEME = "url.scheme"; + exports.ATTR_USER_AGENT_ORIGINAL = "user_agent.original"; +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js +var require_stable_metrics = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_DOTNET_TIMER_COUNT = exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = exports.METRIC_DOTNET_PROCESS_CPU_TIME = exports.METRIC_DOTNET_PROCESS_CPU_COUNT = exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = exports.METRIC_DOTNET_JIT_COMPILED_METHODS = exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = exports.METRIC_DOTNET_JIT_COMPILATION_TIME = exports.METRIC_DOTNET_GC_PAUSE_TIME = exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = exports.METRIC_DOTNET_GC_COLLECTIONS = exports.METRIC_DOTNET_EXCEPTIONS = exports.METRIC_DOTNET_ASSEMBLY_COUNT = exports.METRIC_DB_CLIENT_OPERATION_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = undefined; + exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = undefined; + exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = "aspnetcore.diagnostics.exceptions"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = "aspnetcore.rate_limiting.active_request_leases"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = "aspnetcore.rate_limiting.queued_requests"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = "aspnetcore.rate_limiting.request.time_in_queue"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = "aspnetcore.rate_limiting.request_lease.duration"; + exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = "aspnetcore.rate_limiting.requests"; + exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = "aspnetcore.routing.match_attempts"; + exports.METRIC_DB_CLIENT_OPERATION_DURATION = "db.client.operation.duration"; + exports.METRIC_DOTNET_ASSEMBLY_COUNT = "dotnet.assembly.count"; + exports.METRIC_DOTNET_EXCEPTIONS = "dotnet.exceptions"; + exports.METRIC_DOTNET_GC_COLLECTIONS = "dotnet.gc.collections"; + exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = "dotnet.gc.heap.total_allocated"; + exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = "dotnet.gc.last_collection.heap.fragmentation.size"; + exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = "dotnet.gc.last_collection.heap.size"; + exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = "dotnet.gc.last_collection.memory.committed_size"; + exports.METRIC_DOTNET_GC_PAUSE_TIME = "dotnet.gc.pause.time"; + exports.METRIC_DOTNET_JIT_COMPILATION_TIME = "dotnet.jit.compilation.time"; + exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = "dotnet.jit.compiled_il.size"; + exports.METRIC_DOTNET_JIT_COMPILED_METHODS = "dotnet.jit.compiled_methods"; + exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = "dotnet.monitor.lock_contentions"; + exports.METRIC_DOTNET_PROCESS_CPU_COUNT = "dotnet.process.cpu.count"; + exports.METRIC_DOTNET_PROCESS_CPU_TIME = "dotnet.process.cpu.time"; + exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = "dotnet.process.memory.working_set"; + exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = "dotnet.thread_pool.queue.length"; + exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = "dotnet.thread_pool.thread.count"; + exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = "dotnet.thread_pool.work_item.count"; + exports.METRIC_DOTNET_TIMER_COUNT = "dotnet.timer.count"; + exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = "http.client.request.duration"; + exports.METRIC_HTTP_SERVER_REQUEST_DURATION = "http.server.request.duration"; + exports.METRIC_JVM_CLASS_COUNT = "jvm.class.count"; + exports.METRIC_JVM_CLASS_LOADED = "jvm.class.loaded"; + exports.METRIC_JVM_CLASS_UNLOADED = "jvm.class.unloaded"; + exports.METRIC_JVM_CPU_COUNT = "jvm.cpu.count"; + exports.METRIC_JVM_CPU_RECENT_UTILIZATION = "jvm.cpu.recent_utilization"; + exports.METRIC_JVM_CPU_TIME = "jvm.cpu.time"; + exports.METRIC_JVM_GC_DURATION = "jvm.gc.duration"; + exports.METRIC_JVM_MEMORY_COMMITTED = "jvm.memory.committed"; + exports.METRIC_JVM_MEMORY_LIMIT = "jvm.memory.limit"; + exports.METRIC_JVM_MEMORY_USED = "jvm.memory.used"; + exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = "jvm.memory.used_after_last_gc"; + exports.METRIC_JVM_THREAD_COUNT = "jvm.thread.count"; + exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = "kestrel.active_connections"; + exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = "kestrel.active_tls_handshakes"; + exports.METRIC_KESTREL_CONNECTION_DURATION = "kestrel.connection.duration"; + exports.METRIC_KESTREL_QUEUED_CONNECTIONS = "kestrel.queued_connections"; + exports.METRIC_KESTREL_QUEUED_REQUESTS = "kestrel.queued_requests"; + exports.METRIC_KESTREL_REJECTED_CONNECTIONS = "kestrel.rejected_connections"; + exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = "kestrel.tls_handshake.duration"; + exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = "kestrel.upgraded_connections"; + exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = "signalr.server.active_connections"; + exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = "signalr.server.connection.duration"; +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js +var require_stable_events = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EVENT_EXCEPTION = undefined; + exports.EVENT_EXCEPTION = "exception"; +}); + +// node_modules/@opentelemetry/semantic-conventions/build/src/index.js +var require_src2 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_trace2(), exports); + __exportStar(require_resource(), exports); + __exportStar(require_stable_attributes(), exports); + __exportStar(require_stable_metrics(), exports); + __exportStar(require_stable_events(), exports); +}); + +// node_modules/@opentelemetry/core/build/src/semconv.js +var require_semconv = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_PROCESS_RUNTIME_NAME = undefined; + exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name"; +}); + +// node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js +var require_sdk_info = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDK_INFO = undefined; + var version_1 = require_version3(); + var semantic_conventions_1 = require_src2(); + var semconv_1 = require_semconv(); + exports.SDK_INFO = { + [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: "opentelemetry", + [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "node", + [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: semantic_conventions_1.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, + [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: version_1.VERSION + }; +}); + +// node_modules/@opentelemetry/core/build/src/platform/node/index.js +var require_node = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.otperformance = exports.SDK_INFO = exports._globalThis = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = undefined; + var environment_1 = require_environment(); + Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function() { + return environment_1.getStringFromEnv; + } }); + Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function() { + return environment_1.getBooleanFromEnv; + } }); + Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function() { + return environment_1.getNumberFromEnv; + } }); + Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function() { + return environment_1.getStringListFromEnv; + } }); + var globalThis_1 = require_globalThis(); + Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function() { + return globalThis_1._globalThis; + } }); + var sdk_info_1 = require_sdk_info(); + Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function() { + return sdk_info_1.SDK_INFO; + } }); + exports.otperformance = performance; +}); + +// node_modules/@opentelemetry/core/build/src/platform/index.js +var require_platform = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getStringFromEnv = exports.getBooleanFromEnv = exports.otperformance = exports._globalThis = exports.SDK_INFO = undefined; + var node_1 = require_node(); + Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function() { + return node_1.SDK_INFO; + } }); + Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function() { + return node_1._globalThis; + } }); + Object.defineProperty(exports, "otperformance", { enumerable: true, get: function() { + return node_1.otperformance; + } }); + Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function() { + return node_1.getBooleanFromEnv; + } }); + Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function() { + return node_1.getStringFromEnv; + } }); + Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function() { + return node_1.getNumberFromEnv; + } }); + Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function() { + return node_1.getStringListFromEnv; + } }); +}); + +// node_modules/@opentelemetry/core/build/src/common/time.js +var require_time = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.addHrTimes = exports.isTimeInput = exports.isTimeInputHrTime = exports.hrTimeToSeconds = exports.hrTimeToMilliseconds = exports.hrTimeToMicroseconds = exports.hrTimeToNanoseconds = exports.hrTimeToTimeStamp = exports.hrTimeDuration = exports.timeInputToHrTime = exports.hrTime = exports.getTimeOrigin = exports.millisToHrTime = undefined; + var platform_1 = require_platform(); + var NANOSECOND_DIGITS = 9; + var NANOSECOND_DIGITS_IN_MILLIS = 6; + var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS); + var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); + function millisToHrTime(epochMillis) { + const epochSeconds = epochMillis / 1000; + const seconds = Math.trunc(epochSeconds); + const nanos = Math.round(epochMillis % 1000 * MILLISECONDS_TO_NANOSECONDS); + return [seconds, nanos]; + } + exports.millisToHrTime = millisToHrTime; + function getTimeOrigin() { + return platform_1.otperformance.timeOrigin; + } + exports.getTimeOrigin = getTimeOrigin; + function hrTime(performanceNow) { + const timeOrigin = millisToHrTime(platform_1.otperformance.timeOrigin); + const now = millisToHrTime(typeof performanceNow === "number" ? performanceNow : platform_1.otperformance.now()); + return addHrTimes(timeOrigin, now); + } + exports.hrTime = hrTime; + function timeInputToHrTime(time) { + if (isTimeInputHrTime(time)) { + return time; + } else if (typeof time === "number") { + if (time < platform_1.otperformance.timeOrigin) { + return hrTime(time); + } else { + return millisToHrTime(time); + } + } else if (time instanceof Date) { + return millisToHrTime(time.getTime()); + } else { + throw TypeError("Invalid input type"); + } + } + exports.timeInputToHrTime = timeInputToHrTime; + function hrTimeDuration(startTime, endTime) { + let seconds = endTime[0] - startTime[0]; + let nanos = endTime[1] - startTime[1]; + if (nanos < 0) { + seconds -= 1; + nanos += SECOND_TO_NANOSECONDS; + } + return [seconds, nanos]; + } + exports.hrTimeDuration = hrTimeDuration; + function hrTimeToTimeStamp(time) { + const precision = NANOSECOND_DIGITS; + const tmp = `${"0".repeat(precision)}${time[1]}Z`; + const nanoString = tmp.substring(tmp.length - precision - 1); + const date = new Date(time[0] * 1000).toISOString(); + return date.replace("000Z", nanoString); + } + exports.hrTimeToTimeStamp = hrTimeToTimeStamp; + function hrTimeToNanoseconds(time) { + return time[0] * SECOND_TO_NANOSECONDS + time[1]; + } + exports.hrTimeToNanoseconds = hrTimeToNanoseconds; + function hrTimeToMicroseconds(time) { + return time[0] * 1e6 + time[1] / 1000; + } + exports.hrTimeToMicroseconds = hrTimeToMicroseconds; + function hrTimeToMilliseconds(time) { + return time[0] * 1000 + time[1] / 1e6; + } + exports.hrTimeToMilliseconds = hrTimeToMilliseconds; + function hrTimeToSeconds(time) { + return time[0] + time[1] / SECOND_TO_NANOSECONDS; + } + exports.hrTimeToSeconds = hrTimeToSeconds; + function isTimeInputHrTime(value) { + return Array.isArray(value) && value.length === 2 && typeof value[0] === "number" && typeof value[1] === "number"; + } + exports.isTimeInputHrTime = isTimeInputHrTime; + function isTimeInput(value) { + return isTimeInputHrTime(value) || typeof value === "number" || value instanceof Date; + } + exports.isTimeInput = isTimeInput; + function addHrTimes(time1, time2) { + const out = [time1[0] + time2[0], time1[1] + time2[1]]; + if (out[1] >= SECOND_TO_NANOSECONDS) { + out[1] -= SECOND_TO_NANOSECONDS; + out[0] += 1; + } + return out; + } + exports.addHrTimes = addHrTimes; +}); + +// node_modules/@opentelemetry/core/build/src/common/timer-util.js +var require_timer_util = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.unrefTimer = undefined; + function unrefTimer(timer) { + if (typeof timer !== "number") { + timer.unref(); + } + } + exports.unrefTimer = unrefTimer; +}); + +// node_modules/@opentelemetry/core/build/src/ExportResult.js +var require_ExportResult = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExportResultCode = undefined; + var ExportResultCode; + (function(ExportResultCode2) { + ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS"; + ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED"; + })(ExportResultCode = exports.ExportResultCode || (exports.ExportResultCode = {})); +}); + +// node_modules/@opentelemetry/core/build/src/propagation/composite.js +var require_composite = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompositePropagator = undefined; + var api_1 = require_src(); + + class CompositePropagator { + _propagators; + _fields; + constructor(config = {}) { + this._propagators = config.propagators ?? []; + const fields = new Set; + for (const propagator of this._propagators) { + const propagatorFields = typeof propagator.fields === "function" ? propagator.fields() : []; + for (const field of propagatorFields) { + fields.add(field); + } + } + this._fields = Array.from(fields); + } + inject(context, carrier, setter) { + for (const propagator of this._propagators) { + try { + propagator.inject(context, carrier, setter); + } catch (err) { + api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`); + } + } + } + extract(context, carrier, getter) { + return this._propagators.reduce((ctx, propagator) => { + try { + return propagator.extract(ctx, carrier, getter); + } catch (err) { + api_1.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`); + } + return ctx; + }, context); + } + fields() { + return this._fields.slice(); + } + } + exports.CompositePropagator = CompositePropagator; +}); + +// node_modules/@opentelemetry/core/build/src/internal/validators.js +var require_validators = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateValue = exports.validateKey = undefined; + var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]"; + var VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; + var VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; + var VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); + var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; + var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; + function validateKey(key) { + return VALID_KEY_REGEX.test(key); + } + exports.validateKey = validateKey; + function validateValue(value) { + return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value); + } + exports.validateValue = validateValue; +}); + +// node_modules/@opentelemetry/core/build/src/trace/TraceState.js +var require_TraceState = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceState = undefined; + var validators_1 = require_validators(); + var MAX_TRACE_STATE_ITEMS = 32; + var MAX_TRACE_STATE_LEN = 512; + var LIST_MEMBERS_SEPARATOR = ","; + var LIST_MEMBER_KEY_VALUE_SPLITTER = "="; + + class TraceState { + _length; + _rawTraceState; + _internalState; + constructor(rawTraceState) { + this._rawTraceState = typeof rawTraceState === "string" ? rawTraceState : ""; + this._length = this._rawTraceState.length; + } + set(key, value) { + if (!(0, validators_1.validateKey)(key) || !(0, validators_1.validateValue)(value)) { + return this; + } + const currState = this._getState(); + const currValue = currState.get(key); + let newLength = this._length; + if (typeof currValue === "string") { + newLength += value.length - currValue.length; + } else { + newLength += key.length + value.length + (currState.size > 0 ? 2 : 1); + } + if (newLength > MAX_TRACE_STATE_LEN) { + return this; + } + const newState = new Map(currState); + newState.delete(key); + newState.set(key, value); + return this._fromState(newState, newLength); + } + unset(key) { + const currState = this._getState(); + const currValue = currState.get(key); + if (typeof currValue !== "string") { + return this; + } + let newLength = this._length - (key.length + currValue.length + 1); + if (currState.size > 1) { + newLength = newLength - 1; + } + const newState = new Map(currState); + newState.delete(key); + return this._fromState(newState, newLength); + } + get(key) { + const currState = this._getState(); + return currState.get(key); + } + serialize() { + let serialized = ""; + let index = 0; + for (const entry of this._getState()) { + if (index > 0) { + serialized = LIST_MEMBERS_SEPARATOR + serialized; + } + serialized = `${entry[0]}${LIST_MEMBER_KEY_VALUE_SPLITTER}${entry[1]}` + serialized; + index++; + } + return serialized; + } + _getState() { + if (this._internalState) { + return this._internalState; + } + const vendorMembers = this._rawTraceState.split(LIST_MEMBERS_SEPARATOR); + const vendorEntries = new Map; + let currentLength = 0; + for (const member of vendorMembers) { + const m = member.trim(); + const idx = m.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); + if (idx === -1) { + continue; + } + const key = m.slice(0, idx); + const value = m.slice(idx + 1); + if (!(0, validators_1.validateKey)(key) || !(0, validators_1.validateValue)(value)) { + continue; + } + const futureLength = currentLength + m.length + (vendorEntries.size > 0 ? 1 : 0); + if (futureLength > MAX_TRACE_STATE_LEN) { + continue; + } + vendorEntries.set(key, value); + currentLength = futureLength; + if (vendorEntries.size >= MAX_TRACE_STATE_ITEMS) { + break; + } + } + this._length = currentLength; + this._internalState = new Map(Array.from(vendorEntries.entries()).reverse()); + return this._internalState; + } + _fromState(state, length) { + const traceState = Object.create(TraceState.prototype); + traceState._internalState = state; + traceState._length = length; + return traceState; + } + } + exports.TraceState = TraceState; +}); + +// node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js +var require_W3CTraceContextPropagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.W3CTraceContextPropagator = exports.parseTraceParent = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = undefined; + var api_1 = require_src(); + var suppress_tracing_1 = require_suppress_tracing(); + var TraceState_1 = require_TraceState(); + exports.TRACE_PARENT_HEADER = "traceparent"; + exports.TRACE_STATE_HEADER = "tracestate"; + var VERSION = "00"; + var VERSION_PART = "(?!ff)[\\da-f]{2}"; + var TRACE_ID_PART = "(?![0]{32})[\\da-f]{32}"; + var PARENT_ID_PART = "(?![0]{16})[\\da-f]{16}"; + var FLAGS_PART = "[\\da-f]{2}"; + var TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`); + function parseTraceParent(traceParent) { + const match = TRACE_PARENT_REGEX.exec(traceParent); + if (!match) + return null; + if (match[1] === "00" && match[5]) + return null; + return { + traceId: match[2], + spanId: match[3], + traceFlags: parseInt(match[4], 16) + }; + } + exports.parseTraceParent = parseTraceParent; + + class W3CTraceContextPropagator { + inject(context, carrier, setter) { + const spanContext = api_1.trace.getSpanContext(context); + if (!spanContext || (0, suppress_tracing_1.isTracingSuppressed)(context) || !(0, api_1.isSpanContextValid)(spanContext)) + return; + const traceParent = `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`; + setter.set(carrier, exports.TRACE_PARENT_HEADER, traceParent); + if (spanContext.traceState) { + setter.set(carrier, exports.TRACE_STATE_HEADER, spanContext.traceState.serialize()); + } + } + extract(context, carrier, getter) { + const traceParentHeader = getter.get(carrier, exports.TRACE_PARENT_HEADER); + if (!traceParentHeader) + return context; + const traceParent = Array.isArray(traceParentHeader) ? traceParentHeader[0] : traceParentHeader; + if (typeof traceParent !== "string") + return context; + const spanContext = parseTraceParent(traceParent); + if (!spanContext) + return context; + spanContext.isRemote = true; + const traceStateHeader = getter.get(carrier, exports.TRACE_STATE_HEADER); + if (traceStateHeader) { + const state = Array.isArray(traceStateHeader) ? traceStateHeader.join(",") : traceStateHeader; + spanContext.traceState = new TraceState_1.TraceState(typeof state === "string" ? state : undefined); + } + return api_1.trace.setSpanContext(context, spanContext); + } + fields() { + return [exports.TRACE_PARENT_HEADER, exports.TRACE_STATE_HEADER]; + } + } + exports.W3CTraceContextPropagator = W3CTraceContextPropagator; +}); + +// node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js +var require_rpc_metadata = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRPCMetadata = exports.deleteRPCMetadata = exports.setRPCMetadata = exports.RPCType = undefined; + var api_1 = require_src(); + var RPC_METADATA_KEY = (0, api_1.createContextKey)("OpenTelemetry SDK Context Key RPC_METADATA"); + var RPCType; + (function(RPCType2) { + RPCType2["HTTP"] = "http"; + })(RPCType = exports.RPCType || (exports.RPCType = {})); + function setRPCMetadata(context, meta) { + return context.setValue(RPC_METADATA_KEY, meta); + } + exports.setRPCMetadata = setRPCMetadata; + function deleteRPCMetadata(context) { + return context.deleteValue(RPC_METADATA_KEY); + } + exports.deleteRPCMetadata = deleteRPCMetadata; + function getRPCMetadata(context) { + return context.getValue(RPC_METADATA_KEY); + } + exports.getRPCMetadata = getRPCMetadata; +}); + +// node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js +var require_lodash_merge = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPlainObject = undefined; + var objectTag = "[object Object]"; + var nullTag = "[object Null]"; + var undefinedTag = "[object Undefined]"; + var funcProto = Function.prototype; + var funcToString = funcProto.toString; + var objectCtorString = funcToString.call(Object); + var getPrototypeOf = Object.getPrototypeOf; + var objectProto = Object.prototype; + var hasOwnProperty = objectProto.hasOwnProperty; + var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + var nativeObjectToString = objectProto.toString; + function isPlainObject2(value) { + if (!isObjectLike(value) || baseGetTag(value) !== objectTag) { + return false; + } + const proto = getPrototypeOf(value); + if (proto === null) { + return true; + } + const Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) === objectCtorString; + } + exports.isPlainObject = isPlainObject2; + function isObjectLike(value) { + return value != null && typeof value == "object"; + } + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); + } + function getRawTag(value) { + const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; + let unmasked = false; + try { + value[symToStringTag] = undefined; + unmasked = true; + } catch {} + const result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + function objectToString(value) { + return nativeObjectToString.call(value); + } +}); + +// node_modules/@opentelemetry/core/build/src/utils/merge.js +var require_merge = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.merge = undefined; + var lodash_merge_1 = require_lodash_merge(); + var MAX_LEVEL = 20; + function merge(...args) { + let result = args.shift(); + const objects = new WeakMap; + while (args.length > 0) { + result = mergeTwoObjects(result, args.shift(), 0, objects); + } + return result; + } + exports.merge = merge; + function takeValue(value) { + if (isArray(value)) { + return value.slice(); + } + return value; + } + function mergeTwoObjects(one, two, level = 0, objects) { + let result; + if (level > MAX_LEVEL) { + return; + } + level++; + if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) { + result = takeValue(two); + } else if (isArray(one)) { + result = one.slice(); + if (isArray(two)) { + for (let i = 0, j = two.length;i < j; i++) { + result.push(takeValue(two[i])); + } + } else if (isObject(two)) { + const keys = Object.keys(two); + for (let i = 0, j = keys.length;i < j; i++) { + const key = keys[i]; + if (key === "__proto__" || key === "constructor" || key === "prototype") { + continue; + } + result[key] = takeValue(two[key]); + } + } + } else if (isObject(one)) { + if (isObject(two)) { + if (!shouldMerge(one, two)) { + return two; + } + result = Object.assign({}, one); + const keys = Object.keys(two); + for (let i = 0, j = keys.length;i < j; i++) { + const key = keys[i]; + if (key === "__proto__" || key === "constructor" || key === "prototype") { + continue; + } + const twoValue = two[key]; + if (isPrimitive(twoValue)) { + if (typeof twoValue === "undefined") { + delete result[key]; + } else { + result[key] = twoValue; + } + } else { + const obj1 = result[key]; + const obj2 = twoValue; + if (wasObjectReferenced(one, key, objects) || wasObjectReferenced(two, key, objects)) { + delete result[key]; + } else { + if (isObject(obj1) && isObject(obj2)) { + const arr1 = objects.get(obj1) || []; + const arr2 = objects.get(obj2) || []; + arr1.push({ obj: one, key }); + arr2.push({ obj: two, key }); + objects.set(obj1, arr1); + objects.set(obj2, arr2); + } + result[key] = mergeTwoObjects(result[key], twoValue, level, objects); + } + } + } + } else { + result = two; + } + } + return result; + } + function wasObjectReferenced(obj, key, objects) { + const arr = objects.get(obj[key]) || []; + for (let i = 0, j = arr.length;i < j; i++) { + const info = arr[i]; + if (info.key === key && info.obj === obj) { + return true; + } + } + return false; + } + function isArray(value) { + return Array.isArray(value); + } + function isFunction(value) { + return typeof value === "function"; + } + function isObject(value) { + return !isPrimitive(value) && !isArray(value) && !isFunction(value) && typeof value === "object"; + } + function isPrimitive(value) { + return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined" || value instanceof Date || value instanceof RegExp || value === null; + } + function shouldMerge(one, two) { + if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) { + return false; + } + return true; + } +}); + +// node_modules/@opentelemetry/core/build/src/utils/timeout.js +var require_timeout = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callWithTimeout = exports.TimeoutError = undefined; + + class TimeoutError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, TimeoutError.prototype); + } + } + exports.TimeoutError = TimeoutError; + function callWithTimeout(promise, timeout) { + let timeoutHandle; + const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { + timeoutHandle = setTimeout(function timeoutHandler() { + reject(new TimeoutError("Operation timed out.")); + }, timeout); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }, (reason) => { + clearTimeout(timeoutHandle); + throw reason; + }); + } + exports.callWithTimeout = callWithTimeout; +}); + +// node_modules/@opentelemetry/core/build/src/utils/url.js +var require_url = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isUrlIgnored = exports.urlMatches = undefined; + function urlMatches(url, urlToMatch) { + if (typeof urlToMatch === "string") { + return url === urlToMatch; + } else { + return !!url.match(urlToMatch); + } + } + exports.urlMatches = urlMatches; + function isUrlIgnored(url, ignoredUrls) { + if (!ignoredUrls) { + return false; + } + for (const ignoreUrl of ignoredUrls) { + if (urlMatches(url, ignoreUrl)) { + return true; + } + } + return false; + } + exports.isUrlIgnored = isUrlIgnored; +}); + +// node_modules/@opentelemetry/core/build/src/utils/promise.js +var require_promise = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Deferred = undefined; + + class Deferred { + _promise; + _resolve; + _reject; + constructor() { + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + get promise() { + return this._promise; + } + resolve(val) { + this._resolve(val); + } + reject(err) { + this._reject(err); + } + } + exports.Deferred = Deferred; +}); + +// node_modules/@opentelemetry/core/build/src/utils/callback.js +var require_callback = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BindOnceFuture = undefined; + var promise_1 = require_promise(); + + class BindOnceFuture { + _isCalled = false; + _deferred = new promise_1.Deferred; + _callback; + _that; + constructor(callback, that) { + this._callback = callback; + this._that = that; + } + get isCalled() { + return this._isCalled; + } + get promise() { + return this._deferred.promise; + } + call(...args) { + if (!this._isCalled) { + this._isCalled = true; + try { + Promise.resolve(this._callback.call(this._that, ...args)).then((val) => this._deferred.resolve(val), (err) => this._deferred.reject(err)); + } catch (err) { + this._deferred.reject(err); + } + } + return this._deferred.promise; + } + } + exports.BindOnceFuture = BindOnceFuture; +}); + +// node_modules/@opentelemetry/core/build/src/utils/configuration.js +var require_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.diagLogLevelFromString = undefined; + var api_1 = require_src(); + var logLevelMap = { + ALL: api_1.DiagLogLevel.ALL, + VERBOSE: api_1.DiagLogLevel.VERBOSE, + DEBUG: api_1.DiagLogLevel.DEBUG, + INFO: api_1.DiagLogLevel.INFO, + WARN: api_1.DiagLogLevel.WARN, + ERROR: api_1.DiagLogLevel.ERROR, + NONE: api_1.DiagLogLevel.NONE + }; + function diagLogLevelFromString(value) { + if (value == null) { + return; + } + const resolvedLogLevel = logLevelMap[value.toUpperCase()]; + if (resolvedLogLevel == null) { + api_1.diag.warn(`Unknown log level "${value}", expected one of ${Object.keys(logLevelMap)}, using default`); + return api_1.DiagLogLevel.INFO; + } + return resolvedLogLevel; + } + exports.diagLogLevelFromString = diagLogLevelFromString; +}); + +// node_modules/@opentelemetry/core/build/src/internal/exporter.js +var require_exporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports._export = undefined; + var api_1 = require_src(); + var suppress_tracing_1 = require_suppress_tracing(); + function _export(exporter, arg) { + return new Promise((resolve) => { + api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => { + exporter.export(arg, resolve); + }); + }); + } + exports._export = _export; +}); + +// node_modules/@opentelemetry/core/build/src/index.js +var require_src3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.diagLogLevelFromString = exports.BindOnceFuture = exports.urlMatches = exports.isUrlIgnored = exports.callWithTimeout = exports.TimeoutError = exports.merge = exports.TraceState = exports.unsuppressTracing = exports.suppressTracing = exports.isTracingSuppressed = exports.setRPCMetadata = exports.getRPCMetadata = exports.deleteRPCMetadata = exports.RPCType = exports.parseTraceParent = exports.W3CTraceContextPropagator = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = exports.CompositePropagator = exports.otperformance = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports._globalThis = exports.SDK_INFO = exports.parseKeyPairsIntoRecord = exports.ExportResultCode = exports.unrefTimer = exports.timeInputToHrTime = exports.millisToHrTime = exports.isTimeInputHrTime = exports.isTimeInput = exports.hrTimeToTimeStamp = exports.hrTimeToSeconds = exports.hrTimeToNanoseconds = exports.hrTimeToMilliseconds = exports.hrTimeToMicroseconds = exports.hrTimeDuration = exports.hrTime = exports.getTimeOrigin = exports.addHrTimes = exports.loggingErrorHandler = exports.setGlobalErrorHandler = exports.globalErrorHandler = exports.sanitizeAttributes = exports.isAttributeValue = exports.AnchoredClock = exports.W3CBaggagePropagator = undefined; + exports.internal = undefined; + var W3CBaggagePropagator_1 = require_W3CBaggagePropagator(); + Object.defineProperty(exports, "W3CBaggagePropagator", { enumerable: true, get: function() { + return W3CBaggagePropagator_1.W3CBaggagePropagator; + } }); + var anchored_clock_1 = require_anchored_clock(); + Object.defineProperty(exports, "AnchoredClock", { enumerable: true, get: function() { + return anchored_clock_1.AnchoredClock; + } }); + var attributes_1 = require_attributes(); + Object.defineProperty(exports, "isAttributeValue", { enumerable: true, get: function() { + return attributes_1.isAttributeValue; + } }); + Object.defineProperty(exports, "sanitizeAttributes", { enumerable: true, get: function() { + return attributes_1.sanitizeAttributes; + } }); + var global_error_handler_1 = require_global_error_handler(); + Object.defineProperty(exports, "globalErrorHandler", { enumerable: true, get: function() { + return global_error_handler_1.globalErrorHandler; + } }); + Object.defineProperty(exports, "setGlobalErrorHandler", { enumerable: true, get: function() { + return global_error_handler_1.setGlobalErrorHandler; + } }); + var logging_error_handler_1 = require_logging_error_handler(); + Object.defineProperty(exports, "loggingErrorHandler", { enumerable: true, get: function() { + return logging_error_handler_1.loggingErrorHandler; + } }); + var time_1 = require_time(); + Object.defineProperty(exports, "addHrTimes", { enumerable: true, get: function() { + return time_1.addHrTimes; + } }); + Object.defineProperty(exports, "getTimeOrigin", { enumerable: true, get: function() { + return time_1.getTimeOrigin; + } }); + Object.defineProperty(exports, "hrTime", { enumerable: true, get: function() { + return time_1.hrTime; + } }); + Object.defineProperty(exports, "hrTimeDuration", { enumerable: true, get: function() { + return time_1.hrTimeDuration; + } }); + Object.defineProperty(exports, "hrTimeToMicroseconds", { enumerable: true, get: function() { + return time_1.hrTimeToMicroseconds; + } }); + Object.defineProperty(exports, "hrTimeToMilliseconds", { enumerable: true, get: function() { + return time_1.hrTimeToMilliseconds; + } }); + Object.defineProperty(exports, "hrTimeToNanoseconds", { enumerable: true, get: function() { + return time_1.hrTimeToNanoseconds; + } }); + Object.defineProperty(exports, "hrTimeToSeconds", { enumerable: true, get: function() { + return time_1.hrTimeToSeconds; + } }); + Object.defineProperty(exports, "hrTimeToTimeStamp", { enumerable: true, get: function() { + return time_1.hrTimeToTimeStamp; + } }); + Object.defineProperty(exports, "isTimeInput", { enumerable: true, get: function() { + return time_1.isTimeInput; + } }); + Object.defineProperty(exports, "isTimeInputHrTime", { enumerable: true, get: function() { + return time_1.isTimeInputHrTime; + } }); + Object.defineProperty(exports, "millisToHrTime", { enumerable: true, get: function() { + return time_1.millisToHrTime; + } }); + Object.defineProperty(exports, "timeInputToHrTime", { enumerable: true, get: function() { + return time_1.timeInputToHrTime; + } }); + var timer_util_1 = require_timer_util(); + Object.defineProperty(exports, "unrefTimer", { enumerable: true, get: function() { + return timer_util_1.unrefTimer; + } }); + var ExportResult_1 = require_ExportResult(); + Object.defineProperty(exports, "ExportResultCode", { enumerable: true, get: function() { + return ExportResult_1.ExportResultCode; + } }); + var utils_1 = require_utils3(); + Object.defineProperty(exports, "parseKeyPairsIntoRecord", { enumerable: true, get: function() { + return utils_1.parseKeyPairsIntoRecord; + } }); + var platform_1 = require_platform(); + Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function() { + return platform_1.SDK_INFO; + } }); + Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function() { + return platform_1._globalThis; + } }); + Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function() { + return platform_1.getStringFromEnv; + } }); + Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function() { + return platform_1.getBooleanFromEnv; + } }); + Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function() { + return platform_1.getNumberFromEnv; + } }); + Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function() { + return platform_1.getStringListFromEnv; + } }); + Object.defineProperty(exports, "otperformance", { enumerable: true, get: function() { + return platform_1.otperformance; + } }); + var composite_1 = require_composite(); + Object.defineProperty(exports, "CompositePropagator", { enumerable: true, get: function() { + return composite_1.CompositePropagator; + } }); + var W3CTraceContextPropagator_1 = require_W3CTraceContextPropagator(); + Object.defineProperty(exports, "TRACE_PARENT_HEADER", { enumerable: true, get: function() { + return W3CTraceContextPropagator_1.TRACE_PARENT_HEADER; + } }); + Object.defineProperty(exports, "TRACE_STATE_HEADER", { enumerable: true, get: function() { + return W3CTraceContextPropagator_1.TRACE_STATE_HEADER; + } }); + Object.defineProperty(exports, "W3CTraceContextPropagator", { enumerable: true, get: function() { + return W3CTraceContextPropagator_1.W3CTraceContextPropagator; + } }); + Object.defineProperty(exports, "parseTraceParent", { enumerable: true, get: function() { + return W3CTraceContextPropagator_1.parseTraceParent; + } }); + var rpc_metadata_1 = require_rpc_metadata(); + Object.defineProperty(exports, "RPCType", { enumerable: true, get: function() { + return rpc_metadata_1.RPCType; + } }); + Object.defineProperty(exports, "deleteRPCMetadata", { enumerable: true, get: function() { + return rpc_metadata_1.deleteRPCMetadata; + } }); + Object.defineProperty(exports, "getRPCMetadata", { enumerable: true, get: function() { + return rpc_metadata_1.getRPCMetadata; + } }); + Object.defineProperty(exports, "setRPCMetadata", { enumerable: true, get: function() { + return rpc_metadata_1.setRPCMetadata; + } }); + var suppress_tracing_1 = require_suppress_tracing(); + Object.defineProperty(exports, "isTracingSuppressed", { enumerable: true, get: function() { + return suppress_tracing_1.isTracingSuppressed; + } }); + Object.defineProperty(exports, "suppressTracing", { enumerable: true, get: function() { + return suppress_tracing_1.suppressTracing; + } }); + Object.defineProperty(exports, "unsuppressTracing", { enumerable: true, get: function() { + return suppress_tracing_1.unsuppressTracing; + } }); + var TraceState_1 = require_TraceState(); + Object.defineProperty(exports, "TraceState", { enumerable: true, get: function() { + return TraceState_1.TraceState; + } }); + var merge_1 = require_merge(); + Object.defineProperty(exports, "merge", { enumerable: true, get: function() { + return merge_1.merge; + } }); + var timeout_1 = require_timeout(); + Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function() { + return timeout_1.TimeoutError; + } }); + Object.defineProperty(exports, "callWithTimeout", { enumerable: true, get: function() { + return timeout_1.callWithTimeout; + } }); + var url_1 = require_url(); + Object.defineProperty(exports, "isUrlIgnored", { enumerable: true, get: function() { + return url_1.isUrlIgnored; + } }); + Object.defineProperty(exports, "urlMatches", { enumerable: true, get: function() { + return url_1.urlMatches; + } }); + var callback_1 = require_callback(); + Object.defineProperty(exports, "BindOnceFuture", { enumerable: true, get: function() { + return callback_1.BindOnceFuture; + } }); + var configuration_1 = require_configuration(); + Object.defineProperty(exports, "diagLogLevelFromString", { enumerable: true, get: function() { + return configuration_1.diagLogLevelFromString; + } }); + var exporter_1 = require_exporter(); + exports.internal = { + _export: exporter_1._export + }; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js +var require_OTLPExporterBase = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPExporterBase = undefined; + + class OTLPExporterBase { + _delegate; + constructor(delegate) { + this._delegate = delegate; + } + export(items, resultCallback) { + this._delegate.export(items, resultCallback); + } + forceFlush() { + return this._delegate.forceFlush(); + } + shutdown() { + return this._delegate.shutdown(); + } + } + exports.OTLPExporterBase = OTLPExporterBase; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js +var require_types2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPExporterError = undefined; + + class OTLPExporterError extends Error { + code; + name = "OTLPExporterError"; + data; + constructor(message, code, data) { + super(message); + this.data = data; + this.code = code; + } + } + exports.OTLPExporterError = OTLPExporterError; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js +var require_shared_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSharedConfigurationDefaults = exports.mergeOtlpSharedConfigurationWithDefaults = exports.wrapStaticHeadersInFunction = exports.validateTimeoutMillis = undefined; + function validateTimeoutMillis(timeoutMillis) { + if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) { + return timeoutMillis; + } + throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`); + } + exports.validateTimeoutMillis = validateTimeoutMillis; + function wrapStaticHeadersInFunction(headers) { + if (headers == null) { + return; + } + return async () => headers; + } + exports.wrapStaticHeadersInFunction = wrapStaticHeadersInFunction; + function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? fallbackConfiguration.timeoutMillis ?? defaultConfiguration.timeoutMillis), + concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? fallbackConfiguration.concurrencyLimit ?? defaultConfiguration.concurrencyLimit, + compression: userProvidedConfiguration.compression ?? fallbackConfiguration.compression ?? defaultConfiguration.compression + }; + } + exports.mergeOtlpSharedConfigurationWithDefaults = mergeOtlpSharedConfigurationWithDefaults; + function getSharedConfigurationDefaults() { + return { + timeoutMillis: 1e4, + concurrencyLimit: 30, + compression: "none" + }; + } + exports.getSharedConfigurationDefaults = getSharedConfigurationDefaults; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js +var require_legacy_node_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompressionAlgorithm = undefined; + var CompressionAlgorithm; + (function(CompressionAlgorithm2) { + CompressionAlgorithm2["NONE"] = "none"; + CompressionAlgorithm2["GZIP"] = "gzip"; + })(CompressionAlgorithm = exports.CompressionAlgorithm || (exports.CompressionAlgorithm = {})); +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js +var require_bounded_queue_export_promise_handler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createBoundedQueueExportPromiseHandler = undefined; + + class BoundedQueueExportPromiseHandler { + _concurrencyLimit; + _sendingPromises = []; + constructor(concurrencyLimit) { + this._concurrencyLimit = concurrencyLimit; + } + pushPromise(promise) { + if (this.hasReachedLimit()) { + throw new Error("Concurrency Limit reached"); + } + this._sendingPromises.push(promise); + const popPromise = () => { + const index = this._sendingPromises.indexOf(promise); + this._sendingPromises.splice(index, 1); + }; + promise.then(popPromise, popPromise); + } + hasReachedLimit() { + return this._sendingPromises.length >= this._concurrencyLimit; + } + async awaitAll() { + await Promise.all(this._sendingPromises); + } + } + function createBoundedQueueExportPromiseHandler(options) { + return new BoundedQueueExportPromiseHandler(options.concurrencyLimit); + } + exports.createBoundedQueueExportPromiseHandler = createBoundedQueueExportPromiseHandler; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js +var require_logging_response_handler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createLoggingPartialSuccessResponseHandler = undefined; + var api_1 = require_src(); + function isPartialSuccessResponse(response) { + return Object.prototype.hasOwnProperty.call(response, "partialSuccess"); + } + function createLoggingPartialSuccessResponseHandler() { + return { + handleResponse(response) { + if (response == null || !isPartialSuccessResponse(response) || response.partialSuccess == null || Object.keys(response.partialSuccess).length === 0) { + return; + } + api_1.diag.warn("Received Partial Success response:", JSON.stringify(response.partialSuccess)); + } + }; + } + exports.createLoggingPartialSuccessResponseHandler = createLoggingPartialSuccessResponseHandler; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js +var require_otlp_export_delegate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createOtlpExportDelegate = undefined; + var core_1 = require_src3(); + var types_1 = require_types2(); + var logging_response_handler_1 = require_logging_response_handler(); + var api_1 = require_src(); + + class OTLPExportDelegate { + _diagLogger; + _transport; + _serializer; + _responseHandler; + _promiseQueue; + _timeout; + constructor(transport, serializer, responseHandler, promiseQueue, timeout) { + this._transport = transport; + this._serializer = serializer; + this._responseHandler = responseHandler; + this._promiseQueue = promiseQueue; + this._timeout = timeout; + this._diagLogger = api_1.diag.createComponentLogger({ + namespace: "OTLPExportDelegate" + }); + } + export(internalRepresentation, resultCallback) { + this._diagLogger.debug("items to be sent", internalRepresentation); + if (this._promiseQueue.hasReachedLimit()) { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error("Concurrent export limit reached") + }); + return; + } + const serializedRequest = this._serializer.serializeRequest(internalRepresentation); + if (serializedRequest == null) { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error("Nothing to send") + }); + return; + } + this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then((response) => { + if (response.status === "success") { + if (response.data != null) { + try { + this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data)); + } catch (e) { + this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?", e, response.data); + } + } + resultCallback({ + code: core_1.ExportResultCode.SUCCESS + }); + return; + } else if (response.status === "failure" && response.error) { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: response.error + }); + return; + } else if (response.status === "retryable") { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: response.error ?? new types_1.OTLPExporterError("Export failed with retryable status") + }); + } else { + resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new types_1.OTLPExporterError("Export failed with unknown error") + }); + } + }, (reason) => resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: reason + }))); + } + forceFlush() { + return this._promiseQueue.awaitAll(); + } + async shutdown() { + this._diagLogger.debug("shutdown started"); + await this.forceFlush(); + this._transport.shutdown(); + } + } + function createOtlpExportDelegate(components, settings) { + return new OTLPExportDelegate(components.transport, components.serializer, (0, logging_response_handler_1.createLoggingPartialSuccessResponseHandler)(), components.promiseHandler, settings.timeout); + } + exports.createOtlpExportDelegate = createOtlpExportDelegate; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js +var require_otlp_network_export_delegate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createOtlpNetworkExportDelegate = undefined; + var bounded_queue_export_promise_handler_1 = require_bounded_queue_export_promise_handler(); + var otlp_export_delegate_1 = require_otlp_export_delegate(); + function createOtlpNetworkExportDelegate(options, serializer, transport) { + return (0, otlp_export_delegate_1.createOtlpExportDelegate)({ + transport, + serializer, + promiseHandler: (0, bounded_queue_export_promise_handler_1.createBoundedQueueExportPromiseHandler)(options) + }, { timeout: options.timeoutMillis }); + } + exports.createOtlpNetworkExportDelegate = createOtlpNetworkExportDelegate; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js +var require_src4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createOtlpNetworkExportDelegate = exports.CompressionAlgorithm = exports.getSharedConfigurationDefaults = exports.mergeOtlpSharedConfigurationWithDefaults = exports.OTLPExporterError = exports.OTLPExporterBase = undefined; + var OTLPExporterBase_1 = require_OTLPExporterBase(); + Object.defineProperty(exports, "OTLPExporterBase", { enumerable: true, get: function() { + return OTLPExporterBase_1.OTLPExporterBase; + } }); + var types_1 = require_types2(); + Object.defineProperty(exports, "OTLPExporterError", { enumerable: true, get: function() { + return types_1.OTLPExporterError; + } }); + var shared_configuration_1 = require_shared_configuration(); + Object.defineProperty(exports, "mergeOtlpSharedConfigurationWithDefaults", { enumerable: true, get: function() { + return shared_configuration_1.mergeOtlpSharedConfigurationWithDefaults; + } }); + Object.defineProperty(exports, "getSharedConfigurationDefaults", { enumerable: true, get: function() { + return shared_configuration_1.getSharedConfigurationDefaults; + } }); + var legacy_node_configuration_1 = require_legacy_node_configuration(); + Object.defineProperty(exports, "CompressionAlgorithm", { enumerable: true, get: function() { + return legacy_node_configuration_1.CompressionAlgorithm; + } }); + var otlp_network_export_delegate_1 = require_otlp_network_export_delegate(); + Object.defineProperty(exports, "createOtlpNetworkExportDelegate", { enumerable: true, get: function() { + return otlp_network_export_delegate_1.createOtlpNetworkExportDelegate; + } }); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/utils.js +var require_utils5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.estimateVarintSize = undefined; + function estimateVarintSize(v) { + if (v < 0) + return 10; + if (v < 128) + return 1; + if (v < 16384) + return 2; + if (v < 2097152) + return 3; + if (v < 268435456) + return 4; + if (v < 34359738368) + return 5; + if (v < 4398046511104) + return 6; + if (v < 562949953421312) + return 7; + if (v < 72057594037927940) + return 8; + return 9; + } + exports.estimateVarintSize = estimateVarintSize; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/protobuf-writer.js +var require_protobuf_writer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufWriter = exports.GROWING_BUFFER_DEBUG_MESSAGE = undefined; + var api_1 = require_src(); + var utils_1 = require_utils5(); + exports.GROWING_BUFFER_DEBUG_MESSAGE = "ProtobufWriter: estimated size was too small, growing buffer."; + var RESERVED_LENGTH_BYTES = 1; + + class ProtobufWriter { + _buffer; + _textEncoder; + _dataView; + pos = 0; + constructor(estimatedSize = 65536) { + this._buffer = new Uint8Array(estimatedSize); + this._textEncoder = new TextEncoder; + this._dataView = new DataView(this._buffer.buffer, this._buffer.byteOffset); + } + _ensureCapacity(size) { + const needed = this.pos + size; + if (needed <= this._buffer.length) { + return; + } + api_1.diag.debug(exports.GROWING_BUFFER_DEBUG_MESSAGE); + let newSize = this._buffer.length * 2; + while (newSize < needed) { + newSize *= 2; + } + const newBuffer = new Uint8Array(newSize); + newBuffer.set(this._buffer); + this._buffer = newBuffer; + this._dataView = new DataView(this._buffer.buffer, this._buffer.byteOffset); + } + finish() { + return this._buffer.subarray(0, this.pos); + } + startLengthDelimited() { + const lengthPos = this.pos; + this._ensureCapacity(RESERVED_LENGTH_BYTES); + this.pos += RESERVED_LENGTH_BYTES; + return lengthPos; + } + finishLengthDelimited(pos, length) { + const v = length >>> 0; + const varintSize = (0, utils_1.estimateVarintSize)(v); + if (varintSize > RESERVED_LENGTH_BYTES) { + const additionalBytes = varintSize - RESERVED_LENGTH_BYTES; + this._ensureCapacity(additionalBytes); + this._buffer.copyWithin(pos + varintSize, pos + RESERVED_LENGTH_BYTES, this.pos); + this.pos += additionalBytes; + } + let writePos = pos; + if (v < 128) { + this._buffer[writePos] = v; + } else if (v < 16384) { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos] = v >>> 7; + } else if (v < 2097152) { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos++] = v >>> 7 & 127 | 128; + this._buffer[writePos] = v >>> 14; + } else if (v < 268435456) { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos++] = v >>> 7 & 127 | 128; + this._buffer[writePos++] = v >>> 14 & 127 | 128; + this._buffer[writePos] = v >>> 21; + } else { + this._buffer[writePos++] = v & 127 | 128; + this._buffer[writePos++] = v >>> 7 & 127 | 128; + this._buffer[writePos++] = v >>> 14 & 127 | 128; + this._buffer[writePos++] = v >>> 21 & 127 | 128; + this._buffer[writePos] = v >>> 28; + } + } + writeSint32(value) { + this.writeVarint((value << 1 ^ value >> 31) >>> 0); + } + writeSfixed64(value) { + let low; + let high; + if (value >= 0) { + low = value >>> 0; + high = value / 4294967296 >>> 0; + } else { + const abs = Math.abs(value); + low = abs >>> 0; + high = abs / 4294967296 >>> 0; + low = ~low >>> 0; + high = ~high >>> 0; + low = low + 1 >>> 0; + if (low === 0) { + high = high + 1 >>> 0; + } + } + this.writeFixed64(low, high); + } + writeVarint(value) { + this._ensureCapacity((0, utils_1.estimateVarintSize)(value)); + if (value >= 0 && value <= 4294967295) { + let v = value >>> 0; + while (v > 127) { + this._buffer[this.pos++] = v & 127 | 128; + v >>>= 7; + } + this._buffer[this.pos++] = v; + } else { + let low; + let high; + if (value >= 0) { + low = value >>> 0; + high = value / 4294967296 >>> 0; + } else { + const abs = Math.abs(value); + low = abs >>> 0; + high = abs / 4294967296 >>> 0; + low = ~low >>> 0; + high = ~high >>> 0; + low = low + 1 >>> 0; + if (low === 0) { + high = high + 1 >>> 0; + } + } + while (high > 0 || low > 127) { + this._buffer[this.pos++] = low & 127 | 128; + low = (low >>> 7 | high << 25) >>> 0; + high >>>= 7; + } + this._buffer[this.pos++] = low & 127; + } + } + writeFixed32(value) { + this._ensureCapacity(4); + const v = value >>> 0; + this._buffer[this.pos++] = v & 255; + this._buffer[this.pos++] = v >>> 8 & 255; + this._buffer[this.pos++] = v >>> 16 & 255; + this._buffer[this.pos++] = v >>> 24 & 255; + } + writeFixed64(low, high) { + this._ensureCapacity(8); + const l = low >>> 0; + const h = high >>> 0; + this._buffer[this.pos++] = l & 255; + this._buffer[this.pos++] = l >>> 8 & 255; + this._buffer[this.pos++] = l >>> 16 & 255; + this._buffer[this.pos++] = l >>> 24 & 255; + this._buffer[this.pos++] = h & 255; + this._buffer[this.pos++] = h >>> 8 & 255; + this._buffer[this.pos++] = h >>> 16 & 255; + this._buffer[this.pos++] = h >>> 24 & 255; + } + writeBytes(bytes) { + this.writeVarint(bytes.length); + this._ensureCapacity(bytes.length); + this._buffer.set(bytes, this.pos); + this.pos += bytes.length; + } + writeTag(fieldNumber, wireType) { + this.writeVarint(fieldNumber << 3 | wireType); + } + writeDouble(value) { + this._ensureCapacity(8); + this._dataView.setFloat64(this.pos, value, true); + this.pos += 8; + } + writeString(str) { + let isAscii = true; + const len = str.length; + for (let i = 0;i < len; i++) { + if (str.charCodeAt(i) > 127) { + isAscii = false; + break; + } + } + if (isAscii) { + this.writeVarint(len); + this._ensureCapacity(len); + for (let i = 0;i < len; i++) { + this._buffer[this.pos++] = str.charCodeAt(i); + } + } else { + const bytes = this._textEncoder.encode(str); + this.writeBytes(bytes); + } + } + } + exports.ProtobufWriter = ProtobufWriter; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js +var require_hex_to_binary = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.hexToBinary = undefined; + function intValue(charCode) { + if (charCode >= 48 && charCode <= 57) { + return charCode - 48; + } + if (charCode >= 97 && charCode <= 102) { + return charCode - 87; + } + return charCode - 55; + } + function hexToBinary(hexStr) { + const buf = new Uint8Array(hexStr.length / 2); + let offset = 0; + for (let i = 0;i < hexStr.length; i += 2) { + const hi = intValue(hexStr.charCodeAt(i)); + const lo = intValue(hexStr.charCodeAt(i + 1)); + buf[offset++] = hi << 4 | lo; + } + return buf; + } + exports.hexToBinary = hexToBinary; +}); + +// node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js +var require_LogRecord = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SeverityNumber = undefined; + var SeverityNumber; + (function(SeverityNumber2) { + SeverityNumber2[SeverityNumber2["UNSPECIFIED"] = 0] = "UNSPECIFIED"; + SeverityNumber2[SeverityNumber2["TRACE"] = 1] = "TRACE"; + SeverityNumber2[SeverityNumber2["TRACE2"] = 2] = "TRACE2"; + SeverityNumber2[SeverityNumber2["TRACE3"] = 3] = "TRACE3"; + SeverityNumber2[SeverityNumber2["TRACE4"] = 4] = "TRACE4"; + SeverityNumber2[SeverityNumber2["DEBUG"] = 5] = "DEBUG"; + SeverityNumber2[SeverityNumber2["DEBUG2"] = 6] = "DEBUG2"; + SeverityNumber2[SeverityNumber2["DEBUG3"] = 7] = "DEBUG3"; + SeverityNumber2[SeverityNumber2["DEBUG4"] = 8] = "DEBUG4"; + SeverityNumber2[SeverityNumber2["INFO"] = 9] = "INFO"; + SeverityNumber2[SeverityNumber2["INFO2"] = 10] = "INFO2"; + SeverityNumber2[SeverityNumber2["INFO3"] = 11] = "INFO3"; + SeverityNumber2[SeverityNumber2["INFO4"] = 12] = "INFO4"; + SeverityNumber2[SeverityNumber2["WARN"] = 13] = "WARN"; + SeverityNumber2[SeverityNumber2["WARN2"] = 14] = "WARN2"; + SeverityNumber2[SeverityNumber2["WARN3"] = 15] = "WARN3"; + SeverityNumber2[SeverityNumber2["WARN4"] = 16] = "WARN4"; + SeverityNumber2[SeverityNumber2["ERROR"] = 17] = "ERROR"; + SeverityNumber2[SeverityNumber2["ERROR2"] = 18] = "ERROR2"; + SeverityNumber2[SeverityNumber2["ERROR3"] = 19] = "ERROR3"; + SeverityNumber2[SeverityNumber2["ERROR4"] = 20] = "ERROR4"; + SeverityNumber2[SeverityNumber2["FATAL"] = 21] = "FATAL"; + SeverityNumber2[SeverityNumber2["FATAL2"] = 22] = "FATAL2"; + SeverityNumber2[SeverityNumber2["FATAL3"] = 23] = "FATAL3"; + SeverityNumber2[SeverityNumber2["FATAL4"] = 24] = "FATAL4"; + })(SeverityNumber = exports.SeverityNumber || (exports.SeverityNumber = {})); +}); + +// node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js +var require_NoopLogger = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createNoopLogger = exports.NOOP_LOGGER = exports.NoopLogger = undefined; + + class NoopLogger { + emit(_logRecord) {} + enabled() { + return false; + } + } + exports.NoopLogger = NoopLogger; + exports.NOOP_LOGGER = new NoopLogger; + function createNoopLogger() { + return exports.NOOP_LOGGER; + } + exports.createNoopLogger = createNoopLogger; +}); + +// node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js +var require_global_utils2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.API_BACKWARDS_COMPATIBILITY_VERSION = exports.makeGetter = exports._global = exports.GLOBAL_LOGS_API_KEY = undefined; + exports.GLOBAL_LOGS_API_KEY = Symbol.for("io.opentelemetry.js.api.logs"); + exports._global = globalThis; + function makeGetter(requiredVersion, instance, fallback) { + return (version) => version === requiredVersion ? instance : fallback; + } + exports.makeGetter = makeGetter; + exports.API_BACKWARDS_COMPATIBILITY_VERSION = 1; +}); + +// node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js +var require_NoopLoggerProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NOOP_LOGGER_PROVIDER = exports.NoopLoggerProvider = undefined; + var NoopLogger_1 = require_NoopLogger(); + + class NoopLoggerProvider { + getLogger(_name, _version, _options) { + return new NoopLogger_1.NoopLogger; + } + } + exports.NoopLoggerProvider = NoopLoggerProvider; + exports.NOOP_LOGGER_PROVIDER = new NoopLoggerProvider; +}); + +// node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js +var require_ProxyLogger = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyLogger = undefined; + var NoopLogger_1 = require_NoopLogger(); + + class ProxyLogger { + constructor(provider, name, version, options) { + this._provider = provider; + this.name = name; + this.version = version; + this.options = options; + } + emit(logRecord) { + this._getLogger().emit(logRecord); + } + enabled(options) { + return this._getLogger().enabled(options); + } + _getLogger() { + if (this._delegate) { + return this._delegate; + } + const logger = this._provider._getDelegateLogger(this.name, this.version, this.options); + if (!logger) { + return NoopLogger_1.NOOP_LOGGER; + } + this._delegate = logger; + return this._delegate; + } + } + exports.ProxyLogger = ProxyLogger; +}); + +// node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js +var require_ProxyLoggerProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProxyLoggerProvider = undefined; + var NoopLoggerProvider_1 = require_NoopLoggerProvider(); + var ProxyLogger_1 = require_ProxyLogger(); + + class ProxyLoggerProvider { + getLogger(name, version, options) { + var _a; + return (_a = this._getDelegateLogger(name, version, options)) !== null && _a !== undefined ? _a : new ProxyLogger_1.ProxyLogger(this, name, version, options); + } + _getDelegate() { + var _a; + return (_a = this._delegate) !== null && _a !== undefined ? _a : NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER; + } + _setDelegate(delegate) { + this._delegate = delegate; + } + _getDelegateLogger(name, version, options) { + var _a; + return (_a = this._delegate) === null || _a === undefined ? undefined : _a.getLogger(name, version, options); + } + } + exports.ProxyLoggerProvider = ProxyLoggerProvider; +}); + +// node_modules/@opentelemetry/api-logs/build/src/api/logs.js +var require_logs = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LogsAPI = undefined; + var global_utils_1 = require_global_utils2(); + var NoopLoggerProvider_1 = require_NoopLoggerProvider(); + var ProxyLoggerProvider_1 = require_ProxyLoggerProvider(); + + class LogsAPI { + constructor() { + this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider; + } + static getInstance() { + if (!this._instance) { + this._instance = new LogsAPI; + } + return this._instance; + } + setGlobalLoggerProvider(provider) { + if (global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) { + return this.getLoggerProvider(); + } + global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY] = (0, global_utils_1.makeGetter)(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, provider, NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER); + this._proxyLoggerProvider._setDelegate(provider); + return provider; + } + getLoggerProvider() { + var _a, _b; + return (_b = (_a = global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) === null || _a === undefined ? undefined : _a.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== undefined ? _b : this._proxyLoggerProvider; + } + getLogger(name, version, options) { + return this.getLoggerProvider().getLogger(name, version, options); + } + disable() { + delete global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]; + this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider; + } + } + exports.LogsAPI = LogsAPI; +}); + +// node_modules/@opentelemetry/api-logs/build/src/index.js +var require_src5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.logs = exports.createNoopLogger = exports.SeverityNumber = undefined; + var LogRecord_1 = require_LogRecord(); + Object.defineProperty(exports, "SeverityNumber", { enumerable: true, get: function() { + return LogRecord_1.SeverityNumber; + } }); + var NoopLogger_1 = require_NoopLogger(); + Object.defineProperty(exports, "createNoopLogger", { enumerable: true, get: function() { + return NoopLogger_1.createNoopLogger; + } }); + var logs_1 = require_logs(); + exports.logs = logs_1.LogsAPI.getInstance(); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/common-serializer.js +var require_common_serializer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.writeResource = exports.writeInstrumentationScope = exports.writeAnyValue = exports.writeKeyValue = exports.writeAttributes = exports.writeHrTimeAsFixed64 = undefined; + function writeHrTimeAsFixed64(serializer, hrTime) { + const seconds = hrTime[0]; + const nanos = hrTime[1]; + const nanosPerSecond = 1e9; + const secondsLower16Bits = seconds & 65535; + const secondsUpperBits = seconds / 65536 >>> 0; + const nanosFromLower16Bits = secondsLower16Bits * nanosPerSecond; + const nanosFromUpperBits = secondsUpperBits * nanosPerSecond; + const lower16ContributionLow32 = nanosFromLower16Bits >>> 0; + const lower16ContributionHigh32 = Math.floor(nanosFromLower16Bits / 4294967296); + const upperBitsContributionLow32 = (nanosFromUpperBits & 65535) * 65536 >>> 0; + const upperBitsContributionHigh32 = nanosFromUpperBits / 65536 >>> 0; + const low32WithCarry = lower16ContributionLow32 + upperBitsContributionLow32 + nanos; + const totalLow = low32WithCarry >>> 0; + const carry = Math.floor(low32WithCarry / 4294967296); + const totalHigh = lower16ContributionHigh32 + upperBitsContributionHigh32 + carry >>> 0; + serializer.writeFixed64(totalLow, totalHigh); + } + exports.writeHrTimeAsFixed64 = writeHrTimeAsFixed64; + function writeAttributes(writer, attributes, fieldNumber) { + for (const key in attributes) { + if (!Object.prototype.hasOwnProperty.call(attributes, key)) { + continue; + } + const value = attributes[key]; + writer.writeTag(fieldNumber, 2); + const kvStart = writer.startLengthDelimited(); + const startPos = writer.pos; + writeKeyValue(writer, key, value); + writer.finishLengthDelimited(kvStart, writer.pos - startPos); + } + } + exports.writeAttributes = writeAttributes; + function writeKeyValue(writer, key, value) { + writer.writeTag(1, 2); + writer.writeString(key); + writer.writeTag(2, 2); + const valueStart = writer.startLengthDelimited(); + const startPos = writer.pos; + writeAnyValue(writer, value); + writer.finishLengthDelimited(valueStart, writer.pos - startPos); + } + exports.writeKeyValue = writeKeyValue; + var MIN_64_BIT_INT = -(2 ** 63); + var MAX_64_BIT_INT = 2 ** 63; + function writeAnyValue(writer, value) { + const t = typeof value; + if (t === "string") { + writer.writeTag(1, 2); + writer.writeString(value); + } else if (t === "boolean") { + writer.writeTag(2, 0); + writer.writeVarint(value ? 1 : 0); + } else if (t === "number") { + const numValue = value; + if (Number.isInteger(numValue) && numValue >= MIN_64_BIT_INT && numValue < MAX_64_BIT_INT) { + writer.writeTag(3, 0); + writer.writeVarint(numValue); + } else { + writer.writeTag(4, 1); + writer.writeDouble(numValue); + } + } else if (value instanceof Uint8Array) { + writer.writeTag(7, 2); + writer.writeBytes(value); + } else if (Array.isArray(value)) { + writer.writeTag(5, 2); + const arrayStart = writer.startLengthDelimited(); + const arrayStartPos = writer.pos; + for (const item of value) { + writer.writeTag(1, 2); + const itemStart = writer.startLengthDelimited(); + const itemStartPos = writer.pos; + writeAnyValue(writer, item); + writer.finishLengthDelimited(itemStart, writer.pos - itemStartPos); + } + writer.finishLengthDelimited(arrayStart, writer.pos - arrayStartPos); + } else if (t === "object" && value != null) { + writer.writeTag(6, 2); + const kvlistStart = writer.startLengthDelimited(); + const kvlistStartPos = writer.pos; + const obj = value; + for (const k in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, k)) { + continue; + } + const v = obj[k]; + writer.writeTag(1, 2); + const kvStart = writer.startLengthDelimited(); + const kvStartPos = writer.pos; + writer.writeTag(1, 2); + writer.writeString(k); + writer.writeTag(2, 2); + const valueStart = writer.startLengthDelimited(); + const valueStartPos = writer.pos; + writeAnyValue(writer, v); + writer.finishLengthDelimited(valueStart, writer.pos - valueStartPos); + writer.finishLengthDelimited(kvStart, writer.pos - kvStartPos); + } + writer.finishLengthDelimited(kvlistStart, writer.pos - kvlistStartPos); + } + } + exports.writeAnyValue = writeAnyValue; + function writeInstrumentationScope(writer, scope, fieldNumber) { + writer.writeTag(fieldNumber, 2); + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + writer.writeTag(1, 2); + writer.writeString(scope.name); + if (scope.version) { + writer.writeTag(2, 2); + writer.writeString(scope.version); + } + if (scope.attributes) { + writeAttributes(writer, scope.attributes, 3); + } + if (scope.droppedAttributesCount) { + writer.writeTag(4, 0); + writer.writeVarint(scope.droppedAttributesCount); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + exports.writeInstrumentationScope = writeInstrumentationScope; + function writeResource(writer, resource, fieldNumber) { + writer.writeTag(fieldNumber, 2); + const resourceStart = writer.startLengthDelimited(); + const resourceStartPos = writer.pos; + if (resource.attributes) { + writeAttributes(writer, resource.attributes, 1); + } + writer.writeTag(2, 0); + writer.writeVarint(0); + writer.finishLengthDelimited(resourceStart, writer.pos - resourceStartPos); + } + exports.writeResource = writeResource; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/protobuf-size-estimator.js +var require_protobuf_size_estimator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufSizeEstimator = undefined; + var utils_1 = require_utils5(); + function utf8ByteLength(str) { + const len = str.length; + let byteLen = 0; + for (let i = 0;i < len; i++) { + const code = str.charCodeAt(i); + if (code < 128) { + byteLen += 1; + } else if (code < 2048) { + byteLen += 2; + } else if (code < 55296 || code >= 57344) { + byteLen += 3; + } else { + i++; + byteLen += 4; + } + } + return byteLen; + } + + class ProtobufSizeEstimator { + pos = 0; + startLengthDelimited() { + return this.pos; + } + finishLengthDelimited(_, length) { + this.pos += (0, utils_1.estimateVarintSize)(length); + } + writeVarint(value) { + this.pos += (0, utils_1.estimateVarintSize)(value); + } + writeSint32(value) { + this.pos += (0, utils_1.estimateVarintSize)((value << 1 ^ value >> 31) >>> 0); + } + writeSfixed64(_value) { + this.pos += 8; + } + writeFixed32(_value) { + this.pos += 4; + } + writeFixed64(_low, _high) { + this.pos += 8; + } + writeBytes(bytes) { + this.pos += (0, utils_1.estimateVarintSize)(bytes.length); + this.pos += bytes.length; + } + writeTag(fieldNumber, wireType) { + this.writeVarint(fieldNumber << 3 | wireType); + } + writeDouble(_value) { + this.pos += 8; + } + writeString(str) { + const byteLen = utf8ByteLength(str); + this.pos += (0, utils_1.estimateVarintSize)(byteLen); + this.pos += byteLen; + } + } + exports.ProtobufSizeEstimator = ProtobufSizeEstimator; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs-serializer.js +var require_logs_serializer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serializeLogsExportRequest = undefined; + var protobuf_writer_1 = require_protobuf_writer(); + var hex_to_binary_1 = require_hex_to_binary(); + var api_logs_1 = require_src5(); + var common_serializer_1 = require_common_serializer(); + var protobuf_size_estimator_1 = require_protobuf_size_estimator(); + function serializeLogRecord(writer, logRecord) { + const logStart = writer.startLengthDelimited(); + const logStartPos = writer.pos; + writer.writeTag(1, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, logRecord.hrTime); + if (logRecord.severityNumber !== undefined && logRecord.severityNumber !== api_logs_1.SeverityNumber.UNSPECIFIED) { + writer.writeTag(2, 0); + writer.writeVarint(logRecord.severityNumber); + } + if (logRecord.severityText) { + writer.writeTag(3, 2); + writer.writeString(logRecord.severityText); + } + if (logRecord.body !== undefined) { + writer.writeTag(5, 2); + const bodyStart = writer.startLengthDelimited(); + const bodyStartPos = writer.pos; + (0, common_serializer_1.writeAnyValue)(writer, logRecord.body); + writer.finishLengthDelimited(bodyStart, writer.pos - bodyStartPos); + } + if (logRecord.attributes) { + (0, common_serializer_1.writeAttributes)(writer, logRecord.attributes, 6); + } + writer.writeTag(7, 0); + writer.writeVarint(logRecord.droppedAttributesCount); + if (logRecord.spanContext?.traceFlags) { + writer.writeTag(8, 5); + writer.writeFixed32(logRecord.spanContext.traceFlags); + } + if (logRecord.spanContext?.traceId) { + writer.writeTag(9, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(logRecord.spanContext.traceId)); + } + if (logRecord.spanContext?.spanId) { + writer.writeTag(10, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(logRecord.spanContext.spanId)); + } + writer.writeTag(11, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, logRecord.hrTimeObserved); + if (logRecord.eventName) { + writer.writeTag(12, 2); + writer.writeString(logRecord.eventName); + } + writer.finishLengthDelimited(logStart, writer.pos - logStartPos); + } + function serializeScopeLogs(writer, scope, logRecords) { + const scopeLogsStart = writer.startLengthDelimited(); + const scopeLogsStartPos = writer.pos; + (0, common_serializer_1.writeInstrumentationScope)(writer, scope, 1); + for (const logRecord of logRecords) { + writer.writeTag(2, 2); + serializeLogRecord(writer, logRecord); + } + if (scope.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(scope.schemaUrl); + } + writer.finishLengthDelimited(scopeLogsStart, writer.pos - scopeLogsStartPos); + } + function serializeResourceLogs(writer, resource, scopeMap) { + const resourceLogsStart = writer.startLengthDelimited(); + const resourceLogsStartPos = writer.pos; + (0, common_serializer_1.writeResource)(writer, resource, 1); + for (const scopeLogs of scopeMap.values()) { + writer.writeTag(2, 2); + const scope = scopeLogs[0].instrumentationScope; + serializeScopeLogs(writer, scope, scopeLogs); + } + if (resource.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(resource.schemaUrl); + } + writer.finishLengthDelimited(resourceLogsStart, writer.pos - resourceLogsStartPos); + } + function createResourceMap(logRecords) { + const resourceMap = new Map; + for (const record of logRecords) { + const resource = record.resource; + const scope = record.instrumentationScope; + let ismMap = resourceMap.get(resource); + if (!ismMap) { + ismMap = new Map; + resourceMap.set(resource, ismMap); + } + let records = ismMap.get(scope); + if (!records) { + records = []; + ismMap.set(scope, records); + } + records.push(record); + } + return resourceMap; + } + function serializeLogsExportRequest(logRecords) { + const resourceMap = createResourceMap(logRecords); + const estimator = new protobuf_size_estimator_1.ProtobufSizeEstimator; + for (const [resource, scopeMap] of resourceMap) { + estimator.writeTag(1, 2); + serializeResourceLogs(estimator, resource, scopeMap); + } + const writer = new protobuf_writer_1.ProtobufWriter(estimator.pos); + for (const [resource, scopeMap] of resourceMap) { + writer.writeTag(1, 2); + serializeResourceLogs(writer, resource, scopeMap); + } + return writer.finish(); + } + exports.serializeLogsExportRequest = serializeLogsExportRequest; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/protobuf/protobuf-reader.js +var require_protobuf_reader = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufReader = undefined; + + class ProtobufReader { + pos = 0; + _buf; + _textDecoder; + constructor(buf) { + this._buf = buf; + this._textDecoder = new TextDecoder; + } + isAtEnd() { + return this.pos >= this._buf.length; + } + readTag() { + const raw = this.readVarint(); + return { fieldNumber: raw >>> 3, wireType: raw & 7 }; + } + readVarint() { + let result = 0; + let shift = 0; + let terminated = false; + while (this.pos < this._buf.length) { + const b = this._buf[this.pos++]; + result += (b & 127) * Math.pow(2, shift); + shift += 7; + if ((b & 128) === 0) { + terminated = true; + break; + } + } + if (!terminated) { + throw new Error("Truncated buffer: unexpected end of data while reading varint"); + } + return result; + } + readBytes() { + const len = this.readVarint(); + if (this.pos + len > this._buf.length) { + throw new Error(`Truncated buffer: expected ${len} bytes at position ${this.pos}, but only ${this._buf.length - this.pos} available`); + } + const slice = this._buf.subarray(this.pos, this.pos + len); + this.pos += len; + return slice; + } + readString() { + return this._textDecoder.decode(this.readBytes()); + } + skip(wireType) { + switch (wireType) { + case 0: + this.readVarint(); + break; + case 1: + this.pos += 8; + break; + case 2: + this.readBytes(); + break; + case 5: + this.pos += 4; + break; + default: + throw new Error(`Unknown wire type ${wireType}, cannot safely skip`); + } + } + } + exports.ProtobufReader = ProtobufReader; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/response-deserializer.js +var require_response_deserializer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deserializeExportLogsServiceResponse = undefined; + var protobuf_reader_1 = require_protobuf_reader(); + function deserializePartialSuccess(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 0) { + result.rejectedLogRecords = reader.readVarint(); + } else { + reader.skip(wireType); + } + break; + case 2: + if (wireType === 2) { + result.errorMessage = reader.readString(); + } else { + reader.skip(wireType); + } + break; + default: + reader.skip(wireType); + break; + } + } + return result; + } + function deserializeExportLogsServiceResponse(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 2) { + result.partialSuccess = deserializePartialSuccess(reader.readBytes()); + } else { + reader.skip(wireType); + } + break; + default: + reader.skip(wireType); + break; + } + } + return result; + } + exports.deserializeExportLogsServiceResponse = deserializeExportLogsServiceResponse; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js +var require_logs2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufLogsSerializer = undefined; + var logs_serializer_1 = require_logs_serializer(); + var response_deserializer_1 = require_response_deserializer(); + exports.ProtobufLogsSerializer = { + serializeRequest: (arg) => { + return (0, logs_serializer_1.serializeLogsExportRequest)(arg); + }, + deserializeResponse: (arg) => { + return (0, response_deserializer_1.deserializeExportLogsServiceResponse)(arg); + } + }; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js +var require_protobuf = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufLogsSerializer = undefined; + var logs_1 = require_logs2(); + Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: function() { + return logs_1.ProtobufLogsSerializer; + } }); +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js +var require_AggregationTemporality = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AggregationTemporality = undefined; + var AggregationTemporality; + (function(AggregationTemporality2) { + AggregationTemporality2[AggregationTemporality2["DELTA"] = 0] = "DELTA"; + AggregationTemporality2[AggregationTemporality2["CUMULATIVE"] = 1] = "CUMULATIVE"; + })(AggregationTemporality = exports.AggregationTemporality || (exports.AggregationTemporality = {})); +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js +var require_MetricData = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DataPointType = exports.InstrumentType = undefined; + var InstrumentType; + (function(InstrumentType2) { + InstrumentType2["COUNTER"] = "COUNTER"; + InstrumentType2["GAUGE"] = "GAUGE"; + InstrumentType2["HISTOGRAM"] = "HISTOGRAM"; + InstrumentType2["UP_DOWN_COUNTER"] = "UP_DOWN_COUNTER"; + InstrumentType2["OBSERVABLE_COUNTER"] = "OBSERVABLE_COUNTER"; + InstrumentType2["OBSERVABLE_GAUGE"] = "OBSERVABLE_GAUGE"; + InstrumentType2["OBSERVABLE_UP_DOWN_COUNTER"] = "OBSERVABLE_UP_DOWN_COUNTER"; + })(InstrumentType = exports.InstrumentType || (exports.InstrumentType = {})); + var DataPointType; + (function(DataPointType2) { + DataPointType2[DataPointType2["HISTOGRAM"] = 0] = "HISTOGRAM"; + DataPointType2[DataPointType2["EXPONENTIAL_HISTOGRAM"] = 1] = "EXPONENTIAL_HISTOGRAM"; + DataPointType2[DataPointType2["GAUGE"] = 2] = "GAUGE"; + DataPointType2[DataPointType2["SUM"] = 3] = "SUM"; + })(DataPointType = exports.DataPointType || (exports.DataPointType = {})); +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/utils.js +var require_utils6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.equalsCaseInsensitive = exports.binarySearchUB = exports.setEquals = exports.callWithTimeout = exports.TimeoutError = exports.instrumentationScopeId = exports.hashAttributes = undefined; + function hashAttributes(attributes) { + let keys = Object.keys(attributes); + if (keys.length === 0) + return ""; + keys = keys.sort(); + return JSON.stringify(keys.map((key) => [key, attributes[key]])); + } + exports.hashAttributes = hashAttributes; + function instrumentationScopeId(instrumentationScope) { + return `${instrumentationScope.name}:${instrumentationScope.version ?? ""}:${instrumentationScope.schemaUrl ?? ""}`; + } + exports.instrumentationScopeId = instrumentationScopeId; + + class TimeoutError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, TimeoutError.prototype); + } + } + exports.TimeoutError = TimeoutError; + function callWithTimeout(promise, timeout) { + let timeoutHandle; + const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { + timeoutHandle = setTimeout(function timeoutHandler() { + reject(new TimeoutError("Operation timed out.")); + }, timeout); + }); + return Promise.race([promise, timeoutPromise]).then((result) => { + clearTimeout(timeoutHandle); + return result; + }, (reason) => { + clearTimeout(timeoutHandle); + throw reason; + }); + } + exports.callWithTimeout = callWithTimeout; + function setEquals(lhs, rhs) { + if (lhs.size !== rhs.size) { + return false; + } + for (const item of lhs) { + if (!rhs.has(item)) { + return false; + } + } + return true; + } + exports.setEquals = setEquals; + function binarySearchUB(arr, value) { + let lo = 0; + let hi = arr.length - 1; + let ret = arr.length; + while (hi >= lo) { + const mid = lo + Math.trunc((hi - lo) / 2); + if (arr[mid] < value) { + lo = mid + 1; + } else { + ret = mid; + hi = mid - 1; + } + } + return ret; + } + exports.binarySearchUB = binarySearchUB; + function equalsCaseInsensitive(lhs, rhs) { + return lhs.toLowerCase() === rhs.toLowerCase(); + } + exports.equalsCaseInsensitive = equalsCaseInsensitive; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js +var require_types3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AggregatorKind = undefined; + var AggregatorKind; + (function(AggregatorKind2) { + AggregatorKind2[AggregatorKind2["DROP"] = 0] = "DROP"; + AggregatorKind2[AggregatorKind2["SUM"] = 1] = "SUM"; + AggregatorKind2[AggregatorKind2["LAST_VALUE"] = 2] = "LAST_VALUE"; + AggregatorKind2[AggregatorKind2["HISTOGRAM"] = 3] = "HISTOGRAM"; + AggregatorKind2[AggregatorKind2["EXPONENTIAL_HISTOGRAM"] = 4] = "EXPONENTIAL_HISTOGRAM"; + })(AggregatorKind = exports.AggregatorKind || (exports.AggregatorKind = {})); +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js +var require_Drop = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DropAggregator = undefined; + var types_1 = require_types3(); + + class DropAggregator { + kind = types_1.AggregatorKind.DROP; + createAccumulation() { + return; + } + merge(_previous, _delta) { + return; + } + diff(_previous, _current) { + return; + } + toMetricData(_descriptor, _aggregationTemporality, _accumulationByAttributes, _endTime) { + return; + } + } + exports.DropAggregator = DropAggregator; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js +var require_Histogram = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HistogramAggregator = exports.HistogramAccumulation = undefined; + var types_1 = require_types3(); + var MetricData_1 = require_MetricData(); + var utils_1 = require_utils6(); + function createNewEmptyCheckpoint(boundaries) { + const counts = boundaries.map(() => 0); + counts.push(0); + return { + buckets: { + boundaries, + counts + }, + sum: 0, + count: 0, + hasMinMax: false, + min: Infinity, + max: -Infinity + }; + } + + class HistogramAccumulation { + startTime; + _boundaries; + _recordMinMax; + _current; + constructor(startTime, boundaries, recordMinMax = true, current = createNewEmptyCheckpoint(boundaries)) { + this.startTime = startTime; + this._boundaries = boundaries; + this._recordMinMax = recordMinMax; + this._current = current; + } + record(value) { + if (Number.isNaN(value)) { + return; + } + this._current.count += 1; + this._current.sum += value; + if (this._recordMinMax) { + this._current.min = Math.min(value, this._current.min); + this._current.max = Math.max(value, this._current.max); + this._current.hasMinMax = true; + } + const idx = (0, utils_1.binarySearchUB)(this._boundaries, value); + this._current.buckets.counts[idx] += 1; + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } + } + exports.HistogramAccumulation = HistogramAccumulation; + + class HistogramAggregator { + kind = types_1.AggregatorKind.HISTOGRAM; + _boundaries; + _recordMinMax; + constructor(boundaries, recordMinMax) { + this._boundaries = boundaries; + this._recordMinMax = recordMinMax; + } + createAccumulation(startTime) { + return new HistogramAccumulation(startTime, this._boundaries, this._recordMinMax); + } + merge(previous, delta) { + const previousValue = previous.toPointValue(); + const deltaValue = delta.toPointValue(); + const previousCounts = previousValue.buckets.counts; + const deltaCounts = deltaValue.buckets.counts; + const mergedCounts = new Array(previousCounts.length); + for (let idx = 0;idx < previousCounts.length; idx++) { + mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx]; + } + let min = Infinity; + let max = -Infinity; + if (this._recordMinMax) { + if (previousValue.hasMinMax && deltaValue.hasMinMax) { + min = Math.min(previousValue.min, deltaValue.min); + max = Math.max(previousValue.max, deltaValue.max); + } else if (previousValue.hasMinMax) { + min = previousValue.min; + max = previousValue.max; + } else if (deltaValue.hasMinMax) { + min = deltaValue.min; + max = deltaValue.max; + } + } + return new HistogramAccumulation(previous.startTime, previousValue.buckets.boundaries, this._recordMinMax, { + buckets: { + boundaries: previousValue.buckets.boundaries, + counts: mergedCounts + }, + count: previousValue.count + deltaValue.count, + sum: previousValue.sum + deltaValue.sum, + hasMinMax: this._recordMinMax && (previousValue.hasMinMax || deltaValue.hasMinMax), + min, + max + }); + } + diff(previous, current) { + const previousValue = previous.toPointValue(); + const currentValue = current.toPointValue(); + const previousCounts = previousValue.buckets.counts; + const currentCounts = currentValue.buckets.counts; + const diffedCounts = new Array(previousCounts.length); + for (let idx = 0;idx < previousCounts.length; idx++) { + diffedCounts[idx] = currentCounts[idx] - previousCounts[idx]; + } + return new HistogramAccumulation(current.startTime, previousValue.buckets.boundaries, this._recordMinMax, { + buckets: { + boundaries: previousValue.buckets.boundaries, + counts: diffedCounts + }, + count: currentValue.count - previousValue.count, + sum: currentValue.sum - previousValue.sum, + hasMinMax: false, + min: Infinity, + max: -Infinity + }); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.HISTOGRAM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + const pointValue = accumulation.toPointValue(); + const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: { + min: pointValue.hasMinMax ? pointValue.min : undefined, + max: pointValue.hasMinMax ? pointValue.max : undefined, + sum: !allowsNegativeValues ? pointValue.sum : undefined, + buckets: pointValue.buckets, + count: pointValue.count + } + }; + }) + }; + } + } + exports.HistogramAggregator = HistogramAggregator; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js +var require_Buckets = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Buckets = undefined; + + class Buckets { + backing; + indexBase; + indexStart; + indexEnd; + constructor(backing = new BucketsBacking, indexBase = 0, indexStart = 0, indexEnd = 0) { + this.backing = backing; + this.indexBase = indexBase; + this.indexStart = indexStart; + this.indexEnd = indexEnd; + } + get offset() { + return this.indexStart; + } + get length() { + if (this.backing.length === 0) { + return 0; + } + if (this.indexEnd === this.indexStart && this.at(0) === 0) { + return 0; + } + return this.indexEnd - this.indexStart + 1; + } + counts() { + return Array.from({ length: this.length }, (_, i) => this.at(i)); + } + at(position) { + const bias = this.indexBase - this.indexStart; + if (position < bias) { + position += this.backing.length; + } + position -= bias; + return this.backing.countAt(position); + } + incrementBucket(bucketIndex, increment) { + this.backing.increment(bucketIndex, increment); + } + decrementBucket(bucketIndex, decrement) { + this.backing.decrement(bucketIndex, decrement); + } + trim() { + for (let i = 0;i < this.length; i++) { + if (this.at(i) !== 0) { + this.indexStart += i; + break; + } else if (i === this.length - 1) { + this.indexStart = this.indexEnd = this.indexBase = 0; + return; + } + } + for (let i = this.length - 1;i >= 0; i--) { + if (this.at(i) !== 0) { + this.indexEnd -= this.length - i - 1; + break; + } + } + this._rotate(); + } + downscale(by) { + this._rotate(); + const size = 1 + this.indexEnd - this.indexStart; + const each = 1 << by; + let inpos = 0; + let outpos = 0; + for (let pos = this.indexStart;pos <= this.indexEnd; ) { + let mod = pos % each; + if (mod < 0) { + mod += each; + } + for (let i = mod;i < each && inpos < size; i++) { + this._relocateBucket(outpos, inpos); + inpos++; + pos++; + } + outpos++; + } + this.indexStart >>= by; + this.indexEnd >>= by; + this.indexBase = this.indexStart; + } + clone() { + return new Buckets(this.backing.clone(), this.indexBase, this.indexStart, this.indexEnd); + } + _rotate() { + const bias = this.indexBase - this.indexStart; + if (bias === 0) { + return; + } else if (bias > 0) { + this.backing.reverse(0, this.backing.length); + this.backing.reverse(0, bias); + this.backing.reverse(bias, this.backing.length); + } else { + this.backing.reverse(0, this.backing.length); + this.backing.reverse(0, this.backing.length + bias); + } + this.indexBase = this.indexStart; + } + _relocateBucket(dest, src) { + if (dest === src) { + return; + } + this.incrementBucket(dest, this.backing.emptyBucket(src)); + } + } + exports.Buckets = Buckets; + + class BucketsBacking { + _counts; + constructor(counts = [0]) { + this._counts = counts; + } + get length() { + return this._counts.length; + } + countAt(pos) { + return this._counts[pos]; + } + growTo(newSize, oldPositiveLimit, newPositiveLimit) { + const tmp = new Array(newSize).fill(0); + tmp.splice(newPositiveLimit, this._counts.length - oldPositiveLimit, ...this._counts.slice(oldPositiveLimit)); + tmp.splice(0, oldPositiveLimit, ...this._counts.slice(0, oldPositiveLimit)); + this._counts = tmp; + } + reverse(from, limit) { + const num = Math.floor((from + limit) / 2) - from; + for (let i = 0;i < num; i++) { + const tmp = this._counts[from + i]; + this._counts[from + i] = this._counts[limit - i - 1]; + this._counts[limit - i - 1] = tmp; + } + } + emptyBucket(src) { + const tmp = this._counts[src]; + this._counts[src] = 0; + return tmp; + } + increment(bucketIndex, increment) { + this._counts[bucketIndex] += increment; + } + decrement(bucketIndex, decrement) { + if (this._counts[bucketIndex] >= decrement) { + this._counts[bucketIndex] -= decrement; + } else { + this._counts[bucketIndex] = 0; + } + } + clone() { + return new BucketsBacking([...this._counts]); + } + } +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js +var require_ieee754 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSignificand = exports.getNormalBase2 = exports.MIN_VALUE = exports.MAX_NORMAL_EXPONENT = exports.MIN_NORMAL_EXPONENT = exports.SIGNIFICAND_WIDTH = undefined; + exports.SIGNIFICAND_WIDTH = 52; + var EXPONENT_MASK = 2146435072; + var SIGNIFICAND_MASK = 1048575; + var EXPONENT_BIAS = 1023; + exports.MIN_NORMAL_EXPONENT = -EXPONENT_BIAS + 1; + exports.MAX_NORMAL_EXPONENT = EXPONENT_BIAS; + exports.MIN_VALUE = Math.pow(2, -1022); + function getNormalBase2(value) { + const dv = new DataView(new ArrayBuffer(8)); + dv.setFloat64(0, value); + const hiBits = dv.getUint32(0); + const expBits = (hiBits & EXPONENT_MASK) >> 20; + return expBits - EXPONENT_BIAS; + } + exports.getNormalBase2 = getNormalBase2; + function getSignificand(value) { + const dv = new DataView(new ArrayBuffer(8)); + dv.setFloat64(0, value); + const hiBits = dv.getUint32(0); + const loBits = dv.getUint32(4); + const significandHiBits = (hiBits & SIGNIFICAND_MASK) * Math.pow(2, 32); + return significandHiBits + loBits; + } + exports.getSignificand = getSignificand; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js +var require_util = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.nextGreaterSquare = exports.ldexp = undefined; + function ldexp(frac, exp) { + if (frac === 0 || frac === Number.POSITIVE_INFINITY || frac === Number.NEGATIVE_INFINITY || Number.isNaN(frac)) { + return frac; + } + return frac * Math.pow(2, exp); + } + exports.ldexp = ldexp; + function nextGreaterSquare(v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; + } + exports.nextGreaterSquare = nextGreaterSquare; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js +var require_types4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MappingError = undefined; + + class MappingError extends Error { + } + exports.MappingError = MappingError; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js +var require_ExponentMapping = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExponentMapping = undefined; + var ieee754 = require_ieee754(); + var util = require_util(); + var types_1 = require_types4(); + + class ExponentMapping { + _shift; + constructor(scale) { + this._shift = -scale; + } + mapToIndex(value) { + if (value < ieee754.MIN_VALUE) { + return this._minNormalLowerBoundaryIndex(); + } + const exp = ieee754.getNormalBase2(value); + const correction = this._rightShift(ieee754.getSignificand(value) - 1, ieee754.SIGNIFICAND_WIDTH); + return exp + correction >> this._shift; + } + lowerBoundary(index) { + const minIndex = this._minNormalLowerBoundaryIndex(); + if (index < minIndex) { + throw new types_1.MappingError(`underflow: ${index} is < minimum lower boundary: ${minIndex}`); + } + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index > maxIndex) { + throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); + } + return util.ldexp(1, index << this._shift); + } + get scale() { + if (this._shift === 0) { + return 0; + } + return -this._shift; + } + _minNormalLowerBoundaryIndex() { + let index = ieee754.MIN_NORMAL_EXPONENT >> this._shift; + if (this._shift < 2) { + index--; + } + return index; + } + _maxNormalLowerBoundaryIndex() { + return ieee754.MAX_NORMAL_EXPONENT >> this._shift; + } + _rightShift(value, shift) { + return Math.floor(value * Math.pow(2, -shift)); + } + } + exports.ExponentMapping = ExponentMapping; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js +var require_LogarithmMapping = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LogarithmMapping = undefined; + var ieee754 = require_ieee754(); + var util = require_util(); + var types_1 = require_types4(); + + class LogarithmMapping { + _scale; + _scaleFactor; + _inverseFactor; + constructor(scale) { + this._scale = scale; + this._scaleFactor = util.ldexp(Math.LOG2E, scale); + this._inverseFactor = util.ldexp(Math.LN2, -scale); + } + mapToIndex(value) { + if (value <= ieee754.MIN_VALUE) { + return this._minNormalLowerBoundaryIndex() - 1; + } + if (ieee754.getSignificand(value) === 0) { + const exp = ieee754.getNormalBase2(value); + return (exp << this._scale) - 1; + } + const index = Math.floor(Math.log(value) * this._scaleFactor); + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index >= maxIndex) { + return maxIndex; + } + return index; + } + lowerBoundary(index) { + const maxIndex = this._maxNormalLowerBoundaryIndex(); + if (index >= maxIndex) { + if (index === maxIndex) { + return 2 * Math.exp((index - (1 << this._scale)) / this._scaleFactor); + } + throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); + } + const minIndex = this._minNormalLowerBoundaryIndex(); + if (index <= minIndex) { + if (index === minIndex) { + return ieee754.MIN_VALUE; + } else if (index === minIndex - 1) { + return Math.exp((index + (1 << this._scale)) / this._scaleFactor) / 2; + } + throw new types_1.MappingError(`overflow: ${index} is < minimum lower boundary: ${minIndex}`); + } + return Math.exp(index * this._inverseFactor); + } + get scale() { + return this._scale; + } + _minNormalLowerBoundaryIndex() { + return ieee754.MIN_NORMAL_EXPONENT << this._scale; + } + _maxNormalLowerBoundaryIndex() { + return (ieee754.MAX_NORMAL_EXPONENT + 1 << this._scale) - 1; + } + } + exports.LogarithmMapping = LogarithmMapping; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js +var require_getMapping = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMapping = undefined; + var ExponentMapping_1 = require_ExponentMapping(); + var LogarithmMapping_1 = require_LogarithmMapping(); + var types_1 = require_types4(); + var MIN_SCALE = -10; + var MAX_SCALE = 20; + var PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => { + if (i > 10) { + return new LogarithmMapping_1.LogarithmMapping(i - 10); + } + return new ExponentMapping_1.ExponentMapping(i - 10); + }); + function getMapping(scale) { + if (scale > MAX_SCALE || scale < MIN_SCALE) { + throw new types_1.MappingError(`expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE}, got: ${scale}`); + } + return PREBUILT_MAPPINGS[scale + 10]; + } + exports.getMapping = getMapping; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js +var require_ExponentialHistogram = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = undefined; + var types_1 = require_types3(); + var MetricData_1 = require_MetricData(); + var api_1 = require_src(); + var Buckets_1 = require_Buckets(); + var getMapping_1 = require_getMapping(); + var util_1 = require_util(); + + class HighLow { + static combine(h1, h2) { + return new HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high)); + } + low; + high; + constructor(low, high) { + this.low = low; + this.high = high; + } + } + var MAX_SCALE = 20; + var DEFAULT_MAX_SIZE = 160; + var MIN_MAX_SIZE = 2; + + class ExponentialHistogramAccumulation { + startTime; + _maxSize; + _recordMinMax; + _sum; + _count; + _zeroCount; + _min; + _max; + _positive; + _negative; + _mapping; + constructor(startTime, maxSize = DEFAULT_MAX_SIZE, recordMinMax = true, sum = 0, count = 0, zeroCount = 0, min = Number.POSITIVE_INFINITY, max = Number.NEGATIVE_INFINITY, positive = new Buckets_1.Buckets, negative = new Buckets_1.Buckets, mapping = (0, getMapping_1.getMapping)(MAX_SCALE)) { + this.startTime = startTime; + this._maxSize = maxSize; + this._recordMinMax = recordMinMax; + this._sum = sum; + this._count = count; + this._zeroCount = zeroCount; + this._min = min; + this._max = max; + this._positive = positive; + this._negative = negative; + this._mapping = mapping; + if (this._maxSize < MIN_MAX_SIZE) { + api_1.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: ${MIN_MAX_SIZE}`); + this._maxSize = MIN_MAX_SIZE; + } + } + record(value) { + this.updateByIncrement(value, 1); + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return { + hasMinMax: this._recordMinMax, + min: this.min, + max: this.max, + sum: this.sum, + positive: { + offset: this.positive.offset, + bucketCounts: this.positive.counts() + }, + negative: { + offset: this.negative.offset, + bucketCounts: this.negative.counts() + }, + count: this.count, + scale: this.scale, + zeroCount: this.zeroCount + }; + } + get sum() { + return this._sum; + } + get min() { + return this._min; + } + get max() { + return this._max; + } + get count() { + return this._count; + } + get zeroCount() { + return this._zeroCount; + } + get scale() { + if (this._count === this._zeroCount) { + return 0; + } + return this._mapping.scale; + } + get positive() { + return this._positive; + } + get negative() { + return this._negative; + } + updateByIncrement(value, increment) { + if (Number.isNaN(value)) { + return; + } + if (value > this._max) { + this._max = value; + } + if (value < this._min) { + this._min = value; + } + this._count += increment; + if (value === 0) { + this._zeroCount += increment; + return; + } + this._sum += value * increment; + if (value > 0) { + this._updateBuckets(this._positive, value, increment); + } else { + this._updateBuckets(this._negative, -value, increment); + } + } + merge(previous) { + if (this._count === 0) { + this._min = previous.min; + this._max = previous.max; + } else if (previous.count !== 0) { + if (previous.min < this.min) { + this._min = previous.min; + } + if (previous.max > this.max) { + this._max = previous.max; + } + } + this.startTime = previous.startTime; + this._sum += previous.sum; + this._count += previous.count; + this._zeroCount += previous.zeroCount; + const minScale = this._minScale(previous); + this._downscale(this.scale - minScale); + this._mergeBuckets(this.positive, previous, previous.positive, minScale); + this._mergeBuckets(this.negative, previous, previous.negative, minScale); + } + diff(other) { + this._min = Infinity; + this._max = -Infinity; + this._sum -= other.sum; + this._count -= other.count; + this._zeroCount -= other.zeroCount; + const minScale = this._minScale(other); + this._downscale(this.scale - minScale); + this._diffBuckets(this.positive, other, other.positive, minScale); + this._diffBuckets(this.negative, other, other.negative, minScale); + } + clone() { + return new ExponentialHistogramAccumulation(this.startTime, this._maxSize, this._recordMinMax, this._sum, this._count, this._zeroCount, this._min, this._max, this.positive.clone(), this.negative.clone(), this._mapping); + } + _updateBuckets(buckets, value, increment) { + let index = this._mapping.mapToIndex(value); + let rescalingNeeded = false; + let high = 0; + let low = 0; + if (buckets.length === 0) { + buckets.indexStart = index; + buckets.indexEnd = buckets.indexStart; + buckets.indexBase = buckets.indexStart; + } else if (index < buckets.indexStart && buckets.indexEnd - index >= this._maxSize) { + rescalingNeeded = true; + low = index; + high = buckets.indexEnd; + } else if (index > buckets.indexEnd && index - buckets.indexStart >= this._maxSize) { + rescalingNeeded = true; + low = buckets.indexStart; + high = index; + } + if (rescalingNeeded) { + const change = this._changeScale(high, low); + this._downscale(change); + index = this._mapping.mapToIndex(value); + } + this._incrementIndexBy(buckets, index, increment); + } + _incrementIndexBy(buckets, index, increment) { + if (increment === 0) { + return; + } + if (buckets.length === 0) { + buckets.indexStart = buckets.indexEnd = buckets.indexBase = index; + } + if (index < buckets.indexStart) { + const span = buckets.indexEnd - index; + if (span >= buckets.backing.length) { + this._grow(buckets, span + 1); + } + buckets.indexStart = index; + } else if (index > buckets.indexEnd) { + const span = index - buckets.indexStart; + if (span >= buckets.backing.length) { + this._grow(buckets, span + 1); + } + buckets.indexEnd = index; + } + let bucketIndex = index - buckets.indexBase; + if (bucketIndex < 0) { + bucketIndex += buckets.backing.length; + } + buckets.incrementBucket(bucketIndex, increment); + } + _grow(buckets, needed) { + const size = buckets.backing.length; + const bias = buckets.indexBase - buckets.indexStart; + const oldPositiveLimit = size - bias; + let newSize = (0, util_1.nextGreaterSquare)(needed); + if (newSize > this._maxSize) { + newSize = this._maxSize; + } + const newPositiveLimit = newSize - bias; + buckets.backing.growTo(newSize, oldPositiveLimit, newPositiveLimit); + } + _changeScale(high, low) { + let change = 0; + while (high - low >= this._maxSize) { + high >>= 1; + low >>= 1; + change++; + } + return change; + } + _downscale(change) { + if (change === 0) { + return; + } + if (change < 0) { + throw new Error(`impossible change of scale: ${this.scale}`); + } + const newScale = this._mapping.scale - change; + this._positive.downscale(change); + this._negative.downscale(change); + this._mapping = (0, getMapping_1.getMapping)(newScale); + } + _minScale(other) { + const minScale = Math.min(this.scale, other.scale); + const highLowPos = HighLow.combine(this._highLowAtScale(this.positive, this.scale, minScale), this._highLowAtScale(other.positive, other.scale, minScale)); + const highLowNeg = HighLow.combine(this._highLowAtScale(this.negative, this.scale, minScale), this._highLowAtScale(other.negative, other.scale, minScale)); + return Math.min(minScale - this._changeScale(highLowPos.high, highLowPos.low), minScale - this._changeScale(highLowNeg.high, highLowNeg.low)); + } + _highLowAtScale(buckets, currentScale, newScale) { + if (buckets.length === 0) { + return new HighLow(0, -1); + } + const shift = currentScale - newScale; + return new HighLow(buckets.indexStart >> shift, buckets.indexEnd >> shift); + } + _mergeBuckets(ours, other, theirs, scale) { + const theirOffset = theirs.offset; + const theirChange = other.scale - scale; + for (let i = 0;i < theirs.length; i++) { + this._incrementIndexBy(ours, theirOffset + i >> theirChange, theirs.at(i)); + } + } + _diffBuckets(ours, other, theirs, scale) { + const theirOffset = theirs.offset; + const theirChange = other.scale - scale; + for (let i = 0;i < theirs.length; i++) { + const ourIndex = theirOffset + i >> theirChange; + let bucketIndex = ourIndex - ours.indexBase; + if (bucketIndex < 0) { + bucketIndex += ours.backing.length; + } + ours.decrementBucket(bucketIndex, theirs.at(i)); + } + ours.trim(); + } + } + exports.ExponentialHistogramAccumulation = ExponentialHistogramAccumulation; + + class ExponentialHistogramAggregator { + kind = types_1.AggregatorKind.EXPONENTIAL_HISTOGRAM; + _maxSize; + _recordMinMax; + constructor(maxSize, recordMinMax) { + this._maxSize = maxSize; + this._recordMinMax = recordMinMax; + } + createAccumulation(startTime) { + return new ExponentialHistogramAccumulation(startTime, this._maxSize, this._recordMinMax); + } + merge(previous, delta) { + const result = delta.clone(); + result.merge(previous); + return result; + } + diff(previous, current) { + const result = current.clone(); + result.diff(previous); + return result; + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.EXPONENTIAL_HISTOGRAM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + const pointValue = accumulation.toPointValue(); + const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: { + min: pointValue.hasMinMax ? pointValue.min : undefined, + max: pointValue.hasMinMax ? pointValue.max : undefined, + sum: !allowsNegativeValues ? pointValue.sum : undefined, + positive: { + offset: pointValue.positive.offset, + bucketCounts: pointValue.positive.bucketCounts + }, + negative: { + offset: pointValue.negative.offset, + bucketCounts: pointValue.negative.bucketCounts + }, + count: pointValue.count, + scale: pointValue.scale, + zeroCount: pointValue.zeroCount + } + }; + }) + }; + } + } + exports.ExponentialHistogramAggregator = ExponentialHistogramAggregator; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js +var require_LastValue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LastValueAggregator = exports.LastValueAccumulation = undefined; + var types_1 = require_types3(); + var core_1 = require_src3(); + var MetricData_1 = require_MetricData(); + + class LastValueAccumulation { + startTime; + _current; + sampleTime; + constructor(startTime, current = 0, sampleTime = [0, 0]) { + this.startTime = startTime; + this._current = current; + this.sampleTime = sampleTime; + } + record(value) { + this._current = value; + this.sampleTime = (0, core_1.millisToHrTime)(Date.now()); + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } + } + exports.LastValueAccumulation = LastValueAccumulation; + + class LastValueAggregator { + kind = types_1.AggregatorKind.LAST_VALUE; + createAccumulation(startTime) { + return new LastValueAccumulation(startTime); + } + merge(previous, delta) { + const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(delta.sampleTime) >= (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) ? delta : previous; + return new LastValueAccumulation(previous.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); + } + diff(previous, current) { + const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(current.sampleTime) >= (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) ? current : previous; + return new LastValueAccumulation(current.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.GAUGE, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: accumulation.toPointValue() + }; + }) + }; + } + } + exports.LastValueAggregator = LastValueAggregator; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js +var require_Sum = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SumAggregator = exports.SumAccumulation = undefined; + var types_1 = require_types3(); + var MetricData_1 = require_MetricData(); + + class SumAccumulation { + startTime; + monotonic; + _current; + reset; + constructor(startTime, monotonic, current = 0, reset = false) { + this.startTime = startTime; + this.monotonic = monotonic; + this._current = current; + this.reset = reset; + } + record(value) { + if (this.monotonic && value < 0) { + return; + } + this._current += value; + } + setStartTime(startTime) { + this.startTime = startTime; + } + toPointValue() { + return this._current; + } + } + exports.SumAccumulation = SumAccumulation; + + class SumAggregator { + kind = types_1.AggregatorKind.SUM; + monotonic; + constructor(monotonic) { + this.monotonic = monotonic; + } + createAccumulation(startTime) { + return new SumAccumulation(startTime, this.monotonic); + } + merge(previous, delta) { + const prevPv = previous.toPointValue(); + const deltaPv = delta.toPointValue(); + if (delta.reset) { + return new SumAccumulation(delta.startTime, this.monotonic, deltaPv, delta.reset); + } + return new SumAccumulation(previous.startTime, this.monotonic, prevPv + deltaPv); + } + diff(previous, current) { + const prevPv = previous.toPointValue(); + const currPv = current.toPointValue(); + if (this.monotonic && prevPv > currPv) { + return new SumAccumulation(current.startTime, this.monotonic, currPv, true); + } + return new SumAccumulation(current.startTime, this.monotonic, currPv - prevPv); + } + toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { + return { + descriptor, + aggregationTemporality, + dataPointType: MetricData_1.DataPointType.SUM, + dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { + return { + attributes, + startTime: accumulation.startTime, + endTime, + value: accumulation.toPointValue() + }; + }), + isMonotonic: this.monotonic + }; + } + } + exports.SumAggregator = SumAggregator; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js +var require_aggregator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SumAggregator = exports.SumAccumulation = exports.LastValueAggregator = exports.LastValueAccumulation = exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = exports.HistogramAggregator = exports.HistogramAccumulation = exports.DropAggregator = undefined; + var Drop_1 = require_Drop(); + Object.defineProperty(exports, "DropAggregator", { enumerable: true, get: function() { + return Drop_1.DropAggregator; + } }); + var Histogram_1 = require_Histogram(); + Object.defineProperty(exports, "HistogramAccumulation", { enumerable: true, get: function() { + return Histogram_1.HistogramAccumulation; + } }); + Object.defineProperty(exports, "HistogramAggregator", { enumerable: true, get: function() { + return Histogram_1.HistogramAggregator; + } }); + var ExponentialHistogram_1 = require_ExponentialHistogram(); + Object.defineProperty(exports, "ExponentialHistogramAccumulation", { enumerable: true, get: function() { + return ExponentialHistogram_1.ExponentialHistogramAccumulation; + } }); + Object.defineProperty(exports, "ExponentialHistogramAggregator", { enumerable: true, get: function() { + return ExponentialHistogram_1.ExponentialHistogramAggregator; + } }); + var LastValue_1 = require_LastValue(); + Object.defineProperty(exports, "LastValueAccumulation", { enumerable: true, get: function() { + return LastValue_1.LastValueAccumulation; + } }); + Object.defineProperty(exports, "LastValueAggregator", { enumerable: true, get: function() { + return LastValue_1.LastValueAggregator; + } }); + var Sum_1 = require_Sum(); + Object.defineProperty(exports, "SumAccumulation", { enumerable: true, get: function() { + return Sum_1.SumAccumulation; + } }); + Object.defineProperty(exports, "SumAggregator", { enumerable: true, get: function() { + return Sum_1.SumAggregator; + } }); +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js +var require_Aggregation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_AGGREGATION = exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = exports.HISTOGRAM_AGGREGATION = exports.LAST_VALUE_AGGREGATION = exports.SUM_AGGREGATION = exports.DROP_AGGREGATION = exports.DefaultAggregation = exports.ExponentialHistogramAggregation = exports.ExplicitBucketHistogramAggregation = exports.HistogramAggregation = exports.LastValueAggregation = exports.SumAggregation = exports.DropAggregation = undefined; + var api = require_src(); + var aggregator_1 = require_aggregator(); + var MetricData_1 = require_MetricData(); + + class DropAggregation { + static DEFAULT_INSTANCE = new aggregator_1.DropAggregator; + createAggregator(_instrument) { + return DropAggregation.DEFAULT_INSTANCE; + } + } + exports.DropAggregation = DropAggregation; + + class SumAggregation { + static MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(true); + static NON_MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(false); + createAggregator(instrument) { + switch (instrument.type) { + case MetricData_1.InstrumentType.COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: + case MetricData_1.InstrumentType.HISTOGRAM: { + return SumAggregation.MONOTONIC_INSTANCE; + } + default: { + return SumAggregation.NON_MONOTONIC_INSTANCE; + } + } + } + } + exports.SumAggregation = SumAggregation; + + class LastValueAggregation { + static DEFAULT_INSTANCE = new aggregator_1.LastValueAggregator; + createAggregator(_instrument) { + return LastValueAggregation.DEFAULT_INSTANCE; + } + } + exports.LastValueAggregation = LastValueAggregation; + + class HistogramAggregation { + static DEFAULT_INSTANCE = new aggregator_1.HistogramAggregator([0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 1e4], true); + createAggregator(_instrument) { + return HistogramAggregation.DEFAULT_INSTANCE; + } + } + exports.HistogramAggregation = HistogramAggregation; + + class ExplicitBucketHistogramAggregation { + _boundaries; + _recordMinMax; + constructor(boundaries, recordMinMax = true) { + if (boundaries == null) { + throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array"); + } + boundaries = boundaries.concat(); + boundaries = boundaries.sort((a, b) => a - b); + const minusInfinityIndex = boundaries.lastIndexOf(-Infinity); + let infinityIndex = boundaries.indexOf(Infinity); + if (infinityIndex === -1) { + infinityIndex = undefined; + } + this._boundaries = boundaries.slice(minusInfinityIndex + 1, infinityIndex); + this._recordMinMax = recordMinMax; + } + createAggregator(_instrument) { + return new aggregator_1.HistogramAggregator(this._boundaries, this._recordMinMax); + } + } + exports.ExplicitBucketHistogramAggregation = ExplicitBucketHistogramAggregation; + + class ExponentialHistogramAggregation { + _maxSize; + _recordMinMax; + constructor(maxSize = 160, recordMinMax = true) { + this._maxSize = maxSize; + this._recordMinMax = recordMinMax; + } + createAggregator(_instrument) { + return new aggregator_1.ExponentialHistogramAggregator(this._maxSize, this._recordMinMax); + } + } + exports.ExponentialHistogramAggregation = ExponentialHistogramAggregation; + + class DefaultAggregation { + _resolve(instrument) { + switch (instrument.type) { + case MetricData_1.InstrumentType.COUNTER: + case MetricData_1.InstrumentType.UP_DOWN_COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: + case MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: { + return exports.SUM_AGGREGATION; + } + case MetricData_1.InstrumentType.GAUGE: + case MetricData_1.InstrumentType.OBSERVABLE_GAUGE: { + return exports.LAST_VALUE_AGGREGATION; + } + case MetricData_1.InstrumentType.HISTOGRAM: { + if (instrument.advice.explicitBucketBoundaries) { + return new ExplicitBucketHistogramAggregation(instrument.advice.explicitBucketBoundaries); + } + return exports.HISTOGRAM_AGGREGATION; + } + } + api.diag.warn(`Unable to recognize instrument type: ${instrument.type}`); + return exports.DROP_AGGREGATION; + } + createAggregator(instrument) { + return this._resolve(instrument).createAggregator(instrument); + } + } + exports.DefaultAggregation = DefaultAggregation; + exports.DROP_AGGREGATION = new DropAggregation; + exports.SUM_AGGREGATION = new SumAggregation; + exports.LAST_VALUE_AGGREGATION = new LastValueAggregation; + exports.HISTOGRAM_AGGREGATION = new HistogramAggregation; + exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = new ExponentialHistogramAggregation; + exports.DEFAULT_AGGREGATION = new DefaultAggregation; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js +var require_AggregationOption = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toAggregation = exports.AggregationType = undefined; + var Aggregation_1 = require_Aggregation(); + var AggregationType; + (function(AggregationType2) { + AggregationType2[AggregationType2["DEFAULT"] = 0] = "DEFAULT"; + AggregationType2[AggregationType2["DROP"] = 1] = "DROP"; + AggregationType2[AggregationType2["SUM"] = 2] = "SUM"; + AggregationType2[AggregationType2["LAST_VALUE"] = 3] = "LAST_VALUE"; + AggregationType2[AggregationType2["EXPLICIT_BUCKET_HISTOGRAM"] = 4] = "EXPLICIT_BUCKET_HISTOGRAM"; + AggregationType2[AggregationType2["EXPONENTIAL_HISTOGRAM"] = 5] = "EXPONENTIAL_HISTOGRAM"; + })(AggregationType = exports.AggregationType || (exports.AggregationType = {})); + function toAggregation(option) { + switch (option.type) { + case AggregationType.DEFAULT: + return Aggregation_1.DEFAULT_AGGREGATION; + case AggregationType.DROP: + return Aggregation_1.DROP_AGGREGATION; + case AggregationType.SUM: + return Aggregation_1.SUM_AGGREGATION; + case AggregationType.LAST_VALUE: + return Aggregation_1.LAST_VALUE_AGGREGATION; + case AggregationType.EXPONENTIAL_HISTOGRAM: { + const expOption = option; + return new Aggregation_1.ExponentialHistogramAggregation(expOption.options?.maxSize, expOption.options?.recordMinMax); + } + case AggregationType.EXPLICIT_BUCKET_HISTOGRAM: { + const expOption = option; + if (expOption.options == null) { + return Aggregation_1.HISTOGRAM_AGGREGATION; + } else { + return new Aggregation_1.ExplicitBucketHistogramAggregation(expOption.options?.boundaries, expOption.options?.recordMinMax); + } + } + default: + throw new Error("Unsupported Aggregation"); + } + } + exports.toAggregation = toAggregation; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js +var require_AggregationSelector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = exports.DEFAULT_AGGREGATION_SELECTOR = undefined; + var AggregationTemporality_1 = require_AggregationTemporality(); + var AggregationOption_1 = require_AggregationOption(); + var DEFAULT_AGGREGATION_SELECTOR = (_instrumentType) => { + return { + type: AggregationOption_1.AggregationType.DEFAULT + }; + }; + exports.DEFAULT_AGGREGATION_SELECTOR = DEFAULT_AGGREGATION_SELECTOR; + var DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = (_instrumentType) => AggregationTemporality_1.AggregationTemporality.CUMULATIVE; + exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/semconv.js +var require_semconv2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_ERROR_TYPE = exports.METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION = exports.OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER = exports.ATTR_OTEL_COMPONENT_TYPE = exports.ATTR_OTEL_COMPONENT_NAME = undefined; + exports.ATTR_OTEL_COMPONENT_NAME = "otel.component.name"; + exports.ATTR_OTEL_COMPONENT_TYPE = "otel.component.type"; + exports.OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER = "periodic_metric_reader"; + exports.METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION = "otel.sdk.metric_reader.collection.duration"; + exports.ATTR_ERROR_TYPE = "error.type"; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReaderMetrics.js +var require_MetricReaderMetrics = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricReaderMetrics = undefined; + var semconv_1 = require_semconv2(); + var componentCounter = new Map; + + class MetricReaderMetrics { + collectionDuration; + standardAttrs; + constructor(componentType, meter) { + const counter = componentCounter.get(componentType) ?? 0; + componentCounter.set(componentType, counter + 1); + this.standardAttrs = { + [semconv_1.ATTR_OTEL_COMPONENT_TYPE]: componentType, + [semconv_1.ATTR_OTEL_COMPONENT_NAME]: `${componentType}/${counter}` + }; + this.collectionDuration = meter.createHistogram(semconv_1.METRIC_OTEL_SDK_METRIC_READER_COLLECTION_DURATION, { + unit: "s", + description: "The duration of the collect operation of the metric reader.", + advice: { + explicitBucketBoundaries: [] + } + }); + } + recordCollection(durationSecs, error) { + const attrs = error ? { ...this.standardAttrs, [semconv_1.ATTR_ERROR_TYPE]: error } : this.standardAttrs; + this.collectionDuration.record(durationSecs, attrs); + } + } + exports.MetricReaderMetrics = MetricReaderMetrics; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/version.js +var require_version4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = undefined; + exports.VERSION = "2.8.0"; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js +var require_MetricReader = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricReader = undefined; + var api = require_src(); + var utils_1 = require_utils6(); + var AggregationSelector_1 = require_AggregationSelector(); + var MetricReaderMetrics_1 = require_MetricReaderMetrics(); + var version_1 = require_version4(); + var core_1 = require_src3(); + + class MetricReader { + _shutdown = false; + _metricProducers; + _sdkMetricProducer; + _selfObsMetrics; + _aggregationTemporalitySelector; + _aggregationSelector; + _cardinalitySelector; + _otelComponentType; + constructor(options) { + this._aggregationSelector = options?.aggregationSelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_SELECTOR; + this._aggregationTemporalitySelector = options?.aggregationTemporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; + this._metricProducers = options?.metricProducers ?? []; + this._cardinalitySelector = options?.cardinalitySelector; + this._otelComponentType = options?.otelComponentType ?? this.constructor.name; + this._selfObsMetrics = new MetricReaderMetrics_1.MetricReaderMetrics(this._otelComponentType, api.createNoopMeter()); + } + setMetricProducer(metricProducer) { + if (this._sdkMetricProducer) { + throw new Error("MetricReader can not be bound to a MeterProvider again."); + } + this._sdkMetricProducer = metricProducer; + this.onInitialized(); + } + _setSelfObsMeterProvider(meterProvider) { + const meter = meterProvider.getMeter("@opentelemetry/sdk-metrics", version_1.VERSION); + this._selfObsMetrics = new MetricReaderMetrics_1.MetricReaderMetrics(this._otelComponentType, meter); + } + selectAggregation(instrumentType) { + return this._aggregationSelector(instrumentType); + } + selectAggregationTemporality(instrumentType) { + return this._aggregationTemporalitySelector(instrumentType); + } + selectCardinalityLimit(instrumentType) { + return this._cardinalitySelector ? this._cardinalitySelector(instrumentType) : 2000; + } + onInitialized() {} + async collect(options) { + if (this._sdkMetricProducer === undefined) { + throw new Error("MetricReader is not bound to a MetricProducer"); + } + if (this._shutdown) { + throw new Error("MetricReader is shutdown"); + } + const startTime = (0, core_1.hrTime)(); + const [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([ + this._sdkMetricProducer.collect({ + timeoutMillis: options?.timeoutMillis + }), + ...this._metricProducers.map((producer) => producer.collect({ + timeoutMillis: options?.timeoutMillis + })) + ]); + const endTime = (0, core_1.hrTime)(); + const errors = sdkCollectionResults.errors.concat(additionalCollectionResults.flatMap((result) => result.errors)); + const collectDuration = (0, core_1.hrTimeToSeconds)((0, core_1.hrTimeDuration)(startTime, endTime)); + this._selfObsMetrics.recordCollection(collectDuration, errors.length > 0 ? errors[0].name ?? "collect_error" : undefined); + const resource = sdkCollectionResults.resourceMetrics.resource; + const scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat(additionalCollectionResults.flatMap((result) => result.resourceMetrics.scopeMetrics)); + return { + resourceMetrics: { + resource, + scopeMetrics + }, + errors + }; + } + async shutdown(options) { + if (this._shutdown) { + api.diag.error("Cannot call shutdown twice."); + return; + } + if (options?.timeoutMillis == null) { + await this.onShutdown(); + } else { + await (0, utils_1.callWithTimeout)(this.onShutdown(), options.timeoutMillis); + } + this._shutdown = true; + } + async forceFlush(options) { + if (this._shutdown) { + api.diag.warn("Cannot forceFlush on already shutdown MetricReader."); + return; + } + if (options?.timeoutMillis == null) { + await this.onForceFlush(); + return; + } + await (0, utils_1.callWithTimeout)(this.onForceFlush(), options.timeoutMillis); + } + } + exports.MetricReader = MetricReader; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js +var require_PeriodicExportingMetricReader = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PeriodicExportingMetricReader = undefined; + var api = require_src(); + var core_1 = require_src3(); + var MetricReader_1 = require_MetricReader(); + var utils_1 = require_utils6(); + var MetricData_1 = require_MetricData(); + var semconv_1 = require_semconv2(); + + class PeriodicExportingMetricReader extends MetricReader_1.MetricReader { + _interval; + _exporter; + _exportInterval; + _exportTimeout; + constructor(options) { + const { exporter, exportIntervalMillis = 60000, metricProducers, cardinalityLimits } = options; + let { exportTimeoutMillis = 30000 } = options; + super({ + aggregationSelector: exporter.selectAggregation?.bind(exporter), + aggregationTemporalitySelector: exporter.selectAggregationTemporality?.bind(exporter), + otelComponentType: semconv_1.OTEL_COMPONENT_TYPE_VALUE_PERIODIC_METRIC_READER, + metricProducers, + cardinalitySelector: (instrumentType) => { + const limits = { + default: 2000, + ...cardinalityLimits + }; + switch (instrumentType) { + case MetricData_1.InstrumentType.COUNTER: + return limits.counter ?? limits.default; + case MetricData_1.InstrumentType.GAUGE: + return limits.gauge ?? limits.default; + case MetricData_1.InstrumentType.HISTOGRAM: + return limits.histogram ?? limits.default; + case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: + return limits.observableCounter ?? limits.default; + case MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: + return limits.observableUpDownCounter ?? limits.default; + case MetricData_1.InstrumentType.OBSERVABLE_GAUGE: + return limits.observableGauge ?? limits.default; + case MetricData_1.InstrumentType.UP_DOWN_COUNTER: + return limits.upDownCounter ?? limits.default; + default: + return limits.default; + } + } + }); + if (exportIntervalMillis <= 0) { + throw Error("exportIntervalMillis must be greater than 0"); + } + if (exportTimeoutMillis <= 0) { + throw Error("exportTimeoutMillis must be greater than 0"); + } + if (exportIntervalMillis < exportTimeoutMillis) { + if ("exportIntervalMillis" in options && "exportTimeoutMillis" in options) { + throw Error("exportIntervalMillis must be greater than or equal to exportTimeoutMillis"); + } else { + api.diag.info(`Timeout of ${exportTimeoutMillis} exceeds the interval of ${exportIntervalMillis}. Clamping timeout to interval duration.`); + exportTimeoutMillis = exportIntervalMillis; + } + } + this._exportInterval = exportIntervalMillis; + this._exportTimeout = exportTimeoutMillis; + this._exporter = exporter; + } + async _runOnce() { + try { + await (0, utils_1.callWithTimeout)(this._doRun(), this._exportTimeout); + } catch (err) { + if (err instanceof utils_1.TimeoutError) { + api.diag.error("Export took longer than %s milliseconds and timed out.", this._exportTimeout); + return; + } + (0, core_1.globalErrorHandler)(err); + } + } + async _doRun() { + const { resourceMetrics, errors } = await this.collect({ + timeoutMillis: this._exportTimeout + }); + if (errors.length > 0) { + api.diag.error("PeriodicExportingMetricReader: metrics collection errors", ...errors); + } + if (resourceMetrics.resource.asyncAttributesPending) { + try { + await resourceMetrics.resource.waitForAsyncAttributes?.(); + } catch (e) { + api.diag.debug("Error while resolving async portion of resource: ", e); + (0, core_1.globalErrorHandler)(e); + } + } + if (resourceMetrics.scopeMetrics.length === 0) { + return; + } + const result = await core_1.internal._export(this._exporter, resourceMetrics); + if (result.code !== core_1.ExportResultCode.SUCCESS) { + throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${result.error})`); + } + } + onInitialized() { + this._interval = setInterval(() => { + this._runOnce(); + }, this._exportInterval); + if (typeof this._interval !== "number") { + this._interval.unref(); + } + } + async onForceFlush() { + await this._runOnce(); + await this._exporter.forceFlush(); + } + async onShutdown() { + if (this._interval) { + clearInterval(this._interval); + } + await this.onForceFlush(); + await this._exporter.shutdown(); + } + } + exports.PeriodicExportingMetricReader = PeriodicExportingMetricReader; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js +var require_InMemoryMetricExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InMemoryMetricExporter = undefined; + var core_1 = require_src3(); + + class InMemoryMetricExporter { + _shutdown = false; + _aggregationTemporality; + _metrics = []; + constructor(aggregationTemporality) { + this._aggregationTemporality = aggregationTemporality; + } + export(metrics, resultCallback) { + if (this._shutdown) { + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.FAILED }), 0); + return; + } + this._metrics.push(metrics); + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); + } + getMetrics() { + return this._metrics; + } + forceFlush() { + return Promise.resolve(); + } + reset() { + this._metrics = []; + } + selectAggregationTemporality(_instrumentType) { + return this._aggregationTemporality; + } + shutdown() { + this._shutdown = true; + return Promise.resolve(); + } + } + exports.InMemoryMetricExporter = InMemoryMetricExporter; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js +var require_ConsoleMetricExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConsoleMetricExporter = undefined; + var core_1 = require_src3(); + var AggregationSelector_1 = require_AggregationSelector(); + + class ConsoleMetricExporter { + _shutdown = false; + _temporalitySelector; + constructor(options) { + this._temporalitySelector = options?.temporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; + } + export(metrics, resultCallback) { + if (this._shutdown) { + resultCallback({ code: core_1.ExportResultCode.FAILED }); + return; + } + return ConsoleMetricExporter._sendMetrics(metrics, resultCallback); + } + forceFlush() { + return Promise.resolve(); + } + selectAggregationTemporality(_instrumentType) { + return this._temporalitySelector(_instrumentType); + } + shutdown() { + this._shutdown = true; + return Promise.resolve(); + } + static _sendMetrics(metrics, done) { + for (const scopeMetrics of metrics.scopeMetrics) { + for (const metric of scopeMetrics.metrics) { + console.dir({ + descriptor: metric.descriptor, + dataPointType: metric.dataPointType, + dataPoints: metric.dataPoints + }, { depth: null }); + } + } + done({ code: core_1.ExportResultCode.SUCCESS }); + } + } + exports.ConsoleMetricExporter = ConsoleMetricExporter; +}); + +// node_modules/@opentelemetry/resources/build/src/default-service-name.js +var require_default_service_name = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports._clearDefaultServiceNameCache = exports.defaultServiceName = undefined; + var serviceName; + function defaultServiceName() { + if (serviceName === undefined) { + try { + const argv0 = globalThis.process.argv0; + serviceName = argv0 ? `unknown_service:${argv0}` : "unknown_service"; + } catch { + serviceName = "unknown_service"; + } + } + return serviceName; + } + exports.defaultServiceName = defaultServiceName; + function _clearDefaultServiceNameCache() { + serviceName = undefined; + } + exports._clearDefaultServiceNameCache = _clearDefaultServiceNameCache; +}); + +// node_modules/@opentelemetry/resources/build/src/utils.js +var require_utils7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPromiseLike = undefined; + var isPromiseLike = (val) => { + return val !== null && typeof val === "object" && typeof val.then === "function"; + }; + exports.isPromiseLike = isPromiseLike; +}); + +// node_modules/@opentelemetry/resources/build/src/ResourceImpl.js +var require_ResourceImpl = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultResource = exports.emptyResource = exports.resourceFromDetectedResource = exports.resourceFromAttributes = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var semantic_conventions_1 = require_src2(); + var default_service_name_1 = require_default_service_name(); + var utils_1 = require_utils7(); + + class ResourceImpl { + _rawAttributes; + _asyncAttributesPending = false; + _schemaUrl; + _memoizedAttributes; + static FromAttributeList(attributes, options) { + const res = new ResourceImpl({}, options); + res._rawAttributes = guardedRawAttributes(attributes); + res._asyncAttributesPending = attributes.filter(([_, val]) => (0, utils_1.isPromiseLike)(val)).length > 0; + return res; + } + constructor(resource, options) { + const attributes = resource.attributes ?? {}; + this._rawAttributes = Object.entries(attributes).map(([k, v]) => { + if ((0, utils_1.isPromiseLike)(v)) { + this._asyncAttributesPending = true; + } + return [k, v]; + }); + this._rawAttributes = guardedRawAttributes(this._rawAttributes); + this._schemaUrl = validateSchemaUrl(options?.schemaUrl); + } + get asyncAttributesPending() { + return this._asyncAttributesPending; + } + async waitForAsyncAttributes() { + if (!this.asyncAttributesPending) { + return; + } + for (let i = 0;i < this._rawAttributes.length; i++) { + const [k, v] = this._rawAttributes[i]; + this._rawAttributes[i] = [k, (0, utils_1.isPromiseLike)(v) ? await v : v]; + } + this._asyncAttributesPending = false; + } + get attributes() { + if (this.asyncAttributesPending) { + api_1.diag.error("Accessing resource attributes before async attributes settled"); + } + if (this._memoizedAttributes) { + return this._memoizedAttributes; + } + const attrs = {}; + for (const [k, v] of this._rawAttributes) { + if ((0, utils_1.isPromiseLike)(v)) { + api_1.diag.debug(`Unsettled resource attribute ${k} skipped`); + continue; + } + if (v != null) { + attrs[k] ??= v; + } + } + if (!this._asyncAttributesPending) { + this._memoizedAttributes = attrs; + } + return attrs; + } + getRawAttributes() { + return this._rawAttributes; + } + get schemaUrl() { + return this._schemaUrl; + } + merge(resource) { + if (resource == null) + return this; + const mergedSchemaUrl = mergeSchemaUrl(this, resource); + const mergedOptions = mergedSchemaUrl ? { schemaUrl: mergedSchemaUrl } : undefined; + return ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions); + } + } + function resourceFromAttributes(attributes, options) { + return ResourceImpl.FromAttributeList(Object.entries(attributes), options); + } + exports.resourceFromAttributes = resourceFromAttributes; + function resourceFromDetectedResource(detectedResource, options) { + return new ResourceImpl(detectedResource, options); + } + exports.resourceFromDetectedResource = resourceFromDetectedResource; + function emptyResource() { + return resourceFromAttributes({}); + } + exports.emptyResource = emptyResource; + function defaultResource() { + return resourceFromAttributes({ + [semantic_conventions_1.ATTR_SERVICE_NAME]: (0, default_service_name_1.defaultServiceName)(), + [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE], + [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME], + [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION] + }); + } + exports.defaultResource = defaultResource; + function guardedRawAttributes(attributes) { + return attributes.map(([k, v]) => { + if ((0, utils_1.isPromiseLike)(v)) { + return [ + k, + v.catch((err) => { + api_1.diag.debug("promise rejection for resource attribute: %s - %s", k, err); + return; + }) + ]; + } + return [k, v]; + }); + } + function validateSchemaUrl(schemaUrl) { + if (typeof schemaUrl === "string" || schemaUrl === undefined) { + return schemaUrl; + } + api_1.diag.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.", schemaUrl); + return; + } + function mergeSchemaUrl(old, updating) { + const oldSchemaUrl = old?.schemaUrl; + const updatingSchemaUrl = updating?.schemaUrl; + const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === ""; + const isUpdatingEmpty = updatingSchemaUrl === undefined || updatingSchemaUrl === ""; + if (isOldEmpty) { + return updatingSchemaUrl; + } + if (isUpdatingEmpty) { + return oldSchemaUrl; + } + if (oldSchemaUrl === updatingSchemaUrl) { + return oldSchemaUrl; + } + api_1.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl); + return; + } +}); + +// node_modules/@opentelemetry/resources/build/src/detect-resources.js +var require_detect_resources = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.detectResources = undefined; + var api_1 = require_src(); + var ResourceImpl_1 = require_ResourceImpl(); + var detectResources = (config = {}) => { + const resources = (config.detectors || []).map((d) => { + try { + const resource = (0, ResourceImpl_1.resourceFromDetectedResource)(d.detect(config)); + api_1.diag.debug(`${d.constructor.name} found resource.`, resource); + return resource; + } catch (e) { + api_1.diag.debug(`${d.constructor.name} failed: ${e.message}`); + return (0, ResourceImpl_1.emptyResource)(); + } + }); + return resources.reduce((acc, resource) => acc.merge(resource), (0, ResourceImpl_1.emptyResource)()); + }; + exports.detectResources = detectResources; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js +var require_EnvDetector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.envDetector = undefined; + var api_1 = require_src(); + var semantic_conventions_1 = require_src2(); + var core_1 = require_src3(); + + class EnvDetector { + _MAX_LENGTH = 255; + _COMMA_SEPARATOR = ","; + _LABEL_KEY_VALUE_SPLITTER = "="; + detect(_config) { + const attributes = {}; + const rawAttributes = (0, core_1.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES"); + const serviceName = (0, core_1.getStringFromEnv)("OTEL_SERVICE_NAME"); + if (rawAttributes) { + try { + const parsedAttributes = this._parseResourceAttributes(rawAttributes); + Object.assign(attributes, parsedAttributes); + } catch (e) { + api_1.diag.debug(`EnvDetector failed: ${e instanceof Error ? e.message : e}`); + } + } + if (serviceName) { + attributes[semantic_conventions_1.ATTR_SERVICE_NAME] = serviceName; + } + return { attributes }; + } + _parseResourceAttributes(rawEnvAttributes) { + if (!rawEnvAttributes) + return {}; + const attributes = {}; + const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR).filter((attr) => attr.trim() !== ""); + for (const rawAttribute of rawAttributes) { + const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER); + if (keyValuePair.length !== 2) { + throw new Error(`Invalid format for OTEL_RESOURCE_ATTRIBUTES: "${rawAttribute}". ` + "Expected format: key=value. The ',' and '=' characters must be percent-encoded in keys and values."); + } + const [rawKey, rawValue] = keyValuePair; + const key = rawKey.trim(); + const value = rawValue.trim(); + if (key.length === 0) { + throw new Error(`Invalid OTEL_RESOURCE_ATTRIBUTES: empty attribute key in "${rawAttribute}".`); + } + let decodedKey; + let decodedValue; + try { + decodedKey = decodeURIComponent(key); + decodedValue = decodeURIComponent(value); + } catch (e) { + throw new Error(`Failed to percent-decode OTEL_RESOURCE_ATTRIBUTES entry "${rawAttribute}": ${e instanceof Error ? e.message : e}`, { cause: e }); + } + if (decodedKey.length > this._MAX_LENGTH) { + throw new Error(`Attribute key exceeds the maximum length of ${this._MAX_LENGTH} characters: "${decodedKey}".`); + } + if (decodedValue.length > this._MAX_LENGTH) { + throw new Error(`Attribute value exceeds the maximum length of ${this._MAX_LENGTH} characters for key "${decodedKey}".`); + } + attributes[decodedKey] = decodedValue; + } + return attributes; + } + } + exports.envDetector = new EnvDetector; +}); + +// node_modules/@opentelemetry/resources/build/src/semconv.js +var require_semconv3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_WEBENGINE_VERSION = exports.ATTR_WEBENGINE_NAME = exports.ATTR_WEBENGINE_DESCRIPTION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_PROCESS_RUNTIME_VERSION = exports.ATTR_PROCESS_RUNTIME_NAME = exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = exports.ATTR_PROCESS_PID = exports.ATTR_PROCESS_OWNER = exports.ATTR_PROCESS_EXECUTABLE_PATH = exports.ATTR_PROCESS_EXECUTABLE_NAME = exports.ATTR_PROCESS_COMMAND_ARGS = exports.ATTR_PROCESS_COMMAND = exports.ATTR_OS_VERSION = exports.ATTR_OS_TYPE = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_CLUSTER_NAME = exports.ATTR_HOST_TYPE = exports.ATTR_HOST_NAME = exports.ATTR_HOST_IMAGE_VERSION = exports.ATTR_HOST_IMAGE_NAME = exports.ATTR_HOST_IMAGE_ID = exports.ATTR_HOST_ID = exports.ATTR_HOST_ARCH = exports.ATTR_CONTAINER_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CLOUD_REGION = exports.ATTR_CLOUD_PROVIDER = exports.ATTR_CLOUD_AVAILABILITY_ZONE = exports.ATTR_CLOUD_ACCOUNT_ID = undefined; + exports.ATTR_CLOUD_ACCOUNT_ID = "cloud.account.id"; + exports.ATTR_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone"; + exports.ATTR_CLOUD_PROVIDER = "cloud.provider"; + exports.ATTR_CLOUD_REGION = "cloud.region"; + exports.ATTR_CONTAINER_ID = "container.id"; + exports.ATTR_CONTAINER_IMAGE_NAME = "container.image.name"; + exports.ATTR_CONTAINER_IMAGE_TAGS = "container.image.tags"; + exports.ATTR_CONTAINER_NAME = "container.name"; + exports.ATTR_HOST_ARCH = "host.arch"; + exports.ATTR_HOST_ID = "host.id"; + exports.ATTR_HOST_IMAGE_ID = "host.image.id"; + exports.ATTR_HOST_IMAGE_NAME = "host.image.name"; + exports.ATTR_HOST_IMAGE_VERSION = "host.image.version"; + exports.ATTR_HOST_NAME = "host.name"; + exports.ATTR_HOST_TYPE = "host.type"; + exports.ATTR_K8S_CLUSTER_NAME = "k8s.cluster.name"; + exports.ATTR_K8S_DEPLOYMENT_NAME = "k8s.deployment.name"; + exports.ATTR_K8S_NAMESPACE_NAME = "k8s.namespace.name"; + exports.ATTR_K8S_POD_NAME = "k8s.pod.name"; + exports.ATTR_OS_TYPE = "os.type"; + exports.ATTR_OS_VERSION = "os.version"; + exports.ATTR_PROCESS_COMMAND = "process.command"; + exports.ATTR_PROCESS_COMMAND_ARGS = "process.command_args"; + exports.ATTR_PROCESS_EXECUTABLE_NAME = "process.executable.name"; + exports.ATTR_PROCESS_EXECUTABLE_PATH = "process.executable.path"; + exports.ATTR_PROCESS_OWNER = "process.owner"; + exports.ATTR_PROCESS_PID = "process.pid"; + exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = "process.runtime.description"; + exports.ATTR_PROCESS_RUNTIME_NAME = "process.runtime.name"; + exports.ATTR_PROCESS_RUNTIME_VERSION = "process.runtime.version"; + exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; + exports.ATTR_SERVICE_NAMESPACE = "service.namespace"; + exports.ATTR_WEBENGINE_DESCRIPTION = "webengine.description"; + exports.ATTR_WEBENGINE_NAME = "webengine.name"; + exports.ATTR_WEBENGINE_VERSION = "webengine.version"; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js +var require_execAsync = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.execAsync = undefined; + var child_process = __require("child_process"); + var util = __require("util"); + exports.execAsync = util.promisify(child_process.exec); +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js +var require_getMachineId_darwin = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = undefined; + var execAsync_1 = require_execAsync(); + var api_1 = require_src(); + async function getMachineId() { + try { + const result = await (0, execAsync_1.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"'); + const idLine = result.stdout.split(` +`).find((line) => line.includes("IOPlatformUUID")); + if (!idLine) { + return; + } + const parts = idLine.split('" = "'); + if (parts.length === 2) { + return parts[1].slice(0, -1); + } + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + return; + } + exports.getMachineId = getMachineId; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js +var require_getMachineId_linux = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = undefined; + var fs_1 = __require("fs"); + var api_1 = require_src(); + async function getMachineId() { + const paths = ["/etc/machine-id", "/var/lib/dbus/machine-id"]; + for (const path of paths) { + try { + const result = await fs_1.promises.readFile(path, { encoding: "utf8" }); + return result.trim(); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + } + return; + } + exports.getMachineId = getMachineId; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js +var require_getMachineId_bsd = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = undefined; + var fs_1 = __require("fs"); + var execAsync_1 = require_execAsync(); + var api_1 = require_src(); + async function getMachineId() { + try { + const result = await fs_1.promises.readFile("/etc/hostid", { encoding: "utf8" }); + return result.trim(); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + try { + const result = await (0, execAsync_1.execAsync)("kenv -q smbios.system.uuid"); + return result.stdout.trim(); + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + return; + } + exports.getMachineId = getMachineId; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js +var require_getMachineId_win = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = undefined; + var process2 = __require("process"); + var execAsync_1 = require_execAsync(); + var api_1 = require_src(); + async function getMachineId() { + const args = "QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid"; + let command = "%windir%\\System32\\REG.exe"; + if (process2.arch === "ia32" && "PROCESSOR_ARCHITEW6432" in process2.env) { + command = "%windir%\\sysnative\\cmd.exe /c " + command; + } + try { + const result = await (0, execAsync_1.execAsync)(`${command} ${args}`); + const parts = result.stdout.split("REG_SZ"); + if (parts.length === 2) { + return parts[1].trim(); + } + } catch (e) { + api_1.diag.debug(`error reading machine id: ${e}`); + } + return; + } + exports.getMachineId = getMachineId; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js +var require_getMachineId_unsupported = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = undefined; + var api_1 = require_src(); + async function getMachineId() { + api_1.diag.debug("could not read machine-id: unsupported platform"); + return; + } + exports.getMachineId = getMachineId; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js +var require_getMachineId = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getMachineId = undefined; + var process2 = __require("process"); + var getMachineIdImpl; + async function getMachineId() { + if (!getMachineIdImpl) { + switch (process2.platform) { + case "darwin": + getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_darwin(), 1))).getMachineId; + break; + case "linux": + getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_linux(), 1))).getMachineId; + break; + case "freebsd": + getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_bsd(), 1))).getMachineId; + break; + case "win32": + getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_win(), 1))).getMachineId; + break; + default: + getMachineIdImpl = (await Promise.resolve().then(() => __toESM(require_getMachineId_unsupported(), 1))).getMachineId; + break; + } + } + return getMachineIdImpl(); + } + exports.getMachineId = getMachineId; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js +var require_utils8 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.normalizeType = exports.normalizeArch = undefined; + var normalizeArch = (nodeArchString) => { + switch (nodeArchString) { + case "arm": + return "arm32"; + case "ppc": + return "ppc32"; + case "x64": + return "amd64"; + default: + return nodeArchString; + } + }; + exports.normalizeArch = normalizeArch; + var normalizeType = (nodePlatform) => { + switch (nodePlatform) { + case "sunos": + return "solaris"; + case "win32": + return "windows"; + default: + return nodePlatform; + } + }; + exports.normalizeType = normalizeType; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js +var require_HostDetector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.hostDetector = undefined; + var semconv_1 = require_semconv3(); + var os_1 = __require("os"); + var getMachineId_1 = require_getMachineId(); + var utils_1 = require_utils8(); + + class HostDetector { + detect(_config) { + const attributes = { + [semconv_1.ATTR_HOST_NAME]: (0, os_1.hostname)(), + [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()), + [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)() + }; + return { attributes }; + } + } + exports.hostDetector = new HostDetector; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js +var require_OSDetector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.osDetector = undefined; + var semconv_1 = require_semconv3(); + var os_1 = __require("os"); + var utils_1 = require_utils8(); + + class OSDetector { + detect(_config) { + const attributes = { + [semconv_1.ATTR_OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()), + [semconv_1.ATTR_OS_VERSION]: (0, os_1.release)() + }; + return { attributes }; + } + } + exports.osDetector = new OSDetector; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js +var require_ProcessDetector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.processDetector = undefined; + var api_1 = require_src(); + var semconv_1 = require_semconv3(); + var os = __require("os"); + + class ProcessDetector { + detect(_config) { + const attributes = { + [semconv_1.ATTR_PROCESS_PID]: process.pid, + [semconv_1.ATTR_PROCESS_EXECUTABLE_NAME]: process.title, + [semconv_1.ATTR_PROCESS_EXECUTABLE_PATH]: process.execPath, + [semconv_1.ATTR_PROCESS_COMMAND_ARGS]: [ + process.argv[0], + ...process.execArgv, + ...process.argv.slice(1) + ], + [semconv_1.ATTR_PROCESS_RUNTIME_VERSION]: process.versions.node, + [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: "nodejs", + [semconv_1.ATTR_PROCESS_RUNTIME_DESCRIPTION]: "Node.js" + }; + if (process.argv.length > 1) { + attributes[semconv_1.ATTR_PROCESS_COMMAND] = process.argv[1]; + } + try { + const userInfo = os.userInfo(); + attributes[semconv_1.ATTR_PROCESS_OWNER] = userInfo.username; + } catch (e) { + api_1.diag.debug(`error obtaining process owner: ${e}`); + } + return { attributes }; + } + } + exports.processDetector = new ProcessDetector; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js +var require_ServiceInstanceIdDetector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serviceInstanceIdDetector = undefined; + var semconv_1 = require_semconv3(); + var crypto_1 = __require("crypto"); + + class ServiceInstanceIdDetector { + detect(_config) { + return { + attributes: { + [semconv_1.ATTR_SERVICE_INSTANCE_ID]: (0, crypto_1.randomUUID)() + } + }; + } + } + exports.serviceInstanceIdDetector = new ServiceInstanceIdDetector; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js +var require_node2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = undefined; + var HostDetector_1 = require_HostDetector(); + Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() { + return HostDetector_1.hostDetector; + } }); + var OSDetector_1 = require_OSDetector(); + Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() { + return OSDetector_1.osDetector; + } }); + var ProcessDetector_1 = require_ProcessDetector(); + Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() { + return ProcessDetector_1.processDetector; + } }); + var ServiceInstanceIdDetector_1 = require_ServiceInstanceIdDetector(); + Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() { + return ServiceInstanceIdDetector_1.serviceInstanceIdDetector; + } }); +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js +var require_platform2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = undefined; + var node_1 = require_node2(); + Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() { + return node_1.hostDetector; + } }); + Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() { + return node_1.osDetector; + } }); + Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() { + return node_1.processDetector; + } }); + Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() { + return node_1.serviceInstanceIdDetector; + } }); +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js +var require_NoopDetector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.noopDetector = exports.NoopDetector = undefined; + + class NoopDetector { + detect() { + return { + attributes: {} + }; + } + } + exports.NoopDetector = NoopDetector; + exports.noopDetector = new NoopDetector; +}); + +// node_modules/@opentelemetry/resources/build/src/detectors/index.js +var require_detectors = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.noopDetector = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = undefined; + var EnvDetector_1 = require_EnvDetector(); + Object.defineProperty(exports, "envDetector", { enumerable: true, get: function() { + return EnvDetector_1.envDetector; + } }); + var platform_1 = require_platform2(); + Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() { + return platform_1.hostDetector; + } }); + Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() { + return platform_1.osDetector; + } }); + Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() { + return platform_1.processDetector; + } }); + Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() { + return platform_1.serviceInstanceIdDetector; + } }); + var NoopDetector_1 = require_NoopDetector(); + Object.defineProperty(exports, "noopDetector", { enumerable: true, get: function() { + return NoopDetector_1.noopDetector; + } }); +}); + +// node_modules/@opentelemetry/resources/build/src/index.js +var require_src6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultServiceName = exports.emptyResource = exports.defaultResource = exports.resourceFromAttributes = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = exports.detectResources = undefined; + var detect_resources_1 = require_detect_resources(); + Object.defineProperty(exports, "detectResources", { enumerable: true, get: function() { + return detect_resources_1.detectResources; + } }); + var detectors_1 = require_detectors(); + Object.defineProperty(exports, "envDetector", { enumerable: true, get: function() { + return detectors_1.envDetector; + } }); + Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function() { + return detectors_1.hostDetector; + } }); + Object.defineProperty(exports, "osDetector", { enumerable: true, get: function() { + return detectors_1.osDetector; + } }); + Object.defineProperty(exports, "processDetector", { enumerable: true, get: function() { + return detectors_1.processDetector; + } }); + Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function() { + return detectors_1.serviceInstanceIdDetector; + } }); + var ResourceImpl_1 = require_ResourceImpl(); + Object.defineProperty(exports, "resourceFromAttributes", { enumerable: true, get: function() { + return ResourceImpl_1.resourceFromAttributes; + } }); + Object.defineProperty(exports, "defaultResource", { enumerable: true, get: function() { + return ResourceImpl_1.defaultResource; + } }); + Object.defineProperty(exports, "emptyResource", { enumerable: true, get: function() { + return ResourceImpl_1.emptyResource; + } }); + var default_service_name_1 = require_default_service_name(); + Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function() { + return default_service_name_1.defaultServiceName; + } }); +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js +var require_ViewRegistry = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ViewRegistry = undefined; + + class ViewRegistry { + _registeredViews = []; + addView(view) { + this._registeredViews.push(view); + } + findViews(instrument, meter) { + const views = this._registeredViews.filter((registeredView) => { + return this._matchInstrument(registeredView.instrumentSelector, instrument) && this._matchMeter(registeredView.meterSelector, meter); + }); + return views; + } + _matchInstrument(selector, instrument) { + return (selector.getType() === undefined || instrument.type === selector.getType()) && selector.getNameFilter().match(instrument.name) && selector.getUnitFilter().match(instrument.unit); + } + _matchMeter(selector, meter) { + return selector.getNameFilter().match(meter.name) && (meter.version === undefined || selector.getVersionFilter().match(meter.version)) && (meter.schemaUrl === undefined || selector.getSchemaUrlFilter().match(meter.schemaUrl)); + } + } + exports.ViewRegistry = ViewRegistry; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js +var require_InstrumentDescriptor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isValidName = exports.isDescriptorCompatibleWith = exports.createInstrumentDescriptorWithView = exports.createInstrumentDescriptor = undefined; + var api_1 = require_src(); + var utils_1 = require_utils6(); + function createInstrumentDescriptor(name, type, options) { + if (!isValidName(name)) { + api_1.diag.warn(`Invalid metric name: "${name}". The metric name should be a ASCII string with a length no greater than 255 characters.`); + } + return { + name, + type, + description: options?.description ?? "", + unit: options?.unit ?? "", + valueType: options?.valueType ?? api_1.ValueType.DOUBLE, + advice: options?.advice ?? {} + }; + } + exports.createInstrumentDescriptor = createInstrumentDescriptor; + function createInstrumentDescriptorWithView(view, instrument) { + return { + name: view.name ?? instrument.name, + description: view.description ?? instrument.description, + type: instrument.type, + unit: instrument.unit, + valueType: instrument.valueType, + advice: instrument.advice + }; + } + exports.createInstrumentDescriptorWithView = createInstrumentDescriptorWithView; + function isDescriptorCompatibleWith(descriptor, otherDescriptor) { + return (0, utils_1.equalsCaseInsensitive)(descriptor.name, otherDescriptor.name) && descriptor.unit === otherDescriptor.unit && descriptor.type === otherDescriptor.type && descriptor.valueType === otherDescriptor.valueType; + } + exports.isDescriptorCompatibleWith = isDescriptorCompatibleWith; + var NAME_REGEXP = /^[a-z][a-z0-9_.\-/]{0,254}$/i; + function isValidName(name) { + return NAME_REGEXP.test(name); + } + exports.isValidName = isValidName; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js +var require_Instruments = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isObservableInstrument = exports.ObservableUpDownCounterInstrument = exports.ObservableGaugeInstrument = exports.ObservableCounterInstrument = exports.ObservableInstrument = exports.HistogramInstrument = exports.GaugeInstrument = exports.CounterInstrument = exports.UpDownCounterInstrument = exports.SyncInstrument = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + + class SyncInstrument { + _writableMetricStorage; + _descriptor; + constructor(writableMetricStorage, descriptor) { + this._writableMetricStorage = writableMetricStorage; + this._descriptor = descriptor; + } + _record(value, attributes = {}, context = api_1.context.active()) { + if (typeof value !== "number") { + api_1.diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${value}`); + return; + } + if (this._descriptor.valueType === api_1.ValueType.INT && !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`); + value = Math.trunc(value); + if (!Number.isInteger(value)) { + return; + } + } + this._writableMetricStorage.record(value, attributes, context, (0, core_1.millisToHrTime)(Date.now())); + } + } + exports.SyncInstrument = SyncInstrument; + + class UpDownCounterInstrument extends SyncInstrument { + add(value, attributes, ctx) { + this._record(value, attributes, ctx); + } + } + exports.UpDownCounterInstrument = UpDownCounterInstrument; + + class CounterInstrument extends SyncInstrument { + add(value, attributes, ctx) { + if (value < 0) { + api_1.diag.warn(`negative value provided to counter ${this._descriptor.name}: ${value}`); + return; + } + this._record(value, attributes, ctx); + } + } + exports.CounterInstrument = CounterInstrument; + + class GaugeInstrument extends SyncInstrument { + record(value, attributes, ctx) { + this._record(value, attributes, ctx); + } + } + exports.GaugeInstrument = GaugeInstrument; + + class HistogramInstrument extends SyncInstrument { + record(value, attributes, ctx) { + if (value < 0) { + api_1.diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${value}`); + return; + } + this._record(value, attributes, ctx); + } + } + exports.HistogramInstrument = HistogramInstrument; + + class ObservableInstrument { + _metricStorages; + _descriptor; + _observableRegistry; + constructor(descriptor, metricStorages, observableRegistry) { + this._descriptor = descriptor; + this._metricStorages = metricStorages; + this._observableRegistry = observableRegistry; + } + addCallback(callback) { + this._observableRegistry.addCallback(callback, this); + } + removeCallback(callback) { + this._observableRegistry.removeCallback(callback, this); + } + } + exports.ObservableInstrument = ObservableInstrument; + + class ObservableCounterInstrument extends ObservableInstrument { + } + exports.ObservableCounterInstrument = ObservableCounterInstrument; + + class ObservableGaugeInstrument extends ObservableInstrument { + } + exports.ObservableGaugeInstrument = ObservableGaugeInstrument; + + class ObservableUpDownCounterInstrument extends ObservableInstrument { + } + exports.ObservableUpDownCounterInstrument = ObservableUpDownCounterInstrument; + function isObservableInstrument(it) { + return it instanceof ObservableInstrument; + } + exports.isObservableInstrument = isObservableInstrument; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js +var require_Meter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Meter = undefined; + var InstrumentDescriptor_1 = require_InstrumentDescriptor(); + var Instruments_1 = require_Instruments(); + var MetricData_1 = require_MetricData(); + + class Meter { + _meterSharedState; + constructor(meterSharedState) { + this._meterSharedState = meterSharedState; + } + createGauge(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.GAUGE, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.GaugeInstrument(storage, descriptor); + } + createHistogram(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.HISTOGRAM, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.HistogramInstrument(storage, descriptor); + } + createCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.COUNTER, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.CounterInstrument(storage, descriptor); + } + createUpDownCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.UP_DOWN_COUNTER, options); + const storage = this._meterSharedState.registerMetricStorage(descriptor); + return new Instruments_1.UpDownCounterInstrument(storage, descriptor); + } + createObservableGauge(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_GAUGE, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableGaugeInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + createObservableCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_COUNTER, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + createObservableUpDownCounter(name, options) { + const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options); + const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); + return new Instruments_1.ObservableUpDownCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); + } + addBatchObservableCallback(callback, observables) { + this._meterSharedState.observableRegistry.addBatchCallback(callback, observables); + } + removeBatchObservableCallback(callback, observables) { + this._meterSharedState.observableRegistry.removeBatchCallback(callback, observables); + } + } + exports.Meter = Meter; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js +var require_MetricStorage = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricStorage = undefined; + var InstrumentDescriptor_1 = require_InstrumentDescriptor(); + + class MetricStorage { + _instrumentDescriptor; + constructor(instrumentDescriptor) { + this._instrumentDescriptor = instrumentDescriptor; + } + getInstrumentDescriptor() { + return this._instrumentDescriptor; + } + updateDescription(description) { + this._instrumentDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(this._instrumentDescriptor.name, this._instrumentDescriptor.type, { + description, + valueType: this._instrumentDescriptor.valueType, + unit: this._instrumentDescriptor.unit, + advice: this._instrumentDescriptor.advice + }); + } + } + exports.MetricStorage = MetricStorage; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js +var require_HashMap = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AttributeHashMap = exports.HashMap = undefined; + var utils_1 = require_utils6(); + + class HashMap { + _valueMap = new Map; + _keyMap = new Map; + _hash; + constructor(hash) { + this._hash = hash; + } + get(key, hashCode) { + hashCode ??= this._hash(key); + return this._valueMap.get(hashCode); + } + getOrDefault(key, defaultFactory) { + const hash = this._hash(key); + if (this._valueMap.has(hash)) { + return this._valueMap.get(hash); + } + const val = defaultFactory(); + if (!this._keyMap.has(hash)) { + this._keyMap.set(hash, key); + } + this._valueMap.set(hash, val); + return val; + } + set(key, value, hashCode) { + hashCode ??= this._hash(key); + if (!this._keyMap.has(hashCode)) { + this._keyMap.set(hashCode, key); + } + this._valueMap.set(hashCode, value); + } + has(key, hashCode) { + hashCode ??= this._hash(key); + return this._valueMap.has(hashCode); + } + *keys() { + const keyIterator = this._keyMap.entries(); + let next = keyIterator.next(); + while (next.done !== true) { + yield [next.value[1], next.value[0]]; + next = keyIterator.next(); + } + } + *entries() { + const valueIterator = this._valueMap.entries(); + let next = valueIterator.next(); + while (next.done !== true) { + yield [this._keyMap.get(next.value[0]), next.value[1], next.value[0]]; + next = valueIterator.next(); + } + } + get size() { + return this._valueMap.size; + } + } + exports.HashMap = HashMap; + + class AttributeHashMap extends HashMap { + constructor() { + super(utils_1.hashAttributes); + } + } + exports.AttributeHashMap = AttributeHashMap; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js +var require_DeltaMetricProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeltaMetricProcessor = undefined; + var utils_1 = require_utils6(); + var HashMap_1 = require_HashMap(); + + class DeltaMetricProcessor { + _activeCollectionStorage = new HashMap_1.AttributeHashMap; + _cumulativeMemoStorage = new HashMap_1.AttributeHashMap; + _cardinalityLimit; + _overflowAttributes = { "otel.metric.overflow": true }; + _overflowHashCode; + _aggregator; + constructor(aggregator, aggregationCardinalityLimit) { + this._aggregator = aggregator; + this._cardinalityLimit = (aggregationCardinalityLimit ?? 2000) - 1; + this._overflowHashCode = (0, utils_1.hashAttributes)(this._overflowAttributes); + } + record(value, attributes, _context, collectionTime) { + let accumulation = this._activeCollectionStorage.get(attributes); + if (!accumulation) { + if (this._activeCollectionStorage.size >= this._cardinalityLimit) { + const overflowAccumulation = this._activeCollectionStorage.getOrDefault(this._overflowAttributes, () => this._aggregator.createAccumulation(collectionTime)); + overflowAccumulation?.record(value); + return; + } + accumulation = this._aggregator.createAccumulation(collectionTime); + this._activeCollectionStorage.set(attributes, accumulation); + } + accumulation?.record(value); + } + batchCumulate(measurements, collectionTime) { + for (const [originalAttributes, value, originalHashCode] of measurements.entries()) { + let attributes = originalAttributes; + let hashCode = originalHashCode; + const accumulation = this._aggregator.createAccumulation(collectionTime); + accumulation?.record(value); + let delta = accumulation; + if (this._cumulativeMemoStorage.has(attributes, hashCode)) { + const previous = this._cumulativeMemoStorage.get(attributes, hashCode); + delta = this._aggregator.diff(previous, accumulation); + } else { + if (this._cumulativeMemoStorage.size >= this._cardinalityLimit) { + attributes = this._overflowAttributes; + hashCode = this._overflowHashCode; + if (this._cumulativeMemoStorage.has(attributes, hashCode)) { + const previous = this._cumulativeMemoStorage.get(attributes, hashCode); + delta = this._aggregator.diff(previous, accumulation); + } + } + } + if (this._activeCollectionStorage.has(attributes, hashCode)) { + const active = this._activeCollectionStorage.get(attributes, hashCode); + delta = this._aggregator.merge(active, delta); + } + this._cumulativeMemoStorage.set(attributes, accumulation, hashCode); + this._activeCollectionStorage.set(attributes, delta, hashCode); + } + } + collect() { + const unreportedDelta = this._activeCollectionStorage; + this._activeCollectionStorage = new HashMap_1.AttributeHashMap; + return unreportedDelta; + } + } + exports.DeltaMetricProcessor = DeltaMetricProcessor; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js +var require_TemporalMetricProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TemporalMetricProcessor = undefined; + var AggregationTemporality_1 = require_AggregationTemporality(); + var HashMap_1 = require_HashMap(); + + class TemporalMetricProcessor { + _aggregator; + _unreportedAccumulations = new Map; + _reportHistory = new Map; + constructor(aggregator, collectorHandles) { + this._aggregator = aggregator; + collectorHandles.forEach((handle) => { + this._unreportedAccumulations.set(handle, []); + }); + } + buildMetrics(collector, instrumentDescriptor, currentAccumulations, collectionTime) { + this._stashAccumulations(currentAccumulations); + const unreportedAccumulations = this._getMergedUnreportedAccumulations(collector); + let result = unreportedAccumulations; + let aggregationTemporality; + if (this._reportHistory.has(collector)) { + const last = this._reportHistory.get(collector); + const lastCollectionTime = last.collectionTime; + aggregationTemporality = last.aggregationTemporality; + if (aggregationTemporality === AggregationTemporality_1.AggregationTemporality.CUMULATIVE) { + result = TemporalMetricProcessor.merge(last.accumulations, unreportedAccumulations, this._aggregator); + } else { + result = TemporalMetricProcessor.calibrateStartTime(last.accumulations, unreportedAccumulations, lastCollectionTime); + } + } else { + aggregationTemporality = collector.selectAggregationTemporality(instrumentDescriptor.type); + } + this._reportHistory.set(collector, { + accumulations: result, + collectionTime, + aggregationTemporality + }); + const accumulationRecords = AttributesMapToAccumulationRecords(result); + if (accumulationRecords.length === 0) { + return; + } + return this._aggregator.toMetricData(instrumentDescriptor, aggregationTemporality, accumulationRecords, collectionTime); + } + _stashAccumulations(currentAccumulation) { + const registeredCollectors = this._unreportedAccumulations.keys(); + for (const collector of registeredCollectors) { + let stash = this._unreportedAccumulations.get(collector); + if (stash === undefined) { + stash = []; + this._unreportedAccumulations.set(collector, stash); + } + stash.push(currentAccumulation); + } + } + _getMergedUnreportedAccumulations(collector) { + let result = new HashMap_1.AttributeHashMap; + const unreportedList = this._unreportedAccumulations.get(collector); + this._unreportedAccumulations.set(collector, []); + if (unreportedList === undefined) { + return result; + } + for (const it of unreportedList) { + result = TemporalMetricProcessor.merge(result, it, this._aggregator); + } + return result; + } + static merge(last, current, aggregator) { + const result = last; + const iterator = current.entries(); + let next = iterator.next(); + while (next.done !== true) { + const [key, record, hash] = next.value; + if (last.has(key, hash)) { + const lastAccumulation = last.get(key, hash); + const accumulation = aggregator.merge(lastAccumulation, record); + result.set(key, accumulation, hash); + } else { + result.set(key, record, hash); + } + next = iterator.next(); + } + return result; + } + static calibrateStartTime(last, current, lastCollectionTime) { + for (const [key, hash] of last.keys()) { + const currentAccumulation = current.get(key, hash); + currentAccumulation?.setStartTime(lastCollectionTime); + } + return current; + } + } + exports.TemporalMetricProcessor = TemporalMetricProcessor; + function AttributesMapToAccumulationRecords(map) { + return Array.from(map.entries()); + } +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js +var require_AsyncMetricStorage = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncMetricStorage = undefined; + var MetricStorage_1 = require_MetricStorage(); + var DeltaMetricProcessor_1 = require_DeltaMetricProcessor(); + var TemporalMetricProcessor_1 = require_TemporalMetricProcessor(); + var HashMap_1 = require_HashMap(); + + class AsyncMetricStorage extends MetricStorage_1.MetricStorage { + _aggregationCardinalityLimit; + _deltaMetricStorage; + _temporalMetricStorage; + _attributesProcessor; + constructor(_instrumentDescriptor, aggregator, attributesProcessor, collectorHandles, aggregationCardinalityLimit) { + super(_instrumentDescriptor); + this._aggregationCardinalityLimit = aggregationCardinalityLimit; + this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); + this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); + this._attributesProcessor = attributesProcessor; + } + record(measurements, observationTime) { + const processed = new HashMap_1.AttributeHashMap; + for (const [attributes, value] of measurements.entries()) { + processed.set(this._attributesProcessor.process(attributes), value); + } + this._deltaMetricStorage.batchCumulate(processed, observationTime); + } + collect(collector, collectionTime) { + const accumulations = this._deltaMetricStorage.collect(); + return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); + } + } + exports.AsyncMetricStorage = AsyncMetricStorage; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js +var require_RegistrationConflicts = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getConflictResolutionRecipe = exports.getDescriptionResolutionRecipe = exports.getTypeConflictResolutionRecipe = exports.getUnitConflictResolutionRecipe = exports.getValueTypeConflictResolutionRecipe = exports.getIncompatibilityDetails = undefined; + function getIncompatibilityDetails(existing, otherDescriptor) { + let incompatibility = ""; + if (existing.unit !== otherDescriptor.unit) { + incompatibility += ` - Unit '${existing.unit}' does not match '${otherDescriptor.unit}' +`; + } + if (existing.type !== otherDescriptor.type) { + incompatibility += ` - Type '${existing.type}' does not match '${otherDescriptor.type}' +`; + } + if (existing.valueType !== otherDescriptor.valueType) { + incompatibility += ` - Value Type '${existing.valueType}' does not match '${otherDescriptor.valueType}' +`; + } + if (existing.description !== otherDescriptor.description) { + incompatibility += ` - Description '${existing.description}' does not match '${otherDescriptor.description}' +`; + } + return incompatibility; + } + exports.getIncompatibilityDetails = getIncompatibilityDetails; + function getValueTypeConflictResolutionRecipe(existing, otherDescriptor) { + return ` - use valueType '${existing.valueType}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; + } + exports.getValueTypeConflictResolutionRecipe = getValueTypeConflictResolutionRecipe; + function getUnitConflictResolutionRecipe(existing, otherDescriptor) { + return ` - use unit '${existing.unit}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; + } + exports.getUnitConflictResolutionRecipe = getUnitConflictResolutionRecipe; + function getTypeConflictResolutionRecipe(existing, otherDescriptor) { + const selector = { + name: otherDescriptor.name, + type: otherDescriptor.type, + unit: otherDescriptor.unit + }; + const selectorString = JSON.stringify(selector); + return ` - create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'`; + } + exports.getTypeConflictResolutionRecipe = getTypeConflictResolutionRecipe; + function getDescriptionResolutionRecipe(existing, otherDescriptor) { + const selector = { + name: otherDescriptor.name, + type: otherDescriptor.type, + unit: otherDescriptor.unit + }; + const selectorString = JSON.stringify(selector); + return ` - create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}' + - OR - create a new view with the name ${existing.name} and description '${existing.description}' and InstrumentSelector ${selectorString} + - OR - create a new view with the name ${otherDescriptor.name} and description '${existing.description}' and InstrumentSelector ${selectorString}`; + } + exports.getDescriptionResolutionRecipe = getDescriptionResolutionRecipe; + function getConflictResolutionRecipe(existing, otherDescriptor) { + if (existing.valueType !== otherDescriptor.valueType) { + return getValueTypeConflictResolutionRecipe(existing, otherDescriptor); + } + if (existing.unit !== otherDescriptor.unit) { + return getUnitConflictResolutionRecipe(existing, otherDescriptor); + } + if (existing.type !== otherDescriptor.type) { + return getTypeConflictResolutionRecipe(existing, otherDescriptor); + } + if (existing.description !== otherDescriptor.description) { + return getDescriptionResolutionRecipe(existing, otherDescriptor); + } + return ""; + } + exports.getConflictResolutionRecipe = getConflictResolutionRecipe; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js +var require_MetricStorageRegistry = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricStorageRegistry = undefined; + var InstrumentDescriptor_1 = require_InstrumentDescriptor(); + var api = require_src(); + var RegistrationConflicts_1 = require_RegistrationConflicts(); + + class MetricStorageRegistry { + _sharedRegistry = new Map; + _perCollectorRegistry = new Map; + static create() { + return new MetricStorageRegistry; + } + getStorages(collector) { + let storages = []; + for (const metricStorages of this._sharedRegistry.values()) { + storages = storages.concat(metricStorages); + } + const perCollectorStorages = this._perCollectorRegistry.get(collector); + if (perCollectorStorages != null) { + for (const metricStorages of perCollectorStorages.values()) { + storages = storages.concat(metricStorages); + } + } + return storages; + } + register(storage) { + this._registerStorage(storage, this._sharedRegistry); + } + registerForCollector(collector, storage) { + let storageMap = this._perCollectorRegistry.get(collector); + if (storageMap == null) { + storageMap = new Map; + this._perCollectorRegistry.set(collector, storageMap); + } + this._registerStorage(storage, storageMap); + } + findOrUpdateCompatibleStorage(expectedDescriptor) { + const storages = this._sharedRegistry.get(expectedDescriptor.name); + if (storages === undefined) { + return null; + } + return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); + } + findOrUpdateCompatibleCollectorStorage(collector, expectedDescriptor) { + const storageMap = this._perCollectorRegistry.get(collector); + if (storageMap === undefined) { + return null; + } + const storages = storageMap.get(expectedDescriptor.name); + if (storages === undefined) { + return null; + } + return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); + } + _registerStorage(storage, storageMap) { + const descriptor = storage.getInstrumentDescriptor(); + const storages = storageMap.get(descriptor.name); + if (storages === undefined) { + storageMap.set(descriptor.name, [storage]); + return; + } + storages.push(storage); + } + _findOrUpdateCompatibleStorage(expectedDescriptor, existingStorages) { + let compatibleStorage = null; + for (const existingStorage of existingStorages) { + const existingDescriptor = existingStorage.getInstrumentDescriptor(); + if ((0, InstrumentDescriptor_1.isDescriptorCompatibleWith)(existingDescriptor, expectedDescriptor)) { + if (existingDescriptor.description !== expectedDescriptor.description) { + if (expectedDescriptor.description.length > existingDescriptor.description.length) { + existingStorage.updateDescription(expectedDescriptor.description); + } + api.diag.warn("A view or instrument with the name ", expectedDescriptor.name, ` has already been registered, but has a different description and is incompatible with another registered view. +`, `Details: +`, (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), `The longer description will be used. +To resolve the conflict:`, (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); + } + compatibleStorage = existingStorage; + } else { + api.diag.warn("A view or instrument with the name ", expectedDescriptor.name, ` has already been registered and is incompatible with another registered view. +`, `Details: +`, (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), `To resolve the conflict: +`, (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); + } + } + return compatibleStorage; + } + } + exports.MetricStorageRegistry = MetricStorageRegistry; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js +var require_MultiWritableMetricStorage = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MultiMetricStorage = undefined; + + class MultiMetricStorage { + _backingStorages; + constructor(backingStorages) { + this._backingStorages = backingStorages; + } + record(value, attributes, context, recordTime) { + const storages = this._backingStorages; + for (let i = 0;i < storages.length; i++) { + storages[i].record(value, attributes, context, recordTime); + } + } + } + exports.MultiMetricStorage = MultiMetricStorage; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js +var require_ObservableResult = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchObservableResultImpl = exports.ObservableResultImpl = undefined; + var api_1 = require_src(); + var HashMap_1 = require_HashMap(); + var Instruments_1 = require_Instruments(); + + class ObservableResultImpl { + _buffer = new HashMap_1.AttributeHashMap; + _instrumentName; + _valueType; + constructor(instrumentName, valueType) { + this._instrumentName = instrumentName; + this._valueType = valueType; + } + observe(value, attributes = {}) { + if (typeof value !== "number") { + api_1.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${value}`); + return; + } + if (this._valueType === api_1.ValueType.INT && !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`); + value = Math.trunc(value); + if (!Number.isInteger(value)) { + return; + } + } + this._buffer.set(attributes, value); + } + } + exports.ObservableResultImpl = ObservableResultImpl; + + class BatchObservableResultImpl { + _buffer = new Map; + observe(metric, value, attributes = {}) { + if (!(0, Instruments_1.isObservableInstrument)(metric)) { + return; + } + let map = this._buffer.get(metric); + if (map == null) { + map = new HashMap_1.AttributeHashMap; + this._buffer.set(metric, map); + } + if (typeof value !== "number") { + api_1.diag.warn(`non-number value provided to metric ${metric._descriptor.name}: ${value}`); + return; + } + if (metric._descriptor.valueType === api_1.ValueType.INT && !Number.isInteger(value)) { + api_1.diag.warn(`INT value type cannot accept a floating-point value for ${metric._descriptor.name}, ignoring the fractional digits.`); + value = Math.trunc(value); + if (!Number.isInteger(value)) { + return; + } + } + map.set(attributes, value); + } + } + exports.BatchObservableResultImpl = BatchObservableResultImpl; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js +var require_ObservableRegistry = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ObservableRegistry = undefined; + var api_1 = require_src(); + var Instruments_1 = require_Instruments(); + var ObservableResult_1 = require_ObservableResult(); + var utils_1 = require_utils6(); + + class ObservableRegistry { + _callbacks = []; + _batchCallbacks = []; + addCallback(callback, instrument) { + const idx = this._findCallback(callback, instrument); + if (idx >= 0) { + return; + } + this._callbacks.push({ callback, instrument }); + } + removeCallback(callback, instrument) { + const idx = this._findCallback(callback, instrument); + if (idx < 0) { + return; + } + this._callbacks.splice(idx, 1); + } + addBatchCallback(callback, instruments) { + const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); + if (observableInstruments.size === 0) { + api_1.diag.error("BatchObservableCallback is not associated with valid instruments", instruments); + return; + } + const idx = this._findBatchCallback(callback, observableInstruments); + if (idx >= 0) { + return; + } + this._batchCallbacks.push({ callback, instruments: observableInstruments }); + } + removeBatchCallback(callback, instruments) { + const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); + const idx = this._findBatchCallback(callback, observableInstruments); + if (idx < 0) { + return; + } + this._batchCallbacks.splice(idx, 1); + } + async observe(collectionTime, timeoutMillis) { + const callbackFutures = this._observeCallbacks(collectionTime, timeoutMillis); + const batchCallbackFutures = this._observeBatchCallbacks(collectionTime, timeoutMillis); + const results = await Promise.allSettled([ + ...callbackFutures, + ...batchCallbackFutures + ]); + const rejections = results.filter((result) => result.status === "rejected").map((result) => result.reason); + return rejections; + } + _observeCallbacks(observationTime, timeoutMillis) { + return this._callbacks.map(async ({ callback, instrument }) => { + const observableResult = new ObservableResult_1.ObservableResultImpl(instrument._descriptor.name, instrument._descriptor.valueType); + let callPromise = Promise.resolve(callback(observableResult)); + if (timeoutMillis != null) { + callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); + } + await callPromise; + instrument._metricStorages.forEach((metricStorage) => { + metricStorage.record(observableResult._buffer, observationTime); + }); + }); + } + _observeBatchCallbacks(observationTime, timeoutMillis) { + return this._batchCallbacks.map(async ({ callback, instruments }) => { + const observableResult = new ObservableResult_1.BatchObservableResultImpl; + let callPromise = Promise.resolve(callback(observableResult)); + if (timeoutMillis != null) { + callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); + } + await callPromise; + instruments.forEach((instrument) => { + const buffer = observableResult._buffer.get(instrument); + if (buffer == null) { + return; + } + instrument._metricStorages.forEach((metricStorage) => { + metricStorage.record(buffer, observationTime); + }); + }); + }); + } + _findCallback(callback, instrument) { + return this._callbacks.findIndex((record) => { + return record.callback === callback && record.instrument === instrument; + }); + } + _findBatchCallback(callback, instruments) { + return this._batchCallbacks.findIndex((record) => { + return record.callback === callback && (0, utils_1.setEquals)(record.instruments, instruments); + }); + } + } + exports.ObservableRegistry = ObservableRegistry; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js +var require_SyncMetricStorage = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SyncMetricStorage = undefined; + var MetricStorage_1 = require_MetricStorage(); + var DeltaMetricProcessor_1 = require_DeltaMetricProcessor(); + var TemporalMetricProcessor_1 = require_TemporalMetricProcessor(); + + class SyncMetricStorage extends MetricStorage_1.MetricStorage { + _aggregationCardinalityLimit; + _deltaMetricStorage; + _temporalMetricStorage; + _attributesProcessor; + constructor(instrumentDescriptor, aggregator, attributesProcessor, collectorHandles, aggregationCardinalityLimit) { + super(instrumentDescriptor); + this._aggregationCardinalityLimit = aggregationCardinalityLimit; + this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); + this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); + this._attributesProcessor = attributesProcessor; + } + record(value, attributes, context, recordTime) { + attributes = this._attributesProcessor.process(attributes, context); + this._deltaMetricStorage.record(value, attributes, context, recordTime); + } + collect(collector, collectionTime) { + const accumulations = this._deltaMetricStorage.collect(); + return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); + } + } + exports.SyncMetricStorage = SyncMetricStorage; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js +var require_AttributesProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.createMultiAttributesProcessor = exports.createNoopAttributesProcessor = undefined; + + class NoopAttributesProcessor { + process(incoming, _context) { + return incoming; + } + } + + class MultiAttributesProcessor { + _processors; + constructor(processors) { + this._processors = processors; + } + process(incoming, context) { + let filteredAttributes = incoming; + for (const processor of this._processors) { + filteredAttributes = processor.process(filteredAttributes, context); + } + return filteredAttributes; + } + } + + class AllowListProcessor { + _allowedAttributeNames; + constructor(allowedAttributeNames) { + this._allowedAttributeNames = new Set(allowedAttributeNames); + } + process(incoming, _context) { + const filteredAttributes = {}; + for (const attributeName in incoming) { + if (Object.prototype.hasOwnProperty.call(incoming, attributeName) && this._allowedAttributeNames.has(attributeName)) { + filteredAttributes[attributeName] = incoming[attributeName]; + } + } + return filteredAttributes; + } + } + + class DenyListProcessor { + _deniedAttributeNames; + constructor(deniedAttributeNames) { + this._deniedAttributeNames = new Set(deniedAttributeNames); + } + process(incoming, _context) { + const filteredAttributes = {}; + for (const attributeName in incoming) { + if (Object.prototype.hasOwnProperty.call(incoming, attributeName) && !this._deniedAttributeNames.has(attributeName)) { + filteredAttributes[attributeName] = incoming[attributeName]; + } + } + return filteredAttributes; + } + } + function createNoopAttributesProcessor() { + return NOOP; + } + exports.createNoopAttributesProcessor = createNoopAttributesProcessor; + function createMultiAttributesProcessor(processors) { + return new MultiAttributesProcessor(processors); + } + exports.createMultiAttributesProcessor = createMultiAttributesProcessor; + function createAllowListAttributesProcessor(attributeAllowList) { + return new AllowListProcessor(attributeAllowList); + } + exports.createAllowListAttributesProcessor = createAllowListAttributesProcessor; + function createDenyListAttributesProcessor(attributeDenyList) { + return new DenyListProcessor(attributeDenyList); + } + exports.createDenyListAttributesProcessor = createDenyListAttributesProcessor; + var NOOP = new NoopAttributesProcessor; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js +var require_MeterSharedState = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterSharedState = undefined; + var InstrumentDescriptor_1 = require_InstrumentDescriptor(); + var Meter_1 = require_Meter(); + var AsyncMetricStorage_1 = require_AsyncMetricStorage(); + var MetricStorageRegistry_1 = require_MetricStorageRegistry(); + var MultiWritableMetricStorage_1 = require_MultiWritableMetricStorage(); + var ObservableRegistry_1 = require_ObservableRegistry(); + var SyncMetricStorage_1 = require_SyncMetricStorage(); + var AttributesProcessor_1 = require_AttributesProcessor(); + + class MeterSharedState { + metricStorageRegistry = new MetricStorageRegistry_1.MetricStorageRegistry; + observableRegistry = new ObservableRegistry_1.ObservableRegistry; + meter; + _meterProviderSharedState; + _instrumentationScope; + constructor(meterProviderSharedState, instrumentationScope) { + this.meter = new Meter_1.Meter(this); + this._meterProviderSharedState = meterProviderSharedState; + this._instrumentationScope = instrumentationScope; + } + registerMetricStorage(descriptor) { + const storages = this._registerMetricStorage(descriptor, SyncMetricStorage_1.SyncMetricStorage); + if (storages.length === 1) { + return storages[0]; + } + return new MultiWritableMetricStorage_1.MultiMetricStorage(storages); + } + registerAsyncMetricStorage(descriptor) { + const storages = this._registerMetricStorage(descriptor, AsyncMetricStorage_1.AsyncMetricStorage); + return storages; + } + async collect(collector, collectionTime, options) { + const errors = await this.observableRegistry.observe(collectionTime, options?.timeoutMillis); + const storages = this.metricStorageRegistry.getStorages(collector); + if (storages.length === 0) { + return null; + } + const metricDataList = []; + storages.forEach((metricStorage) => { + const metricData = metricStorage.collect(collector, collectionTime); + if (metricData != null) { + metricDataList.push(metricData); + } + }); + if (metricDataList.length === 0) { + return { errors }; + } + return { + scopeMetrics: { + scope: this._instrumentationScope, + metrics: metricDataList + }, + errors + }; + } + _registerMetricStorage(descriptor, MetricStorageType) { + const views = this._meterProviderSharedState.viewRegistry.findViews(descriptor, this._instrumentationScope); + let storages = views.map((view) => { + const viewDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptorWithView)(view, descriptor); + const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor); + if (compatibleStorage != null) { + return compatibleStorage; + } + const aggregator = view.aggregation.createAggregator(viewDescriptor); + const viewStorage = new MetricStorageType(viewDescriptor, aggregator, view.attributesProcessor, this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit); + this.metricStorageRegistry.register(viewStorage); + return viewStorage; + }); + if (storages.length === 0) { + const perCollectorAggregations = this._meterProviderSharedState.selectAggregations(descriptor.type); + const collectorStorages = perCollectorAggregations.map(([collector, aggregation]) => { + const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(collector, descriptor); + if (compatibleStorage != null) { + return compatibleStorage; + } + const aggregator = aggregation.createAggregator(descriptor); + const cardinalityLimit = collector.selectCardinalityLimit(descriptor.type); + const storage = new MetricStorageType(descriptor, aggregator, (0, AttributesProcessor_1.createNoopAttributesProcessor)(), [collector], cardinalityLimit); + this.metricStorageRegistry.registerForCollector(collector, storage); + return storage; + }); + storages = storages.concat(collectorStorages); + } + return storages; + } + } + exports.MeterSharedState = MeterSharedState; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js +var require_MeterProviderSharedState = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterProviderSharedState = undefined; + var utils_1 = require_utils6(); + var ViewRegistry_1 = require_ViewRegistry(); + var MeterSharedState_1 = require_MeterSharedState(); + var AggregationOption_1 = require_AggregationOption(); + + class MeterProviderSharedState { + viewRegistry = new ViewRegistry_1.ViewRegistry; + metricCollectors = []; + meterSharedStates = new Map; + resource; + constructor(resource) { + this.resource = resource; + } + getMeterSharedState(instrumentationScope) { + const id = (0, utils_1.instrumentationScopeId)(instrumentationScope); + let meterSharedState = this.meterSharedStates.get(id); + if (meterSharedState == null) { + meterSharedState = new MeterSharedState_1.MeterSharedState(this, instrumentationScope); + this.meterSharedStates.set(id, meterSharedState); + } + return meterSharedState; + } + selectAggregations(instrumentType) { + const result = []; + for (const collector of this.metricCollectors) { + result.push([ + collector, + (0, AggregationOption_1.toAggregation)(collector.selectAggregation(instrumentType)) + ]); + } + return result; + } + } + exports.MeterProviderSharedState = MeterProviderSharedState; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js +var require_MetricCollector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricCollector = undefined; + var core_1 = require_src3(); + + class MetricCollector { + _sharedState; + _metricReader; + constructor(sharedState, metricReader) { + this._sharedState = sharedState; + this._metricReader = metricReader; + } + async collect(options) { + const collectionTime = (0, core_1.millisToHrTime)(Date.now()); + const scopeMetrics = []; + const errors = []; + const meterCollectionPromises = Array.from(this._sharedState.meterSharedStates.values()).map(async (meterSharedState) => { + const current = await meterSharedState.collect(this, collectionTime, options); + if (current?.scopeMetrics != null) { + scopeMetrics.push(current.scopeMetrics); + } + if (current?.errors != null) { + errors.push(...current.errors); + } + }); + await Promise.all(meterCollectionPromises); + return { + resourceMetrics: { + resource: this._sharedState.resource, + scopeMetrics + }, + errors + }; + } + async forceFlush(options) { + await this._metricReader.forceFlush(options); + } + async shutdown(options) { + await this._metricReader.shutdown(options); + } + selectAggregationTemporality(instrumentType) { + return this._metricReader.selectAggregationTemporality(instrumentType); + } + selectAggregation(instrumentType) { + return this._metricReader.selectAggregation(instrumentType); + } + selectCardinalityLimit(instrumentType) { + return this._metricReader.selectCardinalityLimit?.(instrumentType) ?? 2000; + } + } + exports.MetricCollector = MetricCollector; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js +var require_Predicate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExactPredicate = exports.PatternPredicate = undefined; + var ESCAPE = /[\^$\\.+?()[\]{}|]/g; + + class PatternPredicate { + _matchAll; + _regexp; + constructor(pattern) { + if (pattern === "*") { + this._matchAll = true; + this._regexp = /.*/; + } else { + this._matchAll = false; + this._regexp = new RegExp(PatternPredicate.escapePattern(pattern)); + } + } + match(str) { + if (this._matchAll) { + return true; + } + return this._regexp.test(str); + } + static escapePattern(pattern) { + return `^${pattern.replace(ESCAPE, "\\$&").replace("*", ".*")}$`; + } + static hasWildcard(pattern) { + return pattern.includes("*"); + } + } + exports.PatternPredicate = PatternPredicate; + + class ExactPredicate { + _matchAll; + _pattern; + constructor(pattern) { + this._matchAll = pattern === undefined; + this._pattern = pattern; + } + match(str) { + if (this._matchAll) { + return true; + } + if (str === this._pattern) { + return true; + } + return false; + } + } + exports.ExactPredicate = ExactPredicate; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js +var require_InstrumentSelector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstrumentSelector = undefined; + var Predicate_1 = require_Predicate(); + + class InstrumentSelector { + _nameFilter; + _type; + _unitFilter; + constructor(criteria) { + this._nameFilter = new Predicate_1.PatternPredicate(criteria?.name ?? "*"); + this._type = criteria?.type; + this._unitFilter = new Predicate_1.ExactPredicate(criteria?.unit); + } + getType() { + return this._type; + } + getNameFilter() { + return this._nameFilter; + } + getUnitFilter() { + return this._unitFilter; + } + } + exports.InstrumentSelector = InstrumentSelector; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js +var require_MeterSelector = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterSelector = undefined; + var Predicate_1 = require_Predicate(); + + class MeterSelector { + _nameFilter; + _versionFilter; + _schemaUrlFilter; + constructor(criteria) { + this._nameFilter = new Predicate_1.ExactPredicate(criteria?.name); + this._versionFilter = new Predicate_1.ExactPredicate(criteria?.version); + this._schemaUrlFilter = new Predicate_1.ExactPredicate(criteria?.schemaUrl); + } + getNameFilter() { + return this._nameFilter; + } + getVersionFilter() { + return this._versionFilter; + } + getSchemaUrlFilter() { + return this._schemaUrlFilter; + } + } + exports.MeterSelector = MeterSelector; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js +var require_View = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.View = undefined; + var Predicate_1 = require_Predicate(); + var AttributesProcessor_1 = require_AttributesProcessor(); + var InstrumentSelector_1 = require_InstrumentSelector(); + var MeterSelector_1 = require_MeterSelector(); + var AggregationOption_1 = require_AggregationOption(); + function isSelectorNotProvided(options) { + return options.instrumentName == null && options.instrumentType == null && options.instrumentUnit == null && options.meterName == null && options.meterVersion == null && options.meterSchemaUrl == null; + } + function validateViewOptions(viewOptions) { + if (isSelectorNotProvided(viewOptions)) { + throw new Error("Cannot create view with no selector arguments supplied"); + } + if (viewOptions.name != null && (viewOptions?.instrumentName == null || Predicate_1.PatternPredicate.hasWildcard(viewOptions.instrumentName))) { + throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter."); + } + } + + class View { + name; + description; + aggregation; + attributesProcessor; + instrumentSelector; + meterSelector; + aggregationCardinalityLimit; + constructor(viewOptions) { + validateViewOptions(viewOptions); + if (viewOptions.attributesProcessors != null) { + this.attributesProcessor = (0, AttributesProcessor_1.createMultiAttributesProcessor)(viewOptions.attributesProcessors); + } else { + this.attributesProcessor = (0, AttributesProcessor_1.createNoopAttributesProcessor)(); + } + this.name = viewOptions.name; + this.description = viewOptions.description; + this.aggregation = (0, AggregationOption_1.toAggregation)(viewOptions.aggregation ?? { type: AggregationOption_1.AggregationType.DEFAULT }); + this.instrumentSelector = new InstrumentSelector_1.InstrumentSelector({ + name: viewOptions.instrumentName, + type: viewOptions.instrumentType, + unit: viewOptions.instrumentUnit + }); + this.meterSelector = new MeterSelector_1.MeterSelector({ + name: viewOptions.meterName, + version: viewOptions.meterVersion, + schemaUrl: viewOptions.meterSchemaUrl + }); + this.aggregationCardinalityLimit = viewOptions.aggregationCardinalityLimit; + } + } + exports.View = View; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js +var require_MeterProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MeterProvider = undefined; + var api_1 = require_src(); + var resources_1 = require_src6(); + var MetricReader_1 = require_MetricReader(); + var MeterProviderSharedState_1 = require_MeterProviderSharedState(); + var MetricCollector_1 = require_MetricCollector(); + var View_1 = require_View(); + + class MeterProvider { + _sharedState; + _shutdown = false; + constructor(options) { + this._sharedState = new MeterProviderSharedState_1.MeterProviderSharedState(options?.resource ?? (0, resources_1.defaultResource)()); + if (options?.views != null && options.views.length > 0) { + for (const viewOption of options.views) { + this._sharedState.viewRegistry.addView(new View_1.View(viewOption)); + } + } + if (options?.readers != null && options.readers.length > 0) { + for (const metricReader of options.readers) { + const collector = new MetricCollector_1.MetricCollector(this._sharedState, metricReader); + metricReader.setMetricProducer(collector); + this._sharedState.metricCollectors.push(collector); + if (options.sdkMetricsEnabled && metricReader instanceof MetricReader_1.MetricReader) { + metricReader._setSelfObsMeterProvider(this); + } + } + } + } + getMeter(name, version = "", options = {}) { + if (this._shutdown) { + api_1.diag.warn("A shutdown MeterProvider cannot provide a Meter"); + return (0, api_1.createNoopMeter)(); + } + return this._sharedState.getMeterSharedState({ + name, + version, + schemaUrl: options.schemaUrl + }).meter; + } + async shutdown(options) { + if (this._shutdown) { + api_1.diag.warn("shutdown may only be called once per MeterProvider"); + return; + } + this._shutdown = true; + await Promise.all(this._sharedState.metricCollectors.map((collector) => { + return collector.shutdown(options); + })); + } + async forceFlush(options) { + if (this._shutdown) { + api_1.diag.warn("invalid attempt to force flush after MeterProvider shutdown"); + return; + } + await Promise.all(this._sharedState.metricCollectors.map((collector) => { + return collector.forceFlush(options); + })); + } + } + exports.MeterProvider = MeterProvider; +}); + +// node_modules/@opentelemetry/sdk-metrics/build/src/index.js +var require_src7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TimeoutError = exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.AggregationType = exports.MeterProvider = exports.ConsoleMetricExporter = exports.InMemoryMetricExporter = exports.PeriodicExportingMetricReader = exports.MetricReader = exports.InstrumentType = exports.DataPointType = exports.AggregationTemporality = undefined; + var AggregationTemporality_1 = require_AggregationTemporality(); + Object.defineProperty(exports, "AggregationTemporality", { enumerable: true, get: function() { + return AggregationTemporality_1.AggregationTemporality; + } }); + var MetricData_1 = require_MetricData(); + Object.defineProperty(exports, "DataPointType", { enumerable: true, get: function() { + return MetricData_1.DataPointType; + } }); + Object.defineProperty(exports, "InstrumentType", { enumerable: true, get: function() { + return MetricData_1.InstrumentType; + } }); + var MetricReader_1 = require_MetricReader(); + Object.defineProperty(exports, "MetricReader", { enumerable: true, get: function() { + return MetricReader_1.MetricReader; + } }); + var PeriodicExportingMetricReader_1 = require_PeriodicExportingMetricReader(); + Object.defineProperty(exports, "PeriodicExportingMetricReader", { enumerable: true, get: function() { + return PeriodicExportingMetricReader_1.PeriodicExportingMetricReader; + } }); + var InMemoryMetricExporter_1 = require_InMemoryMetricExporter(); + Object.defineProperty(exports, "InMemoryMetricExporter", { enumerable: true, get: function() { + return InMemoryMetricExporter_1.InMemoryMetricExporter; + } }); + var ConsoleMetricExporter_1 = require_ConsoleMetricExporter(); + Object.defineProperty(exports, "ConsoleMetricExporter", { enumerable: true, get: function() { + return ConsoleMetricExporter_1.ConsoleMetricExporter; + } }); + var MeterProvider_1 = require_MeterProvider(); + Object.defineProperty(exports, "MeterProvider", { enumerable: true, get: function() { + return MeterProvider_1.MeterProvider; + } }); + var AggregationOption_1 = require_AggregationOption(); + Object.defineProperty(exports, "AggregationType", { enumerable: true, get: function() { + return AggregationOption_1.AggregationType; + } }); + var AttributesProcessor_1 = require_AttributesProcessor(); + Object.defineProperty(exports, "createAllowListAttributesProcessor", { enumerable: true, get: function() { + return AttributesProcessor_1.createAllowListAttributesProcessor; + } }); + Object.defineProperty(exports, "createDenyListAttributesProcessor", { enumerable: true, get: function() { + return AttributesProcessor_1.createDenyListAttributesProcessor; + } }); + var utils_1 = require_utils6(); + Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function() { + return utils_1.TimeoutError; + } }); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics-serializer.js +var require_metrics_serializer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serializeMetricsExportRequest = undefined; + var api_1 = require_src(); + var sdk_metrics_1 = require_src7(); + var common_serializer_1 = require_common_serializer(); + var protobuf_size_estimator_1 = require_protobuf_size_estimator(); + var protobuf_writer_1 = require_protobuf_writer(); + function serializeNumberDataPoint(writer, dataPoint, valueType) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + writer.writeTag(2, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.startTime); + writer.writeTag(3, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.endTime); + if (valueType === api_1.ValueType.INT) { + writer.writeTag(6, 1); + writer.writeSfixed64(dataPoint.value); + } else { + writer.writeTag(4, 1); + writer.writeDouble(dataPoint.value); + } + if (dataPoint.attributes) { + (0, common_serializer_1.writeAttributes)(writer, dataPoint.attributes, 7); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeHistogramDataPoint(writer, dataPoint) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + const histogram = dataPoint.value; + writer.writeTag(2, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.startTime); + writer.writeTag(3, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.endTime); + writer.writeTag(4, 1); + writer.writeFixed64(histogram.count >>> 0, histogram.count / 4294967296 >>> 0); + if (histogram.sum !== undefined) { + writer.writeTag(5, 1); + writer.writeDouble(histogram.sum); + } + if (histogram.buckets.counts.length > 0) { + writer.writeTag(6, 2); + const countsStart = writer.startLengthDelimited(); + const countsStartPos = writer.pos; + for (const count of histogram.buckets.counts) { + writer.writeFixed64(count >>> 0, count / 4294967296 >>> 0); + } + writer.finishLengthDelimited(countsStart, writer.pos - countsStartPos); + } + if (histogram.buckets.boundaries.length > 0) { + writer.writeTag(7, 2); + const boundsStart = writer.startLengthDelimited(); + const boundsStartPos = writer.pos; + for (const bound of histogram.buckets.boundaries) { + writer.writeDouble(bound); + } + writer.finishLengthDelimited(boundsStart, writer.pos - boundsStartPos); + } + if (dataPoint.attributes) { + (0, common_serializer_1.writeAttributes)(writer, dataPoint.attributes, 9); + } + if (histogram.min !== undefined) { + writer.writeTag(11, 1); + writer.writeDouble(histogram.min); + } + if (histogram.max !== undefined) { + writer.writeTag(12, 1); + writer.writeDouble(histogram.max); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeExponentialBuckets(writer, offset, bucketCounts) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + if (offset !== 0) { + writer.writeTag(1, 0); + writer.writeSint32(offset); + } + if (bucketCounts.length > 0) { + writer.writeTag(2, 2); + const bcStart = writer.startLengthDelimited(); + const bcStartPos = writer.pos; + for (const count of bucketCounts) { + writer.writeVarint(count); + } + writer.finishLengthDelimited(bcStart, writer.pos - bcStartPos); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeExponentialHistogramDataPoint(writer, dataPoint) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + const histogram = dataPoint.value; + if (dataPoint.attributes) { + (0, common_serializer_1.writeAttributes)(writer, dataPoint.attributes, 1); + } + writer.writeTag(2, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.startTime); + writer.writeTag(3, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, dataPoint.endTime); + writer.writeTag(4, 1); + writer.writeFixed64(histogram.count >>> 0, histogram.count / 4294967296 >>> 0); + if (histogram.sum !== undefined) { + writer.writeTag(5, 1); + writer.writeDouble(histogram.sum); + } + if (histogram.scale !== 0) { + writer.writeTag(6, 0); + writer.writeSint32(histogram.scale); + } + writer.writeTag(7, 1); + writer.writeFixed64(histogram.zeroCount >>> 0, histogram.zeroCount / 4294967296 >>> 0); + writer.writeTag(8, 2); + serializeExponentialBuckets(writer, histogram.positive.offset, histogram.positive.bucketCounts); + writer.writeTag(9, 2); + serializeExponentialBuckets(writer, histogram.negative.offset, histogram.negative.bucketCounts); + if (histogram.min !== undefined) { + writer.writeTag(12, 1); + writer.writeDouble(histogram.min); + } + if (histogram.max !== undefined) { + writer.writeTag(13, 1); + writer.writeDouble(histogram.max); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeMetric(writer, metricData) { + const metricStart = writer.startLengthDelimited(); + const metricStartPos = writer.pos; + writer.writeTag(1, 2); + writer.writeString(metricData.descriptor.name); + if (metricData.descriptor.description) { + writer.writeTag(2, 2); + writer.writeString(metricData.descriptor.description); + } + if (metricData.descriptor.unit) { + writer.writeTag(3, 2); + writer.writeString(metricData.descriptor.unit); + } + switch (metricData.dataPointType) { + case sdk_metrics_1.DataPointType.GAUGE: + writer.writeTag(5, 2); + serializeGauge(writer, metricData); + break; + case sdk_metrics_1.DataPointType.SUM: + writer.writeTag(7, 2); + serializeSum(writer, metricData); + break; + case sdk_metrics_1.DataPointType.HISTOGRAM: + writer.writeTag(9, 2); + serializeHistogramMetric(writer, metricData); + break; + case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM: + writer.writeTag(10, 2); + serializeExponentialHistogramMetric(writer, metricData); + break; + default: { + const _exhaustive = metricData; + } + } + writer.finishLengthDelimited(metricStart, writer.pos - metricStartPos); + } + function serializeGauge(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeNumberDataPoint(writer, dataPoint, metricData.descriptor.valueType); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeSum(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeNumberDataPoint(writer, dataPoint, metricData.descriptor.valueType); + } + const temporality = toProtoAggregationTemporality(metricData.aggregationTemporality); + if (temporality !== 0) { + writer.writeTag(2, 0); + writer.writeVarint(temporality); + } + if (metricData.isMonotonic) { + writer.writeTag(3, 0); + writer.writeVarint(1); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeHistogramMetric(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeHistogramDataPoint(writer, dataPoint); + } + const temporality = toProtoAggregationTemporality(metricData.aggregationTemporality); + if (temporality !== 0) { + writer.writeTag(2, 0); + writer.writeVarint(temporality); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeExponentialHistogramMetric(writer, metricData) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + for (const dataPoint of metricData.dataPoints) { + writer.writeTag(1, 2); + serializeExponentialHistogramDataPoint(writer, dataPoint); + } + const temporality = toProtoAggregationTemporality(metricData.aggregationTemporality); + if (temporality !== 0) { + writer.writeTag(2, 0); + writer.writeVarint(temporality); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function serializeScopeMetrics(writer, scopeMetrics) { + const scopeStart = writer.startLengthDelimited(); + const scopeStartPos = writer.pos; + (0, common_serializer_1.writeInstrumentationScope)(writer, scopeMetrics.scope, 1); + for (const metric of scopeMetrics.metrics) { + writer.writeTag(2, 2); + serializeMetric(writer, metric); + } + if (scopeMetrics.scope.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(scopeMetrics.scope.schemaUrl); + } + writer.finishLengthDelimited(scopeStart, writer.pos - scopeStartPos); + } + function serializeResourceMetrics(writer, resourceMetrics) { + const start = writer.startLengthDelimited(); + const startPos = writer.pos; + (0, common_serializer_1.writeResource)(writer, resourceMetrics.resource, 1); + for (const scopeMetrics of resourceMetrics.scopeMetrics) { + writer.writeTag(2, 2); + serializeScopeMetrics(writer, scopeMetrics); + } + if (resourceMetrics.resource.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(resourceMetrics.resource.schemaUrl); + } + writer.finishLengthDelimited(start, writer.pos - startPos); + } + function toProtoAggregationTemporality(temporality) { + switch (temporality) { + case sdk_metrics_1.AggregationTemporality.DELTA: + return 1; + case sdk_metrics_1.AggregationTemporality.CUMULATIVE: + return 2; + default: + return 0; + } + } + function serializeMetricsExportRequest(resourceMetrics) { + const estimator = new protobuf_size_estimator_1.ProtobufSizeEstimator; + estimator.writeTag(1, 2); + serializeResourceMetrics(estimator, resourceMetrics); + const writer = new protobuf_writer_1.ProtobufWriter(estimator.pos); + writer.writeTag(1, 2); + serializeResourceMetrics(writer, resourceMetrics); + return writer.finish(); + } + exports.serializeMetricsExportRequest = serializeMetricsExportRequest; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/response-deserializer.js +var require_response_deserializer2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deserializeExportMetricsServiceResponse = undefined; + var protobuf_reader_1 = require_protobuf_reader(); + function deserializePartialSuccess(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 0) { + result.rejectedDataPoints = reader.readVarint(); + } else { + reader.skip(wireType); + } + break; + case 2: + if (wireType === 2) { + result.errorMessage = reader.readString(); + } else { + reader.skip(wireType); + } + break; + default: + reader.skip(wireType); + break; + } + } + return result; + } + function deserializeExportMetricsServiceResponse(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 2) { + result.partialSuccess = deserializePartialSuccess(reader.readBytes()); + } else { + reader.skip(wireType); + } + break; + default: + reader.skip(wireType); + break; + } + } + return result; + } + exports.deserializeExportMetricsServiceResponse = deserializeExportMetricsServiceResponse; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js +var require_metrics2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufMetricsSerializer = undefined; + var metrics_serializer_1 = require_metrics_serializer(); + var response_deserializer_1 = require_response_deserializer2(); + exports.ProtobufMetricsSerializer = { + serializeRequest: (arg) => { + return (0, metrics_serializer_1.serializeMetricsExportRequest)(arg); + }, + deserializeResponse: (arg) => { + return (0, response_deserializer_1.deserializeExportMetricsServiceResponse)(arg); + } + }; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js +var require_protobuf2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufMetricsSerializer = undefined; + var metrics_1 = require_metrics2(); + Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: function() { + return metrics_1.ProtobufMetricsSerializer; + } }); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace-serializer.js +var require_trace_serializer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.serializeTraceExportRequest = undefined; + var protobuf_writer_1 = require_protobuf_writer(); + var hex_to_binary_1 = require_hex_to_binary(); + var common_serializer_1 = require_common_serializer(); + var protobuf_size_estimator_1 = require_protobuf_size_estimator(); + var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256; + var SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512; + function buildSpanFlags(traceFlags, isRemote) { + let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK; + if (isRemote) { + flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK; + } + return flags; + } + function serializeStatus(writer, status) { + const statusStart = writer.startLengthDelimited(); + const statusStartPos = writer.pos; + if (status.message) { + writer.writeTag(2, 2); + writer.writeString(status.message); + } + writer.writeTag(3, 0); + writer.writeVarint(status.code); + writer.finishLengthDelimited(statusStart, writer.pos - statusStartPos); + } + function serializeEvent(writer, event) { + const eventStart = writer.startLengthDelimited(); + const eventStartPos = writer.pos; + writer.writeTag(1, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, event.time); + writer.writeTag(2, 2); + writer.writeString(event.name); + if (event.attributes) { + (0, common_serializer_1.writeAttributes)(writer, event.attributes, 3); + } + writer.writeTag(4, 0); + writer.writeVarint(event.droppedAttributesCount || 0); + writer.finishLengthDelimited(eventStart, writer.pos - eventStartPos); + } + function serializeLink(writer, link) { + const linkStart = writer.startLengthDelimited(); + const linkStartPos = writer.pos; + const context = link.context; + writer.writeTag(1, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(context.traceId)); + writer.writeTag(2, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(context.spanId)); + const linkTraceState = context.traceState?.serialize(); + if (linkTraceState) { + writer.writeTag(3, 2); + writer.writeString(linkTraceState); + } + if (link.attributes) { + (0, common_serializer_1.writeAttributes)(writer, link.attributes, 4); + } + writer.writeTag(5, 0); + writer.writeVarint(link.droppedAttributesCount || 0); + const linkFlags = buildSpanFlags(context.traceFlags, context.isRemote); + if (linkFlags) { + writer.writeTag(6, 5); + writer.writeFixed32(linkFlags); + } + writer.finishLengthDelimited(linkStart, writer.pos - linkStartPos); + } + function serializeSpan(writer, span) { + const spanStart = writer.startLengthDelimited(); + const spanStartPos = writer.pos; + const ctx = span.spanContext(); + writer.writeTag(1, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(ctx.traceId)); + writer.writeTag(2, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(ctx.spanId)); + const traceState = ctx.traceState?.serialize(); + if (traceState) { + writer.writeTag(3, 2); + writer.writeString(traceState); + } + if (span.parentSpanContext?.spanId) { + writer.writeTag(4, 2); + writer.writeBytes((0, hex_to_binary_1.hexToBinary)(span.parentSpanContext.spanId)); + } + writer.writeTag(5, 2); + writer.writeString(span.name); + const kind2 = span.kind == null ? 0 : span.kind + 1; + if (kind2 !== 0) { + writer.writeTag(6, 0); + writer.writeVarint(kind2); + } + writer.writeTag(7, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, span.startTime); + writer.writeTag(8, 1); + (0, common_serializer_1.writeHrTimeAsFixed64)(writer, span.endTime); + if (span.attributes) { + (0, common_serializer_1.writeAttributes)(writer, span.attributes, 9); + } + writer.writeTag(10, 0); + writer.writeVarint(span.droppedAttributesCount); + for (const event of span.events) { + writer.writeTag(11, 2); + serializeEvent(writer, event); + } + writer.writeTag(12, 0); + writer.writeVarint(span.droppedEventsCount); + for (const link of span.links) { + writer.writeTag(13, 2); + serializeLink(writer, link); + } + writer.writeTag(14, 0); + writer.writeVarint(span.droppedLinksCount); + writer.writeTag(15, 2); + serializeStatus(writer, span.status); + const flags = buildSpanFlags(ctx.traceFlags, span.parentSpanContext?.isRemote); + if (flags) { + writer.writeTag(16, 5); + writer.writeFixed32(flags); + } + writer.finishLengthDelimited(spanStart, writer.pos - spanStartPos); + } + function serializeScopeSpans(writer, scope, spans) { + const scopeSpansStart = writer.startLengthDelimited(); + const scopeSpansStartPos = writer.pos; + (0, common_serializer_1.writeInstrumentationScope)(writer, scope, 1); + for (const span of spans) { + writer.writeTag(2, 2); + serializeSpan(writer, span); + } + if (scope.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(scope.schemaUrl); + } + writer.finishLengthDelimited(scopeSpansStart, writer.pos - scopeSpansStartPos); + } + function serializeResourceSpans(writer, resource, scopeMap) { + const resourceSpansStart = writer.startLengthDelimited(); + const resourceSpansStartPos = writer.pos; + (0, common_serializer_1.writeResource)(writer, resource, 1); + for (const scopeSpans of scopeMap.values()) { + writer.writeTag(2, 2); + const scope = scopeSpans[0].instrumentationScope; + serializeScopeSpans(writer, scope, scopeSpans); + } + if (resource.schemaUrl) { + writer.writeTag(3, 2); + writer.writeString(resource.schemaUrl); + } + writer.finishLengthDelimited(resourceSpansStart, writer.pos - resourceSpansStartPos); + } + function createResourceMap(spans) { + const resourceMap = new Map; + for (const span of spans) { + const resource = span.resource; + const scope = span.instrumentationScope; + let scopeMap = resourceMap.get(resource); + if (!scopeMap) { + scopeMap = new Map; + resourceMap.set(resource, scopeMap); + } + let records = scopeMap.get(scope); + if (!records) { + records = []; + scopeMap.set(scope, records); + } + records.push(span); + } + return resourceMap; + } + function serializeTraceExportRequest(spans) { + const resourceMap = createResourceMap(spans); + const estimator = new protobuf_size_estimator_1.ProtobufSizeEstimator; + for (const [resource, scopeMap] of resourceMap) { + estimator.writeTag(1, 2); + serializeResourceSpans(estimator, resource, scopeMap); + } + const writer = new protobuf_writer_1.ProtobufWriter(estimator.pos); + for (const [resource, scopeMap] of resourceMap) { + writer.writeTag(1, 2); + serializeResourceSpans(writer, resource, scopeMap); + } + return writer.finish(); + } + exports.serializeTraceExportRequest = serializeTraceExportRequest; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/response-deserializer.js +var require_response_deserializer3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.deserializeExportTraceServiceResponse = undefined; + var protobuf_reader_1 = require_protobuf_reader(); + function deserializePartialSuccess(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 0) { + result.rejectedSpans = reader.readVarint(); + } else { + reader.skip(wireType); + } + break; + case 2: + if (wireType === 2) { + result.errorMessage = reader.readString(); + } else { + reader.skip(wireType); + } + break; + default: + reader.skip(wireType); + break; + } + } + return result; + } + function deserializeExportTraceServiceResponse(data) { + const reader = new protobuf_reader_1.ProtobufReader(data); + const result = {}; + while (!reader.isAtEnd()) { + const { fieldNumber, wireType } = reader.readTag(); + switch (fieldNumber) { + case 1: + if (wireType === 2) { + result.partialSuccess = deserializePartialSuccess(reader.readBytes()); + } else { + reader.skip(wireType); + } + break; + default: + reader.skip(wireType); + break; + } + } + return result; + } + exports.deserializeExportTraceServiceResponse = deserializeExportTraceServiceResponse; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js +var require_trace3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufTraceSerializer = undefined; + var trace_serializer_1 = require_trace_serializer(); + var response_deserializer_1 = require_response_deserializer3(); + exports.ProtobufTraceSerializer = { + serializeRequest: (arg) => { + return (0, trace_serializer_1.serializeTraceExportRequest)(arg); + }, + deserializeResponse: (arg) => { + return (0, response_deserializer_1.deserializeExportTraceServiceResponse)(arg); + } + }; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js +var require_protobuf3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProtobufTraceSerializer = undefined; + var trace_1 = require_trace3(); + Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: function() { + return trace_1.ProtobufTraceSerializer; + } }); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js +var require_internal = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toAnyValue = exports.toKeyValue = exports.toAttributes = exports.createInstrumentationScope = exports.createResource = undefined; + function createResource(resource, encoder) { + const result = { + attributes: toAttributes(resource.attributes, encoder), + droppedAttributesCount: 0 + }; + const schemaUrl = resource.schemaUrl; + if (schemaUrl && schemaUrl !== "") + result.schemaUrl = schemaUrl; + return result; + } + exports.createResource = createResource; + function createInstrumentationScope(scope, encoder) { + const result = { + name: scope.name, + version: scope.version + }; + if (scope.attributes && Object.keys(scope.attributes).length > 0) { + result.attributes = toAttributes(scope.attributes, encoder); + result.droppedAttributesCount = scope.droppedAttributesCount ?? 0; + } + return result; + } + exports.createInstrumentationScope = createInstrumentationScope; + function toAttributes(attributes, encoder) { + return Object.keys(attributes).map((key) => toKeyValue(key, attributes[key], encoder)); + } + exports.toAttributes = toAttributes; + function toKeyValue(key, value, encoder) { + return { + key, + value: toAnyValue(value, encoder) + }; + } + exports.toKeyValue = toKeyValue; + function toAnyValue(value, encoder) { + const t = typeof value; + if (t === "string") + return { stringValue: value }; + if (t === "number") { + if (!Number.isInteger(value)) + return { doubleValue: value }; + return { intValue: value }; + } + if (t === "boolean") + return { boolValue: value }; + if (value instanceof Uint8Array) + return { bytesValue: encoder.encodeUint8Array(value) }; + if (Array.isArray(value)) { + const values = new Array(value.length); + for (let i = 0;i < value.length; i++) { + values[i] = toAnyValue(value[i], encoder); + } + return { arrayValue: { values } }; + } + if (t === "object" && value != null) { + const keys = Object.keys(value); + const values = new Array(keys.length); + for (let i = 0;i < keys.length; i++) { + values[i] = { + key: keys[i], + value: toAnyValue(value[keys[i]], encoder) + }; + } + return { kvlistValue: { values } }; + } + return {}; + } + exports.toAnyValue = toAnyValue; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js +var require_internal2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createExportLogsServiceRequest = undefined; + var internal_1 = require_internal(); + function createExportLogsServiceRequest(logRecords, encoder) { + return { + resourceLogs: logRecordsToResourceLogs(logRecords, encoder) + }; + } + exports.createExportLogsServiceRequest = createExportLogsServiceRequest; + function createResourceMap(logRecords) { + const resourceMap = new Map; + for (const record of logRecords) { + const { resource, instrumentationScope } = record; + let ismMap = resourceMap.get(resource); + if (!ismMap) { + ismMap = new Map; + resourceMap.set(resource, ismMap); + } + let records = ismMap.get(instrumentationScope); + if (!records) { + records = []; + ismMap.set(instrumentationScope, records); + } + records.push(record); + } + return resourceMap; + } + function logRecordsToResourceLogs(logRecords, encoder) { + const resourceMap = createResourceMap(logRecords); + return Array.from(resourceMap, ([resource, ismMap]) => { + const processedResource = (0, internal_1.createResource)(resource, encoder); + return { + resource: processedResource, + scopeLogs: Array.from(ismMap, ([, scopeLogs]) => { + return { + scope: (0, internal_1.createInstrumentationScope)(scopeLogs[0].instrumentationScope, encoder), + logRecords: scopeLogs.map((log) => toLogRecord(log, encoder)), + schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl + }; + }), + schemaUrl: processedResource.schemaUrl + }; + }); + } + function toLogRecord(log, encoder) { + return { + timeUnixNano: encoder.encodeHrTime(log.hrTime), + observedTimeUnixNano: encoder.encodeHrTime(log.hrTimeObserved), + severityNumber: toSeverityNumber(log.severityNumber), + severityText: log.severityText, + body: (0, internal_1.toAnyValue)(log.body, encoder), + eventName: log.eventName, + attributes: (0, internal_1.toAttributes)(log.attributes, encoder), + droppedAttributesCount: log.droppedAttributesCount, + flags: log.spanContext?.traceFlags, + traceId: encoder.encodeOptionalSpanContext(log.spanContext?.traceId), + spanId: encoder.encodeOptionalSpanContext(log.spanContext?.spanId) + }; + } + function toSeverityNumber(severityNumber) { + return severityNumber; + } +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js +var require_utils9 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JSON_ENCODER = exports.PROTOBUF_ENCODER = exports.encodeAsString = exports.encodeAsLongBits = exports.toLongBits = exports.hrTimeToNanos = undefined; + var core_1 = require_src3(); + var hex_to_binary_1 = require_hex_to_binary(); + function hrTimeToNanos(hrTime) { + const NANOSECONDS = BigInt(1e9); + return BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1])); + } + exports.hrTimeToNanos = hrTimeToNanos; + function toLongBits(value) { + const low = Number(BigInt.asUintN(32, value)); + const high = Number(BigInt.asUintN(32, value >> BigInt(32))); + return { low, high }; + } + exports.toLongBits = toLongBits; + function encodeAsLongBits(hrTime) { + const nanos = hrTimeToNanos(hrTime); + return toLongBits(nanos); + } + exports.encodeAsLongBits = encodeAsLongBits; + function encodeAsString(hrTime) { + const nanos = hrTimeToNanos(hrTime); + return nanos.toString(); + } + exports.encodeAsString = encodeAsString; + var encodeTimestamp = typeof BigInt !== "undefined" ? encodeAsString : core_1.hrTimeToNanoseconds; + function identity(value) { + return value; + } + function optionalHexToBinary(str) { + if (str === undefined) + return; + return (0, hex_to_binary_1.hexToBinary)(str); + } + exports.PROTOBUF_ENCODER = { + encodeHrTime: encodeAsLongBits, + encodeSpanContext: hex_to_binary_1.hexToBinary, + encodeOptionalSpanContext: optionalHexToBinary, + encodeUint8Array: identity + }; + exports.JSON_ENCODER = { + encodeHrTime: encodeTimestamp, + encodeSpanContext: identity, + encodeOptionalSpanContext: identity, + encodeUint8Array: (bytes) => { + if (typeof Buffer !== "undefined") { + return Buffer.from(bytes).toString("base64"); + } + const chars = new Array(bytes.length); + for (let i = 0;i < bytes.length; i++) { + chars[i] = String.fromCharCode(bytes[i]); + } + return btoa(chars.join("")); + } + }; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js +var require_logs3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonLogsSerializer = undefined; + var internal_1 = require_internal2(); + var utils_1 = require_utils9(); + var api_1 = require_src(); + exports.JsonLogsSerializer = { + serializeRequest: (arg) => { + const request2 = (0, internal_1.createExportLogsServiceRequest)(arg, utils_1.JSON_ENCODER); + const encoder = new TextEncoder; + return encoder.encode(JSON.stringify(request2)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) { + return {}; + } + const decoder = new TextDecoder; + try { + return JSON.parse(decoder.decode(arg)); + } catch (err) { + api_1.diag.warn(`Failed to parse logs export response: ${err.message}. Returning empty response`); + return {}; + } + } + }; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js +var require_json = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonLogsSerializer = undefined; + var logs_1 = require_logs3(); + Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: function() { + return logs_1.JsonLogsSerializer; + } }); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js +var require_internal_types = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EAggregationTemporality = undefined; + var EAggregationTemporality; + (function(EAggregationTemporality2) { + EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"; + EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_DELTA"] = 1] = "AGGREGATION_TEMPORALITY_DELTA"; + EAggregationTemporality2[EAggregationTemporality2["AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"; + })(EAggregationTemporality = exports.EAggregationTemporality || (exports.EAggregationTemporality = {})); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js +var require_internal3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createExportMetricsServiceRequest = exports.toMetric = exports.toScopeMetrics = exports.toResourceMetrics = undefined; + var api_1 = require_src(); + var sdk_metrics_1 = require_src7(); + var internal_types_1 = require_internal_types(); + var internal_1 = require_internal(); + function toResourceMetrics(resourceMetrics, encoder) { + const processedResource = (0, internal_1.createResource)(resourceMetrics.resource, encoder); + return { + resource: processedResource, + schemaUrl: processedResource.schemaUrl, + scopeMetrics: toScopeMetrics(resourceMetrics.scopeMetrics, encoder) + }; + } + exports.toResourceMetrics = toResourceMetrics; + function toScopeMetrics(scopeMetrics, encoder) { + return Array.from(scopeMetrics.map((metrics) => ({ + scope: (0, internal_1.createInstrumentationScope)(metrics.scope, encoder), + metrics: metrics.metrics.map((metricData) => toMetric(metricData, encoder)), + schemaUrl: metrics.scope.schemaUrl + }))); + } + exports.toScopeMetrics = toScopeMetrics; + function toMetric(metricData, encoder) { + const out = { + name: metricData.descriptor.name, + description: metricData.descriptor.description, + unit: metricData.descriptor.unit + }; + const aggregationTemporality = toAggregationTemporality(metricData.aggregationTemporality); + switch (metricData.dataPointType) { + case sdk_metrics_1.DataPointType.SUM: + out.sum = { + aggregationTemporality, + isMonotonic: metricData.isMonotonic, + dataPoints: toSingularDataPoints(metricData, encoder) + }; + break; + case sdk_metrics_1.DataPointType.GAUGE: + out.gauge = { + dataPoints: toSingularDataPoints(metricData, encoder) + }; + break; + case sdk_metrics_1.DataPointType.HISTOGRAM: + out.histogram = { + aggregationTemporality, + dataPoints: toHistogramDataPoints(metricData, encoder) + }; + break; + case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM: + out.exponentialHistogram = { + aggregationTemporality, + dataPoints: toExponentialHistogramDataPoints(metricData, encoder) + }; + break; + } + return out; + } + exports.toMetric = toMetric; + function toSingularDataPoint(dataPoint, valueType, encoder) { + const out = { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes, encoder), + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime) + }; + switch (valueType) { + case api_1.ValueType.INT: + out.asInt = dataPoint.value; + break; + case api_1.ValueType.DOUBLE: + out.asDouble = dataPoint.value; + break; + } + return out; + } + function toSingularDataPoints(metricData, encoder) { + return metricData.dataPoints.map((dataPoint) => { + return toSingularDataPoint(dataPoint, metricData.descriptor.valueType, encoder); + }); + } + function toHistogramDataPoints(metricData, encoder) { + return metricData.dataPoints.map((dataPoint) => { + const histogram = dataPoint.value; + return { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes, encoder), + bucketCounts: histogram.buckets.counts, + explicitBounds: histogram.buckets.boundaries, + count: histogram.count, + sum: histogram.sum, + min: histogram.min, + max: histogram.max, + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime) + }; + }); + } + function toExponentialHistogramDataPoints(metricData, encoder) { + return metricData.dataPoints.map((dataPoint) => { + const histogram = dataPoint.value; + return { + attributes: (0, internal_1.toAttributes)(dataPoint.attributes, encoder), + count: histogram.count, + min: histogram.min, + max: histogram.max, + sum: histogram.sum, + positive: { + offset: histogram.positive.offset, + bucketCounts: histogram.positive.bucketCounts + }, + negative: { + offset: histogram.negative.offset, + bucketCounts: histogram.negative.bucketCounts + }, + scale: histogram.scale, + zeroCount: histogram.zeroCount, + startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), + timeUnixNano: encoder.encodeHrTime(dataPoint.endTime) + }; + }); + } + function toAggregationTemporality(temporality) { + switch (temporality) { + case sdk_metrics_1.AggregationTemporality.DELTA: + return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA; + case sdk_metrics_1.AggregationTemporality.CUMULATIVE: + return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE; + } + } + function createExportMetricsServiceRequest(resourceMetrics, encoder) { + return { + resourceMetrics: resourceMetrics.map((metrics) => toResourceMetrics(metrics, encoder)) + }; + } + exports.createExportMetricsServiceRequest = createExportMetricsServiceRequest; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js +var require_metrics3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonMetricsSerializer = undefined; + var internal_1 = require_internal3(); + var utils_1 = require_utils9(); + var api_1 = require_src(); + exports.JsonMetricsSerializer = { + serializeRequest: (arg) => { + const request2 = (0, internal_1.createExportMetricsServiceRequest)([arg], utils_1.JSON_ENCODER); + const encoder = new TextEncoder; + return encoder.encode(JSON.stringify(request2)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) { + return {}; + } + const decoder = new TextDecoder; + try { + return JSON.parse(decoder.decode(arg)); + } catch (err) { + api_1.diag.warn(`Failed to parse metrics export response: ${err.message}. Returning empty response`); + return {}; + } + } + }; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js +var require_json2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonMetricsSerializer = undefined; + var metrics_1 = require_metrics3(); + Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: function() { + return metrics_1.JsonMetricsSerializer; + } }); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js +var require_internal4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createExportTraceServiceRequest = exports.toOtlpSpanEvent = exports.toOtlpLink = exports.sdkSpanToOtlpSpan = undefined; + var internal_1 = require_internal(); + var SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 256; + var SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 512; + function buildSpanFlagsFrom(traceFlags, isRemote) { + let flags = traceFlags & 255 | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK; + if (isRemote) { + flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK; + } + return flags; + } + function sdkSpanToOtlpSpan(span, encoder) { + const ctx = span.spanContext(); + const status = span.status; + const parentSpanId = span.parentSpanContext?.spanId ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) : undefined; + return { + traceId: encoder.encodeSpanContext(ctx.traceId), + spanId: encoder.encodeSpanContext(ctx.spanId), + parentSpanId, + traceState: ctx.traceState?.serialize(), + name: span.name, + kind: span.kind == null ? 0 : span.kind + 1, + startTimeUnixNano: encoder.encodeHrTime(span.startTime), + endTimeUnixNano: encoder.encodeHrTime(span.endTime), + attributes: (0, internal_1.toAttributes)(span.attributes, encoder), + droppedAttributesCount: span.droppedAttributesCount, + events: span.events.map((event) => toOtlpSpanEvent(event, encoder)), + droppedEventsCount: span.droppedEventsCount, + status: { + code: status.code, + message: status.message + }, + links: span.links.map((link) => toOtlpLink(link, encoder)), + droppedLinksCount: span.droppedLinksCount, + flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote) + }; + } + exports.sdkSpanToOtlpSpan = sdkSpanToOtlpSpan; + function toOtlpLink(link, encoder) { + return { + attributes: link.attributes ? (0, internal_1.toAttributes)(link.attributes, encoder) : [], + spanId: encoder.encodeSpanContext(link.context.spanId), + traceId: encoder.encodeSpanContext(link.context.traceId), + traceState: link.context.traceState?.serialize(), + droppedAttributesCount: link.droppedAttributesCount || 0, + flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote) + }; + } + exports.toOtlpLink = toOtlpLink; + function toOtlpSpanEvent(timedEvent, encoder) { + return { + attributes: timedEvent.attributes ? (0, internal_1.toAttributes)(timedEvent.attributes, encoder) : [], + name: timedEvent.name, + timeUnixNano: encoder.encodeHrTime(timedEvent.time), + droppedAttributesCount: timedEvent.droppedAttributesCount || 0 + }; + } + exports.toOtlpSpanEvent = toOtlpSpanEvent; + function createExportTraceServiceRequest(spans, encoder) { + return { + resourceSpans: spanRecordsToResourceSpans(spans, encoder) + }; + } + exports.createExportTraceServiceRequest = createExportTraceServiceRequest; + function createResourceMap(readableSpans) { + const resourceMap = new Map; + for (const record of readableSpans) { + let ilsMap = resourceMap.get(record.resource); + if (!ilsMap) { + ilsMap = new Map; + resourceMap.set(record.resource, ilsMap); + } + const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ""}:${record.instrumentationScope.schemaUrl || ""}`; + let records = ilsMap.get(instrumentationScopeKey); + if (!records) { + records = []; + ilsMap.set(instrumentationScopeKey, records); + } + records.push(record); + } + return resourceMap; + } + function spanRecordsToResourceSpans(readableSpans, encoder) { + const resourceMap = createResourceMap(readableSpans); + const out = []; + const entryIterator = resourceMap.entries(); + let entry = entryIterator.next(); + while (!entry.done) { + const [resource, ilmMap] = entry.value; + const scopeResourceSpans = []; + const ilmIterator = ilmMap.values(); + let ilmEntry = ilmIterator.next(); + while (!ilmEntry.done) { + const scopeSpans = ilmEntry.value; + if (scopeSpans.length > 0) { + const spans = scopeSpans.map((readableSpan) => sdkSpanToOtlpSpan(readableSpan, encoder)); + scopeResourceSpans.push({ + scope: (0, internal_1.createInstrumentationScope)(scopeSpans[0].instrumentationScope, encoder), + spans, + schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl + }); + } + ilmEntry = ilmIterator.next(); + } + const processedResource = (0, internal_1.createResource)(resource, encoder); + const transformedSpans = { + resource: processedResource, + scopeSpans: scopeResourceSpans, + schemaUrl: processedResource.schemaUrl + }; + out.push(transformedSpans); + entry = entryIterator.next(); + } + return out; + } +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js +var require_trace4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonTraceSerializer = undefined; + var internal_1 = require_internal4(); + var utils_1 = require_utils9(); + var api_1 = require_src(); + exports.JsonTraceSerializer = { + serializeRequest: (arg) => { + const request2 = (0, internal_1.createExportTraceServiceRequest)(arg, utils_1.JSON_ENCODER); + const encoder = new TextEncoder; + return encoder.encode(JSON.stringify(request2)); + }, + deserializeResponse: (arg) => { + if (arg.length === 0) { + return {}; + } + const decoder = new TextDecoder; + try { + return JSON.parse(decoder.decode(arg)); + } catch (err) { + api_1.diag.warn(`Failed to parse trace export response: ${err.message}. Returning empty response`); + return {}; + } + } + }; +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js +var require_json3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonTraceSerializer = undefined; + var trace_1 = require_trace4(); + Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: function() { + return trace_1.JsonTraceSerializer; + } }); +}); + +// node_modules/@opentelemetry/otlp-transformer/build/src/index.js +var require_src8 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonTraceSerializer = exports.JsonMetricsSerializer = exports.JsonLogsSerializer = exports.ProtobufTraceSerializer = exports.ProtobufMetricsSerializer = exports.ProtobufLogsSerializer = undefined; + var protobuf_1 = require_protobuf(); + Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: function() { + return protobuf_1.ProtobufLogsSerializer; + } }); + var protobuf_2 = require_protobuf2(); + Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: function() { + return protobuf_2.ProtobufMetricsSerializer; + } }); + var protobuf_3 = require_protobuf3(); + Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: function() { + return protobuf_3.ProtobufTraceSerializer; + } }); + var json_1 = require_json(); + Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: function() { + return json_1.JsonLogsSerializer; + } }); + var json_2 = require_json2(); + Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: function() { + return json_2.JsonMetricsSerializer; + } }); + var json_3 = require_json3(); + Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: function() { + return json_3.JsonTraceSerializer; + } }); +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js +var require_util2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAndNormalizeHeaders = undefined; + var api_1 = require_src(); + function validateAndNormalizeHeaders(partialHeaders) { + const headers = {}; + Object.entries(partialHeaders ?? {}).forEach(([key, value]) => { + if (typeof value !== "undefined") { + headers[key] = String(value); + } else { + api_1.diag.warn(`Header "${key}" has invalid value (${value}) and will be ignored`); + } + }); + return headers; + } + exports.validateAndNormalizeHeaders = validateAndNormalizeHeaders; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js +var require_otlp_http_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getHttpConfigurationDefaults = exports.mergeOtlpHttpConfigurationWithDefaults = undefined; + var shared_configuration_1 = require_shared_configuration(); + var util_1 = require_util2(); + function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) { + return async () => { + const requiredHeaders = { + ...await defaultHeaders() + }; + const headers = {}; + if (fallbackHeaders != null) { + Object.assign(headers, await fallbackHeaders()); + } + if (userProvidedHeaders != null) { + Object.assign(headers, (0, util_1.validateAndNormalizeHeaders)(await userProvidedHeaders())); + } + return Object.assign(headers, requiredHeaders); + }; + } + function validateUserProvidedUrl(url) { + if (url == null) { + return; + } + try { + const base = globalThis.location?.href; + return new URL(url, base).href; + } catch { + throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`); + } + } + function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + ...(0, shared_configuration_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + headers: mergeHeaders(userProvidedConfiguration.headers, fallbackConfiguration.headers, defaultConfiguration.headers), + url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? fallbackConfiguration.url ?? defaultConfiguration.url + }; + } + exports.mergeOtlpHttpConfigurationWithDefaults = mergeOtlpHttpConfigurationWithDefaults; + function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { + return { + ...(0, shared_configuration_1.getSharedConfigurationDefaults)(), + headers: async () => requiredHeaders, + url: "http://localhost:4318/" + signalResourcePath + }; + } + exports.getHttpConfigurationDefaults = getHttpConfigurationDefaults; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js +var require_otlp_node_http_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getNodeHttpConfigurationDefaults = exports.mergeOtlpNodeHttpConfigurationWithDefaults = exports.httpAgentFactoryFromOptions = undefined; + var otlp_http_configuration_1 = require_otlp_http_configuration(); + function httpAgentFactoryFromOptions(options) { + return async (protocol) => { + const isInsecure = protocol === "http:"; + const module2 = isInsecure ? import("http") : import("https"); + const { Agent } = await module2; + if (isInsecure) { + const { ca, cert, key, ...insecureOptions } = options; + return new Agent(insecureOptions); + } + return new Agent(options); + }; + } + exports.httpAgentFactoryFromOptions = httpAgentFactoryFromOptions; + function mergeOtlpNodeHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + return { + ...(0, otlp_http_configuration_1.mergeOtlpHttpConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + agentFactory: userProvidedConfiguration.agentFactory ?? fallbackConfiguration.agentFactory ?? defaultConfiguration.agentFactory, + userAgent: userProvidedConfiguration.userAgent + }; + } + exports.mergeOtlpNodeHttpConfigurationWithDefaults = mergeOtlpNodeHttpConfigurationWithDefaults; + function getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { + return { + ...(0, otlp_http_configuration_1.getHttpConfigurationDefaults)(requiredHeaders, signalResourcePath), + agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }) + }; + } + exports.getNodeHttpConfigurationDefaults = getNodeHttpConfigurationDefaults; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js +var require_is_export_retryable = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseRetryAfterToMills = exports.isExportHTTPErrorRetryable = undefined; + function isExportHTTPErrorRetryable(statusCode) { + return statusCode === 429 || statusCode === 502 || statusCode === 503 || statusCode === 504; + } + exports.isExportHTTPErrorRetryable = isExportHTTPErrorRetryable; + function parseRetryAfterToMills(retryAfter) { + if (retryAfter == null) { + return; + } + const seconds = Number.parseInt(retryAfter, 10); + if (Number.isInteger(seconds)) { + return seconds > 0 ? seconds * 1000 : -1; + } + const delay = new Date(retryAfter).getTime() - Date.now(); + if (delay >= 0) { + return delay; + } + return 0; + } + exports.parseRetryAfterToMills = parseRetryAfterToMills; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js +var require_version5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = undefined; + exports.VERSION = "0.219.0"; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js +var require_http_transport_utils = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.compressAndSend = exports.sendWithHttp = exports.MAX_RESPONSE_BODY_SIZE = undefined; + var zlib = __require("zlib"); + var stream_1 = __require("stream"); + var is_export_retryable_1 = require_is_export_retryable(); + var types_1 = require_types2(); + var version_1 = require_version5(); + var DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`; + exports.MAX_RESPONSE_BODY_SIZE = 4 * 1024 * 1024; + function sendWithHttp(request2, url, headers, compression, userAgent, agent, data, timeoutMillis) { + return new Promise((resolve) => { + const parsedUrl = new URL(url); + if (userAgent) { + headers["User-Agent"] = `${userAgent} ${DEFAULT_USER_AGENT}`; + } else { + headers["User-Agent"] = DEFAULT_USER_AGENT; + } + const options = { + method: "POST", + headers, + agent + }; + const req = request2(parsedUrl, options, (res) => { + const responseData = []; + let responseSize = 0; + res.on("data", (chunk) => { + responseSize += chunk.length; + if (responseSize > exports.MAX_RESPONSE_BODY_SIZE) { + const sizeError = new Error(`OTLP export response body exceeded size limit of ${exports.MAX_RESPONSE_BODY_SIZE} bytes`); + resolve({ status: "failure", error: sizeError }); + res.destroy(); + return; + } + responseData.push(chunk); + }); + res.on("end", () => { + if (res.statusCode && res.statusCode <= 299) { + resolve({ + status: "success", + data: Buffer.concat(responseData) + }); + } else if (res.statusCode && (0, is_export_retryable_1.isExportHTTPErrorRetryable)(res.statusCode)) { + resolve({ + status: "retryable", + retryInMillis: (0, is_export_retryable_1.parseRetryAfterToMills)(res.headers["retry-after"]) + }); + } else { + const error = new types_1.OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString()); + resolve({ + status: "failure", + error + }); + } + }); + res.on("error", (error) => { + if (res.statusCode && res.statusCode <= 299) { + resolve({ + status: "success" + }); + } else if (res.statusCode && (0, is_export_retryable_1.isExportHTTPErrorRetryable)(res.statusCode)) { + resolve({ + status: "retryable", + error, + retryInMillis: (0, is_export_retryable_1.parseRetryAfterToMills)(res.headers["retry-after"]) + }); + } else { + resolve({ + status: "failure", + error + }); + } + }); + }); + req.setTimeout(timeoutMillis, () => { + req.destroy(); + resolve({ + status: "retryable", + error: new Error("Request timed out") + }); + }); + req.on("error", (error) => { + if (isHttpTransportNetworkErrorRetryable(error)) { + resolve({ + status: "retryable", + error + }); + } else { + resolve({ + status: "failure", + error + }); + } + }); + compressAndSend(req, compression, data, (error) => { + resolve({ + status: "failure", + error + }); + }); + }); + } + exports.sendWithHttp = sendWithHttp; + function compressAndSend(req, compression, data, onError) { + let dataStream = readableFromUint8Array(data); + if (compression === "gzip") { + req.setHeader("Content-Encoding", "gzip"); + dataStream = dataStream.on("error", onError).pipe(zlib.createGzip()).on("error", onError); + } + dataStream.pipe(req).on("error", onError); + } + exports.compressAndSend = compressAndSend; + function readableFromUint8Array(buff) { + const readable = new stream_1.Readable; + readable.push(buff); + readable.push(null); + return readable; + } + function isHttpTransportNetworkErrorRetryable(error) { + const RETRYABLE_NETWORK_ERROR_CODES = new Set([ + "ECONNRESET", + "ECONNREFUSED", + "EPIPE", + "ETIMEDOUT", + "EAI_AGAIN", + "ENOTFOUND", + "ENETUNREACH", + "EHOSTUNREACH" + ]); + if ("code" in error && typeof error.code === "string") { + return RETRYABLE_NETWORK_ERROR_CODES.has(error.code); + } + return false; + } +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js +var require_http_exporter_transport = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createHttpExporterTransport = undefined; + var http_transport_utils_1 = require_http_transport_utils(); + + class HttpExporterTransport { + _utils = null; + _parameters; + constructor(parameters) { + this._parameters = parameters; + } + async send(data, timeoutMillis) { + const { agent, request: request2 } = await this._loadUtils(); + const headers = await this._parameters.headers(); + return (0, http_transport_utils_1.sendWithHttp)(request2, this._parameters.url, headers, this._parameters.compression, this._parameters.userAgent, agent, data, timeoutMillis); + } + shutdown() {} + async _loadUtils() { + let utils = this._utils; + if (utils === null) { + const protocol = new URL(this._parameters.url).protocol; + const [agent, request2] = await Promise.all([ + this._parameters.agentFactory(protocol), + requestFunctionFactory(protocol) + ]); + utils = this._utils = { agent, request: request2 }; + } + return utils; + } + } + async function requestFunctionFactory(protocol) { + const module2 = protocol === "http:" ? import("http") : import("https"); + const { request: request2 } = await module2; + return request2; + } + function createHttpExporterTransport(parameters) { + return new HttpExporterTransport(parameters); + } + exports.createHttpExporterTransport = createHttpExporterTransport; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js +var require_retrying_transport = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createRetryingTransport = undefined; + var api_1 = require_src(); + var MAX_ATTEMPTS = 5; + var INITIAL_BACKOFF = 1000; + var MAX_BACKOFF = 5000; + var BACKOFF_MULTIPLIER = 1.5; + var JITTER = 0.2; + function getJitter() { + return Math.random() * (2 * JITTER) - JITTER; + } + + class RetryingTransport { + _transport; + constructor(transport) { + this._transport = transport; + } + retry(data, timeoutMillis, inMillis) { + return new Promise((resolve, reject) => { + setTimeout(() => { + this._transport.send(data, timeoutMillis).then(resolve, reject); + }, inMillis); + }); + } + async send(data, timeoutMillis) { + let attempts = MAX_ATTEMPTS; + let nextBackoff = INITIAL_BACKOFF; + const deadline = Date.now() + timeoutMillis; + let result = await this._transport.send(data, timeoutMillis); + while (result.status === "retryable" && attempts > 0) { + attempts--; + const backoff = Math.max(Math.min(nextBackoff * (1 + getJitter()), MAX_BACKOFF), 0); + nextBackoff = nextBackoff * BACKOFF_MULTIPLIER; + const retryInMillis = result.retryInMillis ?? backoff; + const remainingTimeoutMillis = deadline - Date.now(); + if (retryInMillis > remainingTimeoutMillis) { + api_1.diag.info(`Export retry time ${Math.round(retryInMillis)}ms exceeds remaining timeout ${Math.round(remainingTimeoutMillis)}ms, not retrying further.`); + return result; + } + api_1.diag.verbose(`Scheduling export retry in ${Math.round(retryInMillis)}ms`); + result = await this.retry(data, remainingTimeoutMillis, retryInMillis); + } + if (result.status === "success") { + api_1.diag.verbose(`Export succeeded after ${MAX_ATTEMPTS - attempts} retry attempts.`); + } else if (result.status === "retryable") { + api_1.diag.info(`Export failed after maximum retry attempts (${MAX_ATTEMPTS}).`); + } else { + api_1.diag.info(`Export failed with non-retryable error: ${result.error}`); + } + return result; + } + shutdown() { + return this._transport.shutdown(); + } + } + function createRetryingTransport(options) { + return new RetryingTransport(options.transport); + } + exports.createRetryingTransport = createRetryingTransport; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js +var require_otlp_http_export_delegate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createOtlpHttpExportDelegate = undefined; + var otlp_export_delegate_1 = require_otlp_export_delegate(); + var http_exporter_transport_1 = require_http_exporter_transport(); + var bounded_queue_export_promise_handler_1 = require_bounded_queue_export_promise_handler(); + var retrying_transport_1 = require_retrying_transport(); + function createOtlpHttpExportDelegate(options, serializer) { + return (0, otlp_export_delegate_1.createOtlpExportDelegate)({ + transport: (0, retrying_transport_1.createRetryingTransport)({ + transport: (0, http_exporter_transport_1.createHttpExporterTransport)(options) + }), + serializer, + promiseHandler: (0, bounded_queue_export_promise_handler_1.createBoundedQueueExportPromiseHandler)(options) + }, { timeout: options.timeoutMillis }); + } + exports.createOtlpHttpExportDelegate = createOtlpHttpExportDelegate; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js +var require_shared_env_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSharedConfigurationFromEnvironment = undefined; + var core_1 = require_src3(); + var api_1 = require_src(); + function parseAndValidateTimeoutFromEnv(timeoutEnvVar) { + const envTimeout = (0, core_1.getNumberFromEnv)(timeoutEnvVar); + if (envTimeout != null) { + if (Number.isFinite(envTimeout) && envTimeout > 0) { + return envTimeout; + } + api_1.diag.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`); + } + return; + } + function getTimeoutFromEnv(signalIdentifier) { + const specificTimeout = parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`); + const nonSpecificTimeout = parseAndValidateTimeoutFromEnv("OTEL_EXPORTER_OTLP_TIMEOUT"); + return specificTimeout ?? nonSpecificTimeout; + } + function parseAndValidateCompressionFromEnv(compressionEnvVar) { + const compression = (0, core_1.getStringFromEnv)(compressionEnvVar)?.trim(); + if (compression == null || compression === "none" || compression === "gzip") { + return compression; + } + api_1.diag.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`); + return; + } + function getCompressionFromEnv(signalIdentifier) { + const specificCompression = parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`); + const nonSpecificCompression = parseAndValidateCompressionFromEnv("OTEL_EXPORTER_OTLP_COMPRESSION"); + return specificCompression ?? nonSpecificCompression; + } + function getSharedConfigurationFromEnvironment(signalIdentifier) { + return { + timeoutMillis: getTimeoutFromEnv(signalIdentifier), + compression: getCompressionFromEnv(signalIdentifier) + }; + } + exports.getSharedConfigurationFromEnvironment = getSharedConfigurationFromEnvironment; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js +var require_otlp_node_http_env_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getNodeHttpConfigurationFromEnvironment = undefined; + var fs = __require("fs"); + var path = __require("path"); + var core_1 = require_src3(); + var api_1 = require_src(); + var shared_env_configuration_1 = require_shared_env_configuration(); + var shared_configuration_1 = require_shared_configuration(); + var otlp_node_http_configuration_1 = require_otlp_node_http_configuration(); + function getStaticHeadersFromEnv(signalIdentifier) { + const signalSpecificRawHeaders = (0, core_1.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`); + const nonSignalSpecificRawHeaders = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_HEADERS"); + const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders); + const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders); + if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) { + return; + } + return Object.assign({}, (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders), (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders)); + } + function appendRootPathToUrlIfNeeded(url) { + try { + const parsedUrl = new URL(url); + return parsedUrl.toString(); + } catch { + api_1.diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); + return; + } + } + function appendResourcePathToUrl(url, path2) { + try { + new URL(url); + } catch { + api_1.diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); + return; + } + if (!url.endsWith("/")) { + url = url + "/"; + } + url += path2; + try { + new URL(url); + } catch { + api_1.diag.warn(`Configuration: Provided URL appended with '${path2}' is not a valid URL, using 'undefined' instead of '${url}'`); + return; + } + return url; + } + function getNonSpecificUrlFromEnv(signalResourcePath) { + const envUrl = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT"); + if (envUrl === undefined) { + return; + } + return appendResourcePathToUrl(envUrl, signalResourcePath); + } + function getSpecificUrlFromEnv(signalIdentifier) { + const envUrl = (0, core_1.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`); + if (envUrl === undefined) { + return; + } + return appendRootPathToUrlIfNeeded(envUrl); + } + function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) { + const signalSpecificPath = (0, core_1.getStringFromEnv)(signalSpecificEnvVar); + const nonSignalSpecificPath = (0, core_1.getStringFromEnv)(nonSignalSpecificEnvVar); + const filePath = signalSpecificPath ?? nonSignalSpecificPath; + if (filePath != null) { + try { + return fs.readFileSync(path.resolve(process.cwd(), filePath)); + } catch { + api_1.diag.warn(warningMessage); + return; + } + } else { + return; + } + } + function getClientCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file"); + } + function getClientKeyFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file"); + } + function getRootCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file"); + } + function getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) { + return { + ...(0, shared_env_configuration_1.getSharedConfigurationFromEnvironment)(signalIdentifier), + url: getSpecificUrlFromEnv(signalIdentifier) ?? getNonSpecificUrlFromEnv(signalResourcePath), + headers: (0, shared_configuration_1.wrapStaticHeadersInFunction)(getStaticHeadersFromEnv(signalIdentifier)), + agentFactory: (0, otlp_node_http_configuration_1.httpAgentFactoryFromOptions)({ + keepAlive: true, + ca: getRootCertificateFromEnv(signalIdentifier), + cert: getClientCertificateFromEnv(signalIdentifier), + key: getClientKeyFromEnv(signalIdentifier) + }) + }; + } + exports.getNodeHttpConfigurationFromEnvironment = getNodeHttpConfigurationFromEnvironment; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js +var require_convert_legacy_http_options = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertLegacyHeaders = undefined; + var shared_configuration_1 = require_shared_configuration(); + function convertLegacyHeaders(config) { + if (typeof config.headers === "function") { + return config.headers; + } + return (0, shared_configuration_1.wrapStaticHeadersInFunction)(config.headers); + } + exports.convertLegacyHeaders = convertLegacyHeaders; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js +var require_convert_legacy_node_http_options = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertLegacyHttpOptions = undefined; + var api_1 = require_src(); + var otlp_node_http_configuration_1 = require_otlp_node_http_configuration(); + var index_node_http_1 = require_index_node_http(); + var otlp_node_http_env_configuration_1 = require_otlp_node_http_env_configuration(); + var convert_legacy_http_options_1 = require_convert_legacy_http_options(); + function convertLegacyAgentOptions(config) { + if (typeof config.httpAgentOptions === "function") { + return config.httpAgentOptions; + } + let legacy = config.httpAgentOptions; + if (config.keepAlive != null) { + legacy = { keepAlive: config.keepAlive, ...legacy }; + } + if (legacy != null) { + return (0, index_node_http_1.httpAgentFactoryFromOptions)(legacy); + } else { + return; + } + } + function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) { + if (config.metadata) { + api_1.diag.warn("Metadata cannot be set when using http"); + } + return (0, otlp_node_http_configuration_1.mergeOtlpNodeHttpConfigurationWithDefaults)({ + url: config.url, + headers: (0, convert_legacy_http_options_1.convertLegacyHeaders)(config), + concurrencyLimit: config.concurrencyLimit, + timeoutMillis: config.timeoutMillis, + compression: config.compression, + agentFactory: convertLegacyAgentOptions(config), + userAgent: config.userAgent + }, (0, otlp_node_http_env_configuration_1.getNodeHttpConfigurationFromEnvironment)(signalIdentifier, signalResourcePath), (0, otlp_node_http_configuration_1.getNodeHttpConfigurationDefaults)(requiredHeaders, signalResourcePath)); + } + exports.convertLegacyHttpOptions = convertLegacyHttpOptions; +}); + +// node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js +var require_index_node_http = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertLegacyHttpOptions = exports.getSharedConfigurationFromEnvironment = exports.createOtlpHttpExportDelegate = exports.httpAgentFactoryFromOptions = undefined; + var otlp_node_http_configuration_1 = require_otlp_node_http_configuration(); + Object.defineProperty(exports, "httpAgentFactoryFromOptions", { enumerable: true, get: function() { + return otlp_node_http_configuration_1.httpAgentFactoryFromOptions; + } }); + var otlp_http_export_delegate_1 = require_otlp_http_export_delegate(); + Object.defineProperty(exports, "createOtlpHttpExportDelegate", { enumerable: true, get: function() { + return otlp_http_export_delegate_1.createOtlpHttpExportDelegate; + } }); + var shared_env_configuration_1 = require_shared_env_configuration(); + Object.defineProperty(exports, "getSharedConfigurationFromEnvironment", { enumerable: true, get: function() { + return shared_env_configuration_1.getSharedConfigurationFromEnvironment; + } }); + var convert_legacy_node_http_options_1 = require_convert_legacy_node_http_options(); + Object.defineProperty(exports, "convertLegacyHttpOptions", { enumerable: true, get: function() { + return convert_legacy_node_http_options_1.convertLegacyHttpOptions; + } }); +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js +var require_OTLPTraceExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var otlp_exporter_base_1 = require_src4(); + var otlp_transformer_1 = require_src8(); + var node_http_1 = require_index_node_http(); + + class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "TRACES", "v1/traces", { + "Content-Type": "application/x-protobuf" + }), otlp_transformer_1.ProtobufTraceSerializer)); + } + } + exports.OTLPTraceExporter = OTLPTraceExporter; +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js +var require_node3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var OTLPTraceExporter_1 = require_OTLPTraceExporter(); + Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function() { + return OTLPTraceExporter_1.OTLPTraceExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js +var require_platform3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var node_1 = require_node3(); + Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function() { + return node_1.OTLPTraceExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js +var require_src9 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var platform_1 = require_platform3(); + Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function() { + return platform_1.OTLPTraceExporter; + } }); +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/utils/validation.js +var require_validation2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.normalizeScopeAttributes = exports.addAttribute = exports.AddAttributeDecision = exports.isLogAttributeValue = undefined; + var api_1 = require_src(); + function isLogAttributeValue(val) { + return isLogAttributeValueInternal(val, new WeakSet); + } + exports.isLogAttributeValue = isLogAttributeValue; + function isLogAttributeValueInternal(val, visited) { + if (val == null) { + return true; + } + if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") { + return true; + } + if (val instanceof Uint8Array) { + return true; + } + if (typeof val === "object") { + if (visited.has(val)) { + return false; + } + visited.add(val); + if (Array.isArray(val)) { + for (const item of val) { + if (!isLogAttributeValueInternal(item, visited)) { + return false; + } + } + return true; + } + const obj = val; + if (obj.constructor !== Object && obj.constructor !== undefined) { + return false; + } + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && !isLogAttributeValueInternal(obj[key], visited)) { + return false; + } + } + return true; + } + return false; + } + var AddAttributeDecision; + (function(AddAttributeDecision2) { + AddAttributeDecision2[AddAttributeDecision2["DROP_INVALID"] = 0] = "DROP_INVALID"; + AddAttributeDecision2[AddAttributeDecision2["DROP_LIMIT_REACHED"] = 1] = "DROP_LIMIT_REACHED"; + AddAttributeDecision2[AddAttributeDecision2["ADD_NEW"] = 2] = "ADD_NEW"; + AddAttributeDecision2[AddAttributeDecision2["ADD_OVERWRITE_EXISTING"] = 3] = "ADD_OVERWRITE_EXISTING"; + })(AddAttributeDecision = exports.AddAttributeDecision || (exports.AddAttributeDecision = {})); + function addAttribute(attributes, limits, currentAttributesCount, key, value) { + if (key.length === 0) { + api_1.diag.warn(`Invalid attribute key: ${key}`); + return AddAttributeDecision.DROP_INVALID; + } + if (!isLogAttributeValue(value)) { + api_1.diag.warn(`Invalid attribute value set for key: ${key}`); + return AddAttributeDecision.DROP_INVALID; + } + const isNewKey = !Object.prototype.hasOwnProperty.call(attributes, key); + if (isNewKey && currentAttributesCount >= limits.attributeCountLimit) { + return AddAttributeDecision.DROP_LIMIT_REACHED; + } + attributes[key] = truncateToSize(value, limits.attributeValueLengthLimit); + if (isNewKey) { + return AddAttributeDecision.ADD_NEW; + } + return AddAttributeDecision.ADD_OVERWRITE_EXISTING; + } + exports.addAttribute = addAttribute; + function truncateToSize(value, limit) { + if (limit <= 0) { + api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`); + return value; + } + if (value == null) { + return value; + } + if (typeof value === "string") { + if (value.length <= limit) { + return value; + } + return value.substring(0, limit); + } + if (value instanceof Uint8Array) { + return value; + } + if (Array.isArray(value)) { + return value.map((val) => truncateToSize(val, limit)); + } + if (typeof value === "object") { + const truncatedObj = {}; + for (const [k, v] of Object.entries(value)) { + truncatedObj[k] = truncateToSize(v, limit); + } + return truncatedObj; + } + return value; + } + function normalizeScopeAttributes(limits, attributes) { + if (attributes == null) { + return {}; + } + const normalizedAttributes = {}; + let currentAttributesCount = 0; + let droppedAttributesCount = 0; + for (const [key, value] of Object.entries(attributes)) { + const decision = addAttribute(normalizedAttributes, limits, currentAttributesCount, key, value); + if (decision === AddAttributeDecision.ADD_NEW) { + currentAttributesCount += 1; + } else if (decision === AddAttributeDecision.DROP_INVALID) { + droppedAttributesCount += 1; + } else if (decision === AddAttributeDecision.DROP_LIMIT_REACHED) { + droppedAttributesCount += 1; + } else {} + } + return { + attributes: currentAttributesCount > 0 ? normalizedAttributes : undefined, + droppedAttributesCount + }; + } + exports.normalizeScopeAttributes = normalizeScopeAttributes; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js +var require_LogRecordImpl = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LogRecordImpl = undefined; + var api = require_src(); + var core_1 = require_src3(); + var semantic_conventions_1 = require_src2(); + var validation_1 = require_validation2(); + + class LogRecordImpl { + hrTime; + hrTimeObserved; + spanContext; + resource; + instrumentationScope; + attributes = {}; + _severityText; + _severityNumber; + _body; + _eventName; + _attributesCount = 0; + _droppedAttributesCount = 0; + _isReadonly = false; + _logRecordLimits; + set severityText(severityText) { + if (this._isLogRecordReadonly()) { + return; + } + this._severityText = severityText; + } + get severityText() { + return this._severityText; + } + set severityNumber(severityNumber) { + if (this._isLogRecordReadonly()) { + return; + } + this._severityNumber = severityNumber; + } + get severityNumber() { + return this._severityNumber; + } + set body(body) { + if (this._isLogRecordReadonly()) { + return; + } + this._body = body; + } + get body() { + return this._body; + } + get eventName() { + return this._eventName; + } + set eventName(eventName) { + if (this._isLogRecordReadonly()) { + return; + } + this._eventName = eventName; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + constructor(_sharedState, instrumentationScope, logRecord) { + const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, exception, context } = logRecord; + const now = Date.now(); + this.hrTime = (0, core_1.timeInputToHrTime)(timestamp ?? now); + this.hrTimeObserved = (0, core_1.timeInputToHrTime)(observedTimestamp ?? now); + if (context) { + const spanContext = api.trace.getSpanContext(context); + if (spanContext && api.isSpanContextValid(spanContext)) { + this.spanContext = spanContext; + } + } + this.severityNumber = severityNumber; + this.severityText = severityText; + this.body = body; + this.resource = _sharedState.resource; + this.instrumentationScope = instrumentationScope; + this._logRecordLimits = _sharedState.logRecordLimits; + this._eventName = eventName; + this.setAttributes(attributes); + if (exception != null) { + this._setException(exception); + } + } + setAttribute(key, value) { + if (this._isLogRecordReadonly()) { + return this; + } + const decision = (0, validation_1.addAttribute)(this.attributes, this._logRecordLimits, this._attributesCount, key, value); + if (decision === validation_1.AddAttributeDecision.DROP_LIMIT_REACHED) { + this._droppedAttributesCount++; + if (this._droppedAttributesCount === 1) { + api.diag.warn("Dropping extra attributes."); + } + } else if (decision === validation_1.AddAttributeDecision.ADD_NEW) { + this._attributesCount++; + } + return this; + } + setAttributes(attributes) { + for (const [k, v] of Object.entries(attributes)) { + this.setAttribute(k, v); + } + return this; + } + setBody(body) { + this.body = body; + return this; + } + setEventName(eventName) { + this.eventName = eventName; + return this; + } + setSeverityNumber(severityNumber) { + this.severityNumber = severityNumber; + return this; + } + setSeverityText(severityText) { + this.severityText = severityText; + return this; + } + _makeReadonly() { + this._isReadonly = true; + } + _setException(exception) { + let hasMinimumAttributes = false; + if (typeof exception === "string" || typeof exception === "number") { + if (!Object.hasOwn(this.attributes, semantic_conventions_1.ATTR_EXCEPTION_MESSAGE)) { + this.setAttribute(semantic_conventions_1.ATTR_EXCEPTION_MESSAGE, String(exception)); + } + hasMinimumAttributes = true; + } else if (exception && typeof exception === "object") { + const exceptionObj = exception; + if (exceptionObj.code) { + if (!Object.hasOwn(this.attributes, semantic_conventions_1.ATTR_EXCEPTION_TYPE)) { + this.setAttribute(semantic_conventions_1.ATTR_EXCEPTION_TYPE, exceptionObj.code.toString()); + } + hasMinimumAttributes = true; + } else if (exceptionObj.name) { + if (!Object.hasOwn(this.attributes, semantic_conventions_1.ATTR_EXCEPTION_TYPE)) { + this.setAttribute(semantic_conventions_1.ATTR_EXCEPTION_TYPE, exceptionObj.name); + } + hasMinimumAttributes = true; + } + if (exceptionObj.message) { + if (!Object.hasOwn(this.attributes, semantic_conventions_1.ATTR_EXCEPTION_MESSAGE)) { + this.setAttribute(semantic_conventions_1.ATTR_EXCEPTION_MESSAGE, exceptionObj.message); + } + hasMinimumAttributes = true; + } + if (exceptionObj.stack) { + if (!Object.hasOwn(this.attributes, semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE)) { + this.setAttribute(semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE, exceptionObj.stack); + } + hasMinimumAttributes = true; + } + } + if (!hasMinimumAttributes) { + api.diag.warn(`Failed to record an exception ${exception}`); + } + } + _isLogRecordReadonly() { + if (this._isReadonly) { + api.diag.warn("Can not execute the operation on emitted log record"); + } + return this._isReadonly; + } + } + exports.LogRecordImpl = LogRecordImpl; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/Logger.js +var require_Logger = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Logger = undefined; + var api_logs_1 = require_src5(); + var api_1 = require_src(); + var LogRecordImpl_1 = require_LogRecordImpl(); + + class Logger { + _instrumentationScope; + _sharedState; + _loggerConfig; + constructor(instrumentationScope, sharedState) { + this._instrumentationScope = instrumentationScope; + this._sharedState = sharedState; + this._loggerConfig = this._sharedState.getLoggerConfig(this._instrumentationScope); + } + emit(logRecord) { + const currentContext = logRecord.context || api_1.context.active(); + if (!this.enabled(logRecord)) { + return; + } + const logRecordInstance = new LogRecordImpl_1.LogRecordImpl(this._sharedState, this._instrumentationScope, { + context: currentContext, + ...logRecord + }); + this._sharedState.loggerMetrics.emitLog(); + this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext); + logRecordInstance._makeReadonly(); + } + enabled(options) { + const loggerConfig = this._loggerConfig; + if (loggerConfig.disabled) { + return false; + } + const severityNumber = options?.severityNumber; + if (typeof severityNumber === "number" && severityNumber !== api_logs_1.SeverityNumber.UNSPECIFIED && severityNumber < loggerConfig.minimumSeverity) { + return false; + } + const currentContext = options?.context || api_1.context.active(); + if (loggerConfig.traceBased) { + const spanContext = api_1.trace.getSpanContext(currentContext); + if (spanContext && (0, api_1.isSpanContextValid)(spanContext)) { + const isSampled = (spanContext.traceFlags & api_1.TraceFlags.SAMPLED) === api_1.TraceFlags.SAMPLED; + if (!isSampled) { + return false; + } + } + } + const enabledOpts = { + context: currentContext, + instrumentationScope: this._instrumentationScope, + severityNumber: options?.severityNumber, + eventName: options?.eventName + }; + for (const processor of this._sharedState.processors) { + if (!processor.enabled || processor.enabled(enabledOpts)) { + return true; + } + } + return false; + } + } + exports.Logger = Logger; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js +var require_NoopLogRecordProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopLogRecordProcessor = undefined; + + class NoopLogRecordProcessor { + forceFlush() { + return Promise.resolve(); + } + onEmit(_logRecord, _context) {} + shutdown() { + return Promise.resolve(); + } + enabled(_options) { + return false; + } + } + exports.NoopLogRecordProcessor = NoopLogRecordProcessor; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js +var require_MultiLogRecordProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MultiLogRecordProcessor = undefined; + var core_1 = require_src3(); + + class MultiLogRecordProcessor { + processors; + forceFlushTimeoutMillis; + constructor(processors, forceFlushTimeoutMillis) { + this.processors = processors; + this.forceFlushTimeoutMillis = forceFlushTimeoutMillis; + } + async forceFlush() { + const timeout = this.forceFlushTimeoutMillis; + await Promise.all(this.processors.map((processor) => (0, core_1.callWithTimeout)(processor.forceFlush(), timeout))); + } + onEmit(logRecord, context) { + this.processors.forEach((processors) => processors.onEmit(logRecord, context)); + } + async shutdown() { + await Promise.all(this.processors.map((processor) => processor.shutdown())); + } + enabled(options) { + for (const processor of this.processors) { + if (!processor.enabled || processor.enabled(options)) { + return true; + } + } + return false; + } + } + exports.MultiLogRecordProcessor = MultiLogRecordProcessor; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/internal/utils.js +var require_utils10 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getInstrumentationScopeKey = undefined; + function normalizeAnyValue(value) { + if (value === undefined) { + return ["u", null]; + } + if (value === null) { + return ["n", null]; + } + const valueType = typeof value; + if (valueType === "string") { + return ["s", value]; + } + if (valueType === "boolean") { + return ["b", value]; + } + if (valueType === "number") { + if (Number.isNaN(value)) + return ["nan", null]; + if (value === Infinity) + return ["inf", null]; + if (value === -Infinity) + return ["-inf", null]; + if (Object.is(value, -0)) + return ["n0", null]; + return ["d", value]; + } + if (value instanceof Uint8Array) { + return ["bytes", Array.from(value)]; + } + if (Array.isArray(value)) { + return ["arr", value.map(normalizeAnyValue)]; + } + return [ + "map", + Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, normalizeAnyValue(v)]) + ]; + } + function getInstrumentationScopeKey(scope) { + return JSON.stringify([ + scope.name, + scope.version || "", + scope.schemaUrl || "", + normalizeAnyValue(scope.attributes), + scope.droppedAttributesCount ?? 0 + ]); + } + exports.getInstrumentationScopeKey = getInstrumentationScopeKey; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/semconv.js +var require_semconv4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.METRIC_OTEL_SDK_LOG_CREATED = undefined; + exports.METRIC_OTEL_SDK_LOG_CREATED = "otel.sdk.log.created"; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/LoggerMetrics.js +var require_LoggerMetrics = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LoggerMetrics = undefined; + var semconv_1 = require_semconv4(); + + class LoggerMetrics { + createdLogs; + constructor(meter) { + this.createdLogs = meter.createCounter(semconv_1.METRIC_OTEL_SDK_LOG_CREATED, { + unit: "{log_record}", + description: "The number of logs submitted to enabled SDK Loggers." + }); + } + emitLog() { + this.createdLogs.add(1); + } + } + exports.LoggerMetrics = LoggerMetrics; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/version.js +var require_version6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = undefined; + exports.VERSION = "0.219.0"; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js +var require_LoggerProviderSharedState = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LoggerProviderSharedState = exports.DEFAULT_LOGGER_CONFIGURATOR = undefined; + var api_1 = require_src(); + var api_logs_1 = require_src5(); + var NoopLogRecordProcessor_1 = require_NoopLogRecordProcessor(); + var MultiLogRecordProcessor_1 = require_MultiLogRecordProcessor(); + var utils_1 = require_utils10(); + var LoggerMetrics_1 = require_LoggerMetrics(); + var version_1 = require_version6(); + var DEFAULT_LOGGER_CONFIG = { + disabled: false, + minimumSeverity: api_logs_1.SeverityNumber.UNSPECIFIED, + traceBased: false + }; + var DEFAULT_LOGGER_CONFIGURATOR = () => ({ + ...DEFAULT_LOGGER_CONFIG + }); + exports.DEFAULT_LOGGER_CONFIGURATOR = DEFAULT_LOGGER_CONFIGURATOR; + + class LoggerProviderSharedState { + loggers = new Map; + activeProcessor; + registeredLogRecordProcessors = []; + resource; + forceFlushTimeoutMillis; + logRecordLimits; + processors; + loggerMetrics; + _loggerConfigurator; + _loggerConfigs = new Map; + constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors, loggerConfigurator, meterProvider) { + this.resource = resource; + this.forceFlushTimeoutMillis = forceFlushTimeoutMillis; + this.logRecordLimits = logRecordLimits; + this.processors = processors; + if (processors.length > 0) { + this.registeredLogRecordProcessors = processors; + this.activeProcessor = new MultiLogRecordProcessor_1.MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis); + } else { + this.activeProcessor = new NoopLogRecordProcessor_1.NoopLogRecordProcessor; + } + this._loggerConfigurator = loggerConfigurator ?? exports.DEFAULT_LOGGER_CONFIGURATOR; + const meter = meterProvider ? meterProvider.getMeter("@opentelemetry/sdk-logs", version_1.VERSION) : (0, api_1.createNoopMeter)(); + this.loggerMetrics = new LoggerMetrics_1.LoggerMetrics(meter); + } + getLoggerConfig(instrumentationScope) { + const key = (0, utils_1.getInstrumentationScopeKey)(instrumentationScope); + let config = this._loggerConfigs.get(key); + if (config) { + return config; + } + config = this._loggerConfigurator(instrumentationScope); + this._loggerConfigs.set(key, config); + return config; + } + } + exports.LoggerProviderSharedState = LoggerProviderSharedState; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js +var require_LoggerProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LoggerProvider = exports.DEFAULT_LOGGER_NAME = undefined; + var api_1 = require_src(); + var api_logs_1 = require_src5(); + var resources_1 = require_src6(); + var core_1 = require_src3(); + var Logger_1 = require_Logger(); + var LoggerProviderSharedState_1 = require_LoggerProviderSharedState(); + var utils_1 = require_utils10(); + var validation_1 = require_validation2(); + exports.DEFAULT_LOGGER_NAME = "unknown"; + + class LoggerProvider { + _shutdownOnce; + _sharedState; + constructor(config = {}) { + const mergedConfig = { + resource: config.resource ?? (0, resources_1.defaultResource)(), + forceFlushTimeoutMillis: config.forceFlushTimeoutMillis ?? 30000, + logRecordLimits: { + attributeCountLimit: config.logRecordLimits?.attributeCountLimit ?? 128, + attributeValueLengthLimit: config.logRecordLimits?.attributeValueLengthLimit ?? Infinity + }, + loggerConfigurator: config.loggerConfigurator ?? LoggerProviderSharedState_1.DEFAULT_LOGGER_CONFIGURATOR, + processors: config.processors ?? [], + meterProvider: config.meterProvider + }; + this._sharedState = new LoggerProviderSharedState_1.LoggerProviderSharedState(mergedConfig.resource, mergedConfig.forceFlushTimeoutMillis, mergedConfig.logRecordLimits, mergedConfig.processors, mergedConfig.loggerConfigurator, mergedConfig.meterProvider); + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + } + getLogger(name, version, options) { + if (this._shutdownOnce.isCalled) { + api_1.diag.warn("A shutdown LoggerProvider cannot provide a Logger"); + return (0, api_logs_1.createNoopLogger)(); + } + if (!name) { + api_1.diag.warn("Logger requested without instrumentation scope name."); + } + const loggerName = name || exports.DEFAULT_LOGGER_NAME; + const instrumentationScope = { + name: loggerName, + version, + schemaUrl: options?.schemaUrl, + ...(0, validation_1.normalizeScopeAttributes)(this._sharedState.logRecordLimits, options?.attributes) + }; + const key = (0, utils_1.getInstrumentationScopeKey)(instrumentationScope); + if (!this._sharedState.loggers.has(key)) { + this._sharedState.loggers.set(key, new Logger_1.Logger(instrumentationScope, this._sharedState)); + } + return this._sharedState.loggers.get(key); + } + forceFlush() { + if (this._shutdownOnce.isCalled) { + api_1.diag.warn("invalid attempt to force flush after LoggerProvider shutdown"); + return this._shutdownOnce.promise; + } + return this._sharedState.activeProcessor.forceFlush(); + } + shutdown() { + if (this._shutdownOnce.isCalled) { + api_1.diag.warn("shutdown may only be called once per LoggerProvider"); + return this._shutdownOnce.promise; + } + return this._shutdownOnce.call(); + } + _shutdown() { + return this._sharedState.activeProcessor.shutdown(); + } + } + exports.LoggerProvider = LoggerProvider; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js +var require_ConsoleLogRecordExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConsoleLogRecordExporter = undefined; + var core_1 = require_src3(); + + class ConsoleLogRecordExporter { + export(logs, resultCallback) { + this._sendLogRecords(logs, resultCallback); + } + async forceFlush() {} + async shutdown() {} + _exportInfo(logRecord) { + return { + resource: { + attributes: logRecord.resource.attributes + }, + instrumentationScope: logRecord.instrumentationScope, + timestamp: (0, core_1.hrTimeToMicroseconds)(logRecord.hrTime), + traceId: logRecord.spanContext?.traceId, + spanId: logRecord.spanContext?.spanId, + traceFlags: logRecord.spanContext?.traceFlags, + severityText: logRecord.severityText, + severityNumber: logRecord.severityNumber, + eventName: logRecord.eventName, + body: logRecord.body, + attributes: logRecord.attributes + }; + } + _sendLogRecords(logRecords, done) { + for (const logRecord of logRecords) { + console.dir(this._exportInfo(logRecord), { depth: 3 }); + } + done?.({ code: core_1.ExportResultCode.SUCCESS }); + } + } + exports.ConsoleLogRecordExporter = ConsoleLogRecordExporter; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js +var require_SimpleLogRecordProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SimpleLogRecordProcessor = undefined; + var core_1 = require_src3(); + + class SimpleLogRecordProcessor { + _exporter; + _shutdownOnce; + _unresolvedExports; + constructor(exporter) { + this._exporter = exporter; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + this._unresolvedExports = new Set; + } + onEmit(logRecord, _context) { + if (this._shutdownOnce.isCalled) { + return; + } + const doExport = () => core_1.internal._export(this._exporter, [logRecord]).then((result) => { + if (result.code !== core_1.ExportResultCode.SUCCESS) { + (0, core_1.globalErrorHandler)(result.error ?? new Error(`SimpleLogRecordProcessor: log record export failed (status ${result})`)); + } + }).catch(core_1.globalErrorHandler); + if (logRecord.resource.asyncAttributesPending) { + const exportPromise = logRecord.resource.waitForAsyncAttributes?.().then(() => { + this._unresolvedExports.delete(exportPromise); + return doExport(); + }, core_1.globalErrorHandler); + if (exportPromise != null) { + this._unresolvedExports.add(exportPromise); + } + } else { + doExport(); + } + } + async forceFlush() { + await Promise.all(Array.from(this._unresolvedExports)); + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + return this._exporter.shutdown(); + } + } + exports.SimpleLogRecordProcessor = SimpleLogRecordProcessor; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js +var require_InMemoryLogRecordExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InMemoryLogRecordExporter = undefined; + var core_1 = require_src3(); + + class InMemoryLogRecordExporter { + _finishedLogRecords = []; + _stopped = false; + export(logs, resultCallback) { + if (this._stopped) { + return resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error("Exporter has been stopped") + }); + } + this._finishedLogRecords.push(...logs); + resultCallback({ code: core_1.ExportResultCode.SUCCESS }); + } + async shutdown() { + this._stopped = true; + this.reset(); + } + async forceFlush() {} + getFinishedLogRecords() { + return this._finishedLogRecords; + } + reset() { + this._finishedLogRecords = []; + } + } + exports.InMemoryLogRecordExporter = InMemoryLogRecordExporter; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js +var require_BatchLogRecordProcessorBase = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchLogRecordProcessorBase = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + async function waitForResources(logRecords) { + const pendingResources = []; + for (let i = 0, len = logRecords.length;i < len; i++) { + const logRecord = logRecords[i]; + if (logRecord.resource.asyncAttributesPending && logRecord.resource.waitForAsyncAttributes) { + pendingResources.push(logRecord.resource.waitForAsyncAttributes()); + } + } + if (pendingResources != null && pendingResources.length > 0) { + await Promise.all(pendingResources); + } + } + + class ExportOperation { + _exportCompleted; + _exportScheduledPromise; + _exportScheduledResolve; + constructor(exporter, logRecords, exportTimeoutMillis) { + this._exportScheduledPromise = new Promise((resolve) => { + this._exportScheduledResolve = resolve; + }); + this._exportCompleted = this._executeExport(exporter, logRecords, exportTimeoutMillis); + } + get exportCompleted() { + return this._exportCompleted; + } + get exportScheduled() { + return this._exportScheduledPromise; + } + async _executeExport(exporter, logRecords, exportTimeoutMillis) { + try { + await waitForResources(logRecords); + await api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), async () => { + return this._exportWithTimeout(exporter, logRecords, exportTimeoutMillis); + }); + } catch (e) { + (0, core_1.globalErrorHandler)(e); + this._exportScheduledResolve(); + } + } + async _exportWithTimeout(exporter, logRecords, exportTimeoutMillis) { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error("Timeout")); + }, exportTimeoutMillis); + exporter.export(logRecords, (result) => { + clearTimeout(timer); + if (result.code === core_1.ExportResultCode.SUCCESS) { + resolve(); + } else { + reject(result.error ?? new Error("BatchLogRecordProcessor: log record export failed")); + } + }); + this._exportScheduledResolve(); + }); + } + } + + class BatchLogRecordProcessorBase { + _maxExportBatchSize; + _maxQueueSize; + _scheduledDelayMillis; + _exportTimeoutMillis; + _exporter; + _currentExport = null; + _finishedLogRecords = []; + _timer; + _shutdownOnce; + _flushing = false; + constructor(exporter, config) { + this._exporter = exporter; + this._maxExportBatchSize = config?.maxExportBatchSize ?? 512; + this._maxQueueSize = config?.maxQueueSize ?? 2048; + this._scheduledDelayMillis = config?.scheduledDelayMillis ?? 5000; + this._exportTimeoutMillis = config?.exportTimeoutMillis ?? 30000; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + if (this._maxExportBatchSize > this._maxQueueSize) { + api_1.diag.warn("BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"); + this._maxExportBatchSize = this._maxQueueSize; + } + } + onEmit(logRecord) { + if (this._shutdownOnce.isCalled) { + return; + } + this._addToBuffer(logRecord); + } + forceFlush() { + if (this._shutdownOnce.isCalled) { + return this._shutdownOnce.promise; + } + return this._flushAll(); + } + _addToBuffer(logRecord) { + if (this._finishedLogRecords.length >= this._maxQueueSize) { + return; + } + this._finishedLogRecords.push(logRecord); + this._maybeStartTimer(); + } + shutdown() { + return this._shutdownOnce.call(); + } + async _shutdown() { + this.onShutdown(); + await this._flushAll(); + await this._exporter.shutdown(); + } + async _flushAll() { + if (this._flushing) { + return; + } + this._flushing = true; + let toFlush = this._finishedLogRecords; + this._finishedLogRecords = []; + this._clearTimer(); + const inFlight = this._currentExport; + if (inFlight !== null) { + await this._exporter.forceFlush(); + await inFlight.exportCompleted; + this._currentExport = null; + } + while (toFlush.length > 0) { + let batch; + if (toFlush.length <= this._maxExportBatchSize) { + batch = toFlush; + toFlush = []; + } else { + batch = toFlush.splice(0, this._maxExportBatchSize); + } + const exportOp = new ExportOperation(this._exporter, batch, this._exportTimeoutMillis); + this._currentExport = exportOp; + try { + await exportOp.exportScheduled; + await this._exporter.forceFlush(); + await exportOp.exportCompleted; + } catch (e) { + (0, core_1.globalErrorHandler)(e); + } finally { + this._currentExport = null; + } + } + this._flushing = false; + this._maybeStartTimer(); + } + _extractBatch() { + if (this._finishedLogRecords.length === 0) { + return null; + } + if (this._finishedLogRecords.length <= this._maxExportBatchSize) { + const batch = this._finishedLogRecords; + this._finishedLogRecords = []; + return batch; + } else { + return this._finishedLogRecords.splice(0, this._maxExportBatchSize); + } + } + _exportOneBatch() { + this._clearTimer(); + const logRecords = this._extractBatch(); + if (logRecords === null) { + return; + } + const exportOp = new ExportOperation(this._exporter, logRecords, this._exportTimeoutMillis); + this._currentExport = exportOp; + exportOp.exportCompleted.then(() => { + this._currentExport = null; + this._maybeStartTimer(); + }).catch((error) => { + this._currentExport = null; + (0, core_1.globalErrorHandler)(error); + this._maybeStartTimer(); + }); + } + _maybeStartTimer() { + if (this._shutdownOnce.isCalled) { + return; + } + if (this._flushing) { + return; + } + if (this._finishedLogRecords.length === 0) { + return; + } + if (this._currentExport !== null) { + return; + } + if (this._finishedLogRecords.length >= this._maxExportBatchSize) { + this._exportOneBatch(); + return; + } + if (this._timer !== undefined) { + return; + } + this._timer = setTimeout(() => { + this._timer = undefined; + this._exportOneBatch(); + }, this._scheduledDelayMillis); + if (typeof this._timer !== "number") { + this._timer.unref(); + } + } + _clearTimer() { + if (this._timer !== undefined) { + clearTimeout(this._timer); + this._timer = undefined; + } + } + } + exports.BatchLogRecordProcessorBase = BatchLogRecordProcessorBase; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js +var require_BatchLogRecordProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchLogRecordProcessor = undefined; + var BatchLogRecordProcessorBase_1 = require_BatchLogRecordProcessorBase(); + + class BatchLogRecordProcessor extends BatchLogRecordProcessorBase_1.BatchLogRecordProcessorBase { + onShutdown() {} + } + exports.BatchLogRecordProcessor = BatchLogRecordProcessor; +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js +var require_node4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchLogRecordProcessor = undefined; + var BatchLogRecordProcessor_1 = require_BatchLogRecordProcessor(); + Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function() { + return BatchLogRecordProcessor_1.BatchLogRecordProcessor; + } }); +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js +var require_platform4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchLogRecordProcessor = undefined; + var node_1 = require_node4(); + Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function() { + return node_1.BatchLogRecordProcessor; + } }); +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/config/LoggerConfigurators.js +var require_LoggerConfigurators = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createLoggerConfigurator = undefined; + var api_logs_1 = require_src5(); + var DEFAULT_LOGGER_CONFIG = { + disabled: false, + minimumSeverity: api_logs_1.SeverityNumber.UNSPECIFIED, + traceBased: false + }; + function createLoggerConfigurator(patterns) { + return (loggerScope) => { + const loggerName = loggerScope.name; + for (const { pattern, config } of patterns) { + if (matchesPattern(loggerName, pattern)) { + return { + disabled: config.disabled ?? DEFAULT_LOGGER_CONFIG.disabled, + minimumSeverity: config.minimumSeverity ?? DEFAULT_LOGGER_CONFIG.minimumSeverity, + traceBased: config.traceBased ?? DEFAULT_LOGGER_CONFIG.traceBased + }; + } + } + return { ...DEFAULT_LOGGER_CONFIG }; + }; + } + exports.createLoggerConfigurator = createLoggerConfigurator; + function matchesPattern(name, pattern) { + if (pattern === name) { + return true; + } + if (pattern.includes("*")) { + const regexPattern = pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*"); + const regex = new RegExp(`^${regexPattern}$`); + return regex.test(name); + } + return false; + } +}); + +// node_modules/@opentelemetry/sdk-logs/build/src/index.js +var require_src10 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createLoggerConfigurator = exports.BatchLogRecordProcessor = exports.InMemoryLogRecordExporter = exports.SimpleLogRecordProcessor = exports.ConsoleLogRecordExporter = exports.LoggerProvider = undefined; + var LoggerProvider_1 = require_LoggerProvider(); + Object.defineProperty(exports, "LoggerProvider", { enumerable: true, get: function() { + return LoggerProvider_1.LoggerProvider; + } }); + var ConsoleLogRecordExporter_1 = require_ConsoleLogRecordExporter(); + Object.defineProperty(exports, "ConsoleLogRecordExporter", { enumerable: true, get: function() { + return ConsoleLogRecordExporter_1.ConsoleLogRecordExporter; + } }); + var SimpleLogRecordProcessor_1 = require_SimpleLogRecordProcessor(); + Object.defineProperty(exports, "SimpleLogRecordProcessor", { enumerable: true, get: function() { + return SimpleLogRecordProcessor_1.SimpleLogRecordProcessor; + } }); + var InMemoryLogRecordExporter_1 = require_InMemoryLogRecordExporter(); + Object.defineProperty(exports, "InMemoryLogRecordExporter", { enumerable: true, get: function() { + return InMemoryLogRecordExporter_1.InMemoryLogRecordExporter; + } }); + var platform_1 = require_platform4(); + Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function() { + return platform_1.BatchLogRecordProcessor; + } }); + var LoggerConfigurators_1 = require_LoggerConfigurators(); + Object.defineProperty(exports, "createLoggerConfigurator", { enumerable: true, get: function() { + return LoggerConfigurators_1.createLoggerConfigurator; + } }); +}); + +// node_modules/@opentelemetry/context-async-hooks/build/src/AbstractAsyncHooksContextManager.js +var require_AbstractAsyncHooksContextManager = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AbstractAsyncHooksContextManager = undefined; + var events_1 = __require("events"); + var ADD_LISTENER_METHODS = [ + "addListener", + "on", + "once", + "prependListener", + "prependOnceListener" + ]; + + class AbstractAsyncHooksContextManager { + bind(context, target) { + if (target instanceof events_1.EventEmitter) { + return this._bindEventEmitter(context, target); + } + if (typeof target === "function") { + return this._bindFunction(context, target); + } + return target; + } + _bindFunction(context, target) { + const manager = this; + const contextWrapper = function(...args) { + return manager.with(context, () => target.apply(this, args)); + }; + Object.defineProperty(contextWrapper, "length", { + enumerable: false, + configurable: true, + writable: false, + value: target.length + }); + return contextWrapper; + } + _bindEventEmitter(context, ee) { + const map = this._getPatchMap(ee); + if (map !== undefined) + return ee; + this._createPatchMap(ee); + ADD_LISTENER_METHODS.forEach((methodName) => { + if (ee[methodName] === undefined) + return; + ee[methodName] = this._patchAddListener(ee, ee[methodName], context); + }); + if (typeof ee.removeListener === "function") { + ee.removeListener = this._patchRemoveListener(ee, ee.removeListener); + } + if (typeof ee.off === "function") { + ee.off = this._patchRemoveListener(ee, ee.off); + } + if (typeof ee.removeAllListeners === "function") { + ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners); + } + return ee; + } + _patchRemoveListener(ee, original) { + const contextManager = this; + return function(event, listener) { + const events = contextManager._getPatchMap(ee)?.[event]; + if (events === undefined) { + return original.call(this, event, listener); + } + const patchedListener = events.get(listener); + return original.call(this, event, patchedListener || listener); + }; + } + _patchRemoveAllListeners(ee, original) { + const contextManager = this; + return function(event) { + const map = contextManager._getPatchMap(ee); + if (map !== undefined) { + if (arguments.length === 0) { + contextManager._createPatchMap(ee); + } else if (map[event] !== undefined) { + delete map[event]; + } + } + return original.apply(this, arguments); + }; + } + _patchAddListener(ee, original, context) { + const contextManager = this; + return function(event, listener) { + if (contextManager._wrapped) { + return original.call(this, event, listener); + } + let map = contextManager._getPatchMap(ee); + if (map === undefined) { + map = contextManager._createPatchMap(ee); + } + let listeners = map[event]; + if (listeners === undefined) { + listeners = new WeakMap; + map[event] = listeners; + } + const patchedListener = contextManager.bind(context, listener); + listeners.set(listener, patchedListener); + contextManager._wrapped = true; + try { + return original.call(this, event, patchedListener); + } finally { + contextManager._wrapped = false; + } + }; + } + _createPatchMap(ee) { + const map = Object.create(null); + ee[this._kOtListeners] = map; + return map; + } + _getPatchMap(ee) { + return ee[this._kOtListeners]; + } + _kOtListeners = Symbol("OtListeners"); + _wrapped = false; + } + exports.AbstractAsyncHooksContextManager = AbstractAsyncHooksContextManager; +}); + +// node_modules/@opentelemetry/context-async-hooks/build/src/AsyncHooksContextManager.js +var require_AsyncHooksContextManager = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncHooksContextManager = undefined; + var api_1 = require_src(); + var asyncHooks = __require("async_hooks"); + var AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager(); + + class AsyncHooksContextManager extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager { + _asyncHook; + _contexts = new Map; + _stack = []; + constructor() { + super(); + this._asyncHook = asyncHooks.createHook({ + init: this._init.bind(this), + before: this._before.bind(this), + after: this._after.bind(this), + destroy: this._destroy.bind(this), + promiseResolve: this._destroy.bind(this) + }); + } + active() { + return this._stack[this._stack.length - 1] ?? api_1.ROOT_CONTEXT; + } + with(context, fn, thisArg, ...args) { + this._enterContext(context); + try { + return fn.call(thisArg, ...args); + } finally { + this._exitContext(); + } + } + enable() { + this._asyncHook.enable(); + return this; + } + disable() { + this._asyncHook.disable(); + this._contexts.clear(); + this._stack = []; + return this; + } + _init(uid, type) { + if (type === "TIMERWRAP") + return; + const context = this._stack[this._stack.length - 1]; + if (context !== undefined) { + this._contexts.set(uid, context); + } + } + _destroy(uid) { + this._contexts.delete(uid); + } + _before(uid) { + const context = this._contexts.get(uid); + if (context !== undefined) { + this._enterContext(context); + } + } + _after() { + this._exitContext(); + } + _enterContext(context) { + this._stack.push(context); + } + _exitContext() { + this._stack.pop(); + } + } + exports.AsyncHooksContextManager = AsyncHooksContextManager; +}); + +// node_modules/@opentelemetry/context-async-hooks/build/src/AsyncLocalStorageContextManager.js +var require_AsyncLocalStorageContextManager = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncLocalStorageContextManager = undefined; + var api_1 = require_src(); + var async_hooks_1 = __require("async_hooks"); + var AbstractAsyncHooksContextManager_1 = require_AbstractAsyncHooksContextManager(); + + class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager_1.AbstractAsyncHooksContextManager { + _asyncLocalStorage; + constructor() { + super(); + this._asyncLocalStorage = new async_hooks_1.AsyncLocalStorage; + } + active() { + return this._asyncLocalStorage.getStore() ?? api_1.ROOT_CONTEXT; + } + with(context, fn, thisArg, ...args) { + const cb = thisArg == null ? fn : fn.bind(thisArg); + return this._asyncLocalStorage.run(context, cb, ...args); + } + enable() { + return this; + } + disable() { + this._asyncLocalStorage.disable(); + return this; + } + } + exports.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager; +}); + +// node_modules/@opentelemetry/context-async-hooks/build/src/index.js +var require_src11 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AsyncLocalStorageContextManager = exports.AsyncHooksContextManager = undefined; + var AsyncHooksContextManager_1 = require_AsyncHooksContextManager(); + Object.defineProperty(exports, "AsyncHooksContextManager", { enumerable: true, get: function() { + return AsyncHooksContextManager_1.AsyncHooksContextManager; + } }); + var AsyncLocalStorageContextManager_1 = require_AsyncLocalStorageContextManager(); + Object.defineProperty(exports, "AsyncLocalStorageContextManager", { enumerable: true, get: function() { + return AsyncLocalStorageContextManager_1.AsyncLocalStorageContextManager; + } }); +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js +var require_enums = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExceptionEventName = undefined; + exports.ExceptionEventName = "exception"; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/inspect.js +var require_inspect2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatInspect = exports.settledResourceAttributes = exports.inspectCustom = undefined; + exports.inspectCustom = Symbol.for("nodejs.util.inspect.custom"); + function settledResourceAttributes(resource) { + const attrs = {}; + for (const [k, v] of resource.getRawAttributes()) { + if (typeof v?.then === "function") { + continue; + } + if (v != null) { + attrs[k] ??= v; + } + } + return attrs; + } + exports.settledResourceAttributes = settledResourceAttributes; + function formatInspect(className, payload, depth, options, inspect) { + if (typeof depth === "number" && depth < 0) { + const tag = `[${className}]`; + return options?.stylize ? options.stylize(tag, "special") : tag; + } + if (typeof inspect !== "function" || !options) { + return payload; + } + const childOptions = { + ...options, + depth: options.depth == null ? options.depth : options.depth - 1 + }; + return `${className} ${inspect(payload, childOptions)}`; + } + exports.formatInspect = formatInspect; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js +var require_Span = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanImpl = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var semantic_conventions_1 = require_src2(); + var enums_1 = require_enums(); + var inspect_1 = require_inspect2(); + + class SpanImpl { + _spanContext; + kind; + parentSpanContext; + attributes = {}; + links = []; + events = []; + startTime; + resource; + instrumentationScope; + _droppedAttributesCount = 0; + _droppedEventsCount = 0; + _droppedLinksCount = 0; + _attributesCount = 0; + name; + status = { + code: api_1.SpanStatusCode.UNSET + }; + endTime = [0, 0]; + _ended = false; + _duration = [-1, -1]; + _spanProcessor; + _spanLimits; + _attributeValueLengthLimit; + _recordEndMetrics; + _performanceStartTime; + _performanceOffset; + _startTimeProvided; + constructor(opts) { + const now = Date.now(); + this._spanContext = opts.spanContext; + this._performanceStartTime = core_1.otperformance.now(); + this._performanceOffset = now - (this._performanceStartTime + core_1.otperformance.timeOrigin); + this._startTimeProvided = opts.startTime != null; + this._spanLimits = opts.spanLimits; + this._attributeValueLengthLimit = this._spanLimits.attributeValueLengthLimit ?? 0; + this._spanProcessor = opts.spanProcessor; + this.name = opts.name; + this.parentSpanContext = opts.parentSpanContext; + this.kind = opts.kind; + if (opts.links) { + for (const link of opts.links) { + this.addLink(link); + } + } + this.startTime = this._getTime(opts.startTime ?? now); + this.resource = opts.resource; + this.instrumentationScope = opts.scope; + this._recordEndMetrics = opts.recordEndMetrics; + if (opts.attributes != null) { + this.setAttributes(opts.attributes); + } + this._spanProcessor.onStart(this, opts.context); + } + spanContext() { + return this._spanContext; + } + setAttribute(key, value) { + if (value == null || this._isSpanEnded()) + return this; + if (key.length === 0) { + api_1.diag.warn(`Invalid attribute key: ${key}`); + return this; + } + if (!(0, core_1.isAttributeValue)(value)) { + api_1.diag.warn(`Invalid attribute value set for key: ${key}`); + return this; + } + const { attributeCountLimit } = this._spanLimits; + const isNewKey = !Object.prototype.hasOwnProperty.call(this.attributes, key); + if (attributeCountLimit !== undefined && this._attributesCount >= attributeCountLimit && isNewKey) { + this._droppedAttributesCount++; + return this; + } + this.attributes[key] = this._truncateToSize(value); + if (isNewKey) { + this._attributesCount++; + } + return this; + } + setAttributes(attributes) { + for (const key in attributes) { + if (Object.prototype.hasOwnProperty.call(attributes, key)) { + this.setAttribute(key, attributes[key]); + } + } + return this; + } + addEvent(name, attributesOrStartTime, timeStamp) { + if (this._isSpanEnded()) + return this; + const { eventCountLimit } = this._spanLimits; + if (eventCountLimit === 0) { + api_1.diag.warn("No events allowed."); + this._droppedEventsCount++; + return this; + } + if (eventCountLimit !== undefined && this.events.length >= eventCountLimit) { + if (this._droppedEventsCount === 0) { + api_1.diag.debug("Dropping extra events."); + } + this.events.shift(); + this._droppedEventsCount++; + } + if ((0, core_1.isTimeInput)(attributesOrStartTime)) { + if (!(0, core_1.isTimeInput)(timeStamp)) { + timeStamp = attributesOrStartTime; + } + attributesOrStartTime = undefined; + } + const sanitized = (0, core_1.sanitizeAttributes)(attributesOrStartTime); + const { attributePerEventCountLimit } = this._spanLimits; + const attributes = {}; + let droppedAttributesCount = 0; + let eventAttributesCount = 0; + for (const attr in sanitized) { + if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) { + continue; + } + const attrVal = sanitized[attr]; + if (attributePerEventCountLimit !== undefined && eventAttributesCount >= attributePerEventCountLimit) { + droppedAttributesCount++; + continue; + } + attributes[attr] = this._truncateToSize(attrVal); + eventAttributesCount++; + } + this.events.push({ + name, + attributes, + time: this._getTime(timeStamp), + droppedAttributesCount + }); + return this; + } + addLink(link) { + if (this._isSpanEnded()) + return this; + const { linkCountLimit } = this._spanLimits; + if (linkCountLimit === 0) { + this._droppedLinksCount++; + return this; + } + if (linkCountLimit !== undefined && this.links.length >= linkCountLimit) { + if (this._droppedLinksCount === 0) { + api_1.diag.debug("Dropping extra links."); + } + this.links.shift(); + this._droppedLinksCount++; + } + const { attributePerLinkCountLimit } = this._spanLimits; + const sanitized = (0, core_1.sanitizeAttributes)(link.attributes); + const attributes = {}; + let droppedAttributesCount = 0; + let linkAttributesCount = 0; + for (const attr in sanitized) { + if (!Object.prototype.hasOwnProperty.call(sanitized, attr)) { + continue; + } + const attrVal = sanitized[attr]; + if (attributePerLinkCountLimit !== undefined && linkAttributesCount >= attributePerLinkCountLimit) { + droppedAttributesCount++; + continue; + } + attributes[attr] = this._truncateToSize(attrVal); + linkAttributesCount++; + } + const processedLink = { context: link.context }; + if (linkAttributesCount > 0) { + processedLink.attributes = attributes; + } + if (droppedAttributesCount > 0) { + processedLink.droppedAttributesCount = droppedAttributesCount; + } + this.links.push(processedLink); + return this; + } + addLinks(links) { + for (const link of links) { + this.addLink(link); + } + return this; + } + setStatus(status) { + if (this._isSpanEnded()) + return this; + if (status.code === api_1.SpanStatusCode.UNSET) + return this; + if (this.status.code === api_1.SpanStatusCode.OK) + return this; + const newStatus = { code: status.code }; + if (status.code === api_1.SpanStatusCode.ERROR) { + if (typeof status.message === "string") { + newStatus.message = status.message; + } else if (status.message != null) { + api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`); + } + } + this.status = newStatus; + return this; + } + updateName(name) { + if (this._isSpanEnded()) + return this; + this.name = name; + return this; + } + end(endTime) { + if (this._isSpanEnded()) { + api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`); + return; + } + this.endTime = this._getTime(endTime); + this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime); + if (this._duration[0] < 0) { + api_1.diag.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.", this.startTime, this.endTime); + this.endTime = this.startTime.slice(); + this._duration = [0, 0]; + } + if (this._droppedEventsCount > 0) { + api_1.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`); + } + if (this._droppedLinksCount > 0) { + api_1.diag.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`); + } + if (this._spanProcessor.onEnding) { + this._spanProcessor.onEnding(this); + } + this._recordEndMetrics?.(); + this._ended = true; + this._spanProcessor.onEnd(this); + } + _getTime(inp) { + if (typeof inp === "number" && inp <= core_1.otperformance.now()) { + return (0, core_1.hrTime)(inp + this._performanceOffset); + } + if (typeof inp === "number") { + return (0, core_1.millisToHrTime)(inp); + } + if (inp instanceof Date) { + return (0, core_1.millisToHrTime)(inp.getTime()); + } + if ((0, core_1.isTimeInputHrTime)(inp)) { + return inp; + } + if (this._startTimeProvided) { + return (0, core_1.millisToHrTime)(Date.now()); + } + const msDuration = core_1.otperformance.now() - this._performanceStartTime; + return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration)); + } + isRecording() { + return this._ended === false; + } + recordException(exception, time) { + const attributes = {}; + if (typeof exception === "string") { + attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception; + } else if (exception) { + if (exception.code) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.code.toString(); + } else if (exception.name) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.name; + } + if (exception.message) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception.message; + } + if (exception.stack) { + attributes[semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE] = exception.stack; + } + } + if (attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] || attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE]) { + this.addEvent(enums_1.ExceptionEventName, attributes, time); + } else { + api_1.diag.warn(`Failed to record an exception ${exception}`); + } + } + get duration() { + return this._duration; + } + get ended() { + return this._ended; + } + get droppedAttributesCount() { + return this._droppedAttributesCount; + } + get droppedEventsCount() { + return this._droppedEventsCount; + } + get droppedLinksCount() { + return this._droppedLinksCount; + } + _isSpanEnded() { + if (this._ended) { + const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`); + api_1.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error); + } + return this._ended; + } + _truncateToLimitUtil(value, limit) { + if (value.length <= limit) { + return value; + } + return value.substring(0, limit); + } + _truncateToSize(value) { + const limit = this._attributeValueLengthLimit; + if (limit <= 0) { + api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`); + return value; + } + if (typeof value === "string") { + return this._truncateToLimitUtil(value, limit); + } + if (Array.isArray(value)) { + return value.map((val) => typeof val === "string" ? this._truncateToLimitUtil(val, limit) : val); + } + return value; + } + [inspect_1.inspectCustom](depth, options, inspect) { + const payload = { + name: this.name, + kind: this.kind, + spanContext: this._spanContext, + parentSpanContext: this.parentSpanContext, + status: this.status, + startTime: this.startTime, + endTime: this.endTime, + duration: this._duration, + ended: this._ended, + attributes: this.attributes, + events: this.events, + links: this.links, + droppedAttributesCount: this._droppedAttributesCount, + droppedEventsCount: this._droppedEventsCount, + droppedLinksCount: this._droppedLinksCount, + instrumentationScope: this.instrumentationScope, + resource: { attributes: (0, inspect_1.settledResourceAttributes)(this.resource) } + }; + return (0, inspect_1.formatInspect)("SpanImpl", payload, depth, options, inspect); + } + } + exports.SpanImpl = SpanImpl; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js +var require_Sampler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SamplingDecision = undefined; + var SamplingDecision; + (function(SamplingDecision2) { + SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD"; + SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD"; + SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; + })(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js +var require_AlwaysOffSampler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AlwaysOffSampler = undefined; + var Sampler_1 = require_Sampler(); + + class AlwaysOffSampler { + shouldSample() { + return { + decision: Sampler_1.SamplingDecision.NOT_RECORD + }; + } + toString() { + return "AlwaysOffSampler"; + } + } + exports.AlwaysOffSampler = AlwaysOffSampler; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js +var require_AlwaysOnSampler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AlwaysOnSampler = undefined; + var Sampler_1 = require_Sampler(); + + class AlwaysOnSampler { + shouldSample() { + return { + decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED + }; + } + toString() { + return "AlwaysOnSampler"; + } + } + exports.AlwaysOnSampler = AlwaysOnSampler; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js +var require_ParentBasedSampler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ParentBasedSampler = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var AlwaysOffSampler_1 = require_AlwaysOffSampler(); + var AlwaysOnSampler_1 = require_AlwaysOnSampler(); + + class ParentBasedSampler { + _root; + _remoteParentSampled; + _remoteParentNotSampled; + _localParentSampled; + _localParentNotSampled; + constructor(config) { + this._root = config.root; + if (!this._root) { + (0, core_1.globalErrorHandler)(new Error("ParentBasedSampler must have a root sampler configured")); + this._root = new AlwaysOnSampler_1.AlwaysOnSampler; + } + this._remoteParentSampled = config.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler; + this._remoteParentNotSampled = config.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler; + this._localParentSampled = config.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler; + this._localParentNotSampled = config.localParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler; + } + shouldSample(context, traceId, spanName, spanKind, attributes, links) { + const parentContext = api_1.trace.getSpanContext(context); + if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) { + return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.isRemote) { + if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) { + return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) { + return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); + } + toString() { + return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`; + } + } + exports.ParentBasedSampler = ParentBasedSampler; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js +var require_TraceIdRatioBasedSampler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceIdRatioBasedSampler = undefined; + var api_1 = require_src(); + var Sampler_1 = require_Sampler(); + + class TraceIdRatioBasedSampler { + _ratio; + _upperBound; + constructor(ratio = 0) { + this._ratio = this._normalize(ratio); + this._upperBound = Math.floor(this._ratio * 4294967295); + } + shouldSample(context, traceId) { + return { + decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound ? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED : Sampler_1.SamplingDecision.NOT_RECORD + }; + } + toString() { + return `TraceIdRatioBased{${this._ratio}}`; + } + _normalize(ratio) { + if (typeof ratio !== "number" || isNaN(ratio)) + return 0; + return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio; + } + _accumulate(traceId) { + let accumulation = 0; + for (let i = 0;i < 32; i += 8) { + let part = 0; + for (let j = 0;j < 8; j++) { + const c = traceId.charCodeAt(i + j); + const v = c < 58 ? c - 48 : c < 71 ? c - 55 : c - 87; + part = part << 4 | v; + } + accumulation = (accumulation ^ part) >>> 0; + } + return accumulation; + } + } + exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/config.js +var require_config = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildSamplerFromEnv = exports.loadDefaultConfig = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var AlwaysOffSampler_1 = require_AlwaysOffSampler(); + var AlwaysOnSampler_1 = require_AlwaysOnSampler(); + var ParentBasedSampler_1 = require_ParentBasedSampler(); + var TraceIdRatioBasedSampler_1 = require_TraceIdRatioBasedSampler(); + var TracesSamplerValues; + (function(TracesSamplerValues2) { + TracesSamplerValues2["AlwaysOff"] = "always_off"; + TracesSamplerValues2["AlwaysOn"] = "always_on"; + TracesSamplerValues2["ParentBasedAlwaysOff"] = "parentbased_always_off"; + TracesSamplerValues2["ParentBasedAlwaysOn"] = "parentbased_always_on"; + TracesSamplerValues2["ParentBasedTraceIdRatio"] = "parentbased_traceidratio"; + TracesSamplerValues2["TraceIdRatio"] = "traceidratio"; + })(TracesSamplerValues || (TracesSamplerValues = {})); + var DEFAULT_RATIO = 1; + function loadDefaultConfig() { + return { + sampler: buildSamplerFromEnv(), + forceFlushTimeoutMillis: 30000, + generalLimits: { + attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity, + attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? 128 + }, + spanLimits: { + attributeValueLengthLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? Infinity, + attributeCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? 128, + linkCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_LINK_COUNT_LIMIT") ?? 128, + eventCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_EVENT_COUNT_LIMIT") ?? 128, + attributePerEventCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT") ?? 128, + attributePerLinkCountLimit: (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT") ?? 128 + } + }; + } + exports.loadDefaultConfig = loadDefaultConfig; + function buildSamplerFromEnv() { + const sampler = (0, core_1.getStringFromEnv)("OTEL_TRACES_SAMPLER") ?? TracesSamplerValues.ParentBasedAlwaysOn; + switch (sampler) { + case TracesSamplerValues.AlwaysOn: + return new AlwaysOnSampler_1.AlwaysOnSampler; + case TracesSamplerValues.AlwaysOff: + return new AlwaysOffSampler_1.AlwaysOffSampler; + case TracesSamplerValues.ParentBasedAlwaysOn: + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new AlwaysOnSampler_1.AlwaysOnSampler + }); + case TracesSamplerValues.ParentBasedAlwaysOff: + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new AlwaysOffSampler_1.AlwaysOffSampler + }); + case TracesSamplerValues.TraceIdRatio: + return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()); + case TracesSamplerValues.ParentBasedTraceIdRatio: + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()) + }); + default: + api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`); + return new ParentBasedSampler_1.ParentBasedSampler({ + root: new AlwaysOnSampler_1.AlwaysOnSampler + }); + } + } + exports.buildSamplerFromEnv = buildSamplerFromEnv; + function getSamplerProbabilityFromEnv() { + const probability = (0, core_1.getNumberFromEnv)("OTEL_TRACES_SAMPLER_ARG"); + if (probability == null) { + api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + if (probability < 0 || probability > 1) { + api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`); + return DEFAULT_RATIO; + } + return probability; + } +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js +var require_utility = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reconfigureLimits = exports.mergeConfig = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = undefined; + var config_1 = require_config(); + var core_1 = require_src3(); + exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128; + exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity; + function mergeConfig(userConfig) { + const perInstanceDefaults = { + sampler: (0, config_1.buildSamplerFromEnv)() + }; + const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)(); + const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig); + target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {}); + target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {}); + return target; + } + exports.mergeConfig = mergeConfig; + function reconfigureLimits(userConfig) { + const spanLimits = Object.assign({}, userConfig.spanLimits); + spanLimits.attributeCountLimit = userConfig.spanLimits?.attributeCountLimit ?? userConfig.generalLimits?.attributeCountLimit ?? (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT") ?? exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT; + spanLimits.attributeValueLengthLimit = userConfig.spanLimits?.attributeValueLengthLimit ?? userConfig.generalLimits?.attributeValueLengthLimit ?? (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT; + return Object.assign({}, userConfig, { spanLimits }); + } + exports.reconfigureLimits = reconfigureLimits; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js +var require_BatchSpanProcessorBase = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchSpanProcessorBase = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + + class BatchSpanProcessorBase { + _maxExportBatchSize; + _maxQueueSize; + _scheduledDelayMillis; + _exportTimeoutMillis; + _exporter; + _isExporting = false; + _finishedSpans = []; + _timer; + _shutdownOnce; + _droppedSpansCount = 0; + constructor(exporter, config) { + this._exporter = exporter; + this._maxExportBatchSize = typeof config?.maxExportBatchSize === "number" ? config.maxExportBatchSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512; + this._maxQueueSize = typeof config?.maxQueueSize === "number" ? config.maxQueueSize : (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048; + this._scheduledDelayMillis = typeof config?.scheduledDelayMillis === "number" ? config.scheduledDelayMillis : (0, core_1.getNumberFromEnv)("OTEL_BSP_SCHEDULE_DELAY") ?? 5000; + this._exportTimeoutMillis = typeof config?.exportTimeoutMillis === "number" ? config.exportTimeoutMillis : (0, core_1.getNumberFromEnv)("OTEL_BSP_EXPORT_TIMEOUT") ?? 30000; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + if (this._maxExportBatchSize > this._maxQueueSize) { + api_1.diag.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"); + this._maxExportBatchSize = this._maxQueueSize; + } + } + forceFlush() { + if (this._shutdownOnce.isCalled) { + return this._shutdownOnce.promise; + } + return this._flushAll(); + } + onStart(_span, _parentContext) {} + onEnd(span) { + if (this._shutdownOnce.isCalled) { + return; + } + if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) { + return; + } + this._addToBuffer(span); + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + return Promise.resolve().then(() => { + return this.onShutdown(); + }).then(() => { + return this._flushAll(); + }).then(() => { + return this._exporter.shutdown(); + }); + } + _addToBuffer(span) { + if (this._finishedSpans.length >= this._maxQueueSize) { + if (this._droppedSpansCount === 0) { + api_1.diag.debug("maxQueueSize reached, dropping spans"); + } + this._droppedSpansCount++; + return; + } + if (this._droppedSpansCount > 0) { + api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`); + this._droppedSpansCount = 0; + } + this._finishedSpans.push(span); + this._maybeStartTimer(); + } + _flushAll() { + return new Promise((resolve, reject) => { + const promises = []; + const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize); + for (let i = 0, j = count;i < j; i++) { + promises.push(this._flushOneBatch()); + } + Promise.all(promises).then(() => { + resolve(); + }).catch(reject); + }); + } + _flushOneBatch() { + this._clearTimer(); + if (this._finishedSpans.length === 0) { + return Promise.resolve(); + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error("Timeout")); + }, this._exportTimeoutMillis); + api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => { + let spans; + if (this._finishedSpans.length <= this._maxExportBatchSize) { + spans = this._finishedSpans; + this._finishedSpans = []; + } else { + spans = this._finishedSpans.splice(0, this._maxExportBatchSize); + } + const doExport = () => this._exporter.export(spans, (result) => { + clearTimeout(timer); + if (result.code === core_1.ExportResultCode.SUCCESS) { + resolve(); + } else { + reject(result.error ?? new Error("BatchSpanProcessor: span export failed")); + } + }); + let pendingResources = null; + for (let i = 0, len = spans.length;i < len; i++) { + const span = spans[i]; + if (span.resource.asyncAttributesPending && span.resource.waitForAsyncAttributes) { + pendingResources ??= []; + pendingResources.push(span.resource.waitForAsyncAttributes()); + } + } + if (pendingResources === null) { + doExport(); + } else { + Promise.all(pendingResources).then(doExport, (err) => { + (0, core_1.globalErrorHandler)(err); + reject(err); + }); + } + }); + }); + } + _maybeStartTimer() { + if (this._isExporting) + return; + const flush = () => { + this._isExporting = true; + this._flushOneBatch().finally(() => { + this._isExporting = false; + if (this._finishedSpans.length > 0) { + this._clearTimer(); + this._maybeStartTimer(); + } + }).catch((e) => { + this._isExporting = false; + (0, core_1.globalErrorHandler)(e); + }); + }; + if (this._finishedSpans.length >= this._maxExportBatchSize) { + return flush(); + } + if (this._timer !== undefined) + return; + this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); + if (typeof this._timer !== "number") { + this._timer.unref(); + } + } + _clearTimer() { + if (this._timer !== undefined) { + clearTimeout(this._timer); + this._timer = undefined; + } + } + } + exports.BatchSpanProcessorBase = BatchSpanProcessorBase; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js +var require_BatchSpanProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchSpanProcessor = undefined; + var BatchSpanProcessorBase_1 = require_BatchSpanProcessorBase(); + + class BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase { + onShutdown() {} + } + exports.BatchSpanProcessor = BatchSpanProcessor; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js +var require_RandomIdGenerator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RandomIdGenerator = undefined; + var SPAN_ID_BYTES = 8; + var TRACE_ID_BYTES = 16; + + class RandomIdGenerator { + generateTraceId = getIdGenerator(TRACE_ID_BYTES); + generateSpanId = getIdGenerator(SPAN_ID_BYTES); + } + exports.RandomIdGenerator = RandomIdGenerator; + var SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES); + function getIdGenerator(bytes) { + return function generateId() { + for (let i = 0;i < bytes / 4; i++) { + SHARED_BUFFER.writeUInt32BE(Math.random() * 2 ** 32 >>> 0, i * 4); + } + for (let i = 0;i < bytes; i++) { + if (SHARED_BUFFER[i] > 0) { + break; + } else if (i === bytes - 1) { + SHARED_BUFFER[bytes - 1] = 1; + } + } + return SHARED_BUFFER.toString("hex", 0, bytes); + }; + } +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js +var require_node5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RandomIdGenerator = exports.BatchSpanProcessor = undefined; + var BatchSpanProcessor_1 = require_BatchSpanProcessor(); + Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function() { + return BatchSpanProcessor_1.BatchSpanProcessor; + } }); + var RandomIdGenerator_1 = require_RandomIdGenerator(); + Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function() { + return RandomIdGenerator_1.RandomIdGenerator; + } }); +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js +var require_platform5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RandomIdGenerator = exports.BatchSpanProcessor = undefined; + var node_1 = require_node5(); + Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function() { + return node_1.BatchSpanProcessor; + } }); + Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function() { + return node_1.RandomIdGenerator; + } }); +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/semconv.js +var require_semconv5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.METRIC_OTEL_SDK_SPAN_STARTED = exports.METRIC_OTEL_SDK_SPAN_LIVE = exports.ATTR_OTEL_SPAN_SAMPLING_RESULT = exports.ATTR_OTEL_SPAN_PARENT_ORIGIN = undefined; + exports.ATTR_OTEL_SPAN_PARENT_ORIGIN = "otel.span.parent.origin"; + exports.ATTR_OTEL_SPAN_SAMPLING_RESULT = "otel.span.sampling_result"; + exports.METRIC_OTEL_SDK_SPAN_LIVE = "otel.sdk.span.live"; + exports.METRIC_OTEL_SDK_SPAN_STARTED = "otel.sdk.span.started"; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/TracerMetrics.js +var require_TracerMetrics = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TracerMetrics = undefined; + var Sampler_1 = require_Sampler(); + var semconv_1 = require_semconv5(); + + class TracerMetrics { + startedSpans; + liveSpans; + constructor(meter) { + this.startedSpans = meter.createCounter(semconv_1.METRIC_OTEL_SDK_SPAN_STARTED, { + unit: "{span}", + description: "The number of created spans." + }); + this.liveSpans = meter.createUpDownCounter(semconv_1.METRIC_OTEL_SDK_SPAN_LIVE, { + unit: "{span}", + description: "The number of currently live spans." + }); + } + startSpan(parentSpanCtx, samplingDecision) { + const samplingDecisionStr = samplingDecisionToString(samplingDecision); + this.startedSpans.add(1, { + [semconv_1.ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx), + [semconv_1.ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr + }); + if (samplingDecision === Sampler_1.SamplingDecision.NOT_RECORD) { + return () => {}; + } + const liveSpanAttributes = { + [semconv_1.ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr + }; + this.liveSpans.add(1, liveSpanAttributes); + return () => { + this.liveSpans.add(-1, liveSpanAttributes); + }; + } + } + exports.TracerMetrics = TracerMetrics; + function parentOrigin(parentSpanContext) { + if (!parentSpanContext) { + return "none"; + } + if (parentSpanContext.isRemote) { + return "remote"; + } + return "local"; + } + function samplingDecisionToString(decision) { + switch (decision) { + case Sampler_1.SamplingDecision.RECORD_AND_SAMPLED: + return "RECORD_AND_SAMPLE"; + case Sampler_1.SamplingDecision.RECORD: + return "RECORD_ONLY"; + case Sampler_1.SamplingDecision.NOT_RECORD: + return "DROP"; + } + } +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/version.js +var require_version7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = undefined; + exports.VERSION = "2.8.0"; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js +var require_Tracer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Tracer = undefined; + var api = require_src(); + var core_1 = require_src3(); + var Span_1 = require_Span(); + var utility_1 = require_utility(); + var platform_1 = require_platform5(); + var TracerMetrics_1 = require_TracerMetrics(); + var version_1 = require_version7(); + var inspect_1 = require_inspect2(); + + class Tracer { + _sampler; + _generalLimits; + _spanLimits; + _idGenerator; + instrumentationScope; + _resource; + _spanProcessor; + _tracerMetrics; + constructor(instrumentationScope, config, resource, spanProcessor) { + const localConfig = (0, utility_1.mergeConfig)(config); + this._sampler = localConfig.sampler; + this._generalLimits = localConfig.generalLimits; + this._spanLimits = localConfig.spanLimits; + this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator; + this._resource = resource; + this._spanProcessor = spanProcessor; + this.instrumentationScope = instrumentationScope; + const meter = localConfig.meterProvider ? localConfig.meterProvider.getMeter("@opentelemetry/sdk-trace", version_1.VERSION) : api.createNoopMeter(); + this._tracerMetrics = new TracerMetrics_1.TracerMetrics(meter); + } + startSpan(name, options = {}, context = api.context.active()) { + if (options.root) { + context = api.trace.deleteSpan(context); + } + const parentSpan = api.trace.getSpan(context); + if ((0, core_1.isTracingSuppressed)(context)) { + api.diag.debug("Instrumentation suppressed, returning Noop Span"); + const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); + return nonRecordingSpan; + } + const parentSpanContext = parentSpan?.spanContext(); + const spanId = this._idGenerator.generateSpanId(); + let validParentSpanContext; + let traceId; + let traceState; + if (!parentSpanContext || !api.trace.isSpanContextValid(parentSpanContext)) { + traceId = this._idGenerator.generateTraceId(); + } else { + traceId = parentSpanContext.traceId; + traceState = parentSpanContext.traceState; + validParentSpanContext = parentSpanContext; + } + const spanKind = options.kind ?? api.SpanKind.INTERNAL; + const links = (options.links ?? []).map((link) => { + return { + context: link.context, + attributes: (0, core_1.sanitizeAttributes)(link.attributes) + }; + }); + const attributes = (0, core_1.sanitizeAttributes)(options.attributes); + const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links); + const recordEndMetrics = this._tracerMetrics.startSpan(parentSpanContext, samplingResult.decision); + traceState = samplingResult.traceState ?? traceState; + const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE; + const spanContext = { traceId, spanId, traceFlags, traceState }; + if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) { + api.diag.debug("Recording is off, propagating context in a non-recording span"); + const nonRecordingSpan = api.trace.wrapSpanContext(spanContext); + return nonRecordingSpan; + } + const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes)); + const span = new Span_1.SpanImpl({ + resource: this._resource, + scope: this.instrumentationScope, + context, + spanContext, + name, + kind: spanKind, + links, + parentSpanContext: validParentSpanContext, + attributes: initAttributes, + startTime: options.startTime, + spanProcessor: this._spanProcessor, + spanLimits: this._spanLimits, + recordEndMetrics + }); + return span; + } + startActiveSpan(name, arg2, arg3, arg4) { + let opts; + let ctx; + let fn; + if (arguments.length < 2) { + return; + } else if (arguments.length === 2) { + fn = arg2; + } else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + const parentContext = ctx ?? api.context.active(); + const span = this.startSpan(name, opts, parentContext); + const contextWithSpanSet = api.trace.setSpan(parentContext, span); + return api.context.with(contextWithSpanSet, fn, undefined, span); + } + getGeneralLimits() { + return this._generalLimits; + } + getSpanLimits() { + return this._spanLimits; + } + [inspect_1.inspectCustom](depth, options, inspect) { + const payload = { + instrumentationScope: this.instrumentationScope, + resource: { attributes: (0, inspect_1.settledResourceAttributes)(this._resource) }, + spanLimits: this._spanLimits, + generalLimits: this._generalLimits + }; + return (0, inspect_1.formatInspect)("Tracer", payload, depth, options, inspect); + } + } + exports.Tracer = Tracer; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js +var require_MultiSpanProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MultiSpanProcessor = undefined; + var core_1 = require_src3(); + + class MultiSpanProcessor { + _spanProcessors; + constructor(spanProcessors) { + this._spanProcessors = spanProcessors; + } + forceFlush() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.forceFlush()); + } + return new Promise((resolve) => { + Promise.all(promises).then(() => { + resolve(); + }).catch((error) => { + (0, core_1.globalErrorHandler)(error || new Error("MultiSpanProcessor: forceFlush failed")); + resolve(); + }); + }); + } + onStart(span, context) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onStart(span, context); + } + } + onEnding(span) { + for (const spanProcessor of this._spanProcessors) { + if (spanProcessor.onEnding) { + spanProcessor.onEnding(span); + } + } + } + onEnd(span) { + for (const spanProcessor of this._spanProcessors) { + spanProcessor.onEnd(span); + } + } + shutdown() { + const promises = []; + for (const spanProcessor of this._spanProcessors) { + promises.push(spanProcessor.shutdown()); + } + return new Promise((resolve, reject) => { + Promise.all(promises).then(() => { + resolve(); + }, reject); + }); + } + } + exports.MultiSpanProcessor = MultiSpanProcessor; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js +var require_BasicTracerProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BasicTracerProvider = exports.ForceFlushState = undefined; + var core_1 = require_src3(); + var resources_1 = require_src6(); + var Tracer_1 = require_Tracer(); + var config_1 = require_config(); + var MultiSpanProcessor_1 = require_MultiSpanProcessor(); + var utility_1 = require_utility(); + var inspect_1 = require_inspect2(); + var ForceFlushState; + (function(ForceFlushState2) { + ForceFlushState2[ForceFlushState2["resolved"] = 0] = "resolved"; + ForceFlushState2[ForceFlushState2["timeout"] = 1] = "timeout"; + ForceFlushState2[ForceFlushState2["error"] = 2] = "error"; + ForceFlushState2[ForceFlushState2["unresolved"] = 3] = "unresolved"; + })(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {})); + + class BasicTracerProvider { + _config; + _tracers = new Map; + _resource; + _activeSpanProcessor; + constructor(config = {}) { + const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config)); + this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)(); + this._config = Object.assign({}, mergedConfig, { + resource: this._resource + }); + const spanProcessors = []; + if (config.spanProcessors?.length) { + spanProcessors.push(...config.spanProcessors); + } + this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors); + } + getTracer(name, version, options) { + const key = `${name}@${version || ""}:${options?.schemaUrl || ""}`; + if (!this._tracers.has(key)) { + this._tracers.set(key, new Tracer_1.Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor)); + } + return this._tracers.get(key); + } + forceFlush() { + const timeout = this._config.forceFlushTimeoutMillis; + const promises = this._activeSpanProcessor["_spanProcessors"].map((spanProcessor) => { + return new Promise((resolve) => { + let state; + const timeoutInterval = setTimeout(() => { + resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`)); + state = ForceFlushState.timeout; + }, timeout); + spanProcessor.forceFlush().then(() => { + clearTimeout(timeoutInterval); + if (state !== ForceFlushState.timeout) { + state = ForceFlushState.resolved; + resolve(state); + } + }).catch((error) => { + clearTimeout(timeoutInterval); + state = ForceFlushState.error; + resolve(error); + }); + }); + }); + return new Promise((resolve, reject) => { + Promise.all(promises).then((results) => { + const errors = results.filter((result) => result !== ForceFlushState.resolved); + if (errors.length > 0) { + reject(errors); + } else { + resolve(); + } + }).catch((error) => reject([error])); + }); + } + shutdown() { + return this._activeSpanProcessor.shutdown(); + } + [inspect_1.inspectCustom](depth, options, inspect) { + const processors = this._activeSpanProcessor["_spanProcessors"]; + const payload = { + resource: { attributes: (0, inspect_1.settledResourceAttributes)(this._resource) }, + tracers: Array.from(this._tracers.keys()), + spanProcessors: processors.map((p) => p.constructor?.name ?? "SpanProcessor") + }; + return (0, inspect_1.formatInspect)("BasicTracerProvider", payload, depth, options, inspect); + } + } + exports.BasicTracerProvider = BasicTracerProvider; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js +var require_ConsoleSpanExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConsoleSpanExporter = undefined; + var core_1 = require_src3(); + + class ConsoleSpanExporter { + export(spans, resultCallback) { + return this._sendSpans(spans, resultCallback); + } + shutdown() { + this._sendSpans([]); + return this.forceFlush(); + } + forceFlush() { + return Promise.resolve(); + } + _exportInfo(span) { + return { + resource: { + attributes: span.resource.attributes + }, + instrumentationScope: span.instrumentationScope, + traceId: span.spanContext().traceId, + parentSpanContext: span.parentSpanContext, + traceState: span.spanContext().traceState?.serialize(), + name: span.name, + id: span.spanContext().spanId, + kind: span.kind, + timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime), + duration: (0, core_1.hrTimeToMicroseconds)(span.duration), + attributes: span.attributes, + status: span.status, + events: span.events, + links: span.links + }; + } + _sendSpans(spans, done) { + for (const span of spans) { + console.dir(this._exportInfo(span), { depth: 3 }); + } + if (done) { + return done({ code: core_1.ExportResultCode.SUCCESS }); + } + } + } + exports.ConsoleSpanExporter = ConsoleSpanExporter; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js +var require_InMemorySpanExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InMemorySpanExporter = undefined; + var core_1 = require_src3(); + + class InMemorySpanExporter { + _finishedSpans = []; + _stopped = false; + export(spans, resultCallback) { + if (this._stopped) + return resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error("Exporter has been stopped") + }); + this._finishedSpans.push(...spans); + setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); + } + shutdown() { + this._stopped = true; + this._finishedSpans = []; + return this.forceFlush(); + } + forceFlush() { + return Promise.resolve(); + } + reset() { + this._finishedSpans = []; + } + getFinishedSpans() { + return this._finishedSpans; + } + } + exports.InMemorySpanExporter = InMemorySpanExporter; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js +var require_SimpleSpanProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SimpleSpanProcessor = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + + class SimpleSpanProcessor { + _exporter; + _shutdownOnce; + _pendingExports; + constructor(exporter) { + this._exporter = exporter; + this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); + this._pendingExports = new Set; + } + async forceFlush() { + await Promise.all(Array.from(this._pendingExports)); + if (this._exporter.forceFlush) { + await this._exporter.forceFlush(); + } + } + onStart(_span, _parentContext) {} + onEnd(span) { + if (this._shutdownOnce.isCalled) { + return; + } + if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) { + return; + } + const pendingExport = this._doExport(span).catch((err) => (0, core_1.globalErrorHandler)(err)); + this._pendingExports.add(pendingExport); + pendingExport.finally(() => this._pendingExports.delete(pendingExport)); + } + async _doExport(span) { + if (span.resource.asyncAttributesPending) { + await span.resource.waitForAsyncAttributes?.(); + } + const result = await core_1.internal._export(this._exporter, [span]); + if (result.code !== core_1.ExportResultCode.SUCCESS) { + throw result.error ?? new Error(`SimpleSpanProcessor: span export failed (status ${result})`); + } + } + shutdown() { + return this._shutdownOnce.call(); + } + _shutdown() { + return this._exporter.shutdown(); + } + } + exports.SimpleSpanProcessor = SimpleSpanProcessor; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js +var require_NoopSpanProcessor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NoopSpanProcessor = undefined; + + class NoopSpanProcessor { + onStart(_span, _context) {} + onEnd(_span) {} + shutdown() { + return Promise.resolve(); + } + forceFlush() { + return Promise.resolve(); + } + } + exports.NoopSpanProcessor = NoopSpanProcessor; +}); + +// node_modules/@opentelemetry/sdk-trace-base/build/src/index.js +var require_src12 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.SimpleSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.RandomIdGenerator = exports.BatchSpanProcessor = exports.BasicTracerProvider = undefined; + var BasicTracerProvider_1 = require_BasicTracerProvider(); + Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: function() { + return BasicTracerProvider_1.BasicTracerProvider; + } }); + var platform_1 = require_platform5(); + Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function() { + return platform_1.BatchSpanProcessor; + } }); + Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function() { + return platform_1.RandomIdGenerator; + } }); + var ConsoleSpanExporter_1 = require_ConsoleSpanExporter(); + Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: function() { + return ConsoleSpanExporter_1.ConsoleSpanExporter; + } }); + var InMemorySpanExporter_1 = require_InMemorySpanExporter(); + Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: function() { + return InMemorySpanExporter_1.InMemorySpanExporter; + } }); + var SimpleSpanProcessor_1 = require_SimpleSpanProcessor(); + Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: function() { + return SimpleSpanProcessor_1.SimpleSpanProcessor; + } }); + var NoopSpanProcessor_1 = require_NoopSpanProcessor(); + Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: function() { + return NoopSpanProcessor_1.NoopSpanProcessor; + } }); + var AlwaysOffSampler_1 = require_AlwaysOffSampler(); + Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: function() { + return AlwaysOffSampler_1.AlwaysOffSampler; + } }); + var AlwaysOnSampler_1 = require_AlwaysOnSampler(); + Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: function() { + return AlwaysOnSampler_1.AlwaysOnSampler; + } }); + var ParentBasedSampler_1 = require_ParentBasedSampler(); + Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: function() { + return ParentBasedSampler_1.ParentBasedSampler; + } }); + var TraceIdRatioBasedSampler_1 = require_TraceIdRatioBasedSampler(); + Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: function() { + return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler; + } }); + var Sampler_1 = require_Sampler(); + Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function() { + return Sampler_1.SamplingDecision; + } }); +}); + +// node_modules/@opentelemetry/sdk-trace-node/build/src/NodeTracerProvider.js +var require_NodeTracerProvider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NodeTracerProvider = undefined; + var context_async_hooks_1 = require_src11(); + var sdk_trace_base_1 = require_src12(); + var api_1 = require_src(); + var core_1 = require_src3(); + function setupContextManager(contextManager) { + if (contextManager === null) { + return; + } + if (contextManager === undefined) { + const defaultContextManager = new context_async_hooks_1.AsyncLocalStorageContextManager; + defaultContextManager.enable(); + api_1.context.setGlobalContextManager(defaultContextManager); + return; + } + contextManager.enable(); + api_1.context.setGlobalContextManager(contextManager); + } + function setupPropagator(propagator) { + if (propagator === null) { + return; + } + if (propagator === undefined) { + api_1.propagation.setGlobalPropagator(new core_1.CompositePropagator({ + propagators: [ + new core_1.W3CTraceContextPropagator, + new core_1.W3CBaggagePropagator + ] + })); + return; + } + api_1.propagation.setGlobalPropagator(propagator); + } + + class NodeTracerProvider extends sdk_trace_base_1.BasicTracerProvider { + constructor(config = {}) { + super(config); + } + register(config = {}) { + api_1.trace.setGlobalTracerProvider(this); + setupContextManager(config.contextManager); + setupPropagator(config.propagator); + } + } + exports.NodeTracerProvider = NodeTracerProvider; +}); + +// node_modules/@opentelemetry/sdk-trace-node/build/src/index.js +var require_src13 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TraceIdRatioBasedSampler = exports.SimpleSpanProcessor = exports.SamplingDecision = exports.RandomIdGenerator = exports.ParentBasedSampler = exports.NoopSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.BatchSpanProcessor = exports.BasicTracerProvider = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NodeTracerProvider = undefined; + var NodeTracerProvider_1 = require_NodeTracerProvider(); + Object.defineProperty(exports, "NodeTracerProvider", { enumerable: true, get: function() { + return NodeTracerProvider_1.NodeTracerProvider; + } }); + var sdk_trace_base_1 = require_src12(); + Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: function() { + return sdk_trace_base_1.AlwaysOffSampler; + } }); + Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: function() { + return sdk_trace_base_1.AlwaysOnSampler; + } }); + Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: function() { + return sdk_trace_base_1.BasicTracerProvider; + } }); + Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function() { + return sdk_trace_base_1.BatchSpanProcessor; + } }); + Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: function() { + return sdk_trace_base_1.ConsoleSpanExporter; + } }); + Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: function() { + return sdk_trace_base_1.InMemorySpanExporter; + } }); + Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: function() { + return sdk_trace_base_1.NoopSpanProcessor; + } }); + Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: function() { + return sdk_trace_base_1.ParentBasedSampler; + } }); + Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function() { + return sdk_trace_base_1.RandomIdGenerator; + } }); + Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function() { + return sdk_trace_base_1.SamplingDecision; + } }); + Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: function() { + return sdk_trace_base_1.SimpleSpanProcessor; + } }); + Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: function() { + return sdk_trace_base_1.TraceIdRatioBasedSampler; + } }); +}); + +// node_modules/@opentelemetry/instrumentation/build/src/autoLoaderUtils.js +var require_autoLoaderUtils = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.disableInstrumentations = exports.enableInstrumentations = undefined; + function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) { + for (let i = 0, j = instrumentations.length;i < j; i++) { + const instrumentation = instrumentations[i]; + if (tracerProvider) { + instrumentation.setTracerProvider(tracerProvider); + } + if (meterProvider) { + instrumentation.setMeterProvider(meterProvider); + } + if (loggerProvider && instrumentation.setLoggerProvider) { + instrumentation.setLoggerProvider(loggerProvider); + } + if (!instrumentation.getConfig().enabled) { + instrumentation.enable(); + } + } + } + exports.enableInstrumentations = enableInstrumentations; + function disableInstrumentations(instrumentations) { + instrumentations.forEach((instrumentation) => instrumentation.disable()); + } + exports.disableInstrumentations = disableInstrumentations; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/autoLoader.js +var require_autoLoader = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.registerInstrumentations = undefined; + var api_1 = require_src(); + var api_logs_1 = require_src5(); + var autoLoaderUtils_1 = require_autoLoaderUtils(); + function registerInstrumentations(options) { + const tracerProvider = options.tracerProvider || api_1.trace.getTracerProvider(); + const meterProvider = options.meterProvider || api_1.metrics.getMeterProvider(); + const loggerProvider = options.loggerProvider || api_logs_1.logs.getLoggerProvider(); + const instrumentations = options.instrumentations?.flat() ?? []; + (0, autoLoaderUtils_1.enableInstrumentations)(instrumentations, tracerProvider, meterProvider, loggerProvider); + return () => { + (0, autoLoaderUtils_1.disableInstrumentations)(instrumentations); + }; + } + exports.registerInstrumentations = registerInstrumentations; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/semver.js +var require_semver2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.satisfies = undefined; + var api_1 = require_src(); + var VERSION_REGEXP = /^(?:v)?(?(?0|[1-9]\d*)\.(?0|[1-9]\d*)\.(?0|[1-9]\d*))(?:-(?(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; + var RANGE_REGEXP = /^(?<|>|=|==|<=|>=|~|\^|~>)?\s*(?:v)?(?(?x|X|\*|0|[1-9]\d*)(?:\.(?x|X|\*|0|[1-9]\d*))?(?:\.(?x|X|\*|0|[1-9]\d*))?)(?:-(?(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; + var operatorResMap = { + ">": [1], + ">=": [0, 1], + "=": [0], + "<=": [-1, 0], + "<": [-1], + "!=": [-1, 1] + }; + function satisfies(version, range, options) { + if (!_validateVersion(version)) { + api_1.diag.error(`Invalid version: ${version}`); + return false; + } + if (!range) { + return true; + } + range = range.replace(/([<>=~^]+)\s+/g, "$1"); + const parsedVersion = _parseVersion(version); + if (!parsedVersion) { + return false; + } + const allParsedRanges = []; + const checkResult = _doSatisfies(parsedVersion, range, allParsedRanges, options); + if (checkResult && !options?.includePrerelease) { + return _doPreleaseCheck(parsedVersion, allParsedRanges); + } + return checkResult; + } + exports.satisfies = satisfies; + function _validateVersion(version) { + return typeof version === "string" && VERSION_REGEXP.test(version); + } + function _doSatisfies(parsedVersion, range, allParsedRanges, options) { + if (range.includes("||")) { + const ranges = range.trim().split("||"); + for (const r of ranges) { + if (_checkRange(parsedVersion, r, allParsedRanges, options)) { + return true; + } + } + return false; + } else if (range.includes(" - ")) { + range = replaceHyphen(range, options); + } else if (range.includes(" ")) { + const ranges = range.trim().replace(/\s{2,}/g, " ").split(" "); + for (const r of ranges) { + if (!_checkRange(parsedVersion, r, allParsedRanges, options)) { + return false; + } + } + return true; + } + return _checkRange(parsedVersion, range, allParsedRanges, options); + } + function _checkRange(parsedVersion, range, allParsedRanges, options) { + range = _normalizeRange(range, options); + if (range.includes(" ")) { + return _doSatisfies(parsedVersion, range, allParsedRanges, options); + } else { + const parsedRange = _parseRange(range); + allParsedRanges.push(parsedRange); + return _satisfies(parsedVersion, parsedRange); + } + } + function _satisfies(parsedVersion, parsedRange) { + if (parsedRange.invalid) { + return false; + } + if (!parsedRange.version || _isWildcard(parsedRange.version)) { + return true; + } + let comparisonResult = _compareVersionSegments(parsedVersion.versionSegments || [], parsedRange.versionSegments || []); + if (comparisonResult === 0) { + const versionPrereleaseSegments = parsedVersion.prereleaseSegments || []; + const rangePrereleaseSegments = parsedRange.prereleaseSegments || []; + if (!versionPrereleaseSegments.length && !rangePrereleaseSegments.length) { + comparisonResult = 0; + } else if (!versionPrereleaseSegments.length && rangePrereleaseSegments.length) { + comparisonResult = 1; + } else if (versionPrereleaseSegments.length && !rangePrereleaseSegments.length) { + comparisonResult = -1; + } else { + comparisonResult = _compareVersionSegments(versionPrereleaseSegments, rangePrereleaseSegments); + } + } + return operatorResMap[parsedRange.op]?.includes(comparisonResult); + } + function _doPreleaseCheck(parsedVersion, allParsedRanges) { + if (parsedVersion.prerelease) { + return allParsedRanges.some((r) => r.prerelease && r.version === parsedVersion.version); + } + return true; + } + function _normalizeRange(range, options) { + range = range.trim(); + range = replaceCaret(range, options); + range = replaceTilde(range); + range = replaceXRange(range, options); + range = range.trim(); + return range; + } + function isX(id) { + return !id || id.toLowerCase() === "x" || id === "*"; + } + function _parseVersion(versionString) { + const match = versionString.match(VERSION_REGEXP); + if (!match) { + api_1.diag.error(`Invalid version: ${versionString}`); + return; + } + const version = match.groups.version; + const prerelease = match.groups.prerelease; + const build = match.groups.build; + const versionSegments = version.split("."); + const prereleaseSegments = prerelease?.split("."); + return { + op: undefined, + version, + versionSegments, + versionSegmentCount: versionSegments.length, + prerelease, + prereleaseSegments, + prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0, + build + }; + } + function _parseRange(rangeString) { + if (!rangeString) { + return {}; + } + const match = rangeString.match(RANGE_REGEXP); + if (!match) { + api_1.diag.error(`Invalid range: ${rangeString}`); + return { + invalid: true + }; + } + let op = match.groups.op; + const version = match.groups.version; + const prerelease = match.groups.prerelease; + const build = match.groups.build; + const versionSegments = version.split("."); + const prereleaseSegments = prerelease?.split("."); + if (op === "==") { + op = "="; + } + return { + op: op || "=", + version, + versionSegments, + versionSegmentCount: versionSegments.length, + prerelease, + prereleaseSegments, + prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0, + build + }; + } + function _isWildcard(s) { + return s === "*" || s === "x" || s === "X"; + } + function _parseVersionString(v) { + const n = parseInt(v, 10); + return isNaN(n) ? v : n; + } + function _normalizeVersionType(a, b) { + if (typeof a === typeof b) { + if (typeof a === "number") { + return [a, b]; + } else if (typeof a === "string") { + return [a, b]; + } else { + throw new Error("Version segments can only be strings or numbers"); + } + } else { + return [String(a), String(b)]; + } + } + function _compareVersionStrings(v1, v2) { + if (_isWildcard(v1) || _isWildcard(v2)) { + return 0; + } + const [parsedV1, parsedV2] = _normalizeVersionType(_parseVersionString(v1), _parseVersionString(v2)); + if (parsedV1 > parsedV2) { + return 1; + } else if (parsedV1 < parsedV2) { + return -1; + } + return 0; + } + function _compareVersionSegments(v1, v2) { + for (let i = 0;i < Math.max(v1.length, v2.length); i++) { + const res = _compareVersionStrings(v1[i] || "0", v2[i] || "0"); + if (res !== 0) { + return res; + } + } + return 0; + } + var LETTERDASHNUMBER = "[a-zA-Z0-9-]"; + var NUMERICIDENTIFIER = "0|[1-9]\\d*"; + var NONNUMERICIDENTIFIER = `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`; + var GTLT = "((?:<|>)?=?)"; + var PRERELEASEIDENTIFIER = `(?:${NUMERICIDENTIFIER}|${NONNUMERICIDENTIFIER})`; + var PRERELEASE = `(?:-(${PRERELEASEIDENTIFIER}(?:\\.${PRERELEASEIDENTIFIER})*))`; + var BUILDIDENTIFIER = `${LETTERDASHNUMBER}+`; + var BUILD = `(?:\\+(${BUILDIDENTIFIER}(?:\\.${BUILDIDENTIFIER})*))`; + var XRANGEIDENTIFIER = `${NUMERICIDENTIFIER}|x|X|\\*`; + var XRANGEPLAIN = `[v=\\s]*(${XRANGEIDENTIFIER})` + `(?:\\.(${XRANGEIDENTIFIER})` + `(?:\\.(${XRANGEIDENTIFIER})` + `(?:${PRERELEASE})?${BUILD}?` + ")?)?"; + var XRANGE = `^${GTLT}\\s*${XRANGEPLAIN}$`; + var XRANGE_REGEXP = new RegExp(XRANGE); + var HYPHENRANGE = `^\\s*(${XRANGEPLAIN})` + "\\s+-\\s+" + `(${XRANGEPLAIN})` + "\\s*$"; + var HYPHENRANGE_REGEXP = new RegExp(HYPHENRANGE); + var LONETILDE = "(?:~>?)"; + var TILDE = `^${LONETILDE}${XRANGEPLAIN}$`; + var TILDE_REGEXP = new RegExp(TILDE); + var LONECARET = "(?:\\^)"; + var CARET = `^${LONECARET}${XRANGEPLAIN}$`; + var CARET_REGEXP = new RegExp(CARET); + function replaceTilde(comp) { + const r = TILDE_REGEXP; + return comp.replace(r, (_, M, m, p, pr) => { + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + return ret; + }); + } + function replaceCaret(comp, options) { + const r = CARET_REGEXP; + const z = options?.includePrerelease ? "-0" : ""; + return comp.replace(r, (_, M, m, p, pr) => { + let ret; + if (isX(M)) { + ret = ""; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === "0") { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + if (M === "0") { + if (m === "0") { + ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + return ret; + }); + } + function replaceXRange(comp, options) { + const r = XRANGE_REGEXP; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + if (gtlt === "=" && anyX) { + gtlt = ""; + } + pr = options?.includePrerelease ? "-0" : ""; + if (xM) { + if (gtlt === ">" || gtlt === "<") { + ret = "<0.0.0-0"; + } else { + ret = "*"; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + p = 0; + if (gtlt === ">") { + gtlt = ">="; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === "<=") { + gtlt = "<"; + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + if (gtlt === "<") { + pr = "-0"; + } + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + return ret; + }); + } + function replaceHyphen(comp, options) { + const r = HYPHENRANGE_REGEXP; + return comp.replace(r, (_, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = ""; + } else if (isX(fm)) { + from = `>=${fM}.0.0${options?.includePrerelease ? "-0" : ""}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${options?.includePrerelease ? "-0" : ""}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${options?.includePrerelease ? "-0" : ""}`; + } + if (isX(tM)) { + to = ""; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (options?.includePrerelease) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + return `${from} ${to}`.trim(); + }); + } +}); + +// node_modules/@opentelemetry/instrumentation/build/src/shimmer.js +var require_shimmer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.massUnwrap = exports.unwrap = exports.massWrap = exports.wrap = undefined; + var logger = console.error.bind(console); + function defineProperty(obj, name, value) { + const enumerable = !!obj[name] && Object.prototype.propertyIsEnumerable.call(obj, name); + Object.defineProperty(obj, name, { + configurable: true, + enumerable, + writable: true, + value + }); + } + var wrap = (nodule, name, wrapper) => { + if (!nodule || !nodule[name]) { + logger("no original function " + String(name) + " to wrap"); + return; + } + if (!wrapper) { + logger("no wrapper function"); + logger(new Error().stack); + return; + } + const original = nodule[name]; + if (typeof original !== "function" || typeof wrapper !== "function") { + logger("original object and wrapper must be functions"); + return; + } + const wrapped = wrapper(original, name); + defineProperty(wrapped, "__original", original); + defineProperty(wrapped, "__unwrap", () => { + if (nodule[name] === wrapped) { + defineProperty(nodule, name, original); + } + }); + defineProperty(wrapped, "__wrapped", true); + defineProperty(nodule, name, wrapped); + return wrapped; + }; + exports.wrap = wrap; + var massWrap = (nodules, names, wrapper) => { + if (!nodules) { + logger("must provide one or more modules to patch"); + logger(new Error().stack); + return; + } else if (!Array.isArray(nodules)) { + nodules = [nodules]; + } + if (!(names && Array.isArray(names))) { + logger("must provide one or more functions to wrap on modules"); + return; + } + nodules.forEach((nodule) => { + names.forEach((name) => { + (0, exports.wrap)(nodule, name, wrapper); + }); + }); + }; + exports.massWrap = massWrap; + var unwrap = (nodule, name) => { + if (!nodule || !nodule[name]) { + logger("no function to unwrap."); + logger(new Error().stack); + return; + } + const wrapped = nodule[name]; + if (!wrapped.__unwrap) { + logger("no original to unwrap to -- has " + String(name) + " already been unwrapped?"); + } else { + wrapped.__unwrap(); + return; + } + }; + exports.unwrap = unwrap; + var massUnwrap = (nodules, names) => { + if (!nodules) { + logger("must provide one or more modules to patch"); + logger(new Error().stack); + return; + } else if (!Array.isArray(nodules)) { + nodules = [nodules]; + } + if (!(names && Array.isArray(names))) { + logger("must provide one or more functions to unwrap on modules"); + return; + } + nodules.forEach((nodule) => { + names.forEach((name) => { + (0, exports.unwrap)(nodule, name); + }); + }); + }; + exports.massUnwrap = massUnwrap; + function shimmer(options) { + if (options && options.logger) { + if (typeof options.logger !== "function") { + logger("new logger isn't a function, not replacing"); + } else { + logger = options.logger; + } + } + } + exports.default = shimmer; + shimmer.wrap = exports.wrap; + shimmer.massWrap = exports.massWrap; + shimmer.unwrap = exports.unwrap; + shimmer.massUnwrap = exports.massUnwrap; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/instrumentation.js +var require_instrumentation = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstrumentationAbstract = undefined; + var api_1 = require_src(); + var api_logs_1 = require_src5(); + var shimmer = require_shimmer(); + + class InstrumentationAbstract { + _config = {}; + _tracer; + _meter; + _logger; + _diag; + instrumentationName; + instrumentationVersion; + constructor(instrumentationName, instrumentationVersion, config) { + this.instrumentationName = instrumentationName; + this.instrumentationVersion = instrumentationVersion; + this.setConfig(config); + this._diag = api_1.diag.createComponentLogger({ + namespace: instrumentationName + }); + this._tracer = api_1.trace.getTracer(instrumentationName, instrumentationVersion); + this._meter = api_1.metrics.getMeter(instrumentationName, instrumentationVersion); + this._logger = api_logs_1.logs.getLogger(instrumentationName, instrumentationVersion); + this._updateMetricInstruments(); + } + _wrap = shimmer.wrap; + _unwrap = shimmer.unwrap; + _massWrap = shimmer.massWrap; + _massUnwrap = shimmer.massUnwrap; + get meter() { + return this._meter; + } + setMeterProvider(meterProvider) { + this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion); + this._updateMetricInstruments(); + } + get logger() { + return this._logger; + } + setLoggerProvider(loggerProvider) { + this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion); + } + getModuleDefinitions() { + const initResult = this.init() ?? []; + if (!Array.isArray(initResult)) { + return [initResult]; + } + return initResult; + } + _updateMetricInstruments() { + return; + } + getConfig() { + return this._config; + } + setConfig(config) { + this._config = { + enabled: true, + ...config + }; + } + setTracerProvider(tracerProvider) { + this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion); + } + get tracer() { + return this._tracer; + } + _runSpanCustomizationHook(hookHandler, triggerName, span, info) { + if (!hookHandler) { + return; + } + try { + hookHandler(span, info); + } catch (e) { + this._diag.error("Error running span customization hook due to exception in handler", { triggerName }, e); + } + } + } + exports.InstrumentationAbstract = InstrumentationAbstract; +}); + +// node_modules/ms/index.js +var require_ms = __commonJS((exports, module) => { + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse2(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); + }; + function parse2(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } +}); + +// node_modules/debug/src/common.js +var require_common = __commonJS((exports, module) => { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0;i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug(...args) { + if (!debug.enabled) { + return; + } + const self2 = debug; + const curr = Number(new Date); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index]; + match = formatter.call(self2, val); + args.splice(index, 1); + index--; + } + return match; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; + Object.defineProperty(debug, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug); + } + return debug; + } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + return false; + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module.exports = setup; +}); + +// node_modules/debug/src/browser.js +var require_browser = __commonJS((exports, module) => { + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } + }); + args.splice(lastC, 0, c); + } + exports.log = console.debug || console.log || (() => {}); + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem("debug", namespaces); + } else { + exports.storage.removeItem("debug"); + } + } catch (error) {} + } + function load() { + let r; + try { + r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); + } catch (error) {} + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error) {} + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; +}); + +// node_modules/has-flag/index.js +var require_has_flag = __commonJS((exports, module) => { + module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); + }; +}); + +// node_modules/supports-color/index.js +var require_supports_color = __commonJS((exports, module) => { + var os = __require("os"); + var tty = __require("tty"); + var hasFlag = require_has_flag(); + var { env } = process; + var flagForceColor; + if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { + flagForceColor = 0; + } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { + flagForceColor = 1; + } + function envForceColor() { + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + return 1; + } + if (env.FORCE_COLOR === "false") { + return 0; + } + return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + } + } + function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; + } + function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + if (forceColor === 0) { + return 0; + } + if (sniffFlags) { + if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + } + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (process.platform === "win32") { + const osRelease = os.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); + switch (env.TERM_PROGRAM) { + case "iTerm.app": + return version >= 3 ? 3 : 2; + case "Apple_Terminal": + return 2; + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; + } + function getSupportLevel(stream, options = {}) { + const level = supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options + }); + return translateLevel(level); + } + module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel({ isTTY: tty.isatty(1) }), + stderr: getSupportLevel({ isTTY: tty.isatty(2) }) + }; +}); + +// node_modules/debug/src/node.js +var require_node6 = __commonJS((exports, module) => { + var tty = __require("tty"); + var util = __require("util"); + exports.init = init; + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + exports.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = require_supports_color(); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error) {} + exports.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs(args) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args[0] = prefix + args[0].split(` +`).join(` +` + prefix); + args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args[0] = getDate() + name + " " + args[0]; + } + } + function getDate() { + if (exports.inspectOpts.hideDate) { + return ""; + } + return new Date().toISOString() + " "; + } + function log(...args) { + return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + ` +`); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load() { + return process.env.DEBUG; + } + function init(debug) { + debug.inspectOpts = {}; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0;i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts).split(` +`).map((str) => str.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); + }; +}); + +// node_modules/debug/src/index.js +var require_src14 = __commonJS((exports, module) => { + if (typeof process === "undefined" || process.type === "renderer" || false || process.__nwjs) { + module.exports = require_browser(); + } else { + module.exports = require_node6(); + } +}); + +// node_modules/module-details-from-path/index.js +var require_module_details_from_path = __commonJS((exports, module) => { + var path = __require("path"); + module.exports = function(file) { + var segments = file.split(path.sep); + var index = segments.lastIndexOf("node_modules"); + if (index === -1) + return; + if (!segments[index + 1]) + return; + var scoped = segments[index + 1][0] === "@"; + var name = scoped ? segments[index + 1] + "/" + segments[index + 2] : segments[index + 1]; + var offset = scoped ? 3 : 2; + return { + name, + basedir: segments.slice(0, index + offset).join(path.sep), + path: segments.slice(index + offset).join(path.sep) + }; + }; +}); + +// node_modules/require-in-the-middle/index.js +var require_require_in_the_middle = __commonJS((exports, module) => { + var path = __require("path"); + var Module = __require("module"); + var debug = require_src14()("require-in-the-middle"); + var moduleDetailsFromPath = require_module_details_from_path(); + module.exports = Hook; + module.exports.Hook = Hook; + var builtinModules; + var isCore; + if (Module.isBuiltin) { + isCore = Module.isBuiltin; + } else if (Module.builtinModules) { + isCore = (moduleName) => { + if (moduleName.startsWith("node:")) { + return true; + } + if (builtinModules === undefined) { + builtinModules = new Set(Module.builtinModules); + } + return builtinModules.has(moduleName); + }; + } else { + throw new Error("'require-in-the-middle' requires Node.js >=v9.3.0 or >=v8.10.0"); + } + var normalize = /([/\\]index)?(\.js)?$/; + + class ExportsCache { + constructor() { + this._localCache = new Map; + this._kRitmExports = Symbol("RitmExports"); + } + has(filename, isBuiltin) { + if (this._localCache.has(filename)) { + return true; + } else if (!isBuiltin) { + const mod = __require.cache[filename]; + return !!(mod && (this._kRitmExports in mod)); + } else { + return false; + } + } + get(filename, isBuiltin) { + const cachedExports = this._localCache.get(filename); + if (cachedExports !== undefined) { + return cachedExports; + } else if (!isBuiltin) { + const mod = __require.cache[filename]; + return mod && mod[this._kRitmExports]; + } + } + set(filename, exports2, isBuiltin) { + if (isBuiltin) { + this._localCache.set(filename, exports2); + } else if (filename in __require.cache) { + __require.cache[filename][this._kRitmExports] = exports2; + } else { + debug('non-core module is unexpectedly not in require.cache: "%s"', filename); + this._localCache.set(filename, exports2); + } + } + } + function Hook(modules, options, onrequire) { + if (this instanceof Hook === false) + return new Hook(modules, options, onrequire); + if (typeof modules === "function") { + onrequire = modules; + modules = null; + options = null; + } else if (typeof options === "function") { + onrequire = options; + options = null; + } + if (typeof Module._resolveFilename !== "function") { + console.error("Error: Expected Module._resolveFilename to be a function (was: %s) - aborting!", typeof Module._resolveFilename); + console.error("Please report this error as an issue related to Node.js %s at https://github.com/nodejs/require-in-the-middle/issues", process.version); + return; + } + this._cache = new ExportsCache; + this._unhooked = false; + this._origRequire = Module.prototype.require; + const self2 = this; + const patching = new Set; + const internals = options ? options.internals === true : false; + const hasWhitelist = Array.isArray(modules); + debug("registering require hook"); + this._require = Module.prototype.require = function(id) { + if (self2._unhooked === true) { + debug("ignoring require call - module is soft-unhooked"); + return self2._origRequire.apply(this, arguments); + } + return patchedRequire.call(this, arguments, false); + }; + if (typeof process.getBuiltinModule === "function") { + this._origGetBuiltinModule = process.getBuiltinModule; + this._getBuiltinModule = process.getBuiltinModule = function(id) { + if (self2._unhooked === true) { + debug("ignoring process.getBuiltinModule call - module is soft-unhooked"); + return self2._origGetBuiltinModule.apply(this, arguments); + } + return patchedRequire.call(this, arguments, true); + }; + } + function patchedRequire(args, coreOnly) { + const id = args[0]; + const core = isCore(id); + let filename; + if (core) { + filename = id; + if (id.startsWith("node:")) { + const idWithoutPrefix = id.slice(5); + if (isCore(idWithoutPrefix)) { + filename = idWithoutPrefix; + } + } + } else if (coreOnly) { + debug("call to process.getBuiltinModule with unknown built-in id"); + return self2._origGetBuiltinModule.apply(this, args); + } else { + try { + filename = Module._resolveFilename(id, this); + } catch (resolveErr) { + debug('Module._resolveFilename("%s") threw %j, calling original Module.require', id, resolveErr.message); + return self2._origRequire.apply(this, args); + } + } + let moduleName, basedir; + debug("processing %s module require('%s'): %s", core === true ? "core" : "non-core", id, filename); + if (self2._cache.has(filename, core) === true) { + debug("returning already patched cached module: %s", filename); + return self2._cache.get(filename, core); + } + const isPatching = patching.has(filename); + if (isPatching === false) { + patching.add(filename); + } + const exports2 = coreOnly ? self2._origGetBuiltinModule.apply(this, args) : self2._origRequire.apply(this, args); + if (isPatching === true) { + debug("module is in the process of being patched already - ignoring: %s", filename); + return exports2; + } + patching.delete(filename); + if (core === true) { + if (hasWhitelist === true && modules.includes(filename) === false) { + debug("ignoring core module not on whitelist: %s", filename); + return exports2; + } + moduleName = filename; + } else if (hasWhitelist === true && modules.includes(filename)) { + const parsedPath = path.parse(filename); + moduleName = parsedPath.name; + basedir = parsedPath.dir; + } else { + const stat = moduleDetailsFromPath(filename); + if (stat === undefined) { + debug("could not parse filename: %s", filename); + return exports2; + } + moduleName = stat.name; + basedir = stat.basedir; + const fullModuleName = resolveModuleName(stat); + debug("resolved filename to module: %s (id: %s, resolved: %s, basedir: %s)", moduleName, id, fullModuleName, basedir); + let matchFound = false; + if (hasWhitelist) { + if (!id.startsWith(".") && modules.includes(id)) { + moduleName = id; + matchFound = true; + } + if (!modules.includes(moduleName) && !modules.includes(fullModuleName)) { + return exports2; + } + if (modules.includes(fullModuleName) && fullModuleName !== moduleName) { + moduleName = fullModuleName; + matchFound = true; + } + } + if (!matchFound) { + let res; + try { + res = __require.resolve(moduleName, { paths: [basedir] }); + } catch (e) { + debug("could not resolve module: %s", moduleName); + self2._cache.set(filename, exports2, core); + return exports2; + } + if (res !== filename) { + if (internals === true) { + moduleName = moduleName + path.sep + path.relative(basedir, filename); + debug("preparing to process require of internal file: %s", moduleName); + } else { + debug("ignoring require of non-main module file: %s", res); + self2._cache.set(filename, exports2, core); + return exports2; + } + } + } + } + self2._cache.set(filename, exports2, core); + debug("calling require hook: %s", moduleName); + const patchedExports = onrequire(exports2, moduleName, basedir); + self2._cache.set(filename, patchedExports, core); + debug("returning module: %s", moduleName); + return patchedExports; + } + } + Hook.prototype.unhook = function() { + this._unhooked = true; + if (this._require === Module.prototype.require) { + Module.prototype.require = this._origRequire; + debug("require unhook successful"); + } else { + debug("require unhook unsuccessful"); + } + if (process.getBuiltinModule !== undefined) { + if (this._getBuiltinModule === process.getBuiltinModule) { + process.getBuiltinModule = this._origGetBuiltinModule; + debug("process.getBuiltinModule unhook successful"); + } else { + debug("process.getBuiltinModule unhook unsuccessful"); + } + } + }; + function resolveModuleName(stat) { + const normalizedPath = path.sep !== "/" ? stat.path.split(path.sep).join("/") : stat.path; + return path.posix.join(stat.name, normalizedPath).replace(normalize, ""); + } +}); + +// node_modules/@opentelemetry/instrumentation/build/src/platform/node/ModuleNameTrie.js +var require_ModuleNameTrie = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModuleNameTrie = exports.ModuleNameSeparator = undefined; + exports.ModuleNameSeparator = "/"; + + class ModuleNameTrieNode { + hooks = []; + children = new Map; + } + + class ModuleNameTrie { + _trie = new ModuleNameTrieNode; + _counter = 0; + insert(hook) { + let trieNode = this._trie; + for (const moduleNamePart of hook.moduleName.split(exports.ModuleNameSeparator)) { + let nextNode = trieNode.children.get(moduleNamePart); + if (!nextNode) { + nextNode = new ModuleNameTrieNode; + trieNode.children.set(moduleNamePart, nextNode); + } + trieNode = nextNode; + } + trieNode.hooks.push({ hook, insertedId: this._counter++ }); + } + search(moduleName, { maintainInsertionOrder, fullOnly } = {}) { + let trieNode = this._trie; + const results = []; + let foundFull = true; + for (const moduleNamePart of moduleName.split(exports.ModuleNameSeparator)) { + const nextNode = trieNode.children.get(moduleNamePart); + if (!nextNode) { + foundFull = false; + break; + } + if (!fullOnly) { + results.push(...nextNode.hooks); + } + trieNode = nextNode; + } + if (fullOnly && foundFull) { + results.push(...trieNode.hooks); + } + if (results.length === 0) { + return []; + } + if (results.length === 1) { + return [results[0].hook]; + } + if (maintainInsertionOrder) { + results.sort((a, b) => a.insertedId - b.insertedId); + } + return results.map(({ hook }) => hook); + } + } + exports.ModuleNameTrie = ModuleNameTrie; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/platform/node/RequireInTheMiddleSingleton.js +var require_RequireInTheMiddleSingleton = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RequireInTheMiddleSingleton = undefined; + var require_in_the_middle_1 = require_require_in_the_middle(); + var path = __require("path"); + var ModuleNameTrie_1 = require_ModuleNameTrie(); + var isMocha = [ + "afterEach", + "after", + "beforeEach", + "before", + "describe", + "it" + ].every((fn) => { + return typeof global[fn] === "function"; + }); + + class RequireInTheMiddleSingleton { + _moduleNameTrie = new ModuleNameTrie_1.ModuleNameTrie; + static _instance; + constructor() { + this._initialize(); + } + _initialize() { + new require_in_the_middle_1.Hook(null, { internals: true }, (exports2, name, basedir) => { + const normalizedModuleName = normalizePathSeparators(name); + const matches = this._moduleNameTrie.search(normalizedModuleName, { + maintainInsertionOrder: true, + fullOnly: basedir === undefined + }); + for (const { onRequire } of matches) { + exports2 = onRequire(exports2, name, basedir); + } + return exports2; + }); + } + register(moduleName, onRequire) { + const hooked = { moduleName, onRequire }; + this._moduleNameTrie.insert(hooked); + return hooked; + } + static getInstance() { + if (isMocha) + return new RequireInTheMiddleSingleton; + return this._instance = this._instance ?? new RequireInTheMiddleSingleton; + } + } + exports.RequireInTheMiddleSingleton = RequireInTheMiddleSingleton; + function normalizePathSeparators(moduleNameOrPath) { + return path.sep !== ModuleNameTrie_1.ModuleNameSeparator ? moduleNameOrPath.split(path.sep).join(ModuleNameTrie_1.ModuleNameSeparator) : moduleNameOrPath; + } +}); + +// node_modules/import-in-the-middle/node_modules/module-details-from-path/index.js +var require_module_details_from_path2 = __commonJS((exports, module) => { + var sep = __require("path").sep; + module.exports = function(file) { + var segments = file.split(sep); + var index = segments.lastIndexOf("node_modules"); + if (index === -1) + return; + if (!segments[index + 1]) + return; + var scoped = segments[index + 1][0] === "@"; + var name = scoped ? segments[index + 1] + "/" + segments[index + 2] : segments[index + 1]; + var offset = scoped ? 3 : 2; + var basedir = ""; + var lastBaseDirSegmentIndex = index + offset - 1; + for (var i = 0;i <= lastBaseDirSegmentIndex; i++) { + if (i === lastBaseDirSegmentIndex) { + basedir += segments[i]; + } else { + basedir += segments[i] + sep; + } + } + var path = ""; + var lastSegmentIndex = segments.length - 1; + for (var i2 = index + offset;i2 <= lastSegmentIndex; i2++) { + if (i2 === lastSegmentIndex) { + path += segments[i2]; + } else { + path += segments[i2] + sep; + } + } + return { + name, + basedir, + path + }; + }; +}); + +// node_modules/import-in-the-middle/lib/register.js +var require_register = __commonJS((exports) => { + var importHooks = []; + var setters = new WeakMap; + var getters = new WeakMap; + var specifiers = new Map; + var toHook = []; + var proxyHandler = { + set(target, name, value) { + const set = setters.get(target); + const setter = set && set[name]; + if (typeof setter === "function") { + return setter(value); + } + return true; + }, + get(target, name) { + if (name === Symbol.toStringTag) { + return "Module"; + } + const getter = getters.get(target)[name]; + if (typeof getter === "function") { + return getter(); + } + }, + defineProperty(target, property, descriptor) { + if (!("value" in descriptor)) { + throw new Error("Getters/setters are not supported for exports property descriptors."); + } + const set = setters.get(target); + const setter = set && set[property]; + if (typeof setter === "function") { + return setter(descriptor.value); + } + return true; + } + }; + function register(name, namespace, set, get, specifier) { + specifiers.set(name, specifier); + setters.set(namespace, set); + getters.set(namespace, get); + const proxy = new Proxy(namespace, proxyHandler); + importHooks.forEach((hook) => hook(name, proxy, specifier)); + toHook.push([name, proxy, specifier]); + } + exports.register = register; + exports.importHooks = importHooks; + exports.specifiers = specifiers; + exports.toHook = toHook; +}); + +// node_modules/import-in-the-middle/index.js +var require_import_in_the_middle = __commonJS((exports, module) => { + var path = __require("path"); + var moduleDetailsFromPath = require_module_details_from_path2(); + var { fileURLToPath } = __require("url"); + var { MessageChannel } = __require("worker_threads"); + var { isBuiltin } = __require("module"); + if (!isBuiltin) { + isBuiltin = () => true; + } + var { + importHooks, + specifiers, + toHook + } = require_register(); + function addHook(hook) { + importHooks.push(hook); + toHook.forEach(([name, namespace, specifier]) => hook(name, namespace, specifier)); + } + function removeHook(hook) { + const index = importHooks.indexOf(hook); + if (index > -1) { + importHooks.splice(index, 1); + } + } + function callHookFn(hookFn, namespace, name, baseDir) { + const newDefault = hookFn(namespace, name, baseDir); + if (newDefault && newDefault !== namespace) { + if ("default" in namespace) { + namespace.default = newDefault; + } + } + } + var sendModulesToLoader; + function createAddHookMessageChannel() { + const { port1, port2 } = new MessageChannel; + let pendingAckCount = 0; + let resolveFn; + sendModulesToLoader = (modules) => { + pendingAckCount++; + port1.postMessage(modules); + }; + port1.on("message", () => { + pendingAckCount--; + if (resolveFn && pendingAckCount <= 0) { + resolveFn(); + } + }).unref(); + function waitForAllMessagesAcknowledged() { + const timer = setInterval(() => {}, 1000); + const promise = new Promise((resolve) => { + resolveFn = resolve; + }).then(() => { + clearInterval(timer); + }); + if (pendingAckCount === 0) { + resolveFn(); + } + return promise; + } + const addHookMessagePort = port2; + const registerOptions = { data: { addHookMessagePort, include: [] }, transferList: [addHookMessagePort] }; + return { registerOptions, addHookMessagePort, waitForAllMessagesAcknowledged }; + } + function Hook(modules, options, hookFn) { + if (this instanceof Hook === false) + return new Hook(modules, options, hookFn); + if (typeof modules === "function") { + hookFn = modules; + modules = null; + options = null; + } else if (typeof options === "function") { + hookFn = options; + options = null; + } + const internals = options ? options.internals === true : false; + if (sendModulesToLoader && Array.isArray(modules)) { + sendModulesToLoader(modules); + } + this._iitmHook = (name, namespace, specifier) => { + const loadUrl = name; + const isNodeUrl = loadUrl.startsWith("node:"); + let filePath, baseDir; + if (isNodeUrl) { + const unprefixed = name.slice(5); + if (isBuiltin(unprefixed)) { + name = unprefixed; + } + } else if (loadUrl.startsWith("file://")) { + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + try { + filePath = fileURLToPath(name); + name = filePath; + } catch (e) {} + Error.stackTraceLimit = stackTraceLimit; + if (filePath) { + const details = moduleDetailsFromPath(filePath); + if (details) { + name = details.name; + baseDir = details.basedir; + } + } + } + if (modules) { + for (const matchArg of modules) { + if (filePath && matchArg === filePath) { + callHookFn(hookFn, namespace, filePath, undefined); + } else if (matchArg === name) { + if (!baseDir) { + callHookFn(hookFn, namespace, name, baseDir); + } else if (baseDir.endsWith(specifiers.get(loadUrl))) { + callHookFn(hookFn, namespace, name, baseDir); + } else if (internals) { + const internalPath = name + path.sep + path.relative(baseDir, filePath); + callHookFn(hookFn, namespace, internalPath, baseDir); + } + } else if (matchArg === specifier) { + callHookFn(hookFn, namespace, specifier, baseDir); + } + } + } else { + callHookFn(hookFn, namespace, name, baseDir); + } + }; + addHook(this._iitmHook); + } + Hook.prototype.unhook = function() { + removeHook(this._iitmHook); + }; + module.exports = Hook; + module.exports.Hook = Hook; + module.exports.addHook = addHook; + module.exports.removeHook = removeHook; + module.exports.createAddHookMessageChannel = createAddHookMessageChannel; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/utils.js +var require_utils11 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isWrapped = exports.safeExecuteInTheMiddleAsync = exports.safeExecuteInTheMiddle = undefined; + function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) { + let error; + let result; + try { + result = execute(); + } catch (e) { + error = e; + } finally { + onFinish(error, result); + if (error && !preventThrowingError) { + throw error; + } + return result; + } + } + exports.safeExecuteInTheMiddle = safeExecuteInTheMiddle; + async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) { + let error; + let result; + try { + result = await execute(); + } catch (e) { + error = e; + } finally { + await onFinish(error, result); + if (error && !preventThrowingError) { + throw error; + } + return result; + } + } + exports.safeExecuteInTheMiddleAsync = safeExecuteInTheMiddleAsync; + function isWrapped(func) { + return typeof func === "function" && typeof func.__original === "function" && typeof func.__unwrap === "function" && func.__wrapped === true; + } + exports.isWrapped = isWrapped; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/platform/node/instrumentation.js +var require_instrumentation2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstrumentationBase = undefined; + var path = __require("path"); + var util_1 = __require("util"); + var semver_1 = require_semver2(); + var shimmer_1 = require_shimmer(); + var instrumentation_1 = require_instrumentation(); + var RequireInTheMiddleSingleton_1 = require_RequireInTheMiddleSingleton(); + var import_in_the_middle_1 = require_import_in_the_middle(); + var api_1 = require_src(); + var require_in_the_middle_1 = require_require_in_the_middle(); + var fs_1 = __require("fs"); + var utils_1 = require_utils11(); + + class InstrumentationBase extends instrumentation_1.InstrumentationAbstract { + _modules; + _hooks = []; + _requireInTheMiddleSingleton = RequireInTheMiddleSingleton_1.RequireInTheMiddleSingleton.getInstance(); + _enabled = false; + constructor(instrumentationName, instrumentationVersion, config) { + super(instrumentationName, instrumentationVersion, config); + let modules = this.init(); + if (modules && !Array.isArray(modules)) { + modules = [modules]; + } + this._modules = modules || []; + if (this._config.enabled) { + this.enable(); + } + } + _wrap = (moduleExports, name, wrapper) => { + if ((0, utils_1.isWrapped)(moduleExports[name])) { + this._unwrap(moduleExports, name); + } + if (!util_1.types.isProxy(moduleExports)) { + return (0, shimmer_1.wrap)(moduleExports, name, wrapper); + } else { + const wrapped = (0, shimmer_1.wrap)(Object.assign({}, moduleExports), name, wrapper); + Object.defineProperty(moduleExports, name, { + value: wrapped + }); + return wrapped; + } + }; + _unwrap = (moduleExports, name) => { + if (!util_1.types.isProxy(moduleExports)) { + return (0, shimmer_1.unwrap)(moduleExports, name); + } else { + return Object.defineProperty(moduleExports, name, { + value: moduleExports[name] + }); + } + }; + _massWrap = (moduleExportsArray, names, wrapper) => { + if (!moduleExportsArray) { + api_1.diag.error("must provide one or more modules to patch"); + return; + } else if (!Array.isArray(moduleExportsArray)) { + moduleExportsArray = [moduleExportsArray]; + } + if (!(names && Array.isArray(names))) { + api_1.diag.error("must provide one or more functions to wrap on modules"); + return; + } + moduleExportsArray.forEach((moduleExports) => { + names.forEach((name) => { + this._wrap(moduleExports, name, wrapper); + }); + }); + }; + _massUnwrap = (moduleExportsArray, names) => { + if (!moduleExportsArray) { + api_1.diag.error("must provide one or more modules to patch"); + return; + } else if (!Array.isArray(moduleExportsArray)) { + moduleExportsArray = [moduleExportsArray]; + } + if (!(names && Array.isArray(names))) { + api_1.diag.error("must provide one or more functions to wrap on modules"); + return; + } + moduleExportsArray.forEach((moduleExports) => { + names.forEach((name) => { + this._unwrap(moduleExports, name); + }); + }); + }; + _warnOnPreloadedModules() { + const nodeRequire = globalThis.require; + if (!nodeRequire?.resolve || !nodeRequire?.cache) + return; + this._modules.forEach((module2) => { + const { name } = module2; + try { + const resolvedModule = nodeRequire.resolve(name); + if (nodeRequire.cache[resolvedModule]?.loaded) { + this._diag.warn(`Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`); + } + } catch {} + }); + } + _extractPackageVersion(baseDir) { + try { + const json = (0, fs_1.readFileSync)(path.join(baseDir, "package.json"), { + encoding: "utf8" + }); + const version = JSON.parse(json).version; + return typeof version === "string" ? version : undefined; + } catch { + api_1.diag.warn("Failed extracting version", baseDir); + } + return; + } + _onRequire(module2, exports2, name, baseDir) { + if (!baseDir) { + if (typeof module2.patch === "function") { + module2.moduleExports = exports2; + if (this._enabled) { + this._diag.debug("Applying instrumentation patch for nodejs core module on require hook", { + module: module2.name + }); + return module2.patch(exports2); + } + } + return exports2; + } + const version = this._extractPackageVersion(baseDir); + module2.moduleVersion = version; + if (module2.name === name) { + if (isSupported(module2.supportedVersions, version, module2.includePrerelease)) { + if (typeof module2.patch === "function") { + module2.moduleExports = exports2; + if (this._enabled) { + this._diag.debug("Applying instrumentation patch for module on require hook", { + module: module2.name, + version: module2.moduleVersion, + baseDir + }); + return module2.patch(exports2, module2.moduleVersion); + } + } + } + return exports2; + } + const files2 = module2.files ?? []; + const normalizedName = path.normalize(name); + const supportedFileInstrumentations = files2.filter((f) => f.name === normalizedName && isSupported(f.supportedVersions, version, module2.includePrerelease)); + return supportedFileInstrumentations.reduce((patchedExports, file) => { + file.moduleExports = patchedExports; + if (this._enabled) { + this._diag.debug("Applying instrumentation patch for nodejs module file on require hook", { + module: module2.name, + version: module2.moduleVersion, + fileName: file.name, + baseDir + }); + return file.patch(patchedExports, module2.moduleVersion); + } + return patchedExports; + }, exports2); + } + enable() { + if (this._enabled) { + return; + } + this._enabled = true; + if (this._hooks.length > 0) { + for (const module2 of this._modules) { + if (typeof module2.patch === "function" && module2.moduleExports) { + this._diag.debug("Applying instrumentation patch for nodejs module on instrumentation enabled", { + module: module2.name, + version: module2.moduleVersion + }); + module2.patch(module2.moduleExports, module2.moduleVersion); + } + for (const file of module2.files) { + if (file.moduleExports) { + this._diag.debug("Applying instrumentation patch for nodejs module file on instrumentation enabled", { + module: module2.name, + version: module2.moduleVersion, + fileName: file.name + }); + file.patch(file.moduleExports, module2.moduleVersion); + } + } + } + return; + } + this._warnOnPreloadedModules(); + for (const module2 of this._modules) { + const hookFn = (exports2, name, baseDir) => { + if (!baseDir && path.isAbsolute(name)) { + const parsedPath = path.parse(name); + name = parsedPath.name; + baseDir = parsedPath.dir; + } + return this._onRequire(module2, exports2, name, baseDir); + }; + const onRequire = (exports2, name, baseDir) => { + return this._onRequire(module2, exports2, name, baseDir); + }; + const hook = path.isAbsolute(module2.name) ? new require_in_the_middle_1.Hook([module2.name], { internals: true }, onRequire) : this._requireInTheMiddleSingleton.register(module2.name, onRequire); + this._hooks.push(hook); + const esmHook = new import_in_the_middle_1.Hook([module2.name], { internals: true }, hookFn); + this._hooks.push(esmHook); + } + } + disable() { + if (!this._enabled) { + return; + } + this._enabled = false; + for (const module2 of this._modules) { + if (typeof module2.unpatch === "function" && module2.moduleExports) { + this._diag.debug("Removing instrumentation patch for nodejs module on instrumentation disabled", { + module: module2.name, + version: module2.moduleVersion + }); + module2.unpatch(module2.moduleExports, module2.moduleVersion); + } + for (const file of module2.files) { + if (file.moduleExports) { + this._diag.debug("Removing instrumentation patch for nodejs module file on instrumentation disabled", { + module: module2.name, + version: module2.moduleVersion, + fileName: file.name + }); + file.unpatch(file.moduleExports, module2.moduleVersion); + } + } + } + } + isEnabled() { + return this._enabled; + } + } + exports.InstrumentationBase = InstrumentationBase; + function isSupported(supportedVersions, version, includePrerelease) { + if (typeof version === "undefined") { + return supportedVersions.includes("*"); + } + return supportedVersions.some((supportedVersion) => { + return (0, semver_1.satisfies)(version, supportedVersion, { includePrerelease }); + }); + } +}); + +// node_modules/@opentelemetry/instrumentation/build/src/platform/node/normalize.js +var require_normalize = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.normalize = undefined; + var path_1 = __require("path"); + Object.defineProperty(exports, "normalize", { enumerable: true, get: function() { + return path_1.normalize; + } }); +}); + +// node_modules/@opentelemetry/instrumentation/build/src/platform/node/index.js +var require_node7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.normalize = exports.InstrumentationBase = undefined; + var instrumentation_1 = require_instrumentation2(); + Object.defineProperty(exports, "InstrumentationBase", { enumerable: true, get: function() { + return instrumentation_1.InstrumentationBase; + } }); + var normalize_1 = require_normalize(); + Object.defineProperty(exports, "normalize", { enumerable: true, get: function() { + return normalize_1.normalize; + } }); +}); + +// node_modules/@opentelemetry/instrumentation/build/src/platform/index.js +var require_platform6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.normalize = exports.InstrumentationBase = undefined; + var node_1 = require_node7(); + Object.defineProperty(exports, "InstrumentationBase", { enumerable: true, get: function() { + return node_1.InstrumentationBase; + } }); + Object.defineProperty(exports, "normalize", { enumerable: true, get: function() { + return node_1.normalize; + } }); +}); + +// node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleDefinition.js +var require_instrumentationNodeModuleDefinition = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstrumentationNodeModuleDefinition = undefined; + + class InstrumentationNodeModuleDefinition { + files; + name; + supportedVersions; + patch; + unpatch; + constructor(name, supportedVersions, patch, unpatch, files2) { + this.files = files2 || []; + this.name = name; + this.supportedVersions = supportedVersions; + this.patch = patch; + this.unpatch = unpatch; + } + } + exports.InstrumentationNodeModuleDefinition = InstrumentationNodeModuleDefinition; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/instrumentationNodeModuleFile.js +var require_instrumentationNodeModuleFile = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstrumentationNodeModuleFile = undefined; + var index_1 = require_platform6(); + + class InstrumentationNodeModuleFile { + name; + supportedVersions; + patch; + unpatch; + constructor(name, supportedVersions, patch, unpatch) { + this.name = (0, index_1.normalize)(name); + this.supportedVersions = supportedVersions; + this.patch = patch; + this.unpatch = unpatch; + } + } + exports.InstrumentationNodeModuleFile = InstrumentationNodeModuleFile; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/semconvStability.js +var require_semconvStability = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.semconvStabilityFromStr = exports.SemconvStability = undefined; + var SemconvStability; + (function(SemconvStability2) { + SemconvStability2[SemconvStability2["STABLE"] = 1] = "STABLE"; + SemconvStability2[SemconvStability2["OLD"] = 2] = "OLD"; + SemconvStability2[SemconvStability2["DUPLICATE"] = 3] = "DUPLICATE"; + })(SemconvStability = exports.SemconvStability || (exports.SemconvStability = {})); + function semconvStabilityFromStr(namespace, str) { + let semconvStability = SemconvStability.OLD; + const entries = str?.split(",").map((v) => v.trim()).filter((s) => s !== ""); + for (const entry of entries ?? []) { + if (entry.toLowerCase() === namespace + "/dup") { + semconvStability = SemconvStability.DUPLICATE; + break; + } else if (entry.toLowerCase() === namespace) { + semconvStability = SemconvStability.STABLE; + } + } + return semconvStability; + } + exports.semconvStabilityFromStr = semconvStabilityFromStr; +}); + +// node_modules/@opentelemetry/instrumentation/build/src/index.js +var require_src15 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.semconvStabilityFromStr = exports.SemconvStability = exports.safeExecuteInTheMiddleAsync = exports.safeExecuteInTheMiddle = exports.isWrapped = exports.InstrumentationNodeModuleFile = exports.InstrumentationNodeModuleDefinition = exports.InstrumentationBase = exports.registerInstrumentations = undefined; + var autoLoader_1 = require_autoLoader(); + Object.defineProperty(exports, "registerInstrumentations", { enumerable: true, get: function() { + return autoLoader_1.registerInstrumentations; + } }); + var index_1 = require_platform6(); + Object.defineProperty(exports, "InstrumentationBase", { enumerable: true, get: function() { + return index_1.InstrumentationBase; + } }); + var instrumentationNodeModuleDefinition_1 = require_instrumentationNodeModuleDefinition(); + Object.defineProperty(exports, "InstrumentationNodeModuleDefinition", { enumerable: true, get: function() { + return instrumentationNodeModuleDefinition_1.InstrumentationNodeModuleDefinition; + } }); + var instrumentationNodeModuleFile_1 = require_instrumentationNodeModuleFile(); + Object.defineProperty(exports, "InstrumentationNodeModuleFile", { enumerable: true, get: function() { + return instrumentationNodeModuleFile_1.InstrumentationNodeModuleFile; + } }); + var utils_1 = require_utils11(); + Object.defineProperty(exports, "isWrapped", { enumerable: true, get: function() { + return utils_1.isWrapped; + } }); + Object.defineProperty(exports, "safeExecuteInTheMiddle", { enumerable: true, get: function() { + return utils_1.safeExecuteInTheMiddle; + } }); + Object.defineProperty(exports, "safeExecuteInTheMiddleAsync", { enumerable: true, get: function() { + return utils_1.safeExecuteInTheMiddleAsync; + } }); + var semconvStability_1 = require_semconvStability(); + Object.defineProperty(exports, "SemconvStability", { enumerable: true, get: function() { + return semconvStability_1.SemconvStability; + } }); + Object.defineProperty(exports, "semconvStabilityFromStr", { enumerable: true, get: function() { + return semconvStability_1.semconvStabilityFromStr; + } }); +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js +var require_OTLPLogExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var otlp_exporter_base_1 = require_src4(); + var otlp_transformer_1 = require_src8(); + var node_http_1 = require_index_node_http(); + + class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "LOGS", "v1/logs", { + "Content-Type": "application/json" + }), otlp_transformer_1.JsonLogsSerializer)); + } + } + exports.OTLPLogExporter = OTLPLogExporter; +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js +var require_node8 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var OTLPLogExporter_1 = require_OTLPLogExporter(); + Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function() { + return OTLPLogExporter_1.OTLPLogExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js +var require_platform7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var node_1 = require_node8(); + Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function() { + return node_1.OTLPLogExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js +var require_src16 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var platform_1 = require_platform7(); + Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function() { + return platform_1.OTLPLogExporter; + } }); +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js +var require_version8 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.VERSION = undefined; + exports.VERSION = "0.219.0"; +}); + +// node_modules/@grpc/grpc-js/build/src/constants.js +var require_constants2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = undefined; + var Status; + (function(Status2) { + Status2[Status2["OK"] = 0] = "OK"; + Status2[Status2["CANCELLED"] = 1] = "CANCELLED"; + Status2[Status2["UNKNOWN"] = 2] = "UNKNOWN"; + Status2[Status2["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + Status2[Status2["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + Status2[Status2["NOT_FOUND"] = 5] = "NOT_FOUND"; + Status2[Status2["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + Status2[Status2["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + Status2[Status2["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + Status2[Status2["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + Status2[Status2["ABORTED"] = 10] = "ABORTED"; + Status2[Status2["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + Status2[Status2["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + Status2[Status2["INTERNAL"] = 13] = "INTERNAL"; + Status2[Status2["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + Status2[Status2["DATA_LOSS"] = 15] = "DATA_LOSS"; + Status2[Status2["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + })(Status || (exports.Status = Status = {})); + var LogVerbosity; + (function(LogVerbosity2) { + LogVerbosity2[LogVerbosity2["DEBUG"] = 0] = "DEBUG"; + LogVerbosity2[LogVerbosity2["INFO"] = 1] = "INFO"; + LogVerbosity2[LogVerbosity2["ERROR"] = 2] = "ERROR"; + LogVerbosity2[LogVerbosity2["NONE"] = 3] = "NONE"; + })(LogVerbosity || (exports.LogVerbosity = LogVerbosity = {})); + var Propagate; + (function(Propagate2) { + Propagate2[Propagate2["DEADLINE"] = 1] = "DEADLINE"; + Propagate2[Propagate2["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; + Propagate2[Propagate2["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; + Propagate2[Propagate2["CANCELLATION"] = 8] = "CANCELLATION"; + Propagate2[Propagate2["DEFAULTS"] = 65535] = "DEFAULTS"; + })(Propagate || (exports.Propagate = Propagate = {})); + exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; + exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; +}); + +// node_modules/@grpc/grpc-js/package.json +var require_package = __commonJS((exports, module) => { + module.exports = { + name: "@grpc/grpc-js", + version: "1.14.4", + description: "gRPC Library for Node - pure JS implementation", + homepage: "https://grpc.io/", + repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js", + main: "build/src/index.js", + engines: { + node: ">=12.10.0" + }, + keywords: [], + author: { + name: "Google Inc." + }, + types: "build/src/index.d.ts", + license: "Apache-2.0", + devDependencies: { + "@grpc/proto-loader": "file:../proto-loader", + "@types/gulp": "^4.0.17", + "@types/gulp-mocha": "0.0.37", + "@types/lodash": "^4.14.202", + "@types/mocha": "^10.0.6", + "@types/ncp": "^2.0.8", + "@types/node": ">=20.11.20", + "@types/pify": "^5.0.4", + "@types/semver": "^7.5.8", + "@typescript-eslint/eslint-plugin": "^7.1.0", + "@typescript-eslint/parser": "^7.1.0", + "@typescript-eslint/typescript-estree": "^7.1.0", + "clang-format": "^1.8.0", + eslint: "^8.42.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^4.2.1", + execa: "^2.0.3", + gulp: "^4.0.2", + "gulp-mocha": "^6.0.0", + lodash: "^4.17.21", + madge: "^5.0.1", + "mocha-jenkins-reporter": "^0.4.1", + ncp: "^2.0.0", + pify: "^4.0.1", + prettier: "^2.8.8", + rimraf: "^3.0.2", + semver: "^7.6.0", + "ts-node": "^10.9.2", + typescript: "^5.3.3" + }, + contributors: [ + { + name: "Google Inc." + } + ], + scripts: { + build: "npm run compile", + clean: "rimraf ./build", + compile: "tsc -p .", + format: 'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts', + lint: "eslint src/*.ts test/*.ts", + prepare: "npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile", + test: "gulp test", + check: "npm run lint", + fix: "eslint --fix src/*.ts test/*.ts", + pretest: "npm run generate-types && npm run generate-test-types && npm run compile", + posttest: "npm run check && madge -c ./build/src", + "generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto", + "generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto", + "copy-protos": "node ./copy-protos" + }, + dependencies: { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + files: [ + "src/**/*.ts", + "build/src/**/*.{js,d.ts,js.map}", + "proto/**/*.proto", + "proto/**/LICENSE", + "LICENSE", + "deps/envoy-api/envoy/api/v2/**/*.proto", + "deps/envoy-api/envoy/config/**/*.proto", + "deps/envoy-api/envoy/service/**/*.proto", + "deps/envoy-api/envoy/type/**/*.proto", + "deps/udpa/udpa/**/*.proto", + "deps/googleapis/google/api/*.proto", + "deps/googleapis/google/rpc/*.proto", + "deps/protoc-gen-validate/validate/**/*.proto" + ] + }; +}); + +// node_modules/@grpc/grpc-js/build/src/logging.js +var require_logging = __commonJS((exports) => { + var _a; + var _b; + var _c; + var _d; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = undefined; + exports.trace = trace; + exports.isTracerEnabled = isTracerEnabled; + var constants_1 = require_constants2(); + var process_1 = __require("process"); + var clientVersion = require_package().version; + var DEFAULT_LOGGER = { + error: (message, ...optionalParams) => { + console.error("E " + message, ...optionalParams); + }, + info: (message, ...optionalParams) => { + console.error("I " + message, ...optionalParams); + }, + debug: (message, ...optionalParams) => { + console.error("D " + message, ...optionalParams); + } + }; + var _logger = DEFAULT_LOGGER; + var _logVerbosity = constants_1.LogVerbosity.ERROR; + var verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== undefined ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== undefined ? _b : ""; + switch (verbosityString.toUpperCase()) { + case "DEBUG": + _logVerbosity = constants_1.LogVerbosity.DEBUG; + break; + case "INFO": + _logVerbosity = constants_1.LogVerbosity.INFO; + break; + case "ERROR": + _logVerbosity = constants_1.LogVerbosity.ERROR; + break; + case "NONE": + _logVerbosity = constants_1.LogVerbosity.NONE; + break; + default: + } + var getLogger = () => { + return _logger; + }; + exports.getLogger = getLogger; + var setLogger = (logger) => { + _logger = logger; + }; + exports.setLogger = setLogger; + var setLoggerVerbosity = (verbosity) => { + _logVerbosity = verbosity; + }; + exports.setLoggerVerbosity = setLoggerVerbosity; + var log = (severity, ...args) => { + let logFunction; + if (severity >= _logVerbosity) { + switch (severity) { + case constants_1.LogVerbosity.DEBUG: + logFunction = _logger.debug; + break; + case constants_1.LogVerbosity.INFO: + logFunction = _logger.info; + break; + case constants_1.LogVerbosity.ERROR: + logFunction = _logger.error; + break; + } + if (!logFunction) { + logFunction = _logger.error; + } + if (logFunction) { + logFunction.bind(_logger)(...args); + } + } + }; + exports.log = log; + var tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== undefined ? _c : process.env.GRPC_TRACE) !== null && _d !== undefined ? _d : ""; + var enabledTracers = new Set; + var disabledTracers = new Set; + for (const tracerName of tracersString.split(",")) { + if (tracerName.startsWith("-")) { + disabledTracers.add(tracerName.substring(1)); + } else { + enabledTracers.add(tracerName); + } + } + var allEnabled = enabledTracers.has("all"); + function trace(severity, tracer, text) { + if (isTracerEnabled(tracer)) { + (0, exports.log)(severity, new Date().toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer + " | " + text); + } + } + function isTracerEnabled(tracer) { + return !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer)); + } +}); + +// node_modules/@grpc/grpc-js/build/src/error.js +var require_error2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getErrorMessage = getErrorMessage; + exports.getErrorCode = getErrorCode; + function getErrorMessage(error) { + if (error instanceof Error) { + return error.message; + } else { + return String(error); + } + } + function getErrorCode(error) { + if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "number") { + return error.code; + } else { + return null; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/metadata.js +var require_metadata = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Metadata = undefined; + var logging_1 = require_logging(); + var constants_1 = require_constants2(); + var error_1 = require_error2(); + var LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; + var LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; + function isLegalKey(key) { + return LEGAL_KEY_REGEX.test(key); + } + function isLegalNonBinaryValue(value) { + return LEGAL_NON_BINARY_VALUE_REGEX.test(value); + } + function isBinaryKey(key) { + return key.endsWith("-bin"); + } + function isCustomMetadata(key) { + return !key.startsWith("grpc-"); + } + function normalizeKey(key) { + return key.toLowerCase(); + } + function validate(key, value) { + if (!isLegalKey(key)) { + throw new Error('Metadata key "' + key + '" contains illegal characters'); + } + if (value !== null && value !== undefined) { + if (isBinaryKey(key)) { + if (!Buffer.isBuffer(value)) { + throw new Error("keys that end with '-bin' must have Buffer values"); + } + } else { + if (Buffer.isBuffer(value)) { + throw new Error("keys that don't end with '-bin' must have String values"); + } + if (!isLegalNonBinaryValue(value)) { + throw new Error('Metadata string value "' + value + '" contains illegal characters'); + } + } + } + } + + class Metadata { + constructor(options = {}) { + this.internalRepr = new Map; + this.opaqueData = new Map; + this.options = options; + } + set(key, value) { + key = normalizeKey(key); + validate(key, value); + this.internalRepr.set(key, [value]); + } + add(key, value) { + key = normalizeKey(key); + validate(key, value); + const existingValue = this.internalRepr.get(key); + if (existingValue === undefined) { + this.internalRepr.set(key, [value]); + } else { + existingValue.push(value); + } + } + remove(key) { + key = normalizeKey(key); + this.internalRepr.delete(key); + } + get(key) { + key = normalizeKey(key); + return this.internalRepr.get(key) || []; + } + getMap() { + const result = {}; + for (const [key, values] of this.internalRepr) { + if (values.length > 0) { + const v = values[0]; + result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; + } + } + return result; + } + clone() { + const newMetadata = new Metadata(this.options); + const newInternalRepr = newMetadata.internalRepr; + for (const [key, value] of this.internalRepr) { + const clonedValue = value.map((v) => { + if (Buffer.isBuffer(v)) { + return Buffer.from(v); + } else { + return v; + } + }); + newInternalRepr.set(key, clonedValue); + } + return newMetadata; + } + merge(other) { + for (const [key, values] of other.internalRepr) { + const mergedValue = (this.internalRepr.get(key) || []).concat(values); + this.internalRepr.set(key, mergedValue); + } + } + setOptions(options) { + this.options = options; + } + getOptions() { + return this.options; + } + toHttp2Headers() { + const result = {}; + for (const [key, values] of this.internalRepr) { + if (key.startsWith(":")) { + continue; + } + result[key] = values.map(bufToString); + } + return result; + } + toJSON() { + const result = {}; + for (const [key, values] of this.internalRepr) { + result[key] = values; + } + return result; + } + setOpaque(key, value) { + this.opaqueData.set(key, value); + } + getOpaque(key) { + return this.opaqueData.get(key); + } + static fromHttp2Headers(headers) { + const result = new Metadata; + for (const key of Object.keys(headers)) { + if (key.charAt(0) === ":") { + continue; + } + const values = headers[key]; + try { + if (isBinaryKey(key)) { + if (Array.isArray(values)) { + values.forEach((value) => { + result.add(key, Buffer.from(value, "base64")); + }); + } else if (values !== undefined) { + if (isCustomMetadata(key)) { + values.split(",").forEach((v) => { + result.add(key, Buffer.from(v.trim(), "base64")); + }); + } else { + result.add(key, Buffer.from(values, "base64")); + } + } + } else { + if (Array.isArray(values)) { + values.forEach((value) => { + result.add(key, value); + }); + } else if (values !== undefined) { + result.add(key, values); + } + } + } catch (error) { + const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); + } + } + return result; + } + } + exports.Metadata = Metadata; + var bufToString = (val) => { + return Buffer.isBuffer(val) ? val.toString("base64") : val; + }; +}); + +// node_modules/@grpc/grpc-js/build/src/call-credentials.js +var require_call_credentials = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CallCredentials = undefined; + var metadata_1 = require_metadata(); + function isCurrentOauth2Client(client) { + return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function"; + } + + class CallCredentials { + static createFromMetadataGenerator(metadataGenerator) { + return new SingleCallCredentials(metadataGenerator); + } + static createFromGoogleCredential(googleCredentials) { + return CallCredentials.createFromMetadataGenerator((options, callback) => { + let getHeaders; + if (isCurrentOauth2Client(googleCredentials)) { + getHeaders = googleCredentials.getRequestHeaders(options.service_url); + } else { + getHeaders = new Promise((resolve, reject) => { + googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { + if (err) { + reject(err); + return; + } + if (!headers) { + reject(new Error("Headers not set by metadata plugin")); + return; + } + resolve(headers); + }); + }); + } + getHeaders.then((headers) => { + const metadata = new metadata_1.Metadata; + for (const key of Object.keys(headers)) { + metadata.add(key, headers[key]); + } + callback(null, metadata); + }, (err) => { + callback(err); + }); + }); + } + static createEmpty() { + return new EmptyCallCredentials; + } + } + exports.CallCredentials = CallCredentials; + + class ComposedCallCredentials extends CallCredentials { + constructor(creds) { + super(); + this.creds = creds; + } + async generateMetadata(options) { + const base = new metadata_1.Metadata; + const generated = await Promise.all(this.creds.map((cred) => cred.generateMetadata(options))); + for (const gen of generated) { + base.merge(gen); + } + return base; + } + compose(other) { + return new ComposedCallCredentials(this.creds.concat([other])); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof ComposedCallCredentials) { + return this.creds.every((value, index) => value._equals(other.creds[index])); + } else { + return false; + } + } + } + + class SingleCallCredentials extends CallCredentials { + constructor(metadataGenerator) { + super(); + this.metadataGenerator = metadataGenerator; + } + generateMetadata(options) { + return new Promise((resolve, reject) => { + this.metadataGenerator(options, (err, metadata) => { + if (metadata !== undefined) { + resolve(metadata); + } else { + reject(err); + } + }); + }); + } + compose(other) { + return new ComposedCallCredentials([this, other]); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof SingleCallCredentials) { + return this.metadataGenerator === other.metadataGenerator; + } else { + return false; + } + } + } + + class EmptyCallCredentials extends CallCredentials { + generateMetadata(options) { + return Promise.resolve(new metadata_1.Metadata); + } + compose(other) { + return other; + } + _equals(other) { + return other instanceof EmptyCallCredentials; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/tls-helpers.js +var require_tls_helpers = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CIPHER_SUITES = undefined; + exports.getDefaultRootsData = getDefaultRootsData; + var fs = __require("fs"); + exports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; + var DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; + var defaultRootsData = null; + function getDefaultRootsData() { + if (DEFAULT_ROOTS_FILE_PATH) { + if (defaultRootsData === null) { + defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); + } + return defaultRootsData; + } + return null; + } +}); + +// node_modules/@grpc/grpc-js/build/src/uri-parser.js +var require_uri_parser = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseUri = parseUri; + exports.splitHostPort = splitHostPort; + exports.combineHostPort = combineHostPort; + exports.uriToString = uriToString; + var URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; + function parseUri(uriString) { + const parsedUri = URI_REGEX.exec(uriString); + if (parsedUri === null) { + return null; + } + return { + scheme: parsedUri[1], + authority: parsedUri[2], + path: parsedUri[3] + }; + } + var NUMBER_REGEX = /^\d+$/; + function splitHostPort(path) { + if (path.startsWith("[")) { + const hostEnd = path.indexOf("]"); + if (hostEnd === -1) { + return null; + } + const host = path.substring(1, hostEnd); + if (host.indexOf(":") === -1) { + return null; + } + if (path.length > hostEnd + 1) { + if (path[hostEnd + 1] === ":") { + const portString = path.substring(hostEnd + 2); + if (NUMBER_REGEX.test(portString)) { + return { + host, + port: +portString + }; + } else { + return null; + } + } else { + return null; + } + } else { + return { + host + }; + } + } else { + const splitPath = path.split(":"); + if (splitPath.length === 2) { + if (NUMBER_REGEX.test(splitPath[1])) { + return { + host: splitPath[0], + port: +splitPath[1] + }; + } else { + return null; + } + } else { + return { + host: path + }; + } + } + } + function combineHostPort(hostPort) { + if (hostPort.port === undefined) { + return hostPort.host; + } else { + if (hostPort.host.includes(":")) { + return `[${hostPort.host}]:${hostPort.port}`; + } else { + return `${hostPort.host}:${hostPort.port}`; + } + } + } + function uriToString(uri) { + let result = ""; + if (uri.scheme !== undefined) { + result += uri.scheme + ":"; + } + if (uri.authority !== undefined) { + result += "//" + uri.authority + "/"; + } + result += uri.path; + return result; + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolver.js +var require_resolver = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = undefined; + exports.registerResolver = registerResolver; + exports.registerDefaultScheme = registerDefaultScheme; + exports.createResolver = createResolver; + exports.getDefaultAuthority = getDefaultAuthority; + exports.mapUriDefaultScheme = mapUriDefaultScheme; + var uri_parser_1 = require_uri_parser(); + exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = "grpc.internal.config_selector"; + var registeredResolvers = {}; + var defaultScheme = null; + function registerResolver(scheme, resolverClass) { + registeredResolvers[scheme] = resolverClass; + } + function registerDefaultScheme(scheme) { + defaultScheme = scheme; + } + function createResolver(target, listener, options) { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return new registeredResolvers[target.scheme](target, listener, options); + } else { + throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); + } + } + function getDefaultAuthority(target) { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return registeredResolvers[target.scheme].getDefaultAuthority(target); + } else { + throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); + } + } + function mapUriDefaultScheme(target) { + if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { + if (defaultScheme !== null) { + return { + scheme: defaultScheme, + authority: undefined, + path: (0, uri_parser_1.uriToString)(target) + }; + } else { + return null; + } + } + return target; + } +}); + +// node_modules/@grpc/grpc-js/build/src/channel-credentials.js +var require_channel_credentials = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChannelCredentials = undefined; + exports.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials; + var tls_1 = __require("tls"); + var call_credentials_1 = require_call_credentials(); + var tls_helpers_1 = require_tls_helpers(); + var uri_parser_1 = require_uri_parser(); + var resolver_1 = require_resolver(); + var logging_1 = require_logging(); + var constants_1 = require_constants2(); + function verifyIsBufferOrNull(obj, friendlyName) { + if (obj && !(obj instanceof Buffer)) { + throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); + } + } + + class ChannelCredentials { + compose(callCredentials) { + return new ComposedChannelCredentialsImpl(this, callCredentials); + } + static createSsl(rootCerts, privateKey, certChain, verifyOptions) { + var _a; + verifyIsBufferOrNull(rootCerts, "Root certificate"); + verifyIsBufferOrNull(privateKey, "Private key"); + verifyIsBufferOrNull(certChain, "Certificate chain"); + if (privateKey && !certChain) { + throw new Error("Private key must be given with accompanying certificate chain"); + } + if (!privateKey && certChain) { + throw new Error("Certificate chain must be given with accompanying private key"); + } + const secureContext = (0, tls_1.createSecureContext)({ + ca: (_a = rootCerts !== null && rootCerts !== undefined ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== undefined ? _a : undefined, + key: privateKey !== null && privateKey !== undefined ? privateKey : undefined, + cert: certChain !== null && certChain !== undefined ? certChain : undefined, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== undefined ? verifyOptions : {}); + } + static createFromSecureContext(secureContext, verifyOptions) { + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== undefined ? verifyOptions : {}); + } + static createInsecure() { + return new InsecureChannelCredentialsImpl; + } + } + exports.ChannelCredentials = ChannelCredentials; + + class InsecureChannelCredentialsImpl extends ChannelCredentials { + constructor() { + super(); + } + compose(callCredentials) { + throw new Error("Cannot compose insecure credentials"); + } + _isSecure() { + return false; + } + _equals(other) { + return other instanceof InsecureChannelCredentialsImpl; + } + _createSecureConnector(channelTarget, options, callCredentials) { + return { + connect(socket) { + return Promise.resolve({ + socket, + secure: false + }); + }, + waitForReady: () => { + return Promise.resolve(); + }, + getCallCredentials: () => { + return callCredentials !== null && callCredentials !== undefined ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); + }, + destroy() {} + }; + } + } + function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) { + var _a, _b; + const connectionOptions = { + secureContext + }; + let realTarget = channelTarget; + if ("grpc.http_connect_target" in options) { + const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]); + if (parsedTarget) { + realTarget = parsedTarget; + } + } + const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); + const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); + const remoteHost = (_a = hostPort === null || hostPort === undefined ? undefined : hostPort.host) !== null && _a !== undefined ? _a : targetPath; + connectionOptions.host = remoteHost; + if (verifyOptions.checkServerIdentity) { + connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; + } + if (verifyOptions.rejectUnauthorized !== undefined) { + connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; + } + connectionOptions.ALPNProtocols = ["h2"]; + if (options["grpc.ssl_target_name_override"]) { + const sslTargetNameOverride = options["grpc.ssl_target_name_override"]; + const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== undefined ? _b : tls_1.checkServerIdentity; + connectionOptions.checkServerIdentity = (host, cert) => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } else { + connectionOptions.servername = remoteHost; + } + if (options["grpc-node.tls_enable_trace"]) { + connectionOptions.enableTrace = true; + } + return connectionOptions; + } + + class SecureConnectorImpl { + constructor(connectionOptions, callCredentials) { + this.connectionOptions = connectionOptions; + this.callCredentials = callCredentials; + } + connect(socket) { + const tlsConnectOptions = Object.assign({ socket }, this.connectionOptions); + return new Promise((resolve, reject) => { + const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { + var _a; + if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== undefined ? _a : true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }); + }); + tlsSocket.on("error", (error) => { + reject(error); + }); + }); + } + waitForReady() { + return Promise.resolve(); + } + getCallCredentials() { + return this.callCredentials; + } + destroy() {} + } + + class SecureChannelCredentialsImpl extends ChannelCredentials { + constructor(secureContext, verifyOptions) { + super(); + this.secureContext = secureContext; + this.verifyOptions = verifyOptions; + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof SecureChannelCredentialsImpl) { + return this.secureContext === other.secureContext && this.verifyOptions.checkServerIdentity === other.verifyOptions.checkServerIdentity; + } else { + return false; + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); + return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== undefined ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + } + } + + class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { + constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) { + super(); + this.caCertificateProvider = caCertificateProvider; + this.identityCertificateProvider = identityCertificateProvider; + this.verifyOptions = verifyOptions; + this.refcount = 0; + this.latestCaUpdate = undefined; + this.latestIdentityUpdate = undefined; + this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + this.secureContextWatchers = []; + } + _isSecure() { + return true; + } + _equals(other) { + var _a, _b; + if (this === other) { + return true; + } + if (other instanceof CertificateProviderChannelCredentialsImpl) { + return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && ((_a = this.verifyOptions) === null || _a === undefined ? undefined : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === undefined ? undefined : _b.checkServerIdentity); + } else { + return false; + } + } + ref() { + var _a; + if (this.refcount === 0) { + this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); + (_a = this.identityCertificateProvider) === null || _a === undefined || _a.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + this.refcount += 1; + } + unref() { + var _a; + this.refcount -= 1; + if (this.refcount === 0) { + this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); + (_a = this.identityCertificateProvider) === null || _a === undefined || _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + this.ref(); + return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== undefined ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + } + maybeUpdateWatchers() { + if (this.hasReceivedUpdates()) { + for (const watcher of this.secureContextWatchers) { + watcher(this.getLatestSecureContext()); + } + this.secureContextWatchers = []; + } + } + handleCaCertificateUpdate(update) { + this.latestCaUpdate = update; + this.maybeUpdateWatchers(); + } + handleIdentityCertitificateUpdate(update) { + this.latestIdentityUpdate = update; + this.maybeUpdateWatchers(); + } + hasReceivedUpdates() { + if (this.latestCaUpdate === undefined) { + return false; + } + if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { + return false; + } + return true; + } + getSecureContext() { + if (this.hasReceivedUpdates()) { + return Promise.resolve(this.getLatestSecureContext()); + } else { + return new Promise((resolve) => { + this.secureContextWatchers.push(resolve); + }); + } + } + getLatestSecureContext() { + var _a, _b; + if (!this.latestCaUpdate) { + return null; + } + if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { + return null; + } + try { + return (0, tls_1.createSecureContext)({ + ca: this.latestCaUpdate.caCertificate, + key: (_a = this.latestIdentityUpdate) === null || _a === undefined ? undefined : _a.privateKey, + cert: (_b = this.latestIdentityUpdate) === null || _b === undefined ? undefined : _b.certificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + } catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to createSecureContext with error " + e.message); + return null; + } + } + } + CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class { + constructor(parent, channelTarget, options, callCredentials) { + this.parent = parent; + this.channelTarget = channelTarget; + this.options = options; + this.callCredentials = callCredentials; + } + connect(socket) { + return new Promise((resolve, reject) => { + const secureContext = this.parent.getLatestSecureContext(); + if (!secureContext) { + reject(new Error("Failed to load credentials")); + return; + } + if (socket.closed) { + reject(new Error("Socket closed while loading credentials")); + } + const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); + const tlsConnectOptions = Object.assign({ socket }, connnectionOptions); + const closeCallback = () => { + reject(new Error("Socket closed")); + }; + const errorCallback = (error) => { + reject(error); + }; + const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { + var _a; + tlsSocket.removeListener("close", closeCallback); + tlsSocket.removeListener("error", errorCallback); + if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== undefined ? _a : true) && !tlsSocket.authorized) { + reject(tlsSocket.authorizationError); + return; + } + resolve({ + socket: tlsSocket, + secure: true + }); + }); + tlsSocket.once("close", closeCallback); + tlsSocket.once("error", errorCallback); + }); + } + async waitForReady() { + await this.parent.getSecureContext(); + } + getCallCredentials() { + return this.callCredentials; + } + destroy() { + this.parent.unref(); + } + }; + function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) { + return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== undefined ? verifyOptions : {}); + } + + class ComposedChannelCredentialsImpl extends ChannelCredentials { + constructor(channelCredentials, callCredentials) { + super(); + this.channelCredentials = channelCredentials; + this.callCredentials = callCredentials; + if (!channelCredentials._isSecure()) { + throw new Error("Cannot compose insecure credentials"); + } + } + compose(callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials); + return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof ComposedChannelCredentialsImpl) { + return this.channelCredentials._equals(other.channelCredentials) && this.callCredentials._equals(other.callCredentials); + } else { + return false; + } + } + _createSecureConnector(channelTarget, options, callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== undefined ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); + return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer.js +var require_load_balancer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createChildChannelControlHelper = createChildChannelControlHelper; + exports.registerLoadBalancerType = registerLoadBalancerType; + exports.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; + exports.createLoadBalancer = createLoadBalancer; + exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; + exports.parseLoadBalancingConfig = parseLoadBalancingConfig; + exports.getDefaultConfig = getDefaultConfig; + exports.selectLbConfigFromList = selectLbConfigFromList; + var logging_1 = require_logging(); + var constants_1 = require_constants2(); + function createChildChannelControlHelper(parent, overrides) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + return { + createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === undefined ? undefined : _a.bind(overrides)) !== null && _b !== undefined ? _b : parent.createSubchannel.bind(parent), + updateState: (_d = (_c = overrides.updateState) === null || _c === undefined ? undefined : _c.bind(overrides)) !== null && _d !== undefined ? _d : parent.updateState.bind(parent), + requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === undefined ? undefined : _e.bind(overrides)) !== null && _f !== undefined ? _f : parent.requestReresolution.bind(parent), + addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === undefined ? undefined : _g.bind(overrides)) !== null && _h !== undefined ? _h : parent.addChannelzChild.bind(parent), + removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === undefined ? undefined : _j.bind(overrides)) !== null && _k !== undefined ? _k : parent.removeChannelzChild.bind(parent) + }; + } + var registeredLoadBalancerTypes = {}; + var defaultLoadBalancerType = null; + function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { + registeredLoadBalancerTypes[typeName] = { + LoadBalancer: loadBalancerType, + LoadBalancingConfig: loadBalancingConfigType + }; + } + function registerDefaultLoadBalancerType(typeName) { + defaultLoadBalancerType = typeName; + } + function createLoadBalancer(config, channelControlHelper) { + const typeName = config.getLoadBalancerName(); + if (typeName in registeredLoadBalancerTypes) { + return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper); + } else { + return null; + } + } + function isLoadBalancerNameRegistered(typeName) { + return typeName in registeredLoadBalancerTypes; + } + function parseLoadBalancingConfig(rawConfig) { + const keys = Object.keys(rawConfig); + if (keys.length !== 1) { + throw new Error("Provided load balancing config has multiple conflicting entries"); + } + const typeName = keys[0]; + if (typeName in registeredLoadBalancerTypes) { + try { + return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); + } catch (e) { + throw new Error(`${typeName}: ${e.message}`); + } + } else { + throw new Error(`Unrecognized load balancing config name ${typeName}`); + } + } + function getDefaultConfig() { + if (!defaultLoadBalancerType) { + throw new Error("No default load balancer type registered"); + } + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig; + } + function selectLbConfigFromList(configs, fallbackTodefault = false) { + for (const config of configs) { + try { + return parseLoadBalancingConfig(config); + } catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, "Config parsing failed with error", e.message); + continue; + } + } + if (fallbackTodefault) { + if (defaultLoadBalancerType) { + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig; + } else { + return null; + } + } else { + return null; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/service-config.js +var require_service_config = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateRetryThrottling = validateRetryThrottling; + exports.validateServiceConfig = validateServiceConfig; + exports.extractAndSelectServiceConfig = extractAndSelectServiceConfig; + var os = __require("os"); + var constants_1 = require_constants2(); + var DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; + var CLIENT_LANGUAGE_STRING = "node"; + function validateName(obj) { + if ("service" in obj && obj.service !== "") { + if (typeof obj.service !== "string") { + throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); + } + if ("method" in obj && obj.method !== "") { + if (typeof obj.method !== "string") { + throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); + } + return { + service: obj.service, + method: obj.method + }; + } else { + return { + service: obj.service + }; + } + } else { + if ("method" in obj && obj.method !== undefined) { + throw new Error(`Invalid method config name: method set with empty or unset service`); + } + return {}; + } + } + function validateRetryPolicy(obj) { + if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) { + throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2"); + } + if (!("initialBackoff" in obj) || typeof obj.initialBackoff !== "string" || !DURATION_REGEX.test(obj.initialBackoff)) { + throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s"); + } + if (!("maxBackoff" in obj) || typeof obj.maxBackoff !== "string" || !DURATION_REGEX.test(obj.maxBackoff)) { + throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s"); + } + if (!("backoffMultiplier" in obj) || typeof obj.backoffMultiplier !== "number" || obj.backoffMultiplier <= 0) { + throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0"); + } + if (!(("retryableStatusCodes" in obj) && Array.isArray(obj.retryableStatusCodes))) { + throw new Error("Invalid method config retry policy: retryableStatusCodes is required"); + } + if (obj.retryableStatusCodes.length === 0) { + throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty"); + } + for (const value of obj.retryableStatusCodes) { + if (typeof value === "number") { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range"); + } + } else if (typeof value === "string") { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name"); + } + } else { + throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number"); + } + } + return { + maxAttempts: obj.maxAttempts, + initialBackoff: obj.initialBackoff, + maxBackoff: obj.maxBackoff, + backoffMultiplier: obj.backoffMultiplier, + retryableStatusCodes: obj.retryableStatusCodes + }; + } + function validateHedgingPolicy(obj) { + if (!("maxAttempts" in obj) || !Number.isInteger(obj.maxAttempts) || obj.maxAttempts < 2) { + throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2"); + } + if ("hedgingDelay" in obj && (typeof obj.hedgingDelay !== "string" || !DURATION_REGEX.test(obj.hedgingDelay))) { + throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s"); + } + if ("nonFatalStatusCodes" in obj && Array.isArray(obj.nonFatalStatusCodes)) { + for (const value of obj.nonFatalStatusCodes) { + if (typeof value === "number") { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range"); + } + } else if (typeof value === "string") { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name"); + } + } else { + throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number"); + } + } + } + const result = { + maxAttempts: obj.maxAttempts + }; + if (obj.hedgingDelay) { + result.hedgingDelay = obj.hedgingDelay; + } + if (obj.nonFatalStatusCodes) { + result.nonFatalStatusCodes = obj.nonFatalStatusCodes; + } + return result; + } + function validateMethodConfig(obj) { + var _a; + const result = { + name: [] + }; + if (!("name" in obj) || !Array.isArray(obj.name)) { + throw new Error("Invalid method config: invalid name array"); + } + for (const name of obj.name) { + result.name.push(validateName(name)); + } + if ("waitForReady" in obj) { + if (typeof obj.waitForReady !== "boolean") { + throw new Error("Invalid method config: invalid waitForReady"); + } + result.waitForReady = obj.waitForReady; + } + if ("timeout" in obj) { + if (typeof obj.timeout === "object") { + if (!("seconds" in obj.timeout) || !(typeof obj.timeout.seconds === "number")) { + throw new Error("Invalid method config: invalid timeout.seconds"); + } + if (!("nanos" in obj.timeout) || !(typeof obj.timeout.nanos === "number")) { + throw new Error("Invalid method config: invalid timeout.nanos"); + } + result.timeout = obj.timeout; + } else if (typeof obj.timeout === "string" && DURATION_REGEX.test(obj.timeout)) { + const timeoutParts = obj.timeout.substring(0, obj.timeout.length - 1).split("."); + result.timeout = { + seconds: timeoutParts[0] | 0, + nanos: ((_a = timeoutParts[1]) !== null && _a !== undefined ? _a : 0) | 0 + }; + } else { + throw new Error("Invalid method config: invalid timeout"); + } + } + if ("maxRequestBytes" in obj) { + if (typeof obj.maxRequestBytes !== "number") { + throw new Error("Invalid method config: invalid maxRequestBytes"); + } + result.maxRequestBytes = obj.maxRequestBytes; + } + if ("maxResponseBytes" in obj) { + if (typeof obj.maxResponseBytes !== "number") { + throw new Error("Invalid method config: invalid maxRequestBytes"); + } + result.maxResponseBytes = obj.maxResponseBytes; + } + if ("retryPolicy" in obj) { + if ("hedgingPolicy" in obj) { + throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified"); + } else { + result.retryPolicy = validateRetryPolicy(obj.retryPolicy); + } + } else if ("hedgingPolicy" in obj) { + result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); + } + return result; + } + function validateRetryThrottling(obj) { + if (!("maxTokens" in obj) || typeof obj.maxTokens !== "number" || obj.maxTokens <= 0 || obj.maxTokens > 1000) { + throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]"); + } + if (!("tokenRatio" in obj) || typeof obj.tokenRatio !== "number" || obj.tokenRatio <= 0) { + throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0"); + } + return { + maxTokens: +obj.maxTokens.toFixed(3), + tokenRatio: +obj.tokenRatio.toFixed(3) + }; + } + function validateLoadBalancingConfig(obj) { + if (!(typeof obj === "object" && obj !== null)) { + throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); + } + const keys = Object.keys(obj); + if (keys.length > 1) { + throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); + } + if (keys.length === 0) { + throw new Error("Invalid loadBalancingConfig: load balancing policy name required"); + } + return { + [keys[0]]: obj[keys[0]] + }; + } + function validateServiceConfig(obj) { + const result = { + loadBalancingConfig: [], + methodConfig: [] + }; + if ("loadBalancingPolicy" in obj) { + if (typeof obj.loadBalancingPolicy === "string") { + result.loadBalancingPolicy = obj.loadBalancingPolicy; + } else { + throw new Error("Invalid service config: invalid loadBalancingPolicy"); + } + } + if ("loadBalancingConfig" in obj) { + if (Array.isArray(obj.loadBalancingConfig)) { + for (const config of obj.loadBalancingConfig) { + result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); + } + } else { + throw new Error("Invalid service config: invalid loadBalancingConfig"); + } + } + if ("methodConfig" in obj) { + if (Array.isArray(obj.methodConfig)) { + for (const methodConfig of obj.methodConfig) { + result.methodConfig.push(validateMethodConfig(methodConfig)); + } + } + } + if ("retryThrottling" in obj) { + result.retryThrottling = validateRetryThrottling(obj.retryThrottling); + } + const seenMethodNames = []; + for (const methodConfig of result.methodConfig) { + for (const name of methodConfig.name) { + for (const seenName of seenMethodNames) { + if (name.service === seenName.service && name.method === seenName.method) { + throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); + } + } + seenMethodNames.push(name); + } + } + return result; + } + function validateCanaryConfig(obj) { + if (!("serviceConfig" in obj)) { + throw new Error("Invalid service config choice: missing service config"); + } + const result = { + serviceConfig: validateServiceConfig(obj.serviceConfig) + }; + if ("clientLanguage" in obj) { + if (Array.isArray(obj.clientLanguage)) { + result.clientLanguage = []; + for (const lang of obj.clientLanguage) { + if (typeof lang === "string") { + result.clientLanguage.push(lang); + } else { + throw new Error("Invalid service config choice: invalid clientLanguage"); + } + } + } else { + throw new Error("Invalid service config choice: invalid clientLanguage"); + } + } + if ("clientHostname" in obj) { + if (Array.isArray(obj.clientHostname)) { + result.clientHostname = []; + for (const lang of obj.clientHostname) { + if (typeof lang === "string") { + result.clientHostname.push(lang); + } else { + throw new Error("Invalid service config choice: invalid clientHostname"); + } + } + } else { + throw new Error("Invalid service config choice: invalid clientHostname"); + } + } + if ("percentage" in obj) { + if (typeof obj.percentage === "number" && 0 <= obj.percentage && obj.percentage <= 100) { + result.percentage = obj.percentage; + } else { + throw new Error("Invalid service config choice: invalid percentage"); + } + } + const allowedFields = [ + "clientLanguage", + "percentage", + "clientHostname", + "serviceConfig" + ]; + for (const field in obj) { + if (!allowedFields.includes(field)) { + throw new Error(`Invalid service config choice: unexpected field ${field}`); + } + } + return result; + } + function validateAndSelectCanaryConfig(obj, percentage) { + if (!Array.isArray(obj)) { + throw new Error("Invalid service config list"); + } + for (const config of obj) { + const validatedConfig = validateCanaryConfig(config); + if (typeof validatedConfig.percentage === "number" && percentage > validatedConfig.percentage) { + continue; + } + if (Array.isArray(validatedConfig.clientHostname)) { + let hostnameMatched = false; + for (const hostname of validatedConfig.clientHostname) { + if (hostname === os.hostname()) { + hostnameMatched = true; + } + } + if (!hostnameMatched) { + continue; + } + } + if (Array.isArray(validatedConfig.clientLanguage)) { + let languageMatched = false; + for (const language of validatedConfig.clientLanguage) { + if (language === CLIENT_LANGUAGE_STRING) { + languageMatched = true; + } + } + if (!languageMatched) { + continue; + } + } + return validatedConfig.serviceConfig; + } + throw new Error("No matching service config found"); + } + function extractAndSelectServiceConfig(txtRecord, percentage) { + for (const record of txtRecord) { + if (record.length > 0 && record[0].startsWith("grpc_config=")) { + const recordString = record.join("").substring("grpc_config=".length); + const recordJson = JSON.parse(recordString); + return validateAndSelectCanaryConfig(recordJson, percentage); + } + } + return null; + } +}); + +// node_modules/@grpc/grpc-js/build/src/connectivity-state.js +var require_connectivity_state = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConnectivityState = undefined; + var ConnectivityState; + (function(ConnectivityState2) { + ConnectivityState2[ConnectivityState2["IDLE"] = 0] = "IDLE"; + ConnectivityState2[ConnectivityState2["CONNECTING"] = 1] = "CONNECTING"; + ConnectivityState2[ConnectivityState2["READY"] = 2] = "READY"; + ConnectivityState2[ConnectivityState2["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; + ConnectivityState2[ConnectivityState2["SHUTDOWN"] = 4] = "SHUTDOWN"; + })(ConnectivityState || (exports.ConnectivityState = ConnectivityState = {})); +}); + +// node_modules/@grpc/grpc-js/build/src/picker.js +var require_picker = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = undefined; + var metadata_1 = require_metadata(); + var constants_1 = require_constants2(); + var PickResultType; + (function(PickResultType2) { + PickResultType2[PickResultType2["COMPLETE"] = 0] = "COMPLETE"; + PickResultType2[PickResultType2["QUEUE"] = 1] = "QUEUE"; + PickResultType2[PickResultType2["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; + PickResultType2[PickResultType2["DROP"] = 3] = "DROP"; + })(PickResultType || (exports.PickResultType = PickResultType = {})); + + class UnavailablePicker { + constructor(status) { + this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: "No connection established", metadata: new metadata_1.Metadata }, status); + } + pick(pickArgs) { + return { + pickResultType: PickResultType.TRANSIENT_FAILURE, + subchannel: null, + status: this.status, + onCallStarted: null, + onCallEnded: null + }; + } + } + exports.UnavailablePicker = UnavailablePicker; + + class QueuePicker { + constructor(loadBalancer, childPicker) { + this.loadBalancer = loadBalancer; + this.childPicker = childPicker; + this.calledExitIdle = false; + } + pick(pickArgs) { + if (!this.calledExitIdle) { + process.nextTick(() => { + this.loadBalancer.exitIdle(); + }); + this.calledExitIdle = true; + } + if (this.childPicker) { + return this.childPicker.pick(pickArgs); + } else { + return { + pickResultType: PickResultType.QUEUE, + subchannel: null, + status: null, + onCallStarted: null, + onCallEnded: null + }; + } + } + } + exports.QueuePicker = QueuePicker; +}); + +// node_modules/@grpc/grpc-js/build/src/backoff-timeout.js +var require_backoff_timeout = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BackoffTimeout = undefined; + var constants_1 = require_constants2(); + var logging = require_logging(); + var TRACER_NAME = "backoff"; + var INITIAL_BACKOFF_MS = 1000; + var BACKOFF_MULTIPLIER = 1.6; + var MAX_BACKOFF_MS = 120000; + var BACKOFF_JITTER = 0.2; + function uniformRandom(min, max) { + return Math.random() * (max - min) + min; + } + + class BackoffTimeout { + constructor(callback, options) { + this.callback = callback; + this.initialDelay = INITIAL_BACKOFF_MS; + this.multiplier = BACKOFF_MULTIPLIER; + this.maxDelay = MAX_BACKOFF_MS; + this.jitter = BACKOFF_JITTER; + this.running = false; + this.hasRef = true; + this.startTime = new Date; + this.endTime = new Date; + this.id = BackoffTimeout.getNextId(); + if (options) { + if (options.initialDelay) { + this.initialDelay = options.initialDelay; + } + if (options.multiplier) { + this.multiplier = options.multiplier; + } + if (options.jitter) { + this.jitter = options.jitter; + } + if (options.maxDelay) { + this.maxDelay = options.maxDelay; + } + } + this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay); + this.nextDelay = this.initialDelay; + this.timerId = setTimeout(() => {}, 0); + clearTimeout(this.timerId); + } + static getNextId() { + return this.nextId++; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text); + } + runTimer(delay) { + var _a, _b; + this.trace("runTimer(delay=" + delay + ")"); + this.endTime = this.startTime; + this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); + clearTimeout(this.timerId); + this.timerId = setTimeout(() => { + this.trace("timer fired"); + this.running = false; + this.callback(); + }, delay); + if (!this.hasRef) { + (_b = (_a = this.timerId).unref) === null || _b === undefined || _b.call(_a); + } + } + runOnce() { + this.trace("runOnce()"); + this.running = true; + this.startTime = new Date; + this.runTimer(this.nextDelay); + const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); + const jitterMagnitude = nextBackoff * this.jitter; + this.nextDelay = nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); + } + stop() { + this.trace("stop()"); + clearTimeout(this.timerId); + this.running = false; + } + reset() { + this.trace("reset() running=" + this.running); + this.nextDelay = this.initialDelay; + if (this.running) { + const now = new Date; + const newEndTime = this.startTime; + newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); + clearTimeout(this.timerId); + if (now < newEndTime) { + this.runTimer(newEndTime.getTime() - now.getTime()); + } else { + this.running = false; + } + } + } + isRunning() { + return this.running; + } + ref() { + var _a, _b; + this.hasRef = true; + (_b = (_a = this.timerId).ref) === null || _b === undefined || _b.call(_a); + } + unref() { + var _a, _b; + this.hasRef = false; + (_b = (_a = this.timerId).unref) === null || _b === undefined || _b.call(_a); + } + getEndTime() { + return this.endTime; + } + } + exports.BackoffTimeout = BackoffTimeout; + BackoffTimeout.nextId = 0; +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js +var require_load_balancer_child_handler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChildLoadBalancerHandler = undefined; + var load_balancer_1 = require_load_balancer(); + var connectivity_state_1 = require_connectivity_state(); + var TYPE_NAME = "child_load_balancer_helper"; + + class ChildLoadBalancerHandler { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.currentChild = null; + this.pendingChild = null; + this.latestConfig = null; + this.ChildPolicyHelper = class { + constructor(parent) { + this.parent = parent; + this.child = null; + } + createSubchannel(subchannelAddress, subchannelArgs) { + return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + } + updateState(connectivityState, picker, errorMessage) { + var _a; + if (this.calledByPendingChild()) { + if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { + return; + } + (_a = this.parent.currentChild) === null || _a === undefined || _a.destroy(); + this.parent.currentChild = this.parent.pendingChild; + this.parent.pendingChild = null; + } else if (!this.calledByCurrentChild()) { + return; + } + this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + requestReresolution() { + var _a; + const latestChild = (_a = this.parent.pendingChild) !== null && _a !== undefined ? _a : this.parent.currentChild; + if (this.child === latestChild) { + this.parent.channelControlHelper.requestReresolution(); + } + } + setChild(newChild) { + this.child = newChild; + } + addChannelzChild(child) { + this.parent.channelControlHelper.addChannelzChild(child); + } + removeChannelzChild(child) { + this.parent.channelControlHelper.removeChannelzChild(child); + } + calledByPendingChild() { + return this.child === this.parent.pendingChild; + } + calledByCurrentChild() { + return this.child === this.parent.currentChild; + } + }; + } + configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { + return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); + } + updateAddressList(endpointList, lbConfig, options, resolutionNote) { + let childToUpdate; + if (this.currentChild === null || this.latestConfig === null || this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { + const newHelper = new this.ChildPolicyHelper(this); + const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper); + newHelper.setChild(newChild); + if (this.currentChild === null) { + this.currentChild = newChild; + childToUpdate = this.currentChild; + } else { + if (this.pendingChild) { + this.pendingChild.destroy(); + } + this.pendingChild = newChild; + childToUpdate = this.pendingChild; + } + } else { + if (this.pendingChild === null) { + childToUpdate = this.currentChild; + } else { + childToUpdate = this.pendingChild; + } + } + this.latestConfig = lbConfig; + return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); + } + exitIdle() { + if (this.currentChild) { + this.currentChild.exitIdle(); + if (this.pendingChild) { + this.pendingChild.exitIdle(); + } + } + } + resetBackoff() { + if (this.currentChild) { + this.currentChild.resetBackoff(); + if (this.pendingChild) { + this.pendingChild.resetBackoff(); + } + } + } + destroy() { + if (this.currentChild) { + this.currentChild.destroy(); + this.currentChild = null; + } + if (this.pendingChild) { + this.pendingChild.destroy(); + this.pendingChild = null; + } + } + getTypeName() { + return TYPE_NAME; + } + } + exports.ChildLoadBalancerHandler = ChildLoadBalancerHandler; +}); + +// node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js +var require_resolving_load_balancer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResolvingLoadBalancer = undefined; + var load_balancer_1 = require_load_balancer(); + var service_config_1 = require_service_config(); + var connectivity_state_1 = require_connectivity_state(); + var resolver_1 = require_resolver(); + var picker_1 = require_picker(); + var backoff_timeout_1 = require_backoff_timeout(); + var constants_1 = require_constants2(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var constants_2 = require_constants2(); + var uri_parser_1 = require_uri_parser(); + var load_balancer_child_handler_1 = require_load_balancer_child_handler(); + var TRACER_NAME = "resolving_load_balancer"; + function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var NAME_MATCH_LEVEL_ORDER = [ + "SERVICE_AND_METHOD", + "SERVICE", + "EMPTY" + ]; + function hasMatchingName(service, method, methodConfig, matchLevel) { + for (const name of methodConfig.name) { + switch (matchLevel) { + case "EMPTY": + if (!name.service && !name.method) { + return true; + } + break; + case "SERVICE": + if (name.service === service && !name.method) { + return true; + } + break; + case "SERVICE_AND_METHOD": + if (name.service === service && name.method === method) { + return true; + } + } + } + return false; + } + function findMatchingConfig(service, method, methodConfigs, matchLevel) { + for (const config of methodConfigs) { + if (hasMatchingName(service, method, config, matchLevel)) { + return config; + } + } + return null; + } + function getDefaultConfigSelector(serviceConfig) { + return { + invoke(methodName, metadata) { + var _a, _b; + const splitName = methodName.split("/").filter((x) => x.length > 0); + const service = (_a = splitName[0]) !== null && _a !== undefined ? _a : ""; + const method = (_b = splitName[1]) !== null && _b !== undefined ? _b : ""; + if (serviceConfig && serviceConfig.methodConfig) { + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); + if (matchingConfig) { + return { + methodConfig: matchingConfig, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [] + }; + } + } + } + return { + methodConfig: { name: [] }, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [] + }; + }, + unref() {} + }; + } + + class ResolvingLoadBalancer { + constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { + this.target = target; + this.channelControlHelper = channelControlHelper; + this.channelOptions = channelOptions; + this.onSuccessfulResolution = onSuccessfulResolution; + this.onFailedResolution = onFailedResolution; + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + this.latestChildErrorMessage = null; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + if (channelOptions["grpc.service_config"]) { + this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions["grpc.service_config"])); + } else { + this.defaultServiceConfig = { + loadBalancingConfig: [], + methodConfig: [] + }; + } + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ + createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), + requestReresolution: () => { + if (this.backoffTimeout.isRunning()) { + trace("requestReresolution delayed by backoff timer until " + this.backoffTimeout.getEndTime().toISOString()); + this.continueResolving = true; + } else { + this.updateResolution(); + } + }, + updateState: (newState, picker, errorMessage) => { + this.latestChildState = newState; + this.latestChildPicker = picker; + this.latestChildErrorMessage = errorMessage; + this.updateState(newState, picker, errorMessage); + }, + addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), + removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper) + }); + this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions); + const backoffOptions = { + initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"], + maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"] + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.updateResolution(); + this.continueResolving = false; + } else { + this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); + } + }, backoffOptions); + this.backoffTimeout.unref(); + } + handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) { + var _a, _b; + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + let resultAccepted = true; + let workingServiceConfig = null; + if (serviceConfig === null) { + workingServiceConfig = this.defaultServiceConfig; + } else if (serviceConfig.ok) { + workingServiceConfig = serviceConfig.value; + } else { + if (this.previousServiceConfig !== null) { + workingServiceConfig = this.previousServiceConfig; + } else { + resultAccepted = false; + this.handleResolutionFailure(serviceConfig.error); + } + } + if (workingServiceConfig !== null) { + const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === undefined ? undefined : workingServiceConfig.loadBalancingConfig) !== null && _a !== undefined ? _a : []; + const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); + if (loadBalancingConfig === null) { + resultAccepted = false; + this.handleResolutionFailure({ + code: constants_1.Status.UNAVAILABLE, + details: "All load balancer options in service config are not compatible", + metadata: new metadata_1.Metadata + }); + } else { + resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote); + } + } + if (resultAccepted) { + this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== undefined ? _b : getDefaultConfigSelector(workingServiceConfig)); + } + return resultAccepted; + } + updateResolution() { + this.innerResolver.updateResolution(); + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); + } + this.backoffTimeout.runOnce(); + } + updateState(connectivityState, picker, errorMessage) { + trace((0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[connectivityState]); + if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { + picker = new picker_1.QueuePicker(this, picker); + } + this.currentState = connectivityState; + this.channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + handleResolutionFailure(error) { + if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error), error.details); + this.onFailedResolution(error); + } + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + if (this.backoffTimeout.isRunning()) { + this.continueResolving = true; + } else { + this.updateResolution(); + } + } + this.childLoadBalancer.exitIdle(); + } + updateAddressList(endpointList, lbConfig) { + throw new Error("updateAddressList not supported on ResolvingLoadBalancer"); + } + resetBackoff() { + this.backoffTimeout.reset(); + this.childLoadBalancer.resetBackoff(); + } + destroy() { + this.childLoadBalancer.destroy(); + this.innerResolver.destroy(); + this.backoffTimeout.reset(); + this.backoffTimeout.stop(); + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + } + getTypeName() { + return "resolving_load_balancer"; + } + } + exports.ResolvingLoadBalancer = ResolvingLoadBalancer; +}); + +// node_modules/@grpc/grpc-js/build/src/channel-options.js +var require_channel_options = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.recognizedOptions = undefined; + exports.channelOptionsEqual = channelOptionsEqual; + exports.recognizedOptions = { + "grpc.ssl_target_name_override": true, + "grpc.primary_user_agent": true, + "grpc.secondary_user_agent": true, + "grpc.default_authority": true, + "grpc.keepalive_time_ms": true, + "grpc.keepalive_timeout_ms": true, + "grpc.keepalive_permit_without_calls": true, + "grpc.service_config": true, + "grpc.max_concurrent_streams": true, + "grpc.initial_reconnect_backoff_ms": true, + "grpc.max_reconnect_backoff_ms": true, + "grpc.use_local_subchannel_pool": true, + "grpc.max_send_message_length": true, + "grpc.max_receive_message_length": true, + "grpc.enable_http_proxy": true, + "grpc.enable_channelz": true, + "grpc.dns_min_time_between_resolutions_ms": true, + "grpc.enable_retries": true, + "grpc.per_rpc_retry_buffer_size": true, + "grpc.retry_buffer_size": true, + "grpc.max_connection_age_ms": true, + "grpc.max_connection_age_grace_ms": true, + "grpc-node.max_session_memory": true, + "grpc.service_config_disable_resolution": true, + "grpc.client_idle_timeout_ms": true, + "grpc-node.tls_enable_trace": true, + "grpc.lb.ring_hash.ring_size_cap": true, + "grpc-node.retry_max_attempts_limit": true, + "grpc-node.flow_control_window": true, + "grpc.server_call_metric_recording": true + }; + function channelOptionsEqual(options1, options2) { + const keys1 = Object.keys(options1).sort(); + const keys2 = Object.keys(options2).sort(); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0;i < keys1.length; i += 1) { + if (keys1[i] !== keys2[i]) { + return false; + } + if (options1[keys1[i]] !== options2[keys2[i]]) { + return false; + } + } + return true; + } +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-address.js +var require_subchannel_address = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EndpointMap = undefined; + exports.isTcpSubchannelAddress = isTcpSubchannelAddress; + exports.subchannelAddressEqual = subchannelAddressEqual; + exports.subchannelAddressToString = subchannelAddressToString; + exports.stringToSubchannelAddress = stringToSubchannelAddress; + exports.endpointEqual = endpointEqual; + exports.endpointToString = endpointToString; + exports.endpointHasAddress = endpointHasAddress; + var net_1 = __require("net"); + function isTcpSubchannelAddress(address) { + return "port" in address; + } + function subchannelAddressEqual(address1, address2) { + if (!address1 && !address2) { + return true; + } + if (!address1 || !address2) { + return false; + } + if (isTcpSubchannelAddress(address1)) { + return isTcpSubchannelAddress(address2) && address1.host === address2.host && address1.port === address2.port; + } else { + return !isTcpSubchannelAddress(address2) && address1.path === address2.path; + } + } + function subchannelAddressToString(address) { + if (isTcpSubchannelAddress(address)) { + if ((0, net_1.isIPv6)(address.host)) { + return "[" + address.host + "]:" + address.port; + } else { + return address.host + ":" + address.port; + } + } else { + return address.path; + } + } + var DEFAULT_PORT = 443; + function stringToSubchannelAddress(addressString, port) { + if ((0, net_1.isIP)(addressString)) { + return { + host: addressString, + port: port !== null && port !== undefined ? port : DEFAULT_PORT + }; + } else { + return { + path: addressString + }; + } + } + function endpointEqual(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (let i = 0;i < endpoint1.addresses.length; i++) { + if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { + return false; + } + } + return true; + } + function endpointToString(endpoint) { + return "[" + endpoint.addresses.map(subchannelAddressToString).join(", ") + "]"; + } + function endpointHasAddress(endpoint, expectedAddress) { + for (const address of endpoint.addresses) { + if (subchannelAddressEqual(address, expectedAddress)) { + return true; + } + } + return false; + } + function endpointEqualUnordered(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (const address1 of endpoint1.addresses) { + let matchFound = false; + for (const address2 of endpoint2.addresses) { + if (subchannelAddressEqual(address1, address2)) { + matchFound = true; + break; + } + } + if (!matchFound) { + return false; + } + } + return true; + } + + class EndpointMap { + constructor() { + this.map = new Set; + } + get size() { + return this.map.size; + } + getForSubchannelAddress(address) { + for (const entry of this.map) { + if (endpointHasAddress(entry.key, address)) { + return entry.value; + } + } + return; + } + deleteMissing(endpoints) { + const removedValues = []; + for (const entry of this.map) { + let foundEntry = false; + for (const endpoint of endpoints) { + if (endpointEqualUnordered(endpoint, entry.key)) { + foundEntry = true; + } + } + if (!foundEntry) { + removedValues.push(entry.value); + this.map.delete(entry); + } + } + return removedValues; + } + get(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return entry.value; + } + } + return; + } + set(endpoint, mapEntry) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + entry.value = mapEntry; + return; + } + } + this.map.add({ key: endpoint, value: mapEntry }); + } + delete(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + this.map.delete(entry); + return; + } + } + } + has(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return true; + } + } + return false; + } + clear() { + this.map.clear(); + } + *keys() { + for (const entry of this.map) { + yield entry.key; + } + } + *values() { + for (const entry of this.map) { + yield entry.value; + } + } + *entries() { + for (const entry of this.map) { + yield [entry.key, entry.value]; + } + } + } + exports.EndpointMap = EndpointMap; +}); + +// node_modules/@js-sdsl/ordered-map/dist/cjs/index.js +var require_cjs = __commonJS((exports) => { + Object.defineProperty(exports, "t", { + value: true + }); + + class TreeNode { + constructor(t, e, s = 1) { + this.i = undefined; + this.h = undefined; + this.o = undefined; + this.u = t; + this.l = e; + this.p = s; + } + I() { + let t = this; + const e = t.o.o === t; + if (e && t.p === 1) { + t = t.h; + } else if (t.i) { + t = t.i; + while (t.h) { + t = t.h; + } + } else { + if (e) { + return t.o; + } + let s = t.o; + while (s.i === t) { + t = s; + s = t.o; + } + t = s; + } + return t; + } + B() { + let t = this; + if (t.h) { + t = t.h; + while (t.i) { + t = t.i; + } + return t; + } else { + let e = t.o; + while (e.h === t) { + t = e; + e = t.o; + } + if (t.h !== e) { + return e; + } else + return t; + } + } + _() { + const t = this.o; + const e = this.h; + const s = e.i; + if (t.o === this) + t.o = e; + else if (t.i === this) + t.i = e; + else + t.h = e; + e.o = t; + e.i = this; + this.o = e; + this.h = s; + if (s) + s.o = this; + return e; + } + g() { + const t = this.o; + const e = this.i; + const s = e.h; + if (t.o === this) + t.o = e; + else if (t.i === this) + t.i = e; + else + t.h = e; + e.o = t; + e.h = this; + this.o = e; + this.i = s; + if (s) + s.o = this; + return e; + } + } + + class TreeNodeEnableIndex extends TreeNode { + constructor() { + super(...arguments); + this.M = 1; + } + _() { + const t = super._(); + this.O(); + t.O(); + return t; + } + g() { + const t = super.g(); + this.O(); + t.O(); + return t; + } + O() { + this.M = 1; + if (this.i) { + this.M += this.i.M; + } + if (this.h) { + this.M += this.h.M; + } + } + } + + class ContainerIterator { + constructor(t = 0) { + this.iteratorType = t; + } + equals(t) { + return this.T === t.T; + } + } + + class Base { + constructor() { + this.m = 0; + } + get length() { + return this.m; + } + size() { + return this.m; + } + empty() { + return this.m === 0; + } + } + + class Container extends Base { + } + function throwIteratorAccessError() { + throw new RangeError("Iterator access denied!"); + } + + class TreeContainer extends Container { + constructor(t = function(t2, e2) { + if (t2 < e2) + return -1; + if (t2 > e2) + return 1; + return 0; + }, e = false) { + super(); + this.v = undefined; + this.A = t; + this.enableIndex = e; + this.N = e ? TreeNodeEnableIndex : TreeNode; + this.C = new this.N; + } + R(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + t = t.h; + } else if (i > 0) { + s = t; + t = t.i; + } else + return t; + } + return s; + } + K(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i <= 0) { + t = t.h; + } else { + s = t; + t = t.i; + } + } + return s; + } + L(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else if (i > 0) { + t = t.i; + } else + return t; + } + return s; + } + k(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else { + t = t.i; + } + } + return s; + } + P(t) { + while (true) { + const e = t.o; + if (e === this.C) + return; + if (t.p === 1) { + t.p = 0; + return; + } + if (t === e.i) { + const s = e.h; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e._(); + } else + e._(); + } else { + if (s.h && s.h.p === 1) { + s.p = e.p; + e.p = 0; + s.h.p = 0; + if (e === this.v) { + this.v = e._(); + } else + e._(); + return; + } else if (s.i && s.i.p === 1) { + s.p = 1; + s.i.p = 0; + s.g(); + } else { + s.p = 1; + t = e; + } + } + } else { + const s = e.i; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e.g(); + } else + e.g(); + } else { + if (s.i && s.i.p === 1) { + s.p = e.p; + e.p = 0; + s.i.p = 0; + if (e === this.v) { + this.v = e.g(); + } else + e.g(); + return; + } else if (s.h && s.h.p === 1) { + s.p = 1; + s.h.p = 0; + s._(); + } else { + s.p = 1; + t = e; + } + } + } + } + } + S(t) { + if (this.m === 1) { + this.clear(); + return; + } + let e = t; + while (e.i || e.h) { + if (e.h) { + e = e.h; + while (e.i) + e = e.i; + } else { + e = e.i; + } + const s2 = t.u; + t.u = e.u; + e.u = s2; + const i = t.l; + t.l = e.l; + e.l = i; + t = e; + } + if (this.C.i === e) { + this.C.i = e.o; + } else if (this.C.h === e) { + this.C.h = e.o; + } + this.P(e); + let s = e.o; + if (e === s.i) { + s.i = undefined; + } else + s.h = undefined; + this.m -= 1; + this.v.p = 0; + if (this.enableIndex) { + while (s !== this.C) { + s.M -= 1; + s = s.o; + } + } + } + U(t) { + const e = typeof t === "number" ? t : undefined; + const s = typeof t === "function" ? t : undefined; + const i = typeof t === "undefined" ? [] : undefined; + let r = 0; + let n = this.v; + const h = []; + while (h.length || n) { + if (n) { + h.push(n); + n = n.i; + } else { + n = h.pop(); + if (r === e) + return n; + i && i.push(n); + s && s(n, r, this); + r += 1; + n = n.h; + } + } + return i; + } + j(t) { + while (true) { + const e = t.o; + if (e.p === 0) + return; + const s = e.o; + if (e === s.i) { + const i = s.h; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) + return; + s.p = 1; + t = s; + continue; + } else if (t === e.h) { + t.p = 0; + if (t.i) { + t.i.o = e; + } + if (t.h) { + t.h.o = s; + } + e.h = t.i; + s.i = t.h; + t.i = e; + t.h = s; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e2 = s.o; + if (e2.i === s) { + e2.i = t; + } else + e2.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s.g(); + } else + s.g(); + s.p = 1; + return; + } + } else { + const i = s.i; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) + return; + s.p = 1; + t = s; + continue; + } else if (t === e.i) { + t.p = 0; + if (t.i) { + t.i.o = s; + } + if (t.h) { + t.h.o = e; + } + s.h = t.i; + e.i = t.h; + t.i = s; + t.h = e; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e2 = s.o; + if (e2.i === s) { + e2.i = t; + } else + e2.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s._(); + } else + s._(); + s.p = 1; + return; + } + } + if (this.enableIndex) { + e.O(); + s.O(); + t.O(); + } + return; + } + } + q(t, e, s) { + if (this.v === undefined) { + this.m += 1; + this.v = new this.N(t, e, 0); + this.v.o = this.C; + this.C.o = this.C.i = this.C.h = this.v; + return this.m; + } + let i; + const r = this.C.i; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n > 0) { + r.i = new this.N(t, e); + r.i.o = r; + i = r.i; + this.C.i = i; + } else { + const r2 = this.C.h; + const n2 = this.A(r2.u, t); + if (n2 === 0) { + r2.l = e; + return this.m; + } else if (n2 < 0) { + r2.h = new this.N(t, e); + r2.h.o = r2; + i = r2.h; + this.C.h = i; + } else { + if (s !== undefined) { + const r3 = s.T; + if (r3 !== this.C) { + const s2 = this.A(r3.u, t); + if (s2 === 0) { + r3.l = e; + return this.m; + } else if (s2 > 0) { + const s3 = r3.I(); + const n3 = this.A(s3.u, t); + if (n3 === 0) { + s3.l = e; + return this.m; + } else if (n3 < 0) { + i = new this.N(t, e); + if (s3.h === undefined) { + s3.h = i; + i.o = s3; + } else { + r3.i = i; + i.o = r3; + } + } + } + } + } + if (i === undefined) { + i = this.v; + while (true) { + const s2 = this.A(i.u, t); + if (s2 > 0) { + if (i.i === undefined) { + i.i = new this.N(t, e); + i.i.o = i; + i = i.i; + break; + } + i = i.i; + } else if (s2 < 0) { + if (i.h === undefined) { + i.h = new this.N(t, e); + i.h.o = i; + i = i.h; + break; + } + i = i.h; + } else { + i.l = e; + return this.m; + } + } + } + } + } + if (this.enableIndex) { + let t2 = i.o; + while (t2 !== this.C) { + t2.M += 1; + t2 = t2.o; + } + } + this.j(i); + this.m += 1; + return this.m; + } + H(t, e) { + while (t) { + const s = this.A(t.u, e); + if (s < 0) { + t = t.h; + } else if (s > 0) { + t = t.i; + } else + return t; + } + return t || this.C; + } + clear() { + this.m = 0; + this.v = undefined; + this.C.o = undefined; + this.C.i = this.C.h = undefined; + } + updateKeyByIterator(t, e) { + const s = t.T; + if (s === this.C) { + throwIteratorAccessError(); + } + if (this.m === 1) { + s.u = e; + return true; + } + const i = s.B().u; + if (s === this.C.i) { + if (this.A(i, e) > 0) { + s.u = e; + return true; + } + return false; + } + const r = s.I().u; + if (s === this.C.h) { + if (this.A(r, e) < 0) { + s.u = e; + return true; + } + return false; + } + if (this.A(r, e) >= 0 || this.A(i, e) <= 0) + return false; + s.u = e; + return true; + } + eraseElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + this.S(e); + return this.m; + } + eraseElementByKey(t) { + if (this.m === 0) + return false; + const e = this.H(this.v, t); + if (e === this.C) + return false; + this.S(e); + return true; + } + eraseElementByIterator(t) { + const e = t.T; + if (e === this.C) { + throwIteratorAccessError(); + } + const s = e.h === undefined; + const i = t.iteratorType === 0; + if (i) { + if (s) + t.next(); + } else { + if (!s || e.i === undefined) + t.next(); + } + this.S(e); + return t; + } + getHeight() { + if (this.m === 0) + return 0; + function traversal(t) { + if (!t) + return 0; + return Math.max(traversal(t.i), traversal(t.h)) + 1; + } + return traversal(this.v); + } + } + + class TreeIterator extends ContainerIterator { + constructor(t, e, s) { + super(s); + this.T = t; + this.C = e; + if (this.iteratorType === 0) { + this.pre = function() { + if (this.T === this.C.i) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + } else { + this.pre = function() { + if (this.T === this.C.h) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + } + } + get index() { + let t = this.T; + const e = this.C.o; + if (t === this.C) { + if (e) { + return e.M - 1; + } + return 0; + } + let s = 0; + if (t.i) { + s += t.i.M; + } + while (t !== e) { + const e2 = t.o; + if (t === e2.h) { + s += 1; + if (e2.i) { + s += e2.i.M; + } + } + t = e2; + } + return s; + } + isAccessible() { + return this.T !== this.C; + } + } + + class OrderedMapIterator extends TreeIterator { + constructor(t, e, s, i) { + super(t, e, i); + this.container = s; + } + get pointer() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + const t = this; + return new Proxy([], { + get(e, s) { + if (s === "0") + return t.T.u; + else if (s === "1") + return t.T.l; + e[0] = t.T.u; + e[1] = t.T.l; + return e[s]; + }, + set(e, s, i) { + if (s !== "1") { + throw new TypeError("prop must be 1"); + } + t.T.l = i; + return true; + } + }); + } + copy() { + return new OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); + } + } + + class OrderedMap extends TreeContainer { + constructor(t = [], e, s) { + super(e, s); + const i = this; + t.forEach(function(t2) { + i.setElement(t2[0], t2[1]); + }); + } + begin() { + return new OrderedMapIterator(this.C.i || this.C, this.C, this); + } + end() { + return new OrderedMapIterator(this.C, this.C, this); + } + rBegin() { + return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); + } + rEnd() { + return new OrderedMapIterator(this.C, this.C, this, 1); + } + front() { + if (this.m === 0) + return; + const t = this.C.i; + return [t.u, t.l]; + } + back() { + if (this.m === 0) + return; + const t = this.C.h; + return [t.u, t.l]; + } + lowerBound(t) { + const e = this.R(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + upperBound(t) { + const e = this.K(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseLowerBound(t) { + const e = this.L(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseUpperBound(t) { + const e = this.k(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + forEach(t) { + this.U(function(e, s, i) { + t([e.u, e.l], s, i); + }); + } + setElement(t, e, s) { + return this.q(t, e, s); + } + getElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + return [e.u, e.l]; + } + find(t) { + const e = this.H(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + getElementByKey(t) { + const e = this.H(this.v, t); + return e.l; + } + union(t) { + const e = this; + t.forEach(function(t2) { + e.setElement(t2[0], t2[1]); + }); + return this.m; + } + *[Symbol.iterator]() { + const t = this.m; + const e = this.U(); + for (let s = 0;s < t; ++s) { + const t2 = e[s]; + yield [t2.u, t2.l]; + } + } + } + exports.OrderedMap = OrderedMap; +}); + +// node_modules/@grpc/grpc-js/build/src/admin.js +var require_admin = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.registerAdminService = registerAdminService; + exports.addAdminServicesToServer = addAdminServicesToServer; + var registeredAdminServices = []; + function registerAdminService(getServiceDefinition, getHandlers) { + registeredAdminServices.push({ getServiceDefinition, getHandlers }); + } + function addAdminServicesToServer(server) { + for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { + server.addService(getServiceDefinition(), getHandlers()); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/call.js +var require_call = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = undefined; + exports.callErrorFromStatus = callErrorFromStatus; + var events_1 = __require("events"); + var stream_1 = __require("stream"); + var constants_1 = require_constants2(); + function callErrorFromStatus(status, callerStack) { + const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; + const error = new Error(message); + const stack = `${error.stack} +for call at +${callerStack}`; + return Object.assign(new Error(message), status, { stack }); + } + + class ClientUnaryCallImpl extends events_1.EventEmitter { + constructor() { + super(); + } + cancel() { + var _a; + (_a = this.call) === null || _a === undefined || _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getPeer()) !== null && _b !== undefined ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getAuthContext()) !== null && _b !== undefined ? _b : null; + } + } + exports.ClientUnaryCallImpl = ClientUnaryCallImpl; + + class ClientReadableStreamImpl extends stream_1.Readable { + constructor(deserialize) { + super({ objectMode: true }); + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === undefined || _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getPeer()) !== null && _b !== undefined ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getAuthContext()) !== null && _b !== undefined ? _b : null; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === undefined || _a.startRead(); + } + } + exports.ClientReadableStreamImpl = ClientReadableStreamImpl; + + class ClientWritableStreamImpl extends stream_1.Writable { + constructor(serialize) { + super({ objectMode: true }); + this.serialize = serialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === undefined || _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getPeer()) !== null && _b !== undefined ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getAuthContext()) !== null && _b !== undefined ? _b : null; + } + _write(chunk, encoding, cb) { + var _a; + const context = { + callback: cb + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + (_a = this.call) === null || _a === undefined || _a.sendMessageWithContext(context, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === undefined || _a.halfClose(); + cb(); + } + } + exports.ClientWritableStreamImpl = ClientWritableStreamImpl; + + class ClientDuplexStreamImpl extends stream_1.Duplex { + constructor(serialize, deserialize) { + super({ objectMode: true }); + this.serialize = serialize; + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === undefined || _a.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled on client"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getPeer()) !== null && _b !== undefined ? _b : "unknown"; + } + getAuthContext() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === undefined ? undefined : _a.getAuthContext()) !== null && _b !== undefined ? _b : null; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === undefined || _a.startRead(); + } + _write(chunk, encoding, cb) { + var _a; + const context = { + callback: cb + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + (_a = this.call) === null || _a === undefined || _a.sendMessageWithContext(context, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === undefined || _a.halfClose(); + cb(); + } + } + exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl; +}); + +// node_modules/@grpc/grpc-js/build/src/call-interface.js +var require_call_interface = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InterceptingListenerImpl = undefined; + exports.statusOrFromValue = statusOrFromValue; + exports.statusOrFromError = statusOrFromError; + exports.isInterceptingListener = isInterceptingListener; + var metadata_1 = require_metadata(); + function statusOrFromValue(value) { + return { + ok: true, + value + }; + } + function statusOrFromError(error) { + var _a; + return { + ok: false, + error: Object.assign(Object.assign({}, error), { metadata: (_a = error.metadata) !== null && _a !== undefined ? _a : new metadata_1.Metadata }) + }; + } + function isInterceptingListener(listener) { + return listener.onReceiveMetadata !== undefined && listener.onReceiveMetadata.length === 1; + } + + class InterceptingListenerImpl { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.processingMessage = false; + this.pendingStatus = null; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextListener.onReceiveStatus(this.pendingStatus); + } + } + onReceiveMetadata(metadata) { + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, (metadata2) => { + this.processingMetadata = false; + this.nextListener.onReceiveMetadata(metadata2); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + onReceiveMessage(message) { + this.processingMessage = true; + this.listener.onReceiveMessage(message, (msg) => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingStatus(); + } + }); + } + onReceiveStatus(status) { + this.listener.onReceiveStatus(status, (processedStatus) => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = processedStatus; + } else { + this.nextListener.onReceiveStatus(processedStatus); + } + }); + } + } + exports.InterceptingListenerImpl = InterceptingListenerImpl; +}); + +// node_modules/@grpc/grpc-js/build/src/client-interceptors.js +var require_client_interceptors = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = undefined; + exports.getInterceptingCall = getInterceptingCall; + var metadata_1 = require_metadata(); + var call_interface_1 = require_call_interface(); + var constants_1 = require_constants2(); + var error_1 = require_error2(); + + class InterceptorConfigurationError extends Error { + constructor(message) { + super(message); + this.name = "InterceptorConfigurationError"; + Error.captureStackTrace(this, InterceptorConfigurationError); + } + } + exports.InterceptorConfigurationError = InterceptorConfigurationError; + + class ListenerBuilder { + constructor() { + this.metadata = undefined; + this.message = undefined; + this.status = undefined; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveStatus(onReceiveStatus) { + this.status = onReceiveStatus; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveStatus: this.status + }; + } + } + exports.ListenerBuilder = ListenerBuilder; + + class RequesterBuilder { + constructor() { + this.start = undefined; + this.message = undefined; + this.halfClose = undefined; + this.cancel = undefined; + } + withStart(start) { + this.start = start; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withHalfClose(halfClose) { + this.halfClose = halfClose; + return this; + } + withCancel(cancel) { + this.cancel = cancel; + return this; + } + build() { + return { + start: this.start, + sendMessage: this.message, + halfClose: this.halfClose, + cancel: this.cancel + }; + } + } + exports.RequesterBuilder = RequesterBuilder; + var defaultListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveStatus: (status, next) => { + next(status); + } + }; + var defaultRequester = { + start: (metadata, listener, next) => { + next(metadata, listener); + }, + sendMessage: (message, next) => { + next(message); + }, + halfClose: (next) => { + next(); + }, + cancel: (next) => { + next(); + } + }; + + class InterceptingCall { + constructor(nextCall, requester) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + this.processingMetadata = false; + this.pendingMessageContext = null; + this.processingMessage = false; + this.pendingHalfClose = false; + if (requester) { + this.requester = { + start: (_a = requester.start) !== null && _a !== undefined ? _a : defaultRequester.start, + sendMessage: (_b = requester.sendMessage) !== null && _b !== undefined ? _b : defaultRequester.sendMessage, + halfClose: (_c = requester.halfClose) !== null && _c !== undefined ? _c : defaultRequester.halfClose, + cancel: (_d = requester.cancel) !== null && _d !== undefined ? _d : defaultRequester.cancel + }; + } else { + this.requester = defaultRequester; + } + } + cancelWithStatus(status, details) { + this.requester.cancel(() => { + this.nextCall.cancelWithStatus(status, details); + }); + } + getPeer() { + return this.nextCall.getPeer(); + } + processPendingMessage() { + if (this.pendingMessageContext) { + this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); + this.pendingMessageContext = null; + this.pendingMessage = null; + } + } + processPendingHalfClose() { + if (this.pendingHalfClose) { + this.nextCall.halfClose(); + } + } + start(metadata, interceptingListener) { + var _a, _b, _c, _d, _e, _f; + const fullInterceptingListener = { + onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === undefined ? undefined : interceptingListener.onReceiveMetadata) === null || _a === undefined ? undefined : _a.bind(interceptingListener)) !== null && _b !== undefined ? _b : (metadata2) => {}, + onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === undefined ? undefined : interceptingListener.onReceiveMessage) === null || _c === undefined ? undefined : _c.bind(interceptingListener)) !== null && _d !== undefined ? _d : (message) => {}, + onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === undefined ? undefined : interceptingListener.onReceiveStatus) === null || _e === undefined ? undefined : _e.bind(interceptingListener)) !== null && _f !== undefined ? _f : (status) => {} + }; + this.processingMetadata = true; + this.requester.start(metadata, fullInterceptingListener, (md, listener) => { + var _a2, _b2, _c2; + this.processingMetadata = false; + let finalInterceptingListener; + if ((0, call_interface_1.isInterceptingListener)(listener)) { + finalInterceptingListener = listener; + } else { + const fullListener = { + onReceiveMetadata: (_a2 = listener.onReceiveMetadata) !== null && _a2 !== undefined ? _a2 : defaultListener.onReceiveMetadata, + onReceiveMessage: (_b2 = listener.onReceiveMessage) !== null && _b2 !== undefined ? _b2 : defaultListener.onReceiveMessage, + onReceiveStatus: (_c2 = listener.onReceiveStatus) !== null && _c2 !== undefined ? _c2 : defaultListener.onReceiveStatus + }; + finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); + } + this.nextCall.start(md, finalInterceptingListener); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + sendMessageWithContext(context, message) { + this.processingMessage = true; + this.requester.sendMessage(message, (finalMessage) => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessageContext = context; + this.pendingMessage = message; + } else { + this.nextCall.sendMessageWithContext(context, finalMessage); + this.processPendingHalfClose(); + } + }); + } + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + startRead() { + this.nextCall.startRead(); + } + halfClose() { + this.requester.halfClose(() => { + if (this.processingMetadata || this.processingMessage) { + this.pendingHalfClose = true; + } else { + this.nextCall.halfClose(); + } + }); + } + getAuthContext() { + return this.nextCall.getAuthContext(); + } + } + exports.InterceptingCall = InterceptingCall; + function getCall(channel, path, options) { + var _a, _b; + const deadline = (_a = options.deadline) !== null && _a !== undefined ? _a : Infinity; + const host = options.host; + const parent = (_b = options.parent) !== null && _b !== undefined ? _b : null; + const propagateFlags = options.propagate_flags; + const credentials = options.credentials; + const call = channel.createCall(path, deadline, host, parent, propagateFlags); + if (credentials) { + call.setCredentials(credentials); + } + return call; + } + + class BaseInterceptingCall { + constructor(call, methodDefinition) { + this.call = call; + this.methodDefinition = methodDefinition; + } + cancelWithStatus(status, details) { + this.call.cancelWithStatus(status, details); + } + getPeer() { + return this.call.getPeer(); + } + sendMessageWithContext(context, message) { + let serialized; + try { + serialized = this.methodDefinition.requestSerialize(message); + } catch (e) { + this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); + return; + } + this.call.sendMessageWithContext(context, serialized); + } + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + start(metadata, interceptingListener) { + let readError = null; + this.call.start(metadata, { + onReceiveMetadata: (metadata2) => { + var _a; + (_a = interceptingListener === null || interceptingListener === undefined ? undefined : interceptingListener.onReceiveMetadata) === null || _a === undefined || _a.call(interceptingListener, metadata2); + }, + onReceiveMessage: (message) => { + var _a; + let deserialized; + try { + deserialized = this.methodDefinition.responseDeserialize(message); + } catch (e) { + readError = { + code: constants_1.Status.INTERNAL, + details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, + metadata: new metadata_1.Metadata + }; + this.call.cancelWithStatus(readError.code, readError.details); + return; + } + (_a = interceptingListener === null || interceptingListener === undefined ? undefined : interceptingListener.onReceiveMessage) === null || _a === undefined || _a.call(interceptingListener, deserialized); + }, + onReceiveStatus: (status) => { + var _a, _b; + if (readError) { + (_a = interceptingListener === null || interceptingListener === undefined ? undefined : interceptingListener.onReceiveStatus) === null || _a === undefined || _a.call(interceptingListener, readError); + } else { + (_b = interceptingListener === null || interceptingListener === undefined ? undefined : interceptingListener.onReceiveStatus) === null || _b === undefined || _b.call(interceptingListener, status); + } + } + }); + } + startRead() { + this.call.startRead(); + } + halfClose() { + this.call.halfClose(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + } + + class BaseUnaryInterceptingCall extends BaseInterceptingCall { + constructor(call, methodDefinition) { + super(call, methodDefinition); + } + start(metadata, listener) { + var _a, _b; + let receivedMessage = false; + const wrapperListener = { + onReceiveMetadata: (_b = (_a = listener === null || listener === undefined ? undefined : listener.onReceiveMetadata) === null || _a === undefined ? undefined : _a.bind(listener)) !== null && _b !== undefined ? _b : (metadata2) => {}, + onReceiveMessage: (message) => { + var _a2; + receivedMessage = true; + (_a2 = listener === null || listener === undefined ? undefined : listener.onReceiveMessage) === null || _a2 === undefined || _a2.call(listener, message); + }, + onReceiveStatus: (status) => { + var _a2, _b2; + if (!receivedMessage) { + (_a2 = listener === null || listener === undefined ? undefined : listener.onReceiveMessage) === null || _a2 === undefined || _a2.call(listener, null); + } + (_b2 = listener === null || listener === undefined ? undefined : listener.onReceiveStatus) === null || _b2 === undefined || _b2.call(listener, status); + } + }; + super.start(metadata, wrapperListener); + this.call.startRead(); + } + } + + class BaseStreamingInterceptingCall extends BaseInterceptingCall { + } + function getBottomInterceptingCall(channel, options, methodDefinition) { + const call = getCall(channel, methodDefinition.path, options); + if (methodDefinition.responseStream) { + return new BaseStreamingInterceptingCall(call, methodDefinition); + } else { + return new BaseUnaryInterceptingCall(call, methodDefinition); + } + } + function getInterceptingCall(interceptorArgs, methodDefinition, options, channel) { + if (interceptorArgs.clientInterceptors.length > 0 && interceptorArgs.clientInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as options " + "to the client constructor. Only one of these is allowed."); + } + if (interceptorArgs.callInterceptors.length > 0 && interceptorArgs.callInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError("Both interceptors and interceptor_providers were passed as call " + "options. Only one of these is allowed."); + } + let interceptors = []; + if (interceptorArgs.callInterceptors.length > 0 || interceptorArgs.callInterceptorProviders.length > 0) { + interceptors = [].concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor); + } else { + interceptors = [].concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map((provider) => provider(methodDefinition))).filter((interceptor) => interceptor); + } + const interceptorOptions = Object.assign({}, options, { + method_definition: methodDefinition + }); + const getCall2 = interceptors.reduceRight((nextCall, nextInterceptor) => { + return (currentOptions) => nextInterceptor(currentOptions, nextCall); + }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); + return getCall2(interceptorOptions); + } +}); + +// node_modules/@grpc/grpc-js/build/src/client.js +var require_client = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Client = undefined; + var call_1 = require_call(); + var channel_1 = require_channel(); + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants2(); + var metadata_1 = require_metadata(); + var client_interceptors_1 = require_client_interceptors(); + var CHANNEL_SYMBOL = Symbol(); + var INTERCEPTOR_SYMBOL = Symbol(); + var INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); + var CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); + function isFunction(arg) { + return typeof arg === "function"; + } + function getErrorStackString(error) { + var _a; + return ((_a = error.stack) === null || _a === undefined ? undefined : _a.split(` +`).slice(1).join(` +`)) || "no stack trace available"; + } + + class Client { + constructor(address, credentials, options = {}) { + var _a, _b; + options = Object.assign({}, options); + this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== undefined ? _a : []; + delete options.interceptors; + this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== undefined ? _b : []; + delete options.interceptor_providers; + if (this[INTERCEPTOR_SYMBOL].length > 0 && this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { + throw new Error("Both interceptors and interceptor_providers were passed as options " + "to the client constructor. Only one of these is allowed."); + } + this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = options.callInvocationTransformer; + delete options.callInvocationTransformer; + if (options.channelOverride) { + this[CHANNEL_SYMBOL] = options.channelOverride; + } else if (options.channelFactoryOverride) { + const channelFactoryOverride = options.channelFactoryOverride; + delete options.channelFactoryOverride; + this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); + } else { + this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); + } + } + close() { + this[CHANNEL_SYMBOL].close(); + } + getChannel() { + return this[CHANNEL_SYMBOL]; + } + waitForReady(deadline, callback) { + const checkState = (err) => { + if (err) { + callback(new Error("Failed to connect before the deadline")); + return; + } + let newState; + try { + newState = this[CHANNEL_SYMBOL].getConnectivityState(true); + } catch (e) { + callback(new Error("The channel has been closed")); + return; + } + if (newState === connectivity_state_1.ConnectivityState.READY) { + callback(); + } else { + try { + this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); + } catch (e) { + callback(new Error("The channel has been closed")); + } + } + }; + setImmediate(checkState); + } + checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { + if (isFunction(arg1)) { + return { metadata: new metadata_1.Metadata, options: {}, callback: arg1 }; + } else if (isFunction(arg2)) { + if (arg1 instanceof metadata_1.Metadata) { + return { metadata: arg1, options: {}, callback: arg2 }; + } else { + return { metadata: new metadata_1.Metadata, options: arg1, callback: arg2 }; + } + } else { + if (!(arg1 instanceof metadata_1.Metadata && arg2 instanceof Object && isFunction(arg3))) { + throw new Error("Incorrect arguments passed"); + } + return { metadata: arg1, options: arg2, callback: arg3 }; + } + } + makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientUnaryCallImpl, + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== undefined ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== undefined ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error; + call.start(callProperties.metadata, { + onReceiveMetadata: (metadata2) => { + emitter.emit("metadata", metadata2); + }, + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received"); + } + responseMessage = message; + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.UNIMPLEMENTED, + details: "No message received", + metadata: status.metadata + }, callerStack)); + } else { + callProperties.callback(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + emitter.emit("status", status); + } + }); + call.sendMessage(argument); + call.halfClose(); + return emitter; + } + makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientWritableStreamImpl(serialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== undefined ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== undefined ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error; + call.start(callProperties.metadata, { + onReceiveMetadata: (metadata2) => { + emitter.emit("metadata", metadata2); + }, + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, "Too many responses received"); + } + responseMessage = message; + call.startRead(); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.UNIMPLEMENTED, + details: "No message received", + metadata: status.metadata + }, callerStack)); + } else { + callProperties.callback(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + emitter.emit("status", status); + } + }); + return emitter; + } + checkMetadataAndOptions(arg1, arg2) { + let metadata; + let options; + if (arg1 instanceof metadata_1.Metadata) { + metadata = arg1; + if (arg2) { + options = arg2; + } else { + options = {}; + } + } else { + if (arg1) { + options = arg1; + } else { + options = {}; + } + metadata = new metadata_1.Metadata; + } + return { metadata, options }; + } + makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientReadableStreamImpl(deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== undefined ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== undefined ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + stream.call = call; + let receivedStatus = false; + let callerStackError = new Error; + call.start(callProperties.metadata, { + onReceiveMetadata(metadata2) { + stream.emit("metadata", metadata2); + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + stream.emit("status", status); + } + }); + call.sendMessage(argument); + call.halfClose(); + return stream; + } + makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition, + callOptions: checkedArguments.options + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== undefined ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== undefined ? _b : [] + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + stream.call = call; + let receivedStatus = false; + let callerStackError = new Error; + call.start(callProperties.metadata, { + onReceiveMetadata(metadata2) { + stream.emit("metadata", metadata2); + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream.emit("error", (0, call_1.callErrorFromStatus)(status, callerStack)); + } + callerStackError = null; + stream.emit("status", status); + } + }); + return stream; + } + } + exports.Client = Client; +}); + +// node_modules/@grpc/grpc-js/build/src/make-client.js +var require_make_client = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.makeClientConstructor = makeClientConstructor; + exports.loadPackageDefinition = loadPackageDefinition; + var client_1 = require_client(); + var requesterFuncs = { + unary: client_1.Client.prototype.makeUnaryRequest, + server_stream: client_1.Client.prototype.makeServerStreamRequest, + client_stream: client_1.Client.prototype.makeClientStreamRequest, + bidi: client_1.Client.prototype.makeBidiStreamRequest + }; + function isPrototypePolluted(key) { + return ["__proto__", "prototype", "constructor"].includes(key); + } + function makeClientConstructor(methods, serviceName, classOptions) { + if (!classOptions) { + classOptions = {}; + } + + class ServiceClientImpl extends client_1.Client { + } + Object.keys(methods).forEach((name) => { + if (isPrototypePolluted(name)) { + return; + } + const attrs = methods[name]; + let methodType; + if (typeof name === "string" && name.charAt(0) === "$") { + throw new Error("Method names cannot start with $"); + } + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = "bidi"; + } else { + methodType = "client_stream"; + } + } else { + if (attrs.responseStream) { + methodType = "server_stream"; + } else { + methodType = "unary"; + } + } + const serialize = attrs.requestSerialize; + const deserialize = attrs.responseDeserialize; + const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); + ServiceClientImpl.prototype[name] = methodFunc; + Object.assign(ServiceClientImpl.prototype[name], attrs); + if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { + ServiceClientImpl.prototype[attrs.originalName] = ServiceClientImpl.prototype[name]; + } + }); + ServiceClientImpl.service = methods; + ServiceClientImpl.serviceName = serviceName; + return ServiceClientImpl; + } + function partial(fn, path, serialize, deserialize) { + return function(...args) { + return fn.call(this, path, serialize, deserialize, ...args); + }; + } + function isProtobufTypeDefinition(obj) { + return "format" in obj; + } + function loadPackageDefinition(packageDef) { + const result = {}; + for (const serviceFqn in packageDef) { + if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { + const service = packageDef[serviceFqn]; + const nameComponents = serviceFqn.split("."); + if (nameComponents.some((comp) => isPrototypePolluted(comp))) { + continue; + } + const serviceName = nameComponents[nameComponents.length - 1]; + let current = result; + for (const packageName of nameComponents.slice(0, -1)) { + if (!current[packageName]) { + current[packageName] = {}; + } + current = current[packageName]; + } + if (isProtobufTypeDefinition(service)) { + current[serviceName] = service; + } else { + current[serviceName] = makeClientConstructor(service, serviceName, {}); + } + } + } + return result; + } +}); + +// node_modules/lodash.camelcase/index.js +var require_lodash = __commonJS((exports, module) => { + var INFINITY = 1 / 0; + var symbolTag = "[object Symbol]"; + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + var rsAstralRange = "\\ud800-\\udfff"; + var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23"; + var rsComboSymbolsRange = "\\u20d0-\\u20f0"; + var rsDingbatRange = "\\u2700-\\u27bf"; + var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff"; + var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7"; + var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf"; + var rsPunctuationRange = "\\u2000-\\u206f"; + var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000"; + var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde"; + var rsVarRange = "\\ufe0e\\ufe0f"; + var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + var rsApos = "['’]"; + var rsAstral = "[" + rsAstralRange + "]"; + var rsBreak = "[" + rsBreakRange + "]"; + var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]"; + var rsDigits = "\\d+"; + var rsDingbat = "[" + rsDingbatRange + "]"; + var rsLower = "[" + rsLowerRange + "]"; + var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]"; + var rsFitz = "\\ud83c[\\udffb-\\udfff]"; + var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")"; + var rsNonAstral = "[^" + rsAstralRange + "]"; + var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}"; + var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]"; + var rsUpper = "[" + rsUpperRange + "]"; + var rsZWJ = "\\u200d"; + var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")"; + var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")"; + var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?"; + var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?"; + var reOptMod = rsModifier + "?"; + var rsOptVar = "[" + rsVarRange + "]?"; + var rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*"; + var rsSeq = rsOptVar + reOptMod + rsOptJoin; + var rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq; + var rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; + var reApos = RegExp(rsApos, "g"); + var reComboMark = RegExp(rsCombo, "g"); + var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); + var reUnicodeWord = RegExp([ + rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", + rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [rsBreak, rsUpper + rsLowerMisc, "$"].join("|") + ")", + rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr, + rsUpper + "+" + rsOptUpperContr, + rsDigits, + rsEmoji + ].join("|"), "g"); + var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]"); + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + var deburredLetters = { + "À": "A", + "Á": "A", + "Â": "A", + "Ã": "A", + "Ä": "A", + "Å": "A", + "à": "a", + "á": "a", + "â": "a", + "ã": "a", + "ä": "a", + "å": "a", + "Ç": "C", + "ç": "c", + "Ð": "D", + "ð": "d", + "È": "E", + "É": "E", + "Ê": "E", + "Ë": "E", + "è": "e", + "é": "e", + "ê": "e", + "ë": "e", + "Ì": "I", + "Í": "I", + "Î": "I", + "Ï": "I", + "ì": "i", + "í": "i", + "î": "i", + "ï": "i", + "Ñ": "N", + "ñ": "n", + "Ò": "O", + "Ó": "O", + "Ô": "O", + "Õ": "O", + "Ö": "O", + "Ø": "O", + "ò": "o", + "ó": "o", + "ô": "o", + "õ": "o", + "ö": "o", + "ø": "o", + "Ù": "U", + "Ú": "U", + "Û": "U", + "Ü": "U", + "ù": "u", + "ú": "u", + "û": "u", + "ü": "u", + "Ý": "Y", + "ý": "y", + "ÿ": "y", + "Æ": "Ae", + "æ": "ae", + "Þ": "Th", + "þ": "th", + "ß": "ss", + "Ā": "A", + "Ă": "A", + "Ą": "A", + "ā": "a", + "ă": "a", + "ą": "a", + "Ć": "C", + "Ĉ": "C", + "Ċ": "C", + "Č": "C", + "ć": "c", + "ĉ": "c", + "ċ": "c", + "č": "c", + "Ď": "D", + "Đ": "D", + "ď": "d", + "đ": "d", + "Ē": "E", + "Ĕ": "E", + "Ė": "E", + "Ę": "E", + "Ě": "E", + "ē": "e", + "ĕ": "e", + "ė": "e", + "ę": "e", + "ě": "e", + "Ĝ": "G", + "Ğ": "G", + "Ġ": "G", + "Ģ": "G", + "ĝ": "g", + "ğ": "g", + "ġ": "g", + "ģ": "g", + "Ĥ": "H", + "Ħ": "H", + "ĥ": "h", + "ħ": "h", + "Ĩ": "I", + "Ī": "I", + "Ĭ": "I", + "Į": "I", + "İ": "I", + "ĩ": "i", + "ī": "i", + "ĭ": "i", + "į": "i", + "ı": "i", + "Ĵ": "J", + "ĵ": "j", + "Ķ": "K", + "ķ": "k", + "ĸ": "k", + "Ĺ": "L", + "Ļ": "L", + "Ľ": "L", + "Ŀ": "L", + "Ł": "L", + "ĺ": "l", + "ļ": "l", + "ľ": "l", + "ŀ": "l", + "ł": "l", + "Ń": "N", + "Ņ": "N", + "Ň": "N", + "Ŋ": "N", + "ń": "n", + "ņ": "n", + "ň": "n", + "ŋ": "n", + "Ō": "O", + "Ŏ": "O", + "Ő": "O", + "ō": "o", + "ŏ": "o", + "ő": "o", + "Ŕ": "R", + "Ŗ": "R", + "Ř": "R", + "ŕ": "r", + "ŗ": "r", + "ř": "r", + "Ś": "S", + "Ŝ": "S", + "Ş": "S", + "Š": "S", + "ś": "s", + "ŝ": "s", + "ş": "s", + "š": "s", + "Ţ": "T", + "Ť": "T", + "Ŧ": "T", + "ţ": "t", + "ť": "t", + "ŧ": "t", + "Ũ": "U", + "Ū": "U", + "Ŭ": "U", + "Ů": "U", + "Ű": "U", + "Ų": "U", + "ũ": "u", + "ū": "u", + "ŭ": "u", + "ů": "u", + "ű": "u", + "ų": "u", + "Ŵ": "W", + "ŵ": "w", + "Ŷ": "Y", + "ŷ": "y", + "Ÿ": "Y", + "Ź": "Z", + "Ż": "Z", + "Ž": "Z", + "ź": "z", + "ż": "z", + "ž": "z", + "IJ": "IJ", + "ij": "ij", + "Œ": "Oe", + "œ": "oe", + "ʼn": "'n", + "ſ": "ss" + }; + var freeGlobal = typeof global == "object" && global && global.Object === Object && global; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, length = array ? array.length : 0; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + function asciiToArray(string) { + return string.split(""); + } + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + var deburrLetter = basePropertyOf(deburredLetters); + function hasUnicode(string) { + return reHasUnicode.test(string); + } + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + function stringToArray(string) { + return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); + } + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + var objectProto = Object.prototype; + var objectToString = objectProto.toString; + var Symbol2 = root.Symbol; + var symbolProto = Symbol2 ? Symbol2.prototype : undefined; + var symbolToString = symbolProto ? symbolProto.toString : undefined; + function baseSlice(array, start, end) { + var index = -1, length = array.length; + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : end - start >>> 0; + start >>>= 0; + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + function baseToString(value) { + if (typeof value == "string") { + return value; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ""; + } + var result = value + ""; + return result == "0" && 1 / value == -INFINITY ? "-0" : result; + } + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return !start && end >= length ? array : baseSlice(array, start, end); + } + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; + var chr = strSymbols ? strSymbols[0] : string.charAt(0); + var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); + return chr[methodName]() + trailing; + }; + } + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); + }; + } + function isObjectLike(value) { + return !!value && typeof value == "object"; + } + function isSymbol(value) { + return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag; + } + function toString(value) { + return value == null ? "" : baseToString(value); + } + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); + } + var upperFirst = createCaseFirst("toUpperCase"); + function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined : pattern; + if (pattern === undefined) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; + } + module.exports = camelCase; +}); + +// node_modules/@protobufjs/aspromise/index.js +var require_aspromise = __commonJS((exports, module) => { + module.exports = asPromise; + function asPromise(fn, ctx) { + var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params2 = new Array(arguments.length - 1), offset2 = 0; + while (offset2 < params2.length) + params2[offset2++] = arguments[offset2]; + resolve.apply(null, params2); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); + } +}); + +// node_modules/@protobufjs/base64/index.js +var require_base64 = __commonJS((exports) => { + var base64 = exports; + base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; + }; + var b64 = new Array(64); + var s64 = new Array(123); + for (i = 0;i < 64; ) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + var i; + base64.encode = function encode(buffer, start, end) { + var parts = null, chunk = []; + var i2 = 0, j = 0, t; + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i2++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i2++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i2++] = b64[t | b >> 6]; + chunk[i2++] = b64[b & 63]; + j = 0; + break; + } + if (i2 > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i2 = 0; + } + } + if (j) { + chunk[i2++] = b64[t]; + chunk[i2++] = 61; + if (j === 1) + chunk[i2++] = 61; + } + if (parts) { + if (i2) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i2)); + }; + var invalidEncoding = "invalid encoding"; + base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, t; + for (var i2 = 0;i2 < string.length; ) { + var c = string.charCodeAt(i2++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; + }; + base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); + }; +}); + +// node_modules/@protobufjs/eventemitter/index.js +var require_eventemitter = __commonJS((exports, module) => { + module.exports = EventEmitter; + function EventEmitter() { + this._listeners = Object.create(null); + } + EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn, + ctx: ctx || this + }); + return this; + }; + EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = Object.create(null); + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + if (!listeners) + return this; + for (var i = 0;i < listeners.length; ) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; + }; + EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], i = 1; + for (;i < arguments.length; ) + args.push(arguments[i++]); + for (i = 0;i < listeners.length; ) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; + }; +}); + +// node_modules/@protobufjs/float/index.js +var require_float = __commonJS((exports, module) => { + module.exports = factory(factory); + function factory(exports2) { + if (typeof Float32Array !== "undefined") + (function() { + var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + exports2.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + exports2.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + exports2.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + exports2.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + })(); + else + (function() { + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? 0 : 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 340282346638528860000000000000000000000) + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 0.000000000000000000000000000000000000011754943508222875) + writeUint((sign << 31 | Math.round(val / 0.000000000000000000000000000000000000000000001401298464324817)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + exports2.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports2.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; + return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 0.000000000000000000000000000000000000000000001401298464324817 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + exports2.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports2.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + })(); + if (typeof Float64Array !== "undefined") + (function() { + var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + exports2.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + exports2.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + exports2.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + exports2.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + })(); + else + (function() { + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? 0 : 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000) { + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014) { + mantissa = val / 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + exports2.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports2.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + exports2.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports2.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + })(); + return exports2; + } + function writeUintLE(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + function writeUintBE(val, buf, pos) { + buf[pos] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; + } + function readUintLE(buf, pos) { + return (buf[pos] | buf[pos + 1] << 8 | buf[pos + 2] << 16 | buf[pos + 3] << 24) >>> 0; + } + function readUintBE(buf, pos) { + return (buf[pos] << 24 | buf[pos + 1] << 16 | buf[pos + 2] << 8 | buf[pos + 3]) >>> 0; + } +}); + +// node_modules/@protobufjs/inquire/index.js +var require_inquire = __commonJS((exports, module) => { + module.exports = inquire; + function inquire(moduleName) { + try { + if (false) {} + var mod = __require(moduleName); + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + return null; + } catch (err) { + return null; + } + } +}); + +// node_modules/@protobufjs/utf8/index.js +var require_utf8 = __commonJS((exports) => { + var utf8 = exports; + var replacementChar = "�"; + utf8.length = function utf8_length(string) { + var len = 0, c = 0; + for (var i = 0;i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 64512) === 55296 && (string.charCodeAt(i + 1) & 64512) === 56320) { + ++i; + len += 4; + } else + len += 3; + } + return len; + }; + utf8.read = function utf8_read(buffer, start, end) { + if (end - start < 1) { + return ""; + } + var str = ""; + for (var i = start;i < end; ) { + var t = buffer[i++]; + if (t <= 127) { + str += String.fromCharCode(t); + } else if (t >= 192 && t < 224) { + var c2 = (t & 31) << 6 | buffer[i++] & 63; + str += c2 >= 128 ? String.fromCharCode(c2) : replacementChar; + } else if (t >= 224 && t < 240) { + var c3 = (t & 15) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63; + str += c3 >= 2048 ? String.fromCharCode(c3) : replacementChar; + } else if (t >= 240) { + var t2 = (t & 7) << 18 | (buffer[i++] & 63) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63; + if (t2 < 65536 || t2 > 1114111) + str += replacementChar; + else { + t2 -= 65536; + str += String.fromCharCode(55296 + (t2 >> 10)); + str += String.fromCharCode(56320 + (t2 & 1023)); + } + } + } + return str; + }; + utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, c1, c2; + for (var i = 0;i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 64512) === 55296 && ((c2 = string.charCodeAt(i + 1)) & 64512) === 56320) { + c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; + }; +}); + +// node_modules/@protobufjs/pool/index.js +var require_pool = __commonJS((exports, module) => { + module.exports = pool; + function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size2) { + if (size2 < 1 || size2 > MAX) + return alloc(size2); + if (offset + size2 > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size2); + if (offset & 7) + offset = (offset | 7) + 1; + return buf; + }; + } +}); + +// node_modules/protobufjs/src/util/longbits.js +var require_longbits = __commonJS((exports, module) => { + module.exports = LongBits; + var util = require_minimal(); + function LongBits(lo, hi) { + this.lo = lo >>> 0; + this.hi = hi >>> 0; + } + var zero = LongBits.zero = new LongBits(0, 0); + zero.toNumber = function() { + return 0; + }; + zero.zzEncode = zero.zzDecode = function() { + return this; + }; + zero.length = function() { + return 1; + }; + var zeroHash = LongBits.zeroHash = "\x00\x00\x00\x00\x00\x00\x00\x00"; + LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); + }; + LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; + }; + LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; + }; + LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; + }; + var charCodeAt = String.prototype.charCodeAt; + LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits((charCodeAt.call(hash, 0) | charCodeAt.call(hash, 1) << 8 | charCodeAt.call(hash, 2) << 16 | charCodeAt.call(hash, 3) << 24) >>> 0, (charCodeAt.call(hash, 4) | charCodeAt.call(hash, 5) << 8 | charCodeAt.call(hash, 6) << 16 | charCodeAt.call(hash, 7) << 24) >>> 0); + }; + LongBits.prototype.toHash = function toHash() { + return String.fromCharCode(this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24); + }; + LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = (this.lo << 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = (this.hi >>> 1 ^ mask) >>> 0; + return this; + }; + LongBits.prototype.length = function length() { + var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; + return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; + }; +}); + +// node_modules/protobufjs/node_modules/long/umd/index.js +var require_umd = __commonJS((exports, module) => { + (function(global2, factory) { + function preferDefault(exports2) { + return exports2.default || exports2; + } + if (typeof define === "function" && define.amd) { + define([], function() { + var exports2 = {}; + factory(exports2); + return preferDefault(exports2); + }); + } else if (typeof exports === "object") { + factory(exports); + if (typeof module === "object") + module.exports = preferDefault(exports); + } else { + (function() { + var exports2 = {}; + factory(exports2); + global2.Long = preferDefault(exports2); + })(); + } + })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports, function(_exports) { + Object.defineProperty(_exports, "__esModule", { + value: true + }); + _exports.default = undefined; + var wasm = null; + try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ + 0, + 97, + 115, + 109, + 1, + 0, + 0, + 0, + 1, + 13, + 2, + 96, + 0, + 1, + 127, + 96, + 4, + 127, + 127, + 127, + 127, + 1, + 127, + 3, + 7, + 6, + 0, + 1, + 1, + 1, + 1, + 1, + 6, + 6, + 1, + 127, + 1, + 65, + 0, + 11, + 7, + 50, + 6, + 3, + 109, + 117, + 108, + 0, + 1, + 5, + 100, + 105, + 118, + 95, + 115, + 0, + 2, + 5, + 100, + 105, + 118, + 95, + 117, + 0, + 3, + 5, + 114, + 101, + 109, + 95, + 115, + 0, + 4, + 5, + 114, + 101, + 109, + 95, + 117, + 0, + 5, + 8, + 103, + 101, + 116, + 95, + 104, + 105, + 103, + 104, + 0, + 0, + 10, + 191, + 1, + 6, + 4, + 0, + 35, + 0, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 126, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 127, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 128, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 129, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11, + 36, + 1, + 1, + 126, + 32, + 0, + 173, + 32, + 1, + 173, + 66, + 32, + 134, + 132, + 32, + 2, + 173, + 32, + 3, + 173, + 66, + 32, + 134, + 132, + 130, + 34, + 4, + 66, + 32, + 135, + 167, + 36, + 0, + 32, + 4, + 167, + 11 + ])), {}).exports; + } catch {} + function Long(low, high, unsigned) { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Long.prototype.__isLong__; + Object.defineProperty(Long.prototype, "__isLong__", { + value: true + }); + function isLong(obj) { + return (obj && obj["__isLong__"]) === true; + } + function ctz32(value) { + var c = Math.clz32(value & -value); + return value ? 31 - c : c; + } + Long.isLong = isLong; + var INT_CACHE = {}; + var UINT_CACHE = {}; + function fromInt(value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if (cache = 0 <= value && value < 256) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if (cache = -128 <= value && value < 128) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + } + Long.fromInt = fromInt; + function fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) + return UZERO; + if (value >= TWO_PWR_64_DBL) + return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) + return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return MAX_VALUE; + } + if (value < 0) + return fromNumber(-value, unsigned).neg(); + return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); + } + Long.fromNumber = fromNumber; + function fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + Long.fromBits = fromBits; + var pow_dbl = Math.pow; + function fromString(str, unsigned, radix) { + if (str.length === 0) + throw Error("empty string"); + if (typeof unsigned === "number") { + radix = unsigned; + unsigned = false; + } else { + unsigned = !!unsigned; + } + if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") + return unsigned ? UZERO : ZERO; + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError("radix"); + var p; + if ((p = str.indexOf("-")) > 0) + throw Error("interior hyphen"); + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + var radixToPower = fromNumber(pow_dbl(radix, 8)); + var result = ZERO; + for (var i = 0;i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + Long.fromString = fromString; + function fromValue(val, unsigned) { + if (typeof val === "number") + return fromNumber(val, unsigned); + if (typeof val === "string") + return fromString(val, unsigned); + return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned); + } + Long.fromValue = fromValue; + var TWO_PWR_16_DBL = 1 << 16; + var TWO_PWR_24_DBL = 1 << 24; + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + var ZERO = fromInt(0); + Long.ZERO = ZERO; + var UZERO = fromInt(0, true); + Long.UZERO = UZERO; + var ONE = fromInt(1); + Long.ONE = ONE; + var UONE = fromInt(1, true); + Long.UONE = UONE; + var NEG_ONE = fromInt(-1); + Long.NEG_ONE = NEG_ONE; + var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); + Long.MAX_VALUE = MAX_VALUE; + var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); + Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + var MIN_VALUE = fromBits(0, 2147483648 | 0, false); + Long.MIN_VALUE = MIN_VALUE; + var LongPrototype = Long.prototype; + LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + }; + LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError("radix"); + if (this.isZero()) + return "0"; + if (this.isNegative()) { + if (this.eq(MIN_VALUE)) { + var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else + return "-" + this.neg().toString(radix); + } + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; + var result = ""; + while (true) { + var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) + return digits + result; + else { + while (digits.length < 6) + digits = "0" + digits; + result = "" + digits + result; + } + } + }; + LongPrototype.getHighBits = function getHighBits() { + return this.high; + }; + LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; + }; + LongPrototype.getLowBits = function getLowBits() { + return this.low; + }; + LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; + }; + LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31;bit > 0; bit--) + if ((val & 1 << bit) != 0) + break; + return this.high != 0 ? bit + 33 : bit + 1; + }; + LongPrototype.isSafeInteger = function isSafeInteger() { + var top11Bits = this.high >> 21; + if (!top11Bits) + return true; + if (this.unsigned) + return false; + return top11Bits === -1 && !(this.low === 0 && this.high === -2097152); + }; + LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; + }; + LongPrototype.eqz = LongPrototype.isZero; + LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; + }; + LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; + }; + LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; + }; + LongPrototype.isEven = function isEven() { + return (this.low & 1) === 0; + }; + LongPrototype.equals = function equals(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + LongPrototype.eq = LongPrototype.equals; + LongPrototype.notEquals = function notEquals(other) { + return !this.eq(other); + }; + LongPrototype.neq = LongPrototype.notEquals; + LongPrototype.ne = LongPrototype.notEquals; + LongPrototype.lessThan = function lessThan(other) { + return this.comp(other) < 0; + }; + LongPrototype.lt = LongPrototype.lessThan; + LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp(other) <= 0; + }; + LongPrototype.lte = LongPrototype.lessThanOrEqual; + LongPrototype.le = LongPrototype.lessThanOrEqual; + LongPrototype.greaterThan = function greaterThan(other) { + return this.comp(other) > 0; + }; + LongPrototype.gt = LongPrototype.greaterThan; + LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp(other) >= 0; + }; + LongPrototype.gte = LongPrototype.greaterThanOrEqual; + LongPrototype.ge = LongPrototype.greaterThanOrEqual; + LongPrototype.compare = function compare(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; + }; + LongPrototype.comp = LongPrototype.compare; + LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) + return MIN_VALUE; + return this.not().add(ONE); + }; + LongPrototype.neg = LongPrototype.negate; + LongPrototype.add = function add(addend) { + if (!isLong(addend)) + addend = fromValue(addend); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = addend.high >>> 16; + var b32 = addend.high & 65535; + var b16 = addend.low >>> 16; + var b00 = addend.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 + b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) + subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + LongPrototype.sub = LongPrototype.subtract; + LongPrototype.multiply = function multiply(multiplier) { + if (this.isZero()) + return this; + if (!isLong(multiplier)) + multiplier = fromValue(multiplier); + if (wasm) { + var low = wasm["mul"](this.low, this.high, multiplier.low, multiplier.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (multiplier.isZero()) + return this.unsigned ? UZERO : ZERO; + if (this.eq(MIN_VALUE)) + return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) + return this.isOdd() ? MIN_VALUE : ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 65535; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 65535; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.mul = LongPrototype.multiply; + LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (divisor.isZero()) + throw Error("division by zero"); + if (wasm) { + if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { + return this; + } + var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])(this.low, this.high, divisor.low, divisor.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; + else if (divisor.eq(MIN_VALUE)) + return ONE; + else { + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) + return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return UZERO; + if (divisor.gt(this.shru(1))) + return UONE; + res = UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) + approxRes = ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + LongPrototype.div = LongPrototype.divide; + LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (wasm) { + var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])(this.low, this.high, divisor.low, divisor.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + LongPrototype.mod = LongPrototype.modulo; + LongPrototype.rem = LongPrototype.modulo; + LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); + }; + LongPrototype.countLeadingZeros = function countLeadingZeros() { + return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; + }; + LongPrototype.clz = LongPrototype.countLeadingZeros; + LongPrototype.countTrailingZeros = function countTrailingZeros() { + return this.low ? ctz32(this.low) : ctz32(this.high) + 32; + }; + LongPrototype.ctz = LongPrototype.countTrailingZeros; + LongPrototype.and = function and(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + LongPrototype.or = function or(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + LongPrototype.xor = function xor(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); + else + return fromBits(0, this.low << numBits - 32, this.unsigned); + }; + LongPrototype.shl = LongPrototype.shiftLeft; + LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); + else + return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); + }; + LongPrototype.shr = LongPrototype.shiftRight; + LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + if (numBits < 32) + return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >>> numBits, this.unsigned); + if (numBits === 32) + return fromBits(this.high, 0, this.unsigned); + return fromBits(this.high >>> numBits - 32, 0, this.unsigned); + }; + LongPrototype.shru = LongPrototype.shiftRightUnsigned; + LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + LongPrototype.rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + if (numBits === 32) + return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits(this.low << numBits | this.high >>> b, this.high << numBits | this.low >>> b, this.unsigned); + } + numBits -= 32; + b = 32 - numBits; + return fromBits(this.high << numBits | this.low >>> b, this.low << numBits | this.high >>> b, this.unsigned); + }; + LongPrototype.rotl = LongPrototype.rotateLeft; + LongPrototype.rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + if (numBits === 32) + return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits(this.high << b | this.low >>> numBits, this.low << b | this.high >>> numBits, this.unsigned); + } + numBits -= 32; + b = 32 - numBits; + return fromBits(this.low << b | this.high >>> numBits, this.high << b | this.low >>> numBits, this.unsigned); + }; + LongPrototype.rotr = LongPrototype.rotateRight; + LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) + return this; + return fromBits(this.low, this.high, false); + }; + LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) + return this; + return fromBits(this.low, this.high, true); + }; + LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, lo = this.low; + return [ + lo & 255, + lo >>> 8 & 255, + lo >>> 16 & 255, + lo >>> 24, + hi & 255, + hi >>> 8 & 255, + hi >>> 16 & 255, + hi >>> 24 + ]; + }; + LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, lo = this.low; + return [ + hi >>> 24, + hi >>> 16 & 255, + hi >>> 8 & 255, + hi & 255, + lo >>> 24, + lo >>> 16 & 255, + lo >>> 8 & 255, + lo & 255 + ]; + }; + Long.fromBytes = function fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + }; + Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned); + }; + Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned); + }; + if (typeof BigInt === "function") { + Long.fromBigInt = function fromBigInt(value, unsigned) { + var lowBits = Number(BigInt.asIntN(32, value)); + var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); + return fromBits(lowBits, highBits, unsigned); + }; + Long.fromValue = function fromValueWithBigInt(value, unsigned) { + if (typeof value === "bigint") + return Long.fromBigInt(value, unsigned); + return fromValue(value, unsigned); + }; + LongPrototype.toBigInt = function toBigInt() { + var lowBigInt = BigInt(this.low >>> 0); + var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); + return highBigInt << BigInt(32) | lowBigInt; + }; + } + var _default = _exports.default = Long; + }); +}); + +// node_modules/protobufjs/src/util/minimal.js +var require_minimal = __commonJS((exports) => { + var util = exports; + util.asPromise = require_aspromise(); + util.base64 = require_base64(); + util.EventEmitter = require_eventemitter(); + util.float = require_float(); + util.inquire = require_inquire(); + util.utf8 = require_utf8(); + util.pool = require_pool(); + util.LongBits = require_longbits(); + function isUnsafeProperty(key) { + return key === "__proto__" || key === "prototype" || key === "constructor"; + } + util.isUnsafeProperty = isUnsafeProperty; + util.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); + util.global = util.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports; + util.emptyArray = Object.freeze ? Object.freeze([]) : []; + util.emptyObject = Object.freeze ? Object.freeze({}) : {}; + util.isInteger = Number.isInteger || function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; + }; + util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; + }; + util.isObject = function isObject(value) { + return value && typeof value === "object"; + }; + util.isset = util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; + }; + util.Buffer = function() { + try { + var Buffer2 = util.global.Buffer; + return Buffer2.prototype.utf8Write ? Buffer2 : null; + } catch (e) { + return null; + } + }(); + util._Buffer_from = null; + util._Buffer_allocUnsafe = null; + util.newBuffer = function newBuffer(sizeOrArray) { + return typeof sizeOrArray === "number" ? util.Buffer ? util._Buffer_allocUnsafe(sizeOrArray) : new util.Array(sizeOrArray) : util.Buffer ? util._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); + }; + util.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + util.Long = util.global.dcodeIO && util.global.dcodeIO.Long || util.global.Long || function() { + try { + var Long = require_umd(); + return Long && Long.isLong ? Long : null; + } catch (e) { + return null; + } + }(); + util.key2Re = /^true|false|0|1$/; + util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + util.longToHash = function longToHash(value) { + return value ? util.LongBits.from(value).toHash() : util.LongBits.zeroHash; + }; + util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); + }; + function merge(dst) { + var ifNotSet = typeof arguments[arguments.length - 1] === "boolean", limit = ifNotSet ? arguments.length - 1 : arguments.length; + ifNotSet = ifNotSet && arguments[arguments.length - 1]; + for (var a = 1;a < limit; ++a) { + var src = arguments[a]; + if (!src) + continue; + for (var keys = Object.keys(src), i = 0;i < keys.length; ++i) + if (!isUnsafeProperty(keys[i]) && (dst[keys[i]] === undefined || !ifNotSet)) + dst[keys[i]] = src[keys[i]]; + } + return dst; + } + util.merge = merge; + util.nestingLimit = 32; + util.recursionLimit = 100; + util.makeProp = function makeProp(obj, key) { + Object.defineProperty(obj, key, { + enumerable: true, + configurable: true, + writable: true + }); + }; + util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); + }; + function newError(name) { + function CustomError(message, properties) { + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + Object.defineProperty(this, "message", { get: function() { + return message; + } }); + if (Error.captureStackTrace) + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + if (properties) + merge(this, properties); + } + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true + }, + name: { + get: function get() { + return name; + }, + set: undefined, + enumerable: false, + configurable: true + }, + toString: { + value: function value() { + return this.name + ": " + this.message; + }, + writable: true, + enumerable: false, + configurable: true + } + }); + return CustomError; + } + util.newError = newError; + util.ProtocolError = newError("ProtocolError"); + util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0;i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + return function() { + for (var keys = Object.keys(this), i2 = keys.length - 1;i2 > -1; --i2) + if (fieldMap[keys[i2]] === 1 && this[keys[i2]] !== undefined && this[keys[i2]] !== null) + return keys[i2]; + }; + }; + util.oneOfSetter = function setOneOf(fieldNames) { + return function(name) { + for (var i = 0;i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; + }; + util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true + }; + util._configure = function() { + var Buffer2 = util.Buffer; + if (!Buffer2) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + util._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || function Buffer_from(value, encoding) { + return new Buffer2(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer2.allocUnsafe || function Buffer_allocUnsafe(size) { + return new Buffer2(size); + }; + }; +}); + +// node_modules/protobufjs/src/writer.js +var require_writer = __commonJS((exports, module) => { + module.exports = Writer; + var util = require_minimal(); + var BufferWriter; + var LongBits = util.LongBits; + var base64 = util.base64; + var utf8 = util.utf8; + function Op(fn, len, val) { + this.fn = fn; + this.len = len; + this.next = undefined; + this.val = val; + } + function noop() {} + function State(writer) { + this.head = writer.head; + this.tail = writer.tail; + this.len = writer.len; + this.next = writer.states; + } + function Writer() { + this.len = 0; + this.head = new Op(noop, 0, 0); + this.tail = this.head; + this.states = null; + } + var create = function create() { + return util.Buffer ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter; + })(); + } : function create_array() { + return new Writer; + }; + }; + Writer.create = create(); + Writer.alloc = function alloc(size) { + return new util.Array(size); + }; + if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; + }; + function writeByte(val, buf, pos) { + buf[pos] = val & 255; + } + function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; + } + function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; + } + VarintOp.prototype = Object.create(Op.prototype); + VarintOp.prototype.fn = writeVarint32; + Writer.prototype.uint32 = function write_uint32(value) { + this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, value)).len; + return this; + }; + Writer.prototype.int32 = function write_int32(value) { + return (value |= 0) < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); + }; + Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); + }; + function writeVarint64(val, buf, pos) { + var { lo, hi } = val; + while (hi) { + buf[pos++] = lo & 127 | 128; + lo = (lo >>> 7 | hi << 25) >>> 0; + hi >>>= 7; + } + while (lo > 127) { + buf[pos++] = lo & 127 | 128; + lo = lo >>> 7; + } + buf[pos++] = lo; + } + Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.int64 = Writer.prototype.uint64; + Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); + }; + Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); + }; + function writeFixed32(val, buf, pos) { + buf[pos] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; + } + Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); + }; + Writer.prototype.sfixed32 = Writer.prototype.fixed32; + Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); + }; + Writer.prototype.sfixed64 = Writer.prototype.fixed64; + Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); + }; + Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); + }; + var writeBytes = util.Array.prototype.set ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytes_for(val, buf, pos) { + for (var i = 0;i < val.length; ++i) + buf[pos + i] = val[i]; + }; + Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); + }; + Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); + }; + Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; + }; + Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; + }; + Writer.prototype.ldelim = function ldelim() { + var head = this.head, tail = this.tail, len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; + this.tail = tail; + this.len += len; + } + return this; + }; + Writer.prototype.finish = function finish() { + var head = this.head.next, buf = this.constructor.alloc(this.len), pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + return buf; + }; + Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); + }; +}); + +// node_modules/protobufjs/src/writer_buffer.js +var require_writer_buffer = __commonJS((exports, module) => { + module.exports = BufferWriter; + var Writer = require_writer(); + (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + var util = require_minimal(); + function BufferWriter() { + Writer.call(this); + } + BufferWriter._configure = function() { + BufferWriter.alloc = util._Buffer_allocUnsafe; + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); + } : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) + val.copy(buf, pos, 0, val.length); + else + for (var i = 0;i < val.length; ) + buf[pos++] = val[i++]; + }; + }; + BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; + }; + function writeStringBuffer(val, buf, pos) { + if (val.length < 40) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); + } + BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; + }; + BufferWriter._configure(); +}); + +// node_modules/protobufjs/src/reader.js +var require_reader = __commonJS((exports, module) => { + module.exports = Reader; + var util = require_minimal(); + var BufferReader; + var LongBits = util.LongBits; + var utf8 = util.utf8; + function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); + } + function Reader(buffer) { + this.buf = buffer; + this.pos = 0; + this.len = buffer.length; + } + var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + var create = function create() { + return util.Buffer ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer2) { + return util.Buffer.isBuffer(buffer2) ? new BufferReader(buffer2) : create_array(buffer2); + })(buffer); + } : create_array; + }; + Reader.create = create(); + Reader.prototype._slice = util.Array.prototype.subarray || util.Array.prototype.slice; + Reader.prototype.uint32 = function read_uint32_setup() { + var value = 4294967295; + return function read_uint32() { + value = (this.buf[this.pos] & 127) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; + if (this.buf[this.pos++] < 128) + return value; + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; + }(); + Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; + }; + Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; + }; + function readLongVarint() { + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { + for (;i < 4; ++i) { + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (;i < 3; ++i) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { + for (;i < 5; ++i) { + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (;i < 5; ++i) { + if (this.pos >= this.len) + throw indexOutOfRange(this); + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + throw Error("invalid varint encoding"); + } + Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; + }; + function readFixed32_end(buf, end) { + return (buf[end - 4] | buf[end - 3] << 8 | buf[end - 2] << 16 | buf[end - 1] << 24) >>> 0; + } + Reader.prototype.fixed32 = function read_fixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4); + }; + Reader.prototype.sfixed32 = function read_sfixed32() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + return readFixed32_end(this.buf, this.pos += 4) | 0; + }; + function readFixed64() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); + } + Reader.prototype.float = function read_float() { + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; + }; + Reader.prototype.double = function read_double() { + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; + }; + Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), start = this.pos, end = this.pos + length; + if (end > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + if (Array.isArray(this.buf)) + return this.buf.slice(start, end); + if (start === end) { + var nativeBuffer = util.Buffer; + return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); + }; + Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); + }; + Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; + }; + Reader.recursionLimit = util.recursionLimit; + Reader.prototype.skipType = function(wireType, depth) { + if (depth === undefined) + depth = 0; + if (depth > Reader.recursionLimit) + throw Error("maximum nesting depth exceeded"); + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType, depth + 1); + } + break; + case 5: + this.skip(4); + break; + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; + }; + Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + var fn = util.Long ? "toLong" : "toNumber"; + util.merge(Reader.prototype, { + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + }); + }; +}); + +// node_modules/protobufjs/src/reader_buffer.js +var require_reader_buffer = __commonJS((exports, module) => { + module.exports = BufferReader; + var Reader = require_reader(); + (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + var util = require_minimal(); + function BufferReader(buffer) { + Reader.call(this, buffer); + } + BufferReader._configure = function() { + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; + }; + BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); + return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); + }; + BufferReader._configure(); +}); + +// node_modules/protobufjs/src/rpc/service.js +var require_service = __commonJS((exports, module) => { + module.exports = Service; + var util = require_minimal(); + (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + function Service(rpcImpl, requestDelimited, responseDelimited) { + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + util.EventEmitter.call(this); + this.rpcImpl = rpcImpl; + this.requestDelimited = Boolean(requestDelimited); + this.responseDelimited = Boolean(responseDelimited); + } + Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request2, callback) { + if (!request2) + throw TypeError("request must be specified"); + var self2 = this; + if (!callback) + return util.asPromise(rpcCall, self2, method, requestCtor, responseCtor, request2); + if (!self2.rpcImpl) { + setTimeout(function() { + callback(Error("already ended")); + }, 0); + return; + } + try { + return self2.rpcImpl(method, requestCtor[self2.requestDelimited ? "encodeDelimited" : "encode"](request2).finish(), function rpcCallback(err, response) { + if (err) { + self2.emit("error", err, method); + return callback(err); + } + if (response === null) { + self2.end(true); + return; + } + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self2.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err2) { + self2.emit("error", err2, method); + return callback(err2); + } + } + self2.emit("data", response, method); + return callback(null, response); + }); + } catch (err) { + self2.emit("error", err, method); + setTimeout(function() { + callback(err); + }, 0); + return; + } + }; + Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; + }; +}); + +// node_modules/protobufjs/src/rpc.js +var require_rpc = __commonJS((exports) => { + var rpc = exports; + rpc.Service = require_service(); +}); + +// node_modules/protobufjs/src/roots.js +var require_roots = __commonJS((exports, module) => { + module.exports = {}; +}); + +// node_modules/protobufjs/src/index-minimal.js +var require_index_minimal = __commonJS((exports) => { + var protobuf = exports; + protobuf.build = "minimal"; + protobuf.Writer = require_writer(); + protobuf.BufferWriter = require_writer_buffer(); + protobuf.Reader = require_reader(); + protobuf.BufferReader = require_reader_buffer(); + protobuf.util = require_minimal(); + protobuf.rpc = require_rpc(); + protobuf.roots = require_roots(); + protobuf.configure = configure; + function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); + } + configure(); +}); + +// node_modules/@protobufjs/codegen/index.js +var require_codegen = __commonJS((exports, module) => { + module.exports = codegen; + var reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/; + function codegen(functionParams, functionName) { + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + var body = []; + function Codegen(formatStringOrScope) { + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), scopeParams = new Array(scopeKeys.length + 1), scopeValues = new Array(scopeKeys.length), scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); + } + return Function(source)(); + } + var formatParams = new Array(arguments.length - 1), formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": + case "f": + return String(Number(value)); + case "i": + return String(Math.floor(value)); + case "j": + return JSON.stringify(value); + case "s": + return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + function toString(functionNameOverride) { + return "function " + safeFunctionName(functionNameOverride || functionName) + "(" + (functionParams && functionParams.join(",") || "") + `){ + ` + body.join(` + `) + ` +}`; + } + Codegen.toString = toString; + return Codegen; + } + codegen.verbose = false; + function safeFunctionName(name) { + if (!name) + return ""; + name = String(name).replace(/[^\w$]/g, ""); + if (!name) + return ""; + if (/^\d/.test(name)) + name = "_" + name; + return reservedRe.test(name) ? name + "_" : name; + } +}); + +// node_modules/@protobufjs/fetch/util/fs.js +var require_fs = __commonJS((exports, module) => { + var fs = null; + try { + fs = __require("fs"); + if (!fs || !fs.readFile || !fs.readFileSync) + fs = null; + } catch (e) {} + module.exports = fs; +}); + +// node_modules/@protobufjs/fetch/index.js +var require_fetch = __commonJS((exports, module) => { + module.exports = fetch2; + var asPromise = require_aspromise(); + var fs = require_fs(); + function fetch2(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + if (!callback) + return asPromise(fetch2, this, filename, options); + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" ? fetch2.xhr(filename, options, callback) : err ? callback(err) : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + return fetch2.xhr(filename, options, callback); + } + fetch2.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest; + xhr.onreadystatechange = function fetchOnReadyStateChange() { + if (xhr.readyState !== 4) + return; + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0;i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + if (options.binary) { + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + xhr.open("GET", filename); + xhr.send(); + }; +}); + +// node_modules/@protobufjs/path/index.js +var require_path = __commonJS((exports) => { + var path = exports; + var isAbsolute = path.isAbsolute = function isAbsolute(path2) { + return /^(?:\/|\w+:)/.test(path2); + }; + var normalize = path.normalize = function normalize(path2) { + path2 = path2.replace(/\\/g, "/").replace(/\/{2,}/g, "/"); + var parts = path2.split("/"), absolute = isAbsolute(path2), prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0;i < parts.length; ) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); + }; + path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; + }; +}); + +// node_modules/protobufjs/src/util/patterns.js +var require_patterns = __commonJS((exports) => { + var patterns = exports; + patterns.numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; + patterns.typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/; + patterns.reservedRe = /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/; +}); + +// node_modules/protobufjs/src/util/fs.js +var require_fs2 = __commonJS((exports, module) => { + var fs = null; + try { + fs = __require("fs"); + if (!fs || !fs.readFile || !fs.readFileSync) + fs = null; + } catch (e) {} + module.exports = fs; +}); + +// node_modules/protobufjs/src/namespace.js +var require_namespace = __commonJS((exports, module) => { + module.exports = Namespace; + var ReflectionObject = require_object(); + ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + var Field = require_field(); + var util = require_util3(); + var OneOf = require_oneof(); + var Type; + var Service; + var Enum; + Namespace.fromJSON = function fromJSON(name, json, depth) { + depth = util.checkDepth(depth); + return new Namespace(name, json.options).addJSON(json.nested, depth); + }; + function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return; + var obj = {}; + for (var i = 0;i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; + } + Namespace.arrayToJSON = arrayToJSON; + Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) { + for (var i = 0;i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + } + return false; + }; + Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) { + for (var i = 0;i < reserved.length; ++i) + if (reserved[i] === name) + return true; + } + return false; + }; + function Namespace(name, options) { + ReflectionObject.call(this, name, options); + this.nested = undefined; + this._nestedArray = null; + this._lookupCache = Object.create(null); + this._needsRecursiveFeatureResolution = true; + this._needsRecursiveResolve = true; + } + function clearCache(namespace) { + namespace._nestedArray = null; + namespace._lookupCache = Object.create(null); + var parent = namespace; + while (parent = parent.parent) { + parent._lookupCache = Object.create(null); + } + return namespace; + } + Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } + }); + Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options", + this.options, + "nested", + arrayToJSON(this.nestedArray, toJSONOptions) + ]); + }; + Namespace.prototype.addJSON = function addJSON(nestedJson, depth) { + depth = util.checkDepth(depth); + var ns = this; + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested;i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add((nested.fields !== undefined ? Type.fromJSON : nested.values !== undefined ? Enum.fromJSON : nested.methods !== undefined ? Service.fromJSON : nested.id !== undefined ? Field.fromJSON : Namespace.fromJSON)(names[i], nested, depth + 1)); + } + } + return this; + }; + Namespace.prototype.get = function get(name) { + return this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) ? this.nested[name] : null; + }; + Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name) && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); + }; + Namespace.prototype.add = function add(object) { + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + if (object.name === "__proto__") + return this; + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + var nested = prev.nestedArray; + for (var i = 0;i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + if (!(this instanceof Type || this instanceof Service || this instanceof Enum || this instanceof Field)) { + if (!object._edition) { + object._edition = object._defaultEdition; + } + } + this._needsRecursiveFeatureResolution = true; + this._needsRecursiveResolve = true; + var parent = this; + while (parent = parent.parent) { + parent._needsRecursiveFeatureResolution = true; + parent._needsRecursiveResolve = true; + } + object.onAdd(this); + return clearCache(this); + }; + Namespace.prototype.remove = function remove(object) { + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + object.onRemove(this); + return clearCache(this); + }; + Namespace.prototype.define = function define(path, json) { + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + if (path.length > util.recursionLimit) + throw Error("max depth exceeded"); + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; + }; + Namespace.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) + return this; + this._resolveFeaturesRecursive(this._edition); + var nested = this.nestedArray, i = 0; + this.resolve(); + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + this._needsRecursiveResolve = false; + return this; + }; + Namespace.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) + return this; + this._needsRecursiveFeatureResolution = false; + edition = this._edition || edition; + ReflectionObject.prototype._resolveFeaturesRecursive.call(this, edition); + this.nestedArray.forEach((nested) => { + nested._resolveFeaturesRecursive(edition); + }); + return this; + }; + Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [filterTypes]; + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + var flatPath = path.join("."); + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + var found = this.root._fullyQualifiedObjects && this.root._fullyQualifiedObjects["." + flatPath]; + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + found = this._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + if (parentAlreadyChecked) + return null; + var current = this; + while (current.parent) { + found = current.parent._lookupImpl(path, flatPath); + if (found && (!filterTypes || filterTypes.indexOf(found.constructor) > -1)) { + return found; + } + current = current.parent; + } + return null; + }; + Namespace.prototype._lookupImpl = function lookup(path, flatPath) { + if (Object.prototype.hasOwnProperty.call(this._lookupCache, flatPath)) { + return this._lookupCache[flatPath]; + } + var found = this.get(path[0]); + var exact = null; + if (found) { + if (path.length === 1) { + exact = found; + } else if (found instanceof Namespace) { + path = path.slice(1); + exact = found._lookupImpl(path, path.join(".")); + } + } else { + for (var i = 0;i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i]._lookupImpl(path, flatPath))) { + exact = found; + break; + } + } + this._lookupCache[flatPath] = exact; + return exact; + }; + Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [Type]); + if (!found) + throw Error("no such type: " + path); + return found; + }; + Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [Enum]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; + }; + Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [Type, Enum]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; + }; + Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [Service]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; + }; + Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; + }; +}); + +// node_modules/protobufjs/src/mapfield.js +var require_mapfield = __commonJS((exports, module) => { + module.exports = MapField; + var Field = require_field(); + ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + var types = require_types5(); + var util = require_util3(); + function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, undefined, undefined, options, comment); + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + this.keyType = keyType; + this.resolvedKeyType = null; + this.map = true; + } + MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); + }; + MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType", + this.keyType, + "type", + this.type, + "id", + this.id, + "extend", + this.extend, + "options", + this.options, + "comment", + keepComments ? this.comment : undefined + ]); + }; + MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + return Field.prototype.resolve.call(this); + }; + MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor).add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; + }; +}); + +// node_modules/protobufjs/src/method.js +var require_method = __commonJS((exports, module) => { + module.exports = Method; + var ReflectionObject = require_object(); + ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + var util = require_util3(); + function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + ReflectionObject.call(this, name, options); + this.type = type || "rpc"; + this.requestType = requestType; + this.requestStream = requestStream ? true : undefined; + this.responseType = responseType; + this.responseStream = responseStream ? true : undefined; + this.resolvedRequestType = null; + this.resolvedResponseType = null; + this.comment = comment; + this.parsedOptions = parsedOptions; + } + Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); + }; + Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type", + this.type !== "rpc" && this.type || undefined, + "requestType", + this.requestType, + "requestStream", + this.requestStream, + "responseType", + this.responseType, + "responseStream", + this.responseStream, + "options", + this.options, + "comment", + keepComments ? this.comment : undefined, + "parsedOptions", + this.parsedOptions + ]); + }; + Method.prototype.resolve = function resolve() { + if (this.resolved) + return this; + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + return ReflectionObject.prototype.resolve.call(this); + }; +}); + +// node_modules/protobufjs/src/service.js +var require_service2 = __commonJS((exports, module) => { + module.exports = Service; + var Namespace = require_namespace(); + ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + var Method = require_method(); + var util = require_util3(); + var rpc = require_rpc(); + var reservedRe = util.patterns.reservedRe; + function Service(name, options) { + Namespace.call(this, name, options); + this.methods = {}; + this._methodsArray = null; + } + Service.fromJSON = function fromJSON(name, json, depth) { + depth = util.checkDepth(depth); + var service = new Service(name, json.options); + if (json.methods) + for (var names = Object.keys(json.methods), i = 0;i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested, depth); + if (json.edition) + service._edition = json.edition; + service.comment = json.comment; + service._defaultEdition = "proto3"; + return service; + }; + Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition", + this._editionToJSON(), + "options", + inherited && inherited.options || undefined, + "methods", + Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || {}, + "nested", + inherited && inherited.nested || undefined, + "comment", + keepComments ? this.comment : undefined + ]); + }; + Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } + }); + function clearCache(service) { + service._methodsArray = null; + return service; + } + Service.prototype.get = function get(name) { + return Object.prototype.hasOwnProperty.call(this.methods, name) ? this.methods[name] : Namespace.prototype.get.call(this, name); + }; + Service.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) + return this; + Namespace.prototype.resolve.call(this); + var methods = this.methodsArray; + for (var i = 0;i < methods.length; ++i) + methods[i].resolve(); + return this; + }; + Service.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) + return this; + edition = this._edition || edition; + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.methodsArray.forEach((method) => { + method._resolveFeaturesRecursive(edition); + }); + return this; + }; + Service.prototype.add = function add(object) { + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + if (object instanceof Method) { + if (object.name === "__proto__") + return this; + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); + }; + Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); + }; + Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method;i < this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r", "c"], reservedRe.test(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; + }; +}); + +// node_modules/protobufjs/src/message.js +var require_message = __commonJS((exports, module) => { + module.exports = Message; + var util = require_minimal(); + function Message(properties) { + if (properties) + for (var keys = Object.keys(properties), i = 0;i < keys.length; ++i) { + var key = keys[i]; + if (key === "__proto__") + continue; + this[key] = properties[key]; + } + } + Message.create = function create(properties) { + return this.$type.create(properties); + }; + Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); + }; + Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); + }; + Message.decode = function decode(reader) { + return this.$type.decode(reader); + }; + Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); + }; + Message.verify = function verify(message) { + return this.$type.verify(message); + }; + Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); + }; + Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); + }; + Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); + }; +}); + +// node_modules/protobufjs/src/decoder.js +var require_decoder = __commonJS((exports, module) => { + module.exports = decoder; + var Enum = require_enum(); + var types = require_types5(); + var util = require_util3(); + function missing(field) { + return "missing required '" + field.name + "'"; + } + function decoder(mtype) { + var gen = util.codegen(["r", "l", "e", "n"], mtype.name + "$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("if(n===undefined)n=0")("if(n>Reader.recursionLimit)")('throw Error("maximum nesting depth exceeded")')("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field2) { + return field2.map; + }).length ? ",k,value" : ""))("while(r.pos>>3){"); + var i = 0; + for (;i < mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), type = field.resolvedType instanceof Enum ? "int32" : field.type, ref = "m" + util.safeProp(field.name); + gen("case %i: {", field.id); + if (field.map) { + gen("if(%s===util.emptyObject)", ref)("%s={}", ref)("var c2 = r.uint32()+r.pos"); + if (types.defaults[field.keyType] !== undefined) + gen("k=%j", types.defaults[field.keyType]); + else + gen("k=null"); + if (types.defaults[type] !== undefined) + gen("value=%j", types.defaults[type]); + else + gen("value=null"); + gen("while(r.pos>>3){")("case 1: k=r.%s(); break", field.keyType)("case 2:"); + if (types.basic[type] === undefined) + gen("value=types[%i].decode(r,r.uint32(),undefined,n+1)", i); + else + gen("value=r.%s()", type); + gen("break")("default:")("r.skipType(tag2&7,n)")("break")("}")("}"); + if (types.long[field.keyType] !== undefined) + gen('%s[typeof k==="object"?util.longToHash(k):k]=value', ref); + else { + if (field.keyType === "string") + gen('if(k==="__proto__")')("util.makeProp(%s,k)", ref); + gen("%s[k]=value", ref); + } + } else if (field.repeated) { + gen("if(!(%s&&%s.length))", ref, ref)("%s=[]", ref); + if (types.packed[type] !== undefined) + gen("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos { + module.exports = verifier; + var Enum = require_enum(); + var util = require_util3(); + function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:" + field.keyType + "}" : "") + " expected"; + } + function genVerifyValue(gen, field, fieldIndex, ref) { + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { + gen("switch(%s){", ref)("default:")("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0;j < keys.length; ++j) + gen("case %i:", field.resolvedType.values[keys[j]]); + gen("break")("}"); + } else { + gen("{")("var e=types[%i].verify(%s,n+1);", fieldIndex, ref)("if(e)")("return%j+e", field.name + ".")("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": + gen("if(!util.isInteger(%s))", ref)("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": + gen("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": + gen('if(typeof %s!=="number")', ref)("return%j", invalid(field, "number")); + break; + case "bool": + gen('if(typeof %s!=="boolean")', ref)("return%j", invalid(field, "boolean")); + break; + case "string": + gen("if(!util.isString(%s))", ref)("return%j", invalid(field, "string")); + break; + case "bytes": + gen('if(!(%s&&typeof %s.length==="number"||util.isString(%s)))', ref, ref, ref)("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + } + function genVerifyKey(gen, field, ref) { + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": + gen("if(!util.key32Re.test(%s))", ref)("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": + gen("if(!util.key64Re.test(%s))", ref)("return%j", invalid(field, "integer|Long key")); + break; + case "bool": + gen("if(!util.key2Re.test(%s))", ref)("return%j", invalid(field, "boolean key")); + break; + } + return gen; + } + function verifier(mtype) { + var gen = util.codegen(["m", "n"], mtype.name + "$verify")('if(typeof m!=="object"||m===null)')("return%j", "object expected")("if(n===undefined)n=0")("if(n>util.recursionLimit)")("return%j", "maximum nesting depth exceeded"); + var oneofs = mtype.oneofsArray, seenFirstField = {}; + if (oneofs.length) + gen("var p={}"); + for (var i = 0;i < mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), ref = "m" + util.safeProp(field.name); + if (field.optional) + gen("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); + if (field.map) { + gen("if(!util.isObject(%s))", ref)("return%j", invalid(field, "object"))("var k=Object.keys(%s)", ref)("for(var i=0;i { + var converter = exports; + var Enum = require_enum(); + var util = require_util3(); + function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + var defaultAlreadyEmitted = false; + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { + gen("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0;i < keys.length; ++i) { + if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { + gen("default:")('if(typeof(d%s)==="number"){m%s=d%s;break}', prop, prop, prop); + if (!field.repeated) + gen("break"); + defaultAlreadyEmitted = true; + } + gen("case%j:", keys[i])("case %i:", values[keys[i]])("m%s=%j", prop, values[keys[i]])("break"); + } + gen("}"); + } else + gen('if(typeof d%s!=="object")', prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s=types[%i].fromObject(d%s,n+1)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": + gen("m%s=Number(d%s)", prop, prop); + break; + case "uint32": + case "fixed32": + gen("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": + gen("m%s=d%s|0", prop, prop); + break; + case "uint64": + case "fixed64": + isUnsigned = true; + case "int64": + case "sint64": + case "sfixed64": + gen("if(util.Long)")("m%s=util.Long.fromValue(d%s,%j)", prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)("m%s=parseInt(d%s,10)", prop, prop)('else if(typeof d%s==="number")', prop)("m%s=d%s", prop, prop)('else if(typeof d%s==="object")', prop)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": + gen('if(typeof d%s==="string")', prop)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)("else if(d%s.length >= 0)", prop)("m%s=d%s", prop, prop); + break; + case "string": + gen("m%s=String(d%s)", prop, prop); + break; + case "bool": + gen("m%s=Boolean(d%s)", prop, prop); + break; + } + } + return gen; + } + converter.fromObject = function fromObject(mtype) { + var fields = mtype.fieldsArray; + var gen = util.codegen(["d", "n"], mtype.name + "$fromObject")("if(d instanceof this.ctor)")("return d")("if(n===undefined)n=0")("if(n>util.recursionLimit)")('throw Error("maximum nesting depth exceeded")'); + if (!fields.length) + return gen("return new this.ctor"); + gen("var m=new this.ctor"); + for (var i = 0;i < fields.length; ++i) { + var field = fields[i].resolve(), prop = util.safeProp(field.name); + if (field.map) { + gen("if(d%s){", prop)('if(typeof d%s!=="object")', prop)("throw TypeError(%j)", field.fullName + ": object expected")("m%s={}", prop)("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0,%j).toBigInt()', prop, prop, prop, prop, prop, isUnsigned)('else if(typeof m%s==="number")', prop)("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true" : "", prop); + break; + case "bytes": + gen("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: + gen("d%s=m%s", prop, prop); + break; + } + } + return gen; + } + converter.toObject = function toObject(mtype) { + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o", "q"], mtype.name + "$toObject")("if(!o)")("o={}")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")')("var d={}"); + var repeatedFields = [], mapFields = [], normalFields = [], i = 0; + for (;i < fields.length; ++i) + if (!fields[i].partOf) + (fields[i].resolve().repeated ? repeatedFields : fields[i].map ? mapFields : normalFields).push(fields[i]); + if (repeatedFields.length) { + gen("if(o.arrays||o.defaults){"); + for (i = 0;i < repeatedFields.length; ++i) + gen("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen("}"); + } + if (mapFields.length) { + gen("if(o.objects||o.defaults){"); + for (i = 0;i < mapFields.length; ++i) + gen("d%s={}", util.safeProp(mapFields[i].name)); + gen("}"); + } + if (normalFields.length) { + gen("if(o.defaults){"); + for (i = 0;i < normalFields.length; ++i) { + var field = normalFields[i], prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) + gen("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) + gen("if(util.Long){")("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)('d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():typeof BigInt!=="undefined"&&o.longs===BigInt?n.toBigInt():n', prop)("}else")('d%s=o.longs===String?%j:typeof BigInt!=="undefined"&&o.longs===BigInt?BigInt(%j):%i', prop, field.typeDefault.toString(), field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = Array.prototype.slice.call(field.typeDefault); + gen("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))("else{")("d%s=%j", prop, arrayDefault)("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)("}"); + } else + gen("d%s=%j", prop, field.typeDefault); + } + gen("}"); + } + var hasKs2 = false; + for (i = 0;i < fields.length; ++i) { + var field = fields[i], index = mtype._fieldsArray.indexOf(field), prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { + hasKs2 = true; + gen("var ks2"); + } + gen("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)("d%s={}", prop)("for(var j=0;j { + var wrappers = exports; + var Message = require_message(); + var util = require_minimal(); + wrappers[".google.protobuf.Any"] = { + fromObject: function(object, depth) { + if (object && object["@type"]) { + var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); + var type = this.lookup(name); + if (type) { + var type_url = object["@type"].charAt(0) === "." ? object["@type"].slice(1) : object["@type"]; + if (type_url.indexOf("/") === -1) { + type_url = "/" + type_url; + } + return this.create({ + type_url, + value: type.encode(type.fromObject(object, depth === undefined ? 1 : depth + 1)).finish() + }); + } + } + return this.fromObject(object, depth); + }, + toObject: function(message, options, depth) { + if (depth === undefined) + depth = 0; + if (depth > util.recursionLimit) + throw Error("max depth exceeded"); + var googleApi = "type.googleapis.com/"; + var prefix = ""; + var name = ""; + if (options && options.json && message.type_url && message.value) { + name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + if (type) + message = type.decode(message.value, undefined, undefined, depth + 1); + } + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options, depth + 1); + var messageName = message.$type.fullName[0] === "." ? message.$type.fullName.slice(1) : message.$type.fullName; + if (prefix === "") { + prefix = googleApi; + } + name = prefix + messageName; + object["@type"] = name; + return object; + } + return this.toObject(message, options, depth); + } + }; +}); + +// node_modules/protobufjs/src/type.js +var require_type2 = __commonJS((exports, module) => { + module.exports = Type; + var Namespace = require_namespace(); + ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + var Enum = require_enum(); + var OneOf = require_oneof(); + var Field = require_field(); + var MapField = require_mapfield(); + var Service = require_service2(); + var Message = require_message(); + var Reader = require_reader(); + var Writer = require_writer(); + var util = require_util3(); + var encoder = require_encoder(); + var decoder = require_decoder(); + var verifier = require_verifier(); + var converter = require_converter(); + var wrappers = require_wrappers(); + function Type(name, options) { + name = name.replace(/\W/g, ""); + Namespace.call(this, name, options); + this.fields = {}; + this.oneofs = undefined; + this.extensions = undefined; + this.reserved = undefined; + this.group = undefined; + this._fieldsById = null; + this._fieldsArray = null; + this._oneofsArray = null; + this._ctor = null; + } + Object.defineProperties(Type.prototype, { + fieldsById: { + get: function() { + if (this._fieldsById) + return this._fieldsById; + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0;i < names.length; ++i) { + var field = this.fields[names[i]], id = field.id; + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + ctor.$type = ctor.prototype.$type = this; + util.merge(ctor, Message, true); + this._ctor = ctor; + var i = 0; + for (;i < this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); + var ctorProperties = {}; + for (i = 0;i < this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } + }); + Type.generateConstructor = function generateConstructor(mtype) { + var gen = util.codegen(["p"], mtype.name); + for (var i = 0, field;i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) + gen("this%s={}", util.safeProp(field.name)); + else if (field.repeated) + gen("this%s=[]", util.safeProp(field.name)); + return gen('if(p)for(var ks=Object.keys(p),i=0;i util.nestingLimit) + throw Error("max depth exceeded"); + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), i = 0; + for (;i < names.length; ++i) + type.add((typeof json.fields[names[i]].keyType !== "undefined" ? MapField.fromJSON : Field.fromJSON)(names[i], json.fields[names[i]])); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0;i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0;i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add((nested.id !== undefined ? Field.fromJSON : nested.fields !== undefined ? Type.fromJSON : nested.values !== undefined ? Enum.fromJSON : nested.methods !== undefined ? Service.fromJSON : Namespace.fromJSON)(names[i], nested, depth + 1)); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + if (json.comment) + type.comment = json.comment; + if (json.edition) + type._edition = json.edition; + type._defaultEdition = "proto3"; + return type; + }; + Type.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition", + this._editionToJSON(), + "options", + inherited && inherited.options || undefined, + "oneofs", + Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + "fields", + Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { + return !obj.declaringField; + }), toJSONOptions) || {}, + "extensions", + this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved", + this.reserved && this.reserved.length ? this.reserved : undefined, + "group", + this.group || undefined, + "nested", + inherited && inherited.nested || undefined, + "comment", + keepComments ? this.comment : undefined + ]); + }; + Type.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) + return this; + Namespace.prototype.resolveAll.call(this); + var oneofs = this.oneofsArray; + i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + return this; + }; + Type.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + if (!this._needsRecursiveFeatureResolution) + return this; + edition = this._edition || edition; + Namespace.prototype._resolveFeaturesRecursive.call(this, edition); + this.oneofsArray.forEach((oneof) => { + oneof._resolveFeatures(edition); + }); + this.fieldsArray.forEach((field) => { + field._resolveFeatures(edition); + }); + return this; + }; + Type.prototype.get = function get(name) { + if (Object.prototype.hasOwnProperty.call(this.fields, name)) + return this.fields[name]; + if (this.oneofs && Object.prototype.hasOwnProperty.call(this.oneofs, name)) + return this.oneofs[name]; + if (this.nested && Object.prototype.hasOwnProperty.call(this.nested, name)) + return this.nested[name]; + return null; + }; + Type.prototype.add = function add(object) { + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + if (object instanceof Field && object.extend === undefined) { + if (this._fieldsById ? this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + if (object.name === "__proto__") + return this; + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (object.name === "__proto__") + return this; + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); + }; + Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); + }; + Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); + }; + Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); + }; + Type.prototype.create = function create(properties) { + return new this.ctor(properties); + }; + Type.prototype.setup = function setup() { + var fullName = this.fullName, types = []; + for (var i = 0;i < this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + this.encode = encoder(this)({ + Writer, + types, + util + }); + this.decode = decoder(this)({ + Reader, + types, + util + }); + this.verify = verifier(this)({ + types, + util + }); + this.fromObject = converter.fromObject(this)({ + types, + util + }); + this.toObject = converter.toObject(this)({ + types, + util + }); + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + } + return this; + }; + Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode.apply(this, arguments); + }; + Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); + }; + Type.prototype.decode = function decode_setup(reader, length, end, depth) { + return this.setup().decode(reader, length, end, depth); + }; + Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); + }; + Type.prototype.verify = function verify_setup(message, depth) { + return this.setup().verify(message, depth); + }; + Type.prototype.fromObject = function fromObject(object, depth) { + return this.setup().fromObject(object, depth); + }; + Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject.apply(this, arguments); + }; + Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; + }; +}); + +// node_modules/protobufjs/src/root.js +var require_root = __commonJS((exports, module) => { + module.exports = Root; + var Namespace = require_namespace(); + ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + var Field = require_field(); + var Enum = require_enum(); + var OneOf = require_oneof(); + var util = require_util3(); + var Type; + var parse2; + var common; + function Root(options) { + Namespace.call(this, "", options); + this.deferred = []; + this.files = []; + this._edition = "proto2"; + this._fullyQualifiedObjects = {}; + } + Root.fromJSON = function fromJSON(json, root, depth) { + depth = util.checkDepth(depth); + if (!root) + root = new Root; + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested, depth).resolveAll(); + }; + Root.prototype.resolvePath = util.path.resolve; + Root.prototype.fetch = util.fetch; + function SYNC() {} + Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self2 = this; + if (!callback) { + return util.asPromise(load, self2, filename, options); + } + var sync = callback === SYNC; + function finish(err, root) { + if (!callback) { + return; + } + if (sync) { + throw err; + } + if (root) { + root.resolveAll(); + } + var cb = callback; + callback = null; + cb(err, root); + } + function getBundledFileName(filename2) { + var idx = filename2.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename2.substring(idx); + if (altname in common) + return altname; + } + return null; + } + function process2(filename2, source, depth) { + if (depth === undefined) + depth = 0; + try { + if (depth > util.recursionLimit) + throw Error("max depth exceeded"); + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self2.setOptions(source.options).addJSON(source.nested); + else { + parse2.filename = filename2; + var parsed = parse2(source, self2, options), resolved2, i2 = 0; + if (parsed.imports) { + for (;i2 < parsed.imports.length; ++i2) + if (resolved2 = getBundledFileName(parsed.imports[i2]) || self2.resolvePath(filename2, parsed.imports[i2])) + fetch2(resolved2, false, depth + 1); + } + if (parsed.weakImports) { + for (i2 = 0;i2 < parsed.weakImports.length; ++i2) + if (resolved2 = getBundledFileName(parsed.weakImports[i2]) || self2.resolvePath(filename2, parsed.weakImports[i2])) + fetch2(resolved2, true, depth + 1); + } + } + } catch (err) { + finish(err); + } + if (!sync && !queued) { + finish(null, self2); + } + } + function fetch2(filename2, weak, depth) { + if (depth === undefined) + depth = 0; + filename2 = getBundledFileName(filename2) || filename2; + if (self2.files.indexOf(filename2) > -1) { + return; + } + self2.files.push(filename2); + if (filename2 in common) { + if (sync) { + process2(filename2, common[filename2], depth); + } else { + ++queued; + setTimeout(function() { + --queued; + process2(filename2, common[filename2], depth); + }); + } + return; + } + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename2).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process2(filename2, source, depth); + } else { + ++queued; + self2.fetch(filename2, function(err, source2) { + --queued; + if (!callback) { + return; + } + if (err) { + if (!weak) + finish(err); + else if (!queued) + finish(null, self2); + return; + } + process2(filename2, source2, depth); + }); + } + } + var queued = 0; + if (util.isString(filename)) { + filename = [filename]; + } + for (var i = 0, resolved;i < filename.length; ++i) + if (resolved = self2.resolvePath("", filename[i])) + fetch2(resolved); + if (sync) { + self2.resolveAll(); + return self2; + } + if (!queued) { + finish(null, self2); + } + return self2; + }; + Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); + }; + Root.prototype.resolveAll = function resolveAll() { + if (!this._needsRecursiveResolve) + return this; + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); + }; + var exposeRe = /^[A-Z]/; + function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; + } + Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + if (object.extend !== undefined && !object.extensionField) { + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + } + } else if (object instanceof Enum) { + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; + } else if (!(object instanceof OneOf)) { + if (object instanceof Type) + for (var i = 0;i < this.deferred.length; ) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0;j < object.nestedArray.length; ++j) + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; + } + if (object instanceof Type || object instanceof Enum || object instanceof Field) { + this._fullyQualifiedObjects[object.fullName] = object; + } + }; + Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + if (object.extend !== undefined) { + if (object.extensionField) { + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { + var index = this.deferred.indexOf(object); + if (index > -1) + this.deferred.splice(index, 1); + } + } + } else if (object instanceof Enum) { + if (exposeRe.test(object.name)) + delete object.parent[object.name]; + } else if (object instanceof Namespace) { + for (var i = 0;i < object.nestedArray.length; ++i) + this._handleRemove(object._nestedArray[i]); + if (exposeRe.test(object.name)) + delete object.parent[object.name]; + } + delete this._fullyQualifiedObjects[object.fullName]; + }; + Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse2 = parse_; + common = common_; + }; +}); + +// node_modules/protobufjs/src/util.js +var require_util3 = __commonJS((exports, module) => { + var util = module.exports = require_minimal(); + var roots = require_roots(); + var Type; + var Enum; + util.codegen = require_codegen(); + util.fetch = require_fetch(); + util.path = require_path(); + util.patterns = require_patterns(); + var reservedRe = util.patterns.reservedRe; + util.fs = require_fs2(); + util.checkDepth = function checkDepth(depth) { + if (depth === undefined) + depth = 0; + if (depth > util.recursionLimit) + throw Error("max depth exceeded"); + return depth; + }; + util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), array = new Array(keys.length), index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; + }; + util.toObject = function toObject(array) { + var object = {}, index = 0; + while (index < array.length) { + var key = array[index++], val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; + }; + util.isReserved = function isReserved(name) { + return reservedRe.test(name); + }; + util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || reservedRe.test(prop)) + return "[" + JSON.stringify(prop) + "]"; + return "." + prop; + }; + util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); + }; + var camelCaseRe = /_([a-z])/g; + util.camelCase = function camelCase(str) { + return str.substring(0, 1) + str.substring(1).replace(camelCaseRe, function($0, $1) { + return $1.toUpperCase(); + }); + }; + util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; + }; + util.decorateType = function decorateType(ctor, typeName) { + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + if (!Type) + Type = require_type2(); + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; + }; + var decorateEnumIndex = 0; + util.decorateEnum = function decorateEnum(object) { + if (object.$type) + return object.$type; + if (!Enum) + Enum = require_enum(); + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; + }; + util.setProperty = function setProperty(dst, path, value, ifNotSet) { + function setProp(dst2, path2, value2) { + var part = path2.shift(); + if (util.isUnsafeProperty(part)) + return dst2; + if (path2.length > 0) { + dst2[part] = setProp(dst2[part] || {}, path2, value2); + } else { + var prevValue = dst2[part]; + if (prevValue && ifNotSet) + return dst2; + if (prevValue) + value2 = [].concat(prevValue).concat(value2); + dst2[part] = value2; + } + return dst2; + } + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + path = path.split("."); + if (path.length > util.recursionLimit) + throw Error("max depth exceeded"); + return setProp(dst, path, value); + }; + Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require_root())); + } + }); +}); + +// node_modules/protobufjs/src/types.js +var require_types5 = __commonJS((exports) => { + var types = exports; + var util = require_util3(); + var s = [ + "double", + "float", + "int32", + "uint32", + "sint32", + "fixed32", + "sfixed32", + "int64", + "uint64", + "sint64", + "fixed64", + "sfixed64", + "bool", + "string", + "bytes" + ]; + function bake(values, offset) { + var i = 0, o = Object.create(null); + offset |= 0; + while (i < values.length) + o[s[i + offset]] = values[i++]; + return o; + } + types.basic = bake([ + 1, + 5, + 0, + 0, + 0, + 5, + 5, + 0, + 0, + 0, + 1, + 1, + 0, + 2, + 2 + ]); + types.defaults = bake([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + false, + "", + util.emptyArray, + null + ]); + types.long = bake([ + 0, + 0, + 0, + 1, + 1 + ], 7); + types.mapKey = bake([ + 0, + 0, + 0, + 5, + 5, + 0, + 0, + 0, + 1, + 1, + 0, + 2 + ], 2); + types.packed = bake([ + 1, + 5, + 0, + 0, + 0, + 5, + 5, + 0, + 0, + 0, + 1, + 1, + 0 + ]); +}); + +// node_modules/protobufjs/src/field.js +var require_field = __commonJS((exports, module) => { + module.exports = Field; + var ReflectionObject = require_object(); + ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + var Enum = require_enum(); + var types = require_types5(); + var util = require_util3(); + var Type; + var ruleRe = /^required|optional|repeated$/; + Field.fromJSON = function fromJSON(name, json) { + var field = new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); + if (json.edition) + field._edition = json.edition; + field._defaultEdition = "proto3"; + return field; + }; + function Field(name, id, type, rule, extend, options, comment) { + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = undefined; + } + ReflectionObject.call(this, name, options); + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + if (!util.isString(type)) + throw TypeError("type must be a string"); + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : undefined; + this.type = type; + this.id = id; + this.extend = extend || undefined; + this.repeated = rule === "repeated"; + this.map = false; + this.message = null; + this.partOf = null; + this.typeDefault = null; + this.defaultValue = null; + this.long = util.Long ? types.long[type] !== undefined : false; + this.bytes = type === "bytes"; + this.resolvedType = null; + this.extensionField = null; + this.declaringField = null; + this.comment = comment; + } + Object.defineProperty(Field.prototype, "required", { + get: function() { + return this._features.field_presence === "LEGACY_REQUIRED"; + } + }); + Object.defineProperty(Field.prototype, "optional", { + get: function() { + return !this.required; + } + }); + Object.defineProperty(Field.prototype, "delimited", { + get: function() { + return this.resolvedType instanceof Type && this._features.message_encoding === "DELIMITED"; + } + }); + Object.defineProperty(Field.prototype, "packed", { + get: function() { + return this._features.repeated_field_encoding === "PACKED"; + } + }); + Object.defineProperty(Field.prototype, "hasPresence", { + get: function() { + if (this.repeated || this.map) { + return false; + } + return this.partOf || this.declaringField || this.extensionField || this._features.field_presence !== "IMPLICIT"; + } + }); + Field.prototype.setOption = function setOption(name, value, ifNotSet) { + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); + }; + Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition", + this._editionToJSON(), + "rule", + this.rule !== "optional" && this.rule || undefined, + "type", + this.type, + "id", + this.id, + "extend", + this.extend, + "options", + this.options, + "comment", + keepComments ? this.comment : undefined + ]); + }; + Field.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if ((this.typeDefault = types.defaults[this.type]) === undefined) { + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; + } else if (this.options && this.options.proto3_optional) { + this.typeDefault = null; + } + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + if (this.options) { + if (this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type === "uint64" || this.type === "fixed64"); + if (Object.freeze) + Object.freeze(this.typeDefault); + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + return ReflectionObject.prototype.resolve.call(this); + }; + Field.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures(edition) { + if (edition !== "proto2" && edition !== "proto3") { + return {}; + } + var features = {}; + if (this.rule === "required") { + features.field_presence = "LEGACY_REQUIRED"; + } + if (this.parent && types.defaults[this.type] === undefined) { + var type = this.parent.get(this.type.split(".").pop()); + if (type && type instanceof Type && type.group) { + features.message_encoding = "DELIMITED"; + } + } + if (this.getOption("packed") === true) { + features.repeated_field_encoding = "PACKED"; + } else if (this.getOption("packed") === false) { + features.repeated_field_encoding = "EXPANDED"; + } + return features; + }; + Field.prototype._resolveFeatures = function _resolveFeatures(edition) { + return ReflectionObject.prototype._resolveFeatures.call(this, this._edition || edition); + }; + Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor).add(new Field(fieldName, fieldId, fieldType, fieldRule, { default: defaultValue })); + }; + }; + Field._configure = function configure(Type_) { + Type = Type_; + }; +}); + +// node_modules/protobufjs/src/oneof.js +var require_oneof = __commonJS((exports, module) => { + module.exports = OneOf; + var ReflectionObject = require_object(); + ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + var Field = require_field(); + var util = require_util3(); + function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + this.oneof = fieldNames || []; + this.fieldsArray = []; + this.comment = comment; + } + OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); + }; + OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options", + this.options, + "oneof", + this.oneof, + "comment", + keepComments ? this.comment : undefined + ]); + }; + function addFieldsToParent(oneof) { + if (oneof.parent) { + for (var i = 0;i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); + } + } + OneOf.prototype.add = function add(field) { + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; + addFieldsToParent(this); + return this; + }; + OneOf.prototype.remove = function remove(field) { + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + var index = this.fieldsArray.indexOf(field); + if (index < 0) + throw Error(field + " is not a member of " + this); + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + if (index > -1) + this.oneof.splice(index, 1); + field.partOf = null; + return this; + }; + OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self2 = this; + for (var i = 0;i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self2; + self2.fieldsArray.push(field); + } + } + addFieldsToParent(this); + }; + OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field;i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); + }; + Object.defineProperty(OneOf.prototype, "isProto3Optional", { + get: function() { + if (this.fieldsArray == null || this.fieldsArray.length !== 1) { + return false; + } + var field = this.fieldsArray[0]; + return field.options != null && field.options["proto3_optional"] === true; + } + }); + OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor).add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; + }; +}); + +// node_modules/protobufjs/src/object.js +var require_object = __commonJS((exports, module) => { + module.exports = ReflectionObject; + ReflectionObject.className = "ReflectionObject"; + var OneOf = require_oneof(); + var util = require_util3(); + var Root; + var editions2023Defaults = { enum_type: "OPEN", field_presence: "EXPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" }; + var proto2Defaults = { enum_type: "CLOSED", field_presence: "EXPLICIT", json_format: "LEGACY_BEST_EFFORT", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "EXPANDED", utf8_validation: "NONE" }; + var proto3Defaults = { enum_type: "OPEN", field_presence: "IMPLICIT", json_format: "ALLOW", message_encoding: "LENGTH_PREFIXED", repeated_field_encoding: "PACKED", utf8_validation: "VERIFY" }; + function ReflectionObject(name, options) { + if (!util.isString(name)) + throw TypeError("name must be a string"); + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + this.options = options; + this.parsedOptions = null; + this.name = name; + this._edition = null; + this._defaultEdition = "proto2"; + this._features = {}; + this._featuresResolved = false; + this.parent = null; + this.resolved = false; + this.comment = null; + this.filename = null; + } + Object.defineProperties(ReflectionObject.prototype, { + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + fullName: { + get: function() { + var path = [this.name], ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } + }); + ReflectionObject.prototype.toJSON = function toJSON() { + throw Error(); + }; + ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); + }; + ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; + }; + ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; + return this; + }; + ReflectionObject.prototype._resolveFeaturesRecursive = function _resolveFeaturesRecursive(edition) { + return this._resolveFeatures(this._edition || edition); + }; + ReflectionObject.prototype._resolveFeatures = function _resolveFeatures(edition) { + if (this._featuresResolved) { + return; + } + var defaults = {}; + if (!edition) { + throw new Error("Unknown edition for " + this.fullName); + } + var protoFeatures = util.merge({}, this.options && this.options.features, this._inferLegacyProtoFeatures(edition)); + if (this._edition) { + if (edition === "proto2") { + defaults = Object.assign({}, proto2Defaults); + } else if (edition === "proto3") { + defaults = Object.assign({}, proto3Defaults); + } else if (edition === "2023") { + defaults = Object.assign({}, editions2023Defaults); + } else { + throw new Error("Unknown edition: " + edition); + } + this._features = util.merge(defaults, protoFeatures); + this._featuresResolved = true; + return; + } + if (this.partOf instanceof OneOf) { + var lexicalParentFeaturesCopy = util.merge({}, this.partOf._features); + this._features = util.merge(lexicalParentFeaturesCopy, protoFeatures); + } else if (this.declaringField) {} else if (this.parent) { + var parentFeaturesCopy = util.merge({}, this.parent._features); + this._features = util.merge(parentFeaturesCopy, protoFeatures); + } else { + throw new Error("Unable to find a parent for " + this.fullName); + } + if (this.extensionField) { + this.extensionField._features = this._features; + } + this._featuresResolved = true; + }; + ReflectionObject.prototype._inferLegacyProtoFeatures = function _inferLegacyProtoFeatures() { + return {}; + }; + ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return; + }; + ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (name === "__proto__") + return this; + if (!this.options) + this.options = {}; + if (/^features\./.test(name)) { + util.setProperty(this.options, name, value, ifNotSet); + } else if (!ifNotSet || this.options[name] === undefined) { + if (this.getOption(name) !== value) + this.resolved = false; + this.options[name] = value; + } + return this; + }; + ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (name === "__proto__") + return this; + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + var opt = parsedOptions.find(function(opt2) { + return Object.prototype.hasOwnProperty.call(opt2, name); + }); + if (opt) { + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + return this; + }; + ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0;i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; + }; + ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; + }; + ReflectionObject.prototype._editionToJSON = function _editionToJSON() { + if (!this._edition || this._edition === "proto3") { + return; + } + return this._edition; + }; + ReflectionObject._configure = function(Root_) { + Root = Root_; + }; +}); + +// node_modules/protobufjs/src/enum.js +var require_enum = __commonJS((exports, module) => { + module.exports = Enum; + var ReflectionObject = require_object(); + ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + var Namespace = require_namespace(); + var util = require_util3(); + function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + this.valuesById = {}; + this.values = Object.create(this.valuesById); + this.comment = comment; + this.comments = comments || {}; + this.valuesOptions = valuesOptions; + this._valuesFeatures = {}; + this.reserved = undefined; + if (values) { + for (var keys = Object.keys(values), i = 0;i < keys.length; ++i) + if (keys[i] !== "__proto__" && typeof values[keys[i]] === "number") + this.valuesById[this.values[keys[i]] = values[keys[i]]] = keys[i]; + } + } + Enum.prototype._resolveFeatures = function _resolveFeatures(edition) { + edition = this._edition || edition; + ReflectionObject.prototype._resolveFeatures.call(this, edition); + Object.keys(this.values).forEach((key) => { + var parentFeaturesCopy = util.merge({}, this._features); + this._valuesFeatures[key] = util.merge(parentFeaturesCopy, this.valuesOptions && this.valuesOptions[key] && this.valuesOptions[key].features || {}); + }); + return this; + }; + Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + if (json.edition) + enm._edition = json.edition; + enm._defaultEdition = "proto3"; + return enm; + }; + Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "edition", + this._editionToJSON(), + "options", + this.options, + "valuesOptions", + this.valuesOptions, + "values", + this.values, + "reserved", + this.reserved && this.reserved.length ? this.reserved : undefined, + "comment", + keepComments ? this.comment : undefined, + "comments", + keepComments ? this.comments : undefined + ]); + }; + Enum.prototype.add = function add(name, id, comment, options) { + if (!util.isString(name)) + throw TypeError("name must be a string"); + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + if (name === "__proto__") + return this; + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + if (options) { + if (this.valuesOptions === undefined) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + this.comments[name] = comment || null; + return this; + }; + Enum.prototype.remove = function remove(name) { + if (!util.isString(name)) + throw TypeError("name must be a string"); + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + return this; + }; + Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); + }; + Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); + }; +}); + +// node_modules/protobufjs/src/encoder.js +var require_encoder = __commonJS((exports, module) => { + module.exports = encoder; + var Enum = require_enum(); + var types = require_types5(); + var util = require_util3(); + function genTypePartial(gen, field, fieldIndex, ref) { + return field.delimited ? gen("types[%i].encode(%s,w.uint32(%i),q+1).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) : gen("types[%i].encode(%s,w.uint32(%i).fork(),q+1).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); + } + function encoder(mtype) { + var gen = util.codegen(["m", "w", "q"], mtype.name + "$encode")("if(!w)")("w=Writer.create()")("if(q===undefined)q=0")("if(q>util.recursionLimit)")('throw Error("max depth exceeded")'); + var i, ref; + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + for (var i = 0;i < fields.length; ++i) { + var field = fields[i].resolve(), index = mtype._fieldsArray.indexOf(field), type = field.resolvedType instanceof Enum ? "int32" : field.type, wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + if (field.map) { + gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name)("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) + gen("types[%i].encode(%s[ks[i]],w.uint32(18).fork(),q+1).ldelim().ldelim()", index, ref); + else + gen(".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen("}")("}"); + } else if (field.repeated) { + gen("if(%s!=null&&%s.length){", ref, ref); + if (field.packed && types.packed[type] !== undefined) { + gen("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)("for(var i=0;i<%s.length;++i)", ref)("w.%s(%s[i])", type, ref)("w.ldelim()"); + } else { + gen("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else + gen("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + } + gen("}"); + } else { + if (field.optional) + gen("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else + gen("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + } + } + return gen("return w"); + } +}); + +// node_modules/protobufjs/src/index-light.js +var require_index_light = __commonJS((exports, module) => { + var protobuf = module.exports = require_index_minimal(); + protobuf.build = "light"; + function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root; + } else if (!root) + root = new protobuf.Root; + return root.load(filename, callback); + } + protobuf.load = load; + function loadSync(filename, root) { + if (!root) + root = new protobuf.Root; + return root.loadSync(filename); + } + protobuf.loadSync = loadSync; + protobuf.encoder = require_encoder(); + protobuf.decoder = require_decoder(); + protobuf.verifier = require_verifier(); + protobuf.converter = require_converter(); + protobuf.ReflectionObject = require_object(); + protobuf.Namespace = require_namespace(); + protobuf.Root = require_root(); + protobuf.Enum = require_enum(); + protobuf.Type = require_type2(); + protobuf.Field = require_field(); + protobuf.OneOf = require_oneof(); + protobuf.MapField = require_mapfield(); + protobuf.Service = require_service2(); + protobuf.Method = require_method(); + protobuf.Message = require_message(); + protobuf.wrappers = require_wrappers(); + protobuf.types = require_types5(); + protobuf.util = require_util3(); + protobuf.ReflectionObject._configure(protobuf.Root); + protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); + protobuf.Root._configure(protobuf.Type); + protobuf.Field._configure(protobuf.Type); +}); + +// node_modules/protobufjs/src/tokenize.js +var require_tokenize = __commonJS((exports, module) => { + module.exports = tokenize; + var delimRe = /[\s{}=;:[\],'"()<>]/g; + var stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g; + var stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; + var setCommentRe = /^ *[*/]+ */; + var setCommentAltRe = /^\s*\*?\/*/; + var setCommentSplitRe = /\n/g; + var whitespaceRe = /\s/; + var unescapeRe = /\\(.?)/g; + var unescapeMap = { + "0": "\x00", + r: "\r", + n: ` +`, + t: "\t" + }; + function unescape2(str) { + return str.replace(unescapeRe, function($0, $1) { + switch ($1) { + case "\\": + case "": + return $1; + default: + return unescapeMap[$1] || ""; + } + }); + } + tokenize.unescape = unescape2; + function tokenize(source, alternateCommentMode) { + source = source.toString(); + var offset = 0, length = source.length, line = 1, lastCommentLine = 0, comments = {}; + var stack = []; + var stringDelim = null; + function illegal(subject) { + return Error("illegal " + subject + " (line " + line + ")"); + } + function readString() { + var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; + re.lastIndex = offset - 1; + var match = re.exec(source); + if (!match) + throw illegal("string"); + offset = re.lastIndex; + push(stringDelim); + stringDelim = null; + return unescape2(match[1]); + } + function charAt(pos) { + return source.charAt(pos); + } + function setComment(start, end, isLeading) { + var comment = { + type: source.charAt(start++), + lineEmpty: false, + leading: isLeading + }; + var lookback; + if (alternateCommentMode) { + lookback = 2; + } else { + lookback = 3; + } + var commentOffset = start - lookback, c; + do { + if (--commentOffset < 0 || (c = source.charAt(commentOffset)) === ` +`) { + comment.lineEmpty = true; + break; + } + } while (c === " " || c === "\t"); + var lines = source.substring(start, end).split(setCommentSplitRe); + for (var i = 0;i < lines.length; ++i) + lines[i] = lines[i].replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "").trim(); + comment.text = lines.join(` +`).trim(); + comments[line] = comment; + lastCommentLine = line; + } + function isDoubleSlashCommentLine(startOffset) { + var endOffset = findEndOfLine(startOffset); + var lineText = source.substring(startOffset, endOffset); + var isComment = /^\s*\/\//.test(lineText); + return isComment; + } + function findEndOfLine(cursor) { + var endOffset = cursor; + while (endOffset < length && charAt(endOffset) !== ` +`) { + endOffset++; + } + return endOffset; + } + function next() { + if (stack.length > 0) + return stack.shift(); + if (stringDelim) + return readString(); + var repeat, prev, curr, start, isDoc, isLeadingComment = offset === 0; + do { + if (offset === length) + return null; + repeat = false; + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === ` +`) { + isLeadingComment = true; + ++line; + } + if (++offset === length) + return null; + } + if (charAt(offset) === "/") { + if (++offset === length) { + throw illegal("comment"); + } + if (charAt(offset) === "/") { + if (!alternateCommentMode) { + isDoc = charAt(start = offset + 1) === "/"; + while (charAt(++offset) !== ` +`) { + if (offset === length) { + return null; + } + } + ++offset; + if (isDoc) { + setComment(start, offset - 1, isLeadingComment); + isLeadingComment = true; + } + ++line; + repeat = true; + } else { + start = offset; + isDoc = false; + if (isDoubleSlashCommentLine(offset - 1)) { + isDoc = true; + do { + offset = findEndOfLine(offset); + if (offset === length) { + break; + } + offset++; + if (!isLeadingComment) { + break; + } + } while (isDoubleSlashCommentLine(offset)); + } else { + offset = Math.min(length, findEndOfLine(offset) + 1); + } + if (isDoc) { + setComment(start, offset, isLeadingComment); + isLeadingComment = true; + } + line++; + repeat = true; + } + } else if ((curr = charAt(offset)) === "*") { + start = offset + 1; + isDoc = alternateCommentMode || charAt(start) === "*"; + do { + if (curr === ` +`) { + ++line; + } + if (++offset === length) { + throw illegal("comment"); + } + prev = curr; + curr = charAt(offset); + } while (prev !== "*" || curr !== "/"); + ++offset; + if (isDoc) { + setComment(start, offset - 2, isLeadingComment); + isLeadingComment = true; + } + repeat = true; + } else { + return "/"; + } + } + } while (repeat); + var end = offset; + delimRe.lastIndex = 0; + var delim = delimRe.test(charAt(end++)); + if (!delim) + while (end < length && !delimRe.test(charAt(end))) + ++end; + var token = source.substring(offset, offset = end); + if (token === '"' || token === "'") + stringDelim = token; + return token; + } + function push(token) { + stack.push(token); + } + function peek() { + if (!stack.length) { + var token = next(); + if (token === null) + return null; + push(token); + } + return stack[0]; + } + function skip(expected, optional) { + var actual = peek(), equals = actual === expected; + if (equals) { + next(); + return true; + } + if (!optional) + throw illegal("token '" + actual + "', '" + expected + "' expected"); + return false; + } + function cmnt(trailingLine) { + var ret = null; + var comment; + if (trailingLine === undefined) { + comment = comments[line - 1]; + delete comments[line - 1]; + if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { + ret = comment.leading ? comment.text : null; + } + } else { + if (lastCommentLine < trailingLine) { + peek(); + } + comment = comments[trailingLine]; + delete comments[trailingLine]; + if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { + ret = comment.leading ? null : comment.text; + } + } + return ret; + } + return Object.defineProperty({ + next, + peek, + push, + skip, + cmnt + }, "line", { + get: function() { + return line; + } + }); + } +}); + +// node_modules/protobufjs/src/parse.js +var require_parse = __commonJS((exports, module) => { + module.exports = parse2; + parse2.filename = null; + parse2.defaults = { keepCase: false }; + var tokenize = require_tokenize(); + var Root = require_root(); + var Type = require_type2(); + var Field = require_field(); + var MapField = require_mapfield(); + var OneOf = require_oneof(); + var Enum = require_enum(); + var Service = require_service2(); + var Method = require_method(); + var ReflectionObject = require_object(); + var types = require_types5(); + var util = require_util3(); + var base10Re = /^[1-9][0-9]*$/; + var base10NegRe = /^-?[1-9][0-9]*$/; + var base16Re = /^0[x][0-9a-fA-F]+$/; + var base16NegRe = /^-?0[x][0-9a-fA-F]+$/; + var base8Re = /^0[0-7]+$/; + var base8NegRe = /^-?0[0-7]+$/; + var numberRe = util.patterns.numberRe; + var nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/; + var typeRefRe = util.patterns.typeRefRe; + function parse2(source, root, options) { + if (!(root instanceof Root)) { + options = root; + root = new Root; + } + if (!options) + options = parse2.defaults; + var preferTrailingComment = options.preferTrailingComment || false; + var tn = tokenize(source, options.alternateCommentMode || false), next = tn.next, push = tn.push, peek = tn.peek, skip = tn.skip, cmnt = tn.cmnt; + var head = true, pkg, imports, weakImports, edition = "proto2"; + var ptr = root; + var topLevelObjects = []; + var topLevelOptions = {}; + var applyCase = options.keepCase ? function(name) { + return name; + } : util.camelCase; + function resolveFileFeatures() { + topLevelObjects.forEach((obj) => { + obj._edition = edition; + Object.keys(topLevelOptions).forEach((opt) => { + if (obj.getOption(opt) !== undefined) + return; + obj.setOption(opt, topLevelOptions[opt], true); + }); + }); + } + function illegal(token2, name, insideTryCatch) { + var filename = parse2.filename; + if (!insideTryCatch) + parse2.filename = null; + return Error("illegal " + (name || "token") + " '" + token2 + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + } + function readString() { + var values = [], token2; + do { + if ((token2 = next()) !== '"' && token2 !== "'") + throw illegal(token2); + values.push(next()); + skip(token2); + token2 = peek(); + } while (token2 === '"' || token2 === "'"); + return values.join(""); + } + function readValue(acceptTypeRef) { + var token2 = next(); + switch (token2) { + case "'": + case '"': + push(token2); + return readString(); + case "true": + case "TRUE": + return true; + case "false": + case "FALSE": + return false; + } + try { + return parseNumber(token2, true); + } catch (e) { + if (acceptTypeRef && typeRefRe.test(token2)) + return token2; + throw illegal(token2, "value"); + } + } + function readRanges(target, acceptStrings) { + var token2, start; + do { + if (acceptStrings && ((token2 = peek()) === '"' || token2 === "'")) { + var str = readString(); + target.push(str); + if (edition >= 2023) { + throw illegal(str, "id"); + } + } else { + try { + target.push([start = parseId(next()), skip("to", true) ? parseId(next()) : start]); + } catch (err) { + if (acceptStrings && typeRefRe.test(token2) && edition >= 2023) { + target.push(token2); + } else { + throw err; + } + } + } + } while (skip(",", true)); + var dummy = { options: undefined }; + dummy.setOption = function(name, value) { + if (this.options === undefined) + this.options = {}; + this.options[name] = value; + }; + ifBlock(dummy, function parseRange_block(token3) { + if (token3 === "option") { + parseOption(dummy, token3); + skip(";"); + } else + throw illegal(token3); + }, function parseRange_line() { + parseInlineOptions(dummy); + }); + } + function parseNumber(token2, insideTryCatch) { + var sign = 1; + if (token2.charAt(0) === "-") { + sign = -1; + token2 = token2.substring(1); + } + switch (token2) { + case "inf": + case "INF": + case "Inf": + return sign * Infinity; + case "nan": + case "NAN": + case "Nan": + case "NaN": + return NaN; + case "0": + return 0; + } + if (base10Re.test(token2)) + return sign * parseInt(token2, 10); + if (base16Re.test(token2)) + return sign * parseInt(token2, 16); + if (base8Re.test(token2)) + return sign * parseInt(token2, 8); + if (numberRe.test(token2)) + return sign * parseFloat(token2); + throw illegal(token2, "number", insideTryCatch); + } + function parseId(token2, acceptNegative) { + switch (token2) { + case "max": + case "MAX": + case "Max": + return 536870911; + case "0": + return 0; + } + if (!acceptNegative && token2.charAt(0) === "-") + throw illegal(token2, "id"); + if (base10NegRe.test(token2)) + return parseInt(token2, 10); + if (base16NegRe.test(token2)) + return parseInt(token2, 16); + if (base8NegRe.test(token2)) + return parseInt(token2, 8); + throw illegal(token2, "id"); + } + function parsePackage() { + if (pkg !== undefined) + throw illegal("package"); + pkg = next(); + if (!typeRefRe.test(pkg)) + throw illegal(pkg, "name"); + ptr = ptr.define(pkg); + skip(";"); + } + function parseImport() { + var token2 = peek(); + var whichImports; + switch (token2) { + case "weak": + whichImports = weakImports || (weakImports = []); + next(); + break; + case "public": + next(); + default: + whichImports = imports || (imports = []); + break; + } + token2 = readString(); + skip(";"); + whichImports.push(token2); + } + function parseSyntax() { + skip("="); + edition = readString(); + if (edition < 2023) + throw illegal(edition, "syntax"); + skip(";"); + } + function parseEdition() { + skip("="); + edition = readString(); + const supportedEditions = ["2023"]; + if (!supportedEditions.includes(edition)) + throw illegal(edition, "edition"); + skip(";"); + } + function parseCommon(parent, token2, depth) { + if (depth === undefined) + depth = 0; + switch (token2) { + case "option": + parseOption(parent, token2); + skip(";"); + return true; + case "message": + parseType(parent, token2, depth + 1); + return true; + case "enum": + parseEnum(parent, token2); + return true; + case "service": + parseService(parent, token2, depth + 1); + return true; + case "extend": + parseExtension(parent, token2, depth); + return true; + } + return false; + } + function ifBlock(obj, fnIf, fnElse) { + var trailingLine = tn.line; + if (obj) { + if (typeof obj.comment !== "string") { + obj.comment = cmnt(); + } + obj.filename = parse2.filename; + } + if (skip("{", true)) { + var token2; + while ((token2 = next()) !== "}") + fnIf(token2); + skip(";", true); + } else { + if (fnElse) + fnElse(); + skip(";"); + if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) + obj.comment = cmnt(trailingLine) || obj.comment; + } + } + function parseType(parent, token2, depth) { + if (depth === undefined) + depth = 0; + if (depth > util.nestingLimit) + throw Error("max depth exceeded"); + if (!nameRe.test(token2 = next())) + throw illegal(token2, "type name"); + var type = new Type(token2); + ifBlock(type, function parseType_block(token3) { + if (parseCommon(type, token3, depth)) + return; + switch (token3) { + case "map": + parseMapField(type, token3); + break; + case "required": + if (edition !== "proto2") + throw illegal(token3); + case "repeated": + parseField(type, token3, undefined, depth + 1); + break; + case "optional": + if (edition === "proto3") { + parseField(type, "proto3_optional", undefined, depth + 1); + } else if (edition !== "proto2") { + throw illegal(token3); + } else { + parseField(type, "optional", undefined, depth + 1); + } + break; + case "oneof": + parseOneOf(type, token3, depth + 1); + break; + case "extensions": + readRanges(type.extensions || (type.extensions = [])); + break; + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + default: + if (edition === "proto2" || !typeRefRe.test(token3)) { + throw illegal(token3); + } + push(token3); + parseField(type, "optional", undefined, depth + 1); + break; + } + }); + parent.add(type); + if (parent === ptr) { + topLevelObjects.push(type); + } + } + function parseField(parent, rule, extend, depth) { + var type = next(); + if (type === "group") { + parseGroup(parent, rule, depth); + return; + } + while (type.endsWith(".") || peek().startsWith(".")) { + type += next(); + } + if (!typeRefRe.test(type)) + throw illegal(type, "type"); + var name = next(); + if (!nameRe.test(name)) + throw illegal(name, "name"); + name = applyCase(name); + skip("="); + var field = new Field(name, parseId(next()), type, rule, extend); + ifBlock(field, function parseField_block(token2) { + if (token2 === "option") { + parseOption(field, token2); + skip(";"); + } else + throw illegal(token2); + }, function parseField_line() { + parseInlineOptions(field); + }); + if (rule === "proto3_optional") { + var oneof = new OneOf("_" + name); + field.setOption("proto3_optional", true); + oneof.add(field); + parent.add(oneof); + } else { + parent.add(field); + } + if (parent === ptr) { + topLevelObjects.push(field); + } + } + function parseGroup(parent, rule, depth) { + if (depth === undefined) + depth = 0; + if (depth > util.nestingLimit) + throw Error("max depth exceeded"); + if (edition >= 2023) { + throw illegal("group"); + } + var name = next(); + if (!nameRe.test(name)) + throw illegal(name, "name"); + var fieldName = util.lcFirst(name); + if (name === fieldName) + name = util.ucFirst(name); + skip("="); + var id = parseId(next()); + var type = new Type(name); + type.group = true; + var field = new Field(fieldName, id, name, rule); + field.filename = parse2.filename; + ifBlock(type, function parseGroup_block(token2) { + switch (token2) { + case "option": + parseOption(type, token2); + skip(";"); + break; + case "required": + case "repeated": + parseField(type, token2, undefined, depth + 1); + break; + case "optional": + if (edition === "proto3") { + parseField(type, "proto3_optional", undefined, depth + 1); + } else { + parseField(type, "optional", undefined, depth + 1); + } + break; + case "message": + parseType(type, token2, depth + 1); + break; + case "enum": + parseEnum(type, token2); + break; + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + default: + throw illegal(token2); + } + }); + parent.add(type).add(field); + } + function parseMapField(parent) { + skip("<"); + var keyType = next(); + if (types.mapKey[keyType] === undefined) + throw illegal(keyType, "type"); + skip(","); + var valueType = next(); + if (!typeRefRe.test(valueType)) + throw illegal(valueType, "type"); + skip(">"); + var name = next(); + if (!nameRe.test(name)) + throw illegal(name, "name"); + skip("="); + var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); + ifBlock(field, function parseMapField_block(token2) { + if (token2 === "option") { + parseOption(field, token2); + skip(";"); + } else + throw illegal(token2); + }, function parseMapField_line() { + parseInlineOptions(field); + }); + parent.add(field); + } + function parseOneOf(parent, token2, depth) { + if (!nameRe.test(token2 = next())) + throw illegal(token2, "name"); + var oneof = new OneOf(applyCase(token2)); + ifBlock(oneof, function parseOneOf_block(token3) { + if (token3 === "option") { + parseOption(oneof, token3); + skip(";"); + } else { + push(token3); + parseField(oneof, "optional", undefined, depth); + } + }); + parent.add(oneof); + } + function parseEnum(parent, token2) { + if (!nameRe.test(token2 = next())) + throw illegal(token2, "name"); + var enm = new Enum(token2); + ifBlock(enm, function parseEnum_block(token3) { + switch (token3) { + case "option": + parseOption(enm, token3); + skip(";"); + break; + case "reserved": + readRanges(enm.reserved || (enm.reserved = []), true); + if (enm.reserved === undefined) + enm.reserved = []; + break; + default: + parseEnumValue(enm, token3); + } + }); + parent.add(enm); + if (parent === ptr) { + topLevelObjects.push(enm); + } + } + function parseEnumValue(parent, token2) { + if (!nameRe.test(token2)) + throw illegal(token2, "name"); + skip("="); + var value = parseId(next(), true), dummy = { + options: undefined + }; + dummy.getOption = function(name) { + return this.options[name]; + }; + dummy.setOption = function(name, value2) { + ReflectionObject.prototype.setOption.call(dummy, name, value2); + }; + dummy.setParsedOption = function() { + return; + }; + ifBlock(dummy, function parseEnumValue_block(token3) { + if (token3 === "option") { + parseOption(dummy, token3); + skip(";"); + } else + throw illegal(token3); + }, function parseEnumValue_line() { + parseInlineOptions(dummy); + }); + parent.add(token2, value, dummy.comment, dummy.parsedOptions || dummy.options); + } + function parseOption(parent, token2) { + var option; + var propName; + var isOption = true; + if (token2 === "option") { + token2 = next(); + } + while (token2 !== "=") { + if (token2 === "(") { + var parensValue = next(); + skip(")"); + token2 = "(" + parensValue + ")"; + } + if (isOption) { + isOption = false; + if (token2.includes(".") && !token2.includes("(")) { + var tokens = token2.split("."); + option = tokens[0] + "."; + token2 = tokens[1]; + continue; + } + option = token2; + } else { + propName = propName ? propName += token2 : token2; + } + token2 = next(); + } + var name = propName ? option.concat(propName) : option; + var optionValue = parseOptionValue(parent, name); + propName = propName && propName[0] === "." ? propName.slice(1) : propName; + option = option && option[option.length - 1] === "." ? option.slice(0, -1) : option; + setParsedOption(parent, option, optionValue, propName); + } + function parseOptionValue(parent, name, depth) { + if (depth === undefined) + depth = 0; + if (depth > util.recursionLimit) + throw Error("max depth exceeded"); + if (skip("{", true)) { + var objectResult = {}; + while (!skip("}", true)) { + if (!nameRe.test(token = next())) { + throw illegal(token, "name"); + } + if (token === null) { + throw illegal(token, "end of input"); + } + var value; + var propName = token; + skip(":", true); + if (peek() === "{") { + value = parseOptionValue(parent, name + "." + token, depth + 1); + } else if (peek() === "[") { + value = []; + var lastValue; + if (skip("[", true)) { + do { + lastValue = readValue(true); + value.push(lastValue); + } while (skip(",", true)); + skip("]"); + if (typeof lastValue !== "undefined") { + setOption(parent, name + "." + token, lastValue); + } + } + } else { + value = readValue(true); + setOption(parent, name + "." + token, value); + } + var prevValue = objectResult[propName]; + if (prevValue) + value = [].concat(prevValue).concat(value); + if (propName !== "__proto__") + objectResult[propName] = value; + skip(",", true); + skip(";", true); + } + return objectResult; + } + var simpleValue = readValue(true); + setOption(parent, name, simpleValue); + return simpleValue; + } + function setOption(parent, name, value) { + if (ptr === parent && /^features\./.test(name)) { + topLevelOptions[name] = value; + return; + } + if (parent.setOption) + parent.setOption(name, value); + } + function setParsedOption(parent, name, value, propName) { + if (parent.setParsedOption) + parent.setParsedOption(name, value, propName); + } + function parseInlineOptions(parent) { + if (skip("[", true)) { + do { + parseOption(parent, "option"); + } while (skip(",", true)); + skip("]"); + } + return parent; + } + function parseService(parent, token2, depth) { + if (depth === undefined) + depth = 0; + if (depth > util.recursionLimit) + throw Error("max depth exceeded"); + if (!nameRe.test(token2 = next())) + throw illegal(token2, "service name"); + var service = new Service(token2); + ifBlock(service, function parseService_block(token3) { + if (parseCommon(service, token3, depth)) { + return; + } + if (token3 === "rpc") + parseMethod(service, token3); + else + throw illegal(token3); + }); + parent.add(service); + if (parent === ptr) { + topLevelObjects.push(service); + } + } + function parseMethod(parent, token2) { + var commentText = cmnt(); + var type = token2; + if (!nameRe.test(token2 = next())) + throw illegal(token2, "name"); + var name = token2, requestType, requestStream, responseType, responseStream; + skip("("); + if (skip("stream", true)) + requestStream = true; + if (!typeRefRe.test(token2 = next())) + throw illegal(token2); + requestType = token2; + skip(")"); + skip("returns"); + skip("("); + if (skip("stream", true)) + responseStream = true; + if (!typeRefRe.test(token2 = next())) + throw illegal(token2); + responseType = token2; + skip(")"); + var method = new Method(name, type, requestType, responseType, requestStream, responseStream); + method.comment = commentText; + ifBlock(method, function parseMethod_block(token3) { + if (token3 === "option") { + parseOption(method, token3); + skip(";"); + } else + throw illegal(token3); + }); + parent.add(method); + } + function parseExtension(parent, token2, depth) { + if (!typeRefRe.test(token2 = next())) + throw illegal(token2, "reference"); + var reference = token2; + ifBlock(null, function parseExtension_block(token3) { + switch (token3) { + case "required": + case "repeated": + parseField(parent, token3, reference, depth + 1); + break; + case "optional": + if (edition === "proto3") { + parseField(parent, "proto3_optional", reference, depth + 1); + } else { + parseField(parent, "optional", reference, depth + 1); + } + break; + default: + if (edition === "proto2" || !typeRefRe.test(token3)) + throw illegal(token3); + push(token3); + parseField(parent, "optional", reference, depth + 1); + break; + } + }); + } + var token; + while ((token = next()) !== null) { + switch (token) { + case "package": + if (!head) + throw illegal(token); + parsePackage(); + break; + case "import": + if (!head) + throw illegal(token); + parseImport(); + break; + case "syntax": + if (!head) + throw illegal(token); + parseSyntax(); + break; + case "edition": + if (!head) + throw illegal(token); + parseEdition(); + break; + case "option": + parseOption(ptr, token); + skip(";", true); + break; + default: + if (parseCommon(ptr, token, 0)) { + head = false; + continue; + } + throw illegal(token); + } + } + resolveFileFeatures(); + parse2.filename = null; + return { + package: pkg, + imports, + weakImports, + root + }; + } +}); + +// node_modules/protobufjs/src/common.js +var require_common2 = __commonJS((exports, module) => { + module.exports = common; + var commonRe = /\/|\./; + function common(name, json) { + if (!commonRe.test(name)) { + name = "google/protobuf/" + name + ".proto"; + json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; + } + common[name] = json; + } + common("any", { + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } + }); + var timeType; + common("duration", { + Duration: timeType = { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + } + }); + common("timestamp", { + Timestamp: timeType + }); + common("empty", { + Empty: { + fields: {} + } + }); + common("struct", { + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + } + }); + common("wrappers", { + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + } + }); + common("field_mask", { + FieldMask: { + fields: { + paths: { + rule: "repeated", + type: "string", + id: 1 + } + } + } + }); + common.get = function get(file) { + return common[file] || null; + }; +}); + +// node_modules/protobufjs/src/index.js +var require_src17 = __commonJS((exports, module) => { + var protobuf = module.exports = require_index_light(); + protobuf.build = "full"; + protobuf.tokenize = require_tokenize(); + protobuf.parse = require_parse(); + protobuf.common = require_common2(); + protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); +}); + +// node_modules/protobufjs/google/protobuf/descriptor.json +var require_descriptor = __commonJS((exports, module) => { + module.exports = { + nested: { + google: { + nested: { + protobuf: { + options: { + go_package: "google.golang.org/protobuf/types/descriptorpb", + java_package: "com.google.protobuf", + java_outer_classname: "DescriptorProtos", + csharp_namespace: "Google.Protobuf.Reflection", + objc_class_prefix: "GPB", + cc_enable_arenas: true, + optimize_for: "SPEED" + }, + nested: { + FileDescriptorSet: { + edition: "proto2", + fields: { + file: { + rule: "repeated", + type: "FileDescriptorProto", + id: 1 + } + }, + extensions: [ + [ + 536000000, + 536000000 + ] + ] + }, + Edition: { + edition: "proto2", + values: { + EDITION_UNKNOWN: 0, + EDITION_LEGACY: 900, + EDITION_PROTO2: 998, + EDITION_PROTO3: 999, + EDITION_2023: 1000, + EDITION_2024: 1001, + EDITION_1_TEST_ONLY: 1, + EDITION_2_TEST_ONLY: 2, + EDITION_99997_TEST_ONLY: 99997, + EDITION_99998_TEST_ONLY: 99998, + EDITION_99999_TEST_ONLY: 99999, + EDITION_MAX: 2147483647 + } + }, + FileDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + package: { + type: "string", + id: 2 + }, + dependency: { + rule: "repeated", + type: "string", + id: 3 + }, + publicDependency: { + rule: "repeated", + type: "int32", + id: 10 + }, + weakDependency: { + rule: "repeated", + type: "int32", + id: 11 + }, + optionDependency: { + rule: "repeated", + type: "string", + id: 15 + }, + messageType: { + rule: "repeated", + type: "DescriptorProto", + id: 4 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 5 + }, + service: { + rule: "repeated", + type: "ServiceDescriptorProto", + id: 6 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 7 + }, + options: { + type: "FileOptions", + id: 8 + }, + sourceCodeInfo: { + type: "SourceCodeInfo", + id: 9 + }, + syntax: { + type: "string", + id: 12 + }, + edition: { + type: "Edition", + id: 14 + } + } + }, + DescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + field: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 2 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 6 + }, + nestedType: { + rule: "repeated", + type: "DescriptorProto", + id: 3 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 4 + }, + extensionRange: { + rule: "repeated", + type: "ExtensionRange", + id: 5 + }, + oneofDecl: { + rule: "repeated", + type: "OneofDescriptorProto", + id: 8 + }, + options: { + type: "MessageOptions", + id: 7 + }, + reservedRange: { + rule: "repeated", + type: "ReservedRange", + id: 9 + }, + reservedName: { + rule: "repeated", + type: "string", + id: 10 + }, + visibility: { + type: "SymbolVisibility", + id: 11 + } + }, + nested: { + ExtensionRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + }, + options: { + type: "ExtensionRangeOptions", + id: 3 + } + } + }, + ReservedRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + } + } + }, + ExtensionRangeOptions: { + edition: "proto2", + fields: { + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + }, + declaration: { + rule: "repeated", + type: "Declaration", + id: 2, + options: { + retention: "RETENTION_SOURCE" + } + }, + features: { + type: "FeatureSet", + id: 50 + }, + verification: { + type: "VerificationState", + id: 3, + options: { + default: "UNVERIFIED", + retention: "RETENTION_SOURCE" + } + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + nested: { + Declaration: { + fields: { + number: { + type: "int32", + id: 1 + }, + fullName: { + type: "string", + id: 2 + }, + type: { + type: "string", + id: 3 + }, + reserved: { + type: "bool", + id: 5 + }, + repeated: { + type: "bool", + id: 6 + } + }, + reserved: [ + [ + 4, + 4 + ] + ] + }, + VerificationState: { + values: { + DECLARATION: 0, + UNVERIFIED: 1 + } + } + } + }, + FieldDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 3 + }, + label: { + type: "Label", + id: 4 + }, + type: { + type: "Type", + id: 5 + }, + typeName: { + type: "string", + id: 6 + }, + extendee: { + type: "string", + id: 2 + }, + defaultValue: { + type: "string", + id: 7 + }, + oneofIndex: { + type: "int32", + id: 9 + }, + jsonName: { + type: "string", + id: 10 + }, + options: { + type: "FieldOptions", + id: 8 + }, + proto3Optional: { + type: "bool", + id: 17 + } + }, + nested: { + Type: { + values: { + TYPE_DOUBLE: 1, + TYPE_FLOAT: 2, + TYPE_INT64: 3, + TYPE_UINT64: 4, + TYPE_INT32: 5, + TYPE_FIXED64: 6, + TYPE_FIXED32: 7, + TYPE_BOOL: 8, + TYPE_STRING: 9, + TYPE_GROUP: 10, + TYPE_MESSAGE: 11, + TYPE_BYTES: 12, + TYPE_UINT32: 13, + TYPE_ENUM: 14, + TYPE_SFIXED32: 15, + TYPE_SFIXED64: 16, + TYPE_SINT32: 17, + TYPE_SINT64: 18 + } + }, + Label: { + values: { + LABEL_OPTIONAL: 1, + LABEL_REPEATED: 3, + LABEL_REQUIRED: 2 + } + } + } + }, + OneofDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + options: { + type: "OneofOptions", + id: 2 + } + } + }, + EnumDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + value: { + rule: "repeated", + type: "EnumValueDescriptorProto", + id: 2 + }, + options: { + type: "EnumOptions", + id: 3 + }, + reservedRange: { + rule: "repeated", + type: "EnumReservedRange", + id: 4 + }, + reservedName: { + rule: "repeated", + type: "string", + id: 5 + }, + visibility: { + type: "SymbolVisibility", + id: 6 + } + }, + nested: { + EnumReservedRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + } + } + }, + EnumValueDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 2 + }, + options: { + type: "EnumValueOptions", + id: 3 + } + } + }, + ServiceDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + method: { + rule: "repeated", + type: "MethodDescriptorProto", + id: 2 + }, + options: { + type: "ServiceOptions", + id: 3 + } + } + }, + MethodDescriptorProto: { + edition: "proto2", + fields: { + name: { + type: "string", + id: 1 + }, + inputType: { + type: "string", + id: 2 + }, + outputType: { + type: "string", + id: 3 + }, + options: { + type: "MethodOptions", + id: 4 + }, + clientStreaming: { + type: "bool", + id: 5 + }, + serverStreaming: { + type: "bool", + id: 6 + } + } + }, + FileOptions: { + edition: "proto2", + fields: { + javaPackage: { + type: "string", + id: 1 + }, + javaOuterClassname: { + type: "string", + id: 8 + }, + javaMultipleFiles: { + type: "bool", + id: 10 + }, + javaGenerateEqualsAndHash: { + type: "bool", + id: 20, + options: { + deprecated: true + } + }, + javaStringCheckUtf8: { + type: "bool", + id: 27 + }, + optimizeFor: { + type: "OptimizeMode", + id: 9, + options: { + default: "SPEED" + } + }, + goPackage: { + type: "string", + id: 11 + }, + ccGenericServices: { + type: "bool", + id: 16 + }, + javaGenericServices: { + type: "bool", + id: 17 + }, + pyGenericServices: { + type: "bool", + id: 18 + }, + deprecated: { + type: "bool", + id: 23 + }, + ccEnableArenas: { + type: "bool", + id: 31, + options: { + default: true + } + }, + objcClassPrefix: { + type: "string", + id: 36 + }, + csharpNamespace: { + type: "string", + id: 37 + }, + swiftPrefix: { + type: "string", + id: 39 + }, + phpClassPrefix: { + type: "string", + id: 40 + }, + phpNamespace: { + type: "string", + id: 41 + }, + phpMetadataNamespace: { + type: "string", + id: 44 + }, + rubyPackage: { + type: "string", + id: 45 + }, + features: { + type: "FeatureSet", + id: 50 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 42, + 42 + ], + [ + 38, + 38 + ], + "php_generic_services" + ], + nested: { + OptimizeMode: { + values: { + SPEED: 1, + CODE_SIZE: 2, + LITE_RUNTIME: 3 + } + } + } + }, + MessageOptions: { + edition: "proto2", + fields: { + messageSetWireFormat: { + type: "bool", + id: 1 + }, + noStandardDescriptorAccessor: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + mapEntry: { + type: "bool", + id: 7 + }, + deprecatedLegacyJsonFieldConflicts: { + type: "bool", + id: 11, + options: { + deprecated: true + } + }, + features: { + type: "FeatureSet", + id: 12 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 4, + 4 + ], + [ + 5, + 5 + ], + [ + 6, + 6 + ], + [ + 8, + 8 + ], + [ + 9, + 9 + ] + ] + }, + FieldOptions: { + edition: "proto2", + fields: { + ctype: { + type: "CType", + id: 1, + options: { + default: "STRING" + } + }, + packed: { + type: "bool", + id: 2 + }, + jstype: { + type: "JSType", + id: 6, + options: { + default: "JS_NORMAL" + } + }, + lazy: { + type: "bool", + id: 5 + }, + unverifiedLazy: { + type: "bool", + id: 15 + }, + deprecated: { + type: "bool", + id: 3 + }, + weak: { + type: "bool", + id: 10, + options: { + deprecated: true + } + }, + debugRedact: { + type: "bool", + id: 16 + }, + retention: { + type: "OptionRetention", + id: 17 + }, + targets: { + rule: "repeated", + type: "OptionTargetType", + id: 19 + }, + editionDefaults: { + rule: "repeated", + type: "EditionDefault", + id: 20 + }, + features: { + type: "FeatureSet", + id: 21 + }, + featureSupport: { + type: "FeatureSupport", + id: 22 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 4, + 4 + ], + [ + 18, + 18 + ] + ], + nested: { + CType: { + values: { + STRING: 0, + CORD: 1, + STRING_PIECE: 2 + } + }, + JSType: { + values: { + JS_NORMAL: 0, + JS_STRING: 1, + JS_NUMBER: 2 + } + }, + OptionRetention: { + values: { + RETENTION_UNKNOWN: 0, + RETENTION_RUNTIME: 1, + RETENTION_SOURCE: 2 + } + }, + OptionTargetType: { + values: { + TARGET_TYPE_UNKNOWN: 0, + TARGET_TYPE_FILE: 1, + TARGET_TYPE_EXTENSION_RANGE: 2, + TARGET_TYPE_MESSAGE: 3, + TARGET_TYPE_FIELD: 4, + TARGET_TYPE_ONEOF: 5, + TARGET_TYPE_ENUM: 6, + TARGET_TYPE_ENUM_ENTRY: 7, + TARGET_TYPE_SERVICE: 8, + TARGET_TYPE_METHOD: 9 + } + }, + EditionDefault: { + fields: { + edition: { + type: "Edition", + id: 3 + }, + value: { + type: "string", + id: 2 + } + } + }, + FeatureSupport: { + fields: { + editionIntroduced: { + type: "Edition", + id: 1 + }, + editionDeprecated: { + type: "Edition", + id: 2 + }, + deprecationWarning: { + type: "string", + id: 3 + }, + editionRemoved: { + type: "Edition", + id: 4 + } + } + } + } + }, + OneofOptions: { + edition: "proto2", + fields: { + features: { + type: "FeatureSet", + id: 1 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + EnumOptions: { + edition: "proto2", + fields: { + allowAlias: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + deprecatedLegacyJsonFieldConflicts: { + type: "bool", + id: 6, + options: { + deprecated: true + } + }, + features: { + type: "FeatureSet", + id: 7 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 5, + 5 + ] + ] + }, + EnumValueOptions: { + edition: "proto2", + fields: { + deprecated: { + type: "bool", + id: 1 + }, + features: { + type: "FeatureSet", + id: 2 + }, + debugRedact: { + type: "bool", + id: 3 + }, + featureSupport: { + type: "FieldOptions.FeatureSupport", + id: 4 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + ServiceOptions: { + edition: "proto2", + fields: { + features: { + type: "FeatureSet", + id: 34 + }, + deprecated: { + type: "bool", + id: 33 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + MethodOptions: { + edition: "proto2", + fields: { + deprecated: { + type: "bool", + id: 33 + }, + idempotencyLevel: { + type: "IdempotencyLevel", + id: 34, + options: { + default: "IDEMPOTENCY_UNKNOWN" + } + }, + features: { + type: "FeatureSet", + id: 35 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + nested: { + IdempotencyLevel: { + values: { + IDEMPOTENCY_UNKNOWN: 0, + NO_SIDE_EFFECTS: 1, + IDEMPOTENT: 2 + } + } + } + }, + UninterpretedOption: { + edition: "proto2", + fields: { + name: { + rule: "repeated", + type: "NamePart", + id: 2 + }, + identifierValue: { + type: "string", + id: 3 + }, + positiveIntValue: { + type: "uint64", + id: 4 + }, + negativeIntValue: { + type: "int64", + id: 5 + }, + doubleValue: { + type: "double", + id: 6 + }, + stringValue: { + type: "bytes", + id: 7 + }, + aggregateValue: { + type: "string", + id: 8 + } + }, + nested: { + NamePart: { + fields: { + namePart: { + rule: "required", + type: "string", + id: 1 + }, + isExtension: { + rule: "required", + type: "bool", + id: 2 + } + } + } + } + }, + FeatureSet: { + edition: "proto2", + fields: { + fieldPresence: { + type: "FieldPresence", + id: 1, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_2023", + "edition_defaults.value": "EXPLICIT" + } + }, + enumType: { + type: "EnumType", + id: 2, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "OPEN" + } + }, + repeatedFieldEncoding: { + type: "RepeatedFieldEncoding", + id: 3, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "PACKED" + } + }, + utf8Validation: { + type: "Utf8Validation", + id: 4, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "VERIFY" + } + }, + messageEncoding: { + type: "MessageEncoding", + id: 5, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_LEGACY", + "edition_defaults.value": "LENGTH_PREFIXED" + } + }, + jsonFormat: { + type: "JsonFormat", + id: 6, + options: { + retention: "RETENTION_RUNTIME", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2023", + "edition_defaults.edition": "EDITION_PROTO3", + "edition_defaults.value": "ALLOW" + } + }, + enforceNamingStyle: { + type: "EnforceNamingStyle", + id: 7, + options: { + retention: "RETENTION_SOURCE", + targets: "TARGET_TYPE_METHOD", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "STYLE2024" + } + }, + defaultSymbolVisibility: { + type: "VisibilityFeature.DefaultSymbolVisibility", + id: 8, + options: { + retention: "RETENTION_SOURCE", + targets: "TARGET_TYPE_FILE", + "feature_support.edition_introduced": "EDITION_2024", + "edition_defaults.edition": "EDITION_2024", + "edition_defaults.value": "EXPORT_TOP_LEVEL" + } + } + }, + extensions: [ + [ + 1000, + 9994 + ], + [ + 9995, + 9999 + ], + [ + 1e4, + 1e4 + ] + ], + reserved: [ + [ + 999, + 999 + ] + ], + nested: { + FieldPresence: { + values: { + FIELD_PRESENCE_UNKNOWN: 0, + EXPLICIT: 1, + IMPLICIT: 2, + LEGACY_REQUIRED: 3 + } + }, + EnumType: { + values: { + ENUM_TYPE_UNKNOWN: 0, + OPEN: 1, + CLOSED: 2 + } + }, + RepeatedFieldEncoding: { + values: { + REPEATED_FIELD_ENCODING_UNKNOWN: 0, + PACKED: 1, + EXPANDED: 2 + } + }, + Utf8Validation: { + values: { + UTF8_VALIDATION_UNKNOWN: 0, + VERIFY: 2, + NONE: 3 + } + }, + MessageEncoding: { + values: { + MESSAGE_ENCODING_UNKNOWN: 0, + LENGTH_PREFIXED: 1, + DELIMITED: 2 + } + }, + JsonFormat: { + values: { + JSON_FORMAT_UNKNOWN: 0, + ALLOW: 1, + LEGACY_BEST_EFFORT: 2 + } + }, + EnforceNamingStyle: { + values: { + ENFORCE_NAMING_STYLE_UNKNOWN: 0, + STYLE2024: 1, + STYLE_LEGACY: 2 + } + }, + VisibilityFeature: { + fields: {}, + reserved: [ + [ + 1, + 536870911 + ] + ], + nested: { + DefaultSymbolVisibility: { + values: { + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: 0, + EXPORT_ALL: 1, + EXPORT_TOP_LEVEL: 2, + LOCAL_ALL: 3, + STRICT: 4 + } + } + } + } + } + }, + FeatureSetDefaults: { + edition: "proto2", + fields: { + defaults: { + rule: "repeated", + type: "FeatureSetEditionDefault", + id: 1 + }, + minimumEdition: { + type: "Edition", + id: 4 + }, + maximumEdition: { + type: "Edition", + id: 5 + } + }, + nested: { + FeatureSetEditionDefault: { + fields: { + edition: { + type: "Edition", + id: 3 + }, + overridableFeatures: { + type: "FeatureSet", + id: 4 + }, + fixedFeatures: { + type: "FeatureSet", + id: 5 + } + }, + reserved: [ + [ + 1, + 1 + ], + [ + 2, + 2 + ], + "features" + ] + } + } + }, + SourceCodeInfo: { + edition: "proto2", + fields: { + location: { + rule: "repeated", + type: "Location", + id: 1 + } + }, + extensions: [ + [ + 536000000, + 536000000 + ] + ], + nested: { + Location: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1, + options: { + packed: true + } + }, + span: { + rule: "repeated", + type: "int32", + id: 2, + options: { + packed: true + } + }, + leadingComments: { + type: "string", + id: 3 + }, + trailingComments: { + type: "string", + id: 4 + }, + leadingDetachedComments: { + rule: "repeated", + type: "string", + id: 6 + } + } + } + } + }, + GeneratedCodeInfo: { + edition: "proto2", + fields: { + annotation: { + rule: "repeated", + type: "Annotation", + id: 1 + } + }, + nested: { + Annotation: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1, + options: { + packed: true + } + }, + sourceFile: { + type: "string", + id: 2 + }, + begin: { + type: "int32", + id: 3 + }, + end: { + type: "int32", + id: 4 + }, + semantic: { + type: "Semantic", + id: 5 + } + }, + nested: { + Semantic: { + values: { + NONE: 0, + SET: 1, + ALIAS: 2 + } + } + } + } + } + }, + SymbolVisibility: { + edition: "proto2", + values: { + VISIBILITY_UNSET: 0, + VISIBILITY_LOCAL: 1, + VISIBILITY_EXPORT: 2 + } + } + } + } + } + } + } + }; +}); + +// node_modules/protobufjs/ext/descriptor/index.js +var require_descriptor2 = __commonJS((exports, module) => { + var $protobuf = require_src17(); + module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(require_descriptor()).lookup(".google.protobuf"); + var Namespace = $protobuf.Namespace; + var Root = $protobuf.Root; + var Enum = $protobuf.Enum; + var Type = $protobuf.Type; + var Field = $protobuf.Field; + var MapField = $protobuf.MapField; + var OneOf = $protobuf.OneOf; + var Service = $protobuf.Service; + var Method = $protobuf.Method; + var patterns = $protobuf.util.patterns; + var numberRe = patterns.numberRe; + var typeRefRe = patterns.typeRefRe; + Root.fromDescriptor = function fromDescriptor(descriptor) { + if (typeof descriptor.length === "number") + descriptor = exports.FileDescriptorSet.decode(descriptor); + var root = new Root; + if (descriptor.file) { + var fileDescriptor, filePackage; + for (var j = 0, i;j < descriptor.file.length; ++j) { + filePackage = root; + if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) + filePackage = root.define(fileDescriptor["package"]); + var edition = editionFromDescriptor(fileDescriptor); + if (fileDescriptor.name && fileDescriptor.name.length) + root.files.push(filePackage.filename = fileDescriptor.name); + if (fileDescriptor.messageType) + for (i = 0;i < fileDescriptor.messageType.length; ++i) + filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], edition)); + if (fileDescriptor.enumType) + for (i = 0;i < fileDescriptor.enumType.length; ++i) + filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i], edition)); + if (fileDescriptor.extension) + for (i = 0;i < fileDescriptor.extension.length; ++i) + filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i], edition)); + if (fileDescriptor.service) + for (i = 0;i < fileDescriptor.service.length; ++i) + filePackage.add(Service.fromDescriptor(fileDescriptor.service[i], edition)); + var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions); + if (opts) { + var ks = Object.keys(opts); + for (i = 0;i < ks.length; ++i) + filePackage.setOption(ks[i], opts[ks[i]]); + } + } + } + return root.resolveAll(); + }; + Root.prototype.toDescriptor = function toDescriptor(edition) { + var set = exports.FileDescriptorSet.create(); + Root_toDescriptorRecursive(this, set.file, edition); + return set; + }; + function Root_toDescriptorRecursive(ns, files2, edition) { + var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); + editionToDescriptor(edition, file); + if (!(ns instanceof Root)) + file["package"] = ns.fullName.substring(1); + for (var i = 0, nested;i < ns.nestedArray.length; ++i) + if ((nested = ns._nestedArray[i]) instanceof Type) + file.messageType.push(nested.toDescriptor(edition)); + else if (nested instanceof Enum) + file.enumType.push(nested.toDescriptor()); + else if (nested instanceof Field) + file.extension.push(nested.toDescriptor(edition)); + else if (nested instanceof Service) + file.service.push(nested.toDescriptor()); + else if (nested instanceof Namespace) + Root_toDescriptorRecursive(nested, files2, edition); + file.options = toDescriptorOptions(ns.options, exports.FileOptions); + if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) + files2.push(file); + } + var unnamedMessageIndex = 0; + Type.fromDescriptor = function fromDescriptor(descriptor, edition, nested, depth) { + if (depth === undefined) + depth = 0; + if (depth > $protobuf.util.nestingLimit) + throw Error("max depth exceeded"); + if (typeof descriptor.length === "number") + descriptor = exports.DescriptorProto.decode(descriptor); + var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)), i; + if (!nested) + type._edition = edition; + if (descriptor.oneofDecl) + for (i = 0;i < descriptor.oneofDecl.length; ++i) + type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); + if (descriptor.field) + for (i = 0;i < descriptor.field.length; ++i) { + var field = Field.fromDescriptor(descriptor.field[i], edition, true); + type.add(field); + if (descriptor.field[i].hasOwnProperty("oneofIndex")) + type.oneofsArray[descriptor.field[i].oneofIndex].add(field); + } + if (descriptor.extension) + for (i = 0;i < descriptor.extension.length; ++i) + type.add(Field.fromDescriptor(descriptor.extension[i], edition, true)); + if (descriptor.nestedType) + for (i = 0;i < descriptor.nestedType.length; ++i) { + type.add(Type.fromDescriptor(descriptor.nestedType[i], edition, true, depth + 1)); + if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) + type.setOption("map_entry", true); + } + if (descriptor.enumType) + for (i = 0;i < descriptor.enumType.length; ++i) + type.add(Enum.fromDescriptor(descriptor.enumType[i], edition, true)); + if (descriptor.extensionRange && descriptor.extensionRange.length) { + type.extensions = []; + for (i = 0;i < descriptor.extensionRange.length; ++i) + type.extensions.push([descriptor.extensionRange[i].start, descriptor.extensionRange[i].end]); + } + if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { + type.reserved = []; + if (descriptor.reservedRange) + for (i = 0;i < descriptor.reservedRange.length; ++i) + type.reserved.push([descriptor.reservedRange[i].start, descriptor.reservedRange[i].end]); + if (descriptor.reservedName) + for (i = 0;i < descriptor.reservedName.length; ++i) + type.reserved.push(descriptor.reservedName[i]); + } + return type; + }; + Type.prototype.toDescriptor = function toDescriptor(edition) { + var descriptor = exports.DescriptorProto.create({ name: this.name }), i; + for (i = 0;i < this.fieldsArray.length; ++i) { + var fieldDescriptor; + descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(edition)); + if (this._fieldsArray[i] instanceof MapField) { + var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType, false), valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType, false), valueTypeName = valueType === 11 || valueType === 14 ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type : undefined; + descriptor.nestedType.push(exports.DescriptorProto.create({ + name: fieldDescriptor.typeName, + field: [ + exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), + exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) + ], + options: exports.MessageOptions.create({ mapEntry: true }) + })); + } + } + for (i = 0;i < this.oneofsArray.length; ++i) + descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); + for (i = 0;i < this.nestedArray.length; ++i) { + if (this._nestedArray[i] instanceof Field) + descriptor.field.push(this._nestedArray[i].toDescriptor(edition)); + else if (this._nestedArray[i] instanceof Type) + descriptor.nestedType.push(this._nestedArray[i].toDescriptor(edition)); + else if (this._nestedArray[i] instanceof Enum) + descriptor.enumType.push(this._nestedArray[i].toDescriptor()); + } + if (this.extensions) + for (i = 0;i < this.extensions.length; ++i) + descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); + if (this.reserved) + for (i = 0;i < this.reserved.length; ++i) + if (typeof this.reserved[i] === "string") + descriptor.reservedName.push(this.reserved[i]); + else + descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); + descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions); + return descriptor; + }; + Field.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + if (typeof descriptor.length === "number") + descriptor = exports.DescriptorProto.decode(descriptor); + if (typeof descriptor.number !== "number") + throw Error("missing field id"); + var typeName = descriptor.typeName, fieldType; + if (typeName != null && typeName !== "") { + if (typeof typeName !== "string" || !typeRefRe.test(typeName)) + throw Error("illegal type name: " + typeName); + fieldType = typeName; + } else + fieldType = fromDescriptorType(descriptor.type); + var fieldRule; + switch (descriptor.label) { + case 1: + fieldRule = undefined; + break; + case 2: + fieldRule = "required"; + break; + case 3: + fieldRule = "repeated"; + break; + default: + throw Error("illegal label: " + descriptor.label); + } + var extendee = descriptor.extendee; + if (extendee != null && extendee !== "") { + if (typeof extendee !== "string" || !typeRefRe.test(extendee)) + throw Error("illegal type name: " + extendee); + } else + extendee = undefined; + var field = new Field(descriptor.name.length ? descriptor.name : "field" + descriptor.number, descriptor.number, fieldType, fieldRule, extendee); + if (!nested) + field._edition = edition; + field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions); + if (descriptor.proto3_optional) + field.options.proto3_optional = true; + if (descriptor.defaultValue && descriptor.defaultValue.length) { + var defaultValue = descriptor.defaultValue; + switch (defaultValue) { + case "true": + case "TRUE": + defaultValue = true; + break; + case "false": + case "FALSE": + defaultValue = false; + break; + default: + var match = numberRe.exec(defaultValue); + if (match) + defaultValue = parseInt(defaultValue); + break; + } + field.setOption("default", defaultValue); + } + if (packableDescriptorType(descriptor.type)) { + if (edition === "proto3") { + if (descriptor.options && !descriptor.options.packed) + field.setOption("packed", false); + } else if ((!edition || edition === "proto2") && descriptor.options && descriptor.options.packed) + field.setOption("packed", true); + } + return field; + }; + Field.prototype.toDescriptor = function toDescriptor(edition) { + var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id }); + if (this.map) { + descriptor.type = 11; + descriptor.typeName = $protobuf.util.ucFirst(this.name); + descriptor.label = 3; + } else { + switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType, this.delimited)) { + case 10: + case 11: + case 14: + descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; + break; + } + if (this.rule === "repeated") { + descriptor.label = 3; + } else if (this.required && edition === "proto2") { + descriptor.label = 2; + } else { + descriptor.label = 1; + } + } + descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; + if (this.partOf && this.parent instanceof Type) { + if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) + throw Error("missing oneof"); + } + if (this.options) { + descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions); + if (this.options["default"] != null) + descriptor.defaultValue = String(this.options["default"]); + if (this.options.proto3_optional) + descriptor.proto3_optional = true; + } + if (edition === "proto3") { + if (!this.packed) + (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false; + } else if ((!edition || edition === "proto2") && this.packed) + (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true; + return descriptor; + }; + var unnamedEnumIndex = 0; + Enum.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + if (typeof descriptor.length === "number") + descriptor = exports.EnumDescriptorProto.decode(descriptor); + var values = {}; + if (descriptor.value) + for (var i = 0;i < descriptor.value.length; ++i) { + var name = descriptor.value[i].name, value = descriptor.value[i].number || 0; + values[name && name.length ? name : "NAME" + value] = value; + } + var enm = new Enum(descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, values, fromDescriptorOptions(descriptor.options, exports.EnumOptions)); + if (!nested) + enm._edition = edition; + return enm; + }; + Enum.prototype.toDescriptor = function toDescriptor() { + var values = []; + for (var i = 0, ks = Object.keys(this.values);i < ks.length; ++i) + values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); + return exports.EnumDescriptorProto.create({ + name: this.name, + value: values, + options: toDescriptorOptions(this.options, exports.EnumOptions) + }); + }; + var unnamedOneofIndex = 0; + OneOf.fromDescriptor = function fromDescriptor(descriptor) { + if (typeof descriptor.length === "number") + descriptor = exports.OneofDescriptorProto.decode(descriptor); + return new OneOf(descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++); + }; + OneOf.prototype.toDescriptor = function toDescriptor() { + return exports.OneofDescriptorProto.create({ + name: this.name + }); + }; + var unnamedServiceIndex = 0; + Service.fromDescriptor = function fromDescriptor(descriptor, edition, nested) { + if (typeof descriptor.length === "number") + descriptor = exports.ServiceDescriptorProto.decode(descriptor); + var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions)); + if (!nested) + service._edition = edition; + if (descriptor.method) + for (var i = 0;i < descriptor.method.length; ++i) + service.add(Method.fromDescriptor(descriptor.method[i])); + return service; + }; + Service.prototype.toDescriptor = function toDescriptor() { + var methods = []; + for (var i = 0;i < this.methodsArray.length; ++i) + methods.push(this._methodsArray[i].toDescriptor()); + return exports.ServiceDescriptorProto.create({ + name: this.name, + method: methods, + options: toDescriptorOptions(this.options, exports.ServiceOptions) + }); + }; + var unnamedMethodIndex = 0; + Method.fromDescriptor = function fromDescriptor(descriptor) { + if (typeof descriptor.length === "number") + descriptor = exports.MethodDescriptorProto.decode(descriptor); + var { inputType, outputType } = descriptor; + if (inputType != null && inputType !== "") { + if (typeof inputType !== "string" || !typeRefRe.test(inputType)) + throw Error("illegal type name: " + inputType); + } + if (outputType != null && outputType !== "") { + if (typeof outputType !== "string" || !typeRefRe.test(outputType)) + throw Error("illegal type name: " + outputType); + } + return new Method(descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, "rpc", inputType, outputType, Boolean(descriptor.clientStreaming), Boolean(descriptor.serverStreaming), fromDescriptorOptions(descriptor.options, exports.MethodOptions)); + }; + Method.prototype.toDescriptor = function toDescriptor() { + return exports.MethodDescriptorProto.create({ + name: this.name, + inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, + outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, + clientStreaming: this.requestStream, + serverStreaming: this.responseStream, + options: toDescriptorOptions(this.options, exports.MethodOptions) + }); + }; + function fromDescriptorType(type) { + switch (type) { + case 1: + return "double"; + case 2: + return "float"; + case 3: + return "int64"; + case 4: + return "uint64"; + case 5: + return "int32"; + case 6: + return "fixed64"; + case 7: + return "fixed32"; + case 8: + return "bool"; + case 9: + return "string"; + case 12: + return "bytes"; + case 13: + return "uint32"; + case 15: + return "sfixed32"; + case 16: + return "sfixed64"; + case 17: + return "sint32"; + case 18: + return "sint64"; + } + throw Error("illegal type: " + type); + } + function packableDescriptorType(type) { + switch (type) { + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 13: + case 14: + case 15: + case 16: + case 17: + case 18: + return true; + } + return false; + } + function toDescriptorType(type, resolvedType, delimited) { + switch (type) { + case "double": + return 1; + case "float": + return 2; + case "int64": + return 3; + case "uint64": + return 4; + case "int32": + return 5; + case "fixed64": + return 6; + case "fixed32": + return 7; + case "bool": + return 8; + case "string": + return 9; + case "bytes": + return 12; + case "uint32": + return 13; + case "sfixed32": + return 15; + case "sfixed64": + return 16; + case "sint32": + return 17; + case "sint64": + return 18; + } + if (resolvedType instanceof Enum) + return 14; + if (resolvedType instanceof Type) + return delimited ? 10 : 11; + throw Error("illegal type: " + type); + } + function fromDescriptorOptionsRecursive(obj, type) { + var val = {}; + for (var i = 0, field, key;i < type.fieldsArray.length; ++i) { + if ((key = (field = type._fieldsArray[i]).name) === "uninterpretedOption") + continue; + if (!Object.prototype.hasOwnProperty.call(obj, key)) + continue; + var newKey = underScore(key); + if (field.resolvedType instanceof Type) { + val[newKey] = fromDescriptorOptionsRecursive(obj[key], field.resolvedType); + } else if (field.resolvedType instanceof Enum) { + val[newKey] = field.resolvedType.valuesById[obj[key]]; + } else { + val[newKey] = obj[key]; + } + } + return val; + } + function fromDescriptorOptions(options, type) { + if (!options) + return; + return fromDescriptorOptionsRecursive(type.toObject(options), type); + } + function toDescriptorOptionsRecursive(obj, type) { + var val = {}; + var keys = Object.keys(obj); + for (var i = 0;i < keys.length; ++i) { + var key = keys[i]; + var newKey = $protobuf.util.camelCase(key); + if (!Object.prototype.hasOwnProperty.call(type.fields, newKey)) + continue; + var field = type.fields[newKey]; + if (field.resolvedType instanceof Type) { + val[newKey] = toDescriptorOptionsRecursive(obj[key], field.resolvedType); + } else { + val[newKey] = obj[key]; + } + if (field.repeated && !Array.isArray(val[newKey])) { + val[newKey] = [val[newKey]]; + } + } + return val; + } + function toDescriptorOptions(options, type) { + if (!options) + return; + return type.fromObject(toDescriptorOptionsRecursive(options, type)); + } + function shortname(from, to) { + var fromPath = from.fullName.split("."), toPath = to.fullName.split("."), i = 0, j = 0, k = toPath.length - 1; + if (!(from instanceof Root) && to instanceof Namespace) + while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { + var other = to.lookup(fromPath[i++], true); + if (other !== null && other !== to) + break; + ++j; + } + else + for (;i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j) + ; + return toPath.slice(j).join("."); + } + function underScore(str) { + return str.substring(0, 1) + str.substring(1).replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { + return "_" + $1.toLowerCase(); + }); + } + function editionFromDescriptor(fileDescriptor) { + if (fileDescriptor.syntax === "editions") { + switch (fileDescriptor.edition) { + case exports.Edition.EDITION_2023: + return "2023"; + default: + throw new Error("Unsupported edition " + fileDescriptor.edition); + } + } + if (fileDescriptor.syntax === "proto3") { + return "proto3"; + } + return "proto2"; + } + function editionToDescriptor(edition, fileDescriptor) { + if (!edition) + return; + if (edition === "proto2" || edition === "proto3") { + fileDescriptor.syntax = edition; + } else { + fileDescriptor.syntax = "editions"; + switch (edition) { + case "2023": + fileDescriptor.edition = exports.Edition.EDITION_2023; + break; + default: + throw new Error("Unsupported edition " + edition); + } + } + } +}); + +// node_modules/protobufjs/google/protobuf/api.json +var require_api = __commonJS((exports, module) => { + module.exports = { + nested: { + google: { + nested: { + protobuf: { + nested: { + Api: { + fields: { + name: { + type: "string", + id: 1 + }, + methods: { + rule: "repeated", + type: "Method", + id: 2 + }, + options: { + rule: "repeated", + type: "Option", + id: 3 + }, + version: { + type: "string", + id: 4 + }, + sourceContext: { + type: "SourceContext", + id: 5 + }, + mixins: { + rule: "repeated", + type: "Mixin", + id: 6 + }, + syntax: { + type: "Syntax", + id: 7 + } + } + }, + Method: { + fields: { + name: { + type: "string", + id: 1 + }, + requestTypeUrl: { + type: "string", + id: 2 + }, + requestStreaming: { + type: "bool", + id: 3 + }, + responseTypeUrl: { + type: "string", + id: 4 + }, + responseStreaming: { + type: "bool", + id: 5 + }, + options: { + rule: "repeated", + type: "Option", + id: 6 + }, + syntax: { + type: "Syntax", + id: 7 + } + } + }, + Mixin: { + fields: { + name: { + type: "string", + id: 1 + }, + root: { + type: "string", + id: 2 + } + } + }, + SourceContext: { + fields: { + fileName: { + type: "string", + id: 1 + } + } + }, + Option: { + fields: { + name: { + type: "string", + id: 1 + }, + value: { + type: "Any", + id: 2 + } + } + }, + Syntax: { + values: { + SYNTAX_PROTO2: 0, + SYNTAX_PROTO3: 1 + } + } + } + } + } + } + } + }; +}); + +// node_modules/protobufjs/google/protobuf/source_context.json +var require_source_context = __commonJS((exports, module) => { + module.exports = { + nested: { + google: { + nested: { + protobuf: { + nested: { + SourceContext: { + fields: { + fileName: { + type: "string", + id: 1 + } + } + } + } + } + } + } + } + }; +}); + +// node_modules/protobufjs/google/protobuf/type.json +var require_type3 = __commonJS((exports, module) => { + module.exports = { + nested: { + google: { + nested: { + protobuf: { + nested: { + Type: { + fields: { + name: { + type: "string", + id: 1 + }, + fields: { + rule: "repeated", + type: "Field", + id: 2 + }, + oneofs: { + rule: "repeated", + type: "string", + id: 3 + }, + options: { + rule: "repeated", + type: "Option", + id: 4 + }, + sourceContext: { + type: "SourceContext", + id: 5 + }, + syntax: { + type: "Syntax", + id: 6 + } + } + }, + Field: { + fields: { + kind: { + type: "Kind", + id: 1 + }, + cardinality: { + type: "Cardinality", + id: 2 + }, + number: { + type: "int32", + id: 3 + }, + name: { + type: "string", + id: 4 + }, + typeUrl: { + type: "string", + id: 6 + }, + oneofIndex: { + type: "int32", + id: 7 + }, + packed: { + type: "bool", + id: 8 + }, + options: { + rule: "repeated", + type: "Option", + id: 9 + }, + jsonName: { + type: "string", + id: 10 + }, + defaultValue: { + type: "string", + id: 11 + } + }, + nested: { + Kind: { + values: { + TYPE_UNKNOWN: 0, + TYPE_DOUBLE: 1, + TYPE_FLOAT: 2, + TYPE_INT64: 3, + TYPE_UINT64: 4, + TYPE_INT32: 5, + TYPE_FIXED64: 6, + TYPE_FIXED32: 7, + TYPE_BOOL: 8, + TYPE_STRING: 9, + TYPE_GROUP: 10, + TYPE_MESSAGE: 11, + TYPE_BYTES: 12, + TYPE_UINT32: 13, + TYPE_ENUM: 14, + TYPE_SFIXED32: 15, + TYPE_SFIXED64: 16, + TYPE_SINT32: 17, + TYPE_SINT64: 18 + } + }, + Cardinality: { + values: { + CARDINALITY_UNKNOWN: 0, + CARDINALITY_OPTIONAL: 1, + CARDINALITY_REQUIRED: 2, + CARDINALITY_REPEATED: 3 + } + } + } + }, + Enum: { + fields: { + name: { + type: "string", + id: 1 + }, + enumvalue: { + rule: "repeated", + type: "EnumValue", + id: 2 + }, + options: { + rule: "repeated", + type: "Option", + id: 3 + }, + sourceContext: { + type: "SourceContext", + id: 4 + }, + syntax: { + type: "Syntax", + id: 5 + } + } + }, + EnumValue: { + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 2 + }, + options: { + rule: "repeated", + type: "Option", + id: 3 + } + } + }, + Option: { + fields: { + name: { + type: "string", + id: 1 + }, + value: { + type: "Any", + id: 2 + } + } + }, + Syntax: { + values: { + SYNTAX_PROTO2: 0, + SYNTAX_PROTO3: 1 + } + }, + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + }, + SourceContext: { + fields: { + fileName: { + type: "string", + id: 1 + } + } + } + } + } + } + } + } + }; +}); + +// node_modules/@grpc/proto-loader/build/src/util.js +var require_util4 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = undefined; + var fs = __require("fs"); + var path = __require("path"); + var Protobuf = require_src17(); + function addIncludePathResolver(root, includePaths) { + const originalResolvePath = root.resolvePath; + root.resolvePath = (origin, target) => { + if (path.isAbsolute(target)) { + return target; + } + for (const directory of includePaths) { + const fullPath = path.join(directory, target); + try { + fs.accessSync(fullPath, fs.constants.R_OK); + return fullPath; + } catch (err) { + continue; + } + } + process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); + return originalResolvePath(origin, target); + }; + } + async function loadProtosWithOptions(filename, options) { + const root = new Protobuf.Root; + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + return Promise.reject(new Error("The includeDirs option must be an array")); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = await root.load(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; + } + exports.loadProtosWithOptions = loadProtosWithOptions; + function loadProtosWithOptionsSync(filename, options) { + const root = new Protobuf.Root; + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + throw new Error("The includeDirs option must be an array"); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = root.loadSync(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; + } + exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; + function addCommonProtos() { + const apiDescriptor = require_api(); + const descriptorDescriptor = require_descriptor(); + const sourceContextDescriptor = require_source_context(); + const typeDescriptor = require_type3(); + Protobuf.common("api", apiDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("descriptor", descriptorDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("source_context", sourceContextDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common("type", typeDescriptor.nested.google.nested.protobuf.nested); + } + exports.addCommonProtos = addCommonProtos; +}); + +// node_modules/long/umd/index.js +var require_umd2 = __commonJS((exports, module) => { + var Long = function(exports2) { + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2.default = undefined; + var wasm = null; + try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports; + } catch (e) {} + function Long2(low, high, unsigned) { + this.low = low | 0; + this.high = high | 0; + this.unsigned = !!unsigned; + } + Long2.prototype.__isLong__; + Object.defineProperty(Long2.prototype, "__isLong__", { + value: true + }); + function isLong(obj) { + return (obj && obj["__isLong__"]) === true; + } + function ctz32(value) { + var c = Math.clz32(value & -value); + return value ? 31 - c : c; + } + Long2.isLong = isLong; + var INT_CACHE = {}; + var UINT_CACHE = {}; + function fromInt(value, unsigned) { + var obj, cachedObj, cache; + if (unsigned) { + value >>>= 0; + if (cache = 0 <= value && value < 256) { + cachedObj = UINT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, 0, true); + if (cache) + UINT_CACHE[value] = obj; + return obj; + } else { + value |= 0; + if (cache = -128 <= value && value < 128) { + cachedObj = INT_CACHE[value]; + if (cachedObj) + return cachedObj; + } + obj = fromBits(value, value < 0 ? -1 : 0, false); + if (cache) + INT_CACHE[value] = obj; + return obj; + } + } + Long2.fromInt = fromInt; + function fromNumber(value, unsigned) { + if (isNaN(value)) + return unsigned ? UZERO : ZERO; + if (unsigned) { + if (value < 0) + return UZERO; + if (value >= TWO_PWR_64_DBL) + return MAX_UNSIGNED_VALUE; + } else { + if (value <= -TWO_PWR_63_DBL) + return MIN_VALUE; + if (value + 1 >= TWO_PWR_63_DBL) + return MAX_VALUE; + } + if (value < 0) + return fromNumber(-value, unsigned).neg(); + return fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned); + } + Long2.fromNumber = fromNumber; + function fromBits(lowBits, highBits, unsigned) { + return new Long2(lowBits, highBits, unsigned); + } + Long2.fromBits = fromBits; + var pow_dbl = Math.pow; + function fromString(str, unsigned, radix) { + if (str.length === 0) + throw Error("empty string"); + if (typeof unsigned === "number") { + radix = unsigned; + unsigned = false; + } else { + unsigned = !!unsigned; + } + if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") + return unsigned ? UZERO : ZERO; + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError("radix"); + var p; + if ((p = str.indexOf("-")) > 0) + throw Error("interior hyphen"); + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg(); + } + var radixToPower = fromNumber(pow_dbl(radix, 8)); + var result = ZERO; + for (var i = 0;i < str.length; i += 8) { + var size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = fromNumber(pow_dbl(radix, size)); + result = result.mul(power).add(fromNumber(value)); + } else { + result = result.mul(radixToPower); + result = result.add(fromNumber(value)); + } + } + result.unsigned = unsigned; + return result; + } + Long2.fromString = fromString; + function fromValue(val, unsigned) { + if (typeof val === "number") + return fromNumber(val, unsigned); + if (typeof val === "string") + return fromString(val, unsigned); + return fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned); + } + Long2.fromValue = fromValue; + var TWO_PWR_16_DBL = 1 << 16; + var TWO_PWR_24_DBL = 1 << 24; + var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; + var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; + var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; + var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); + var ZERO = fromInt(0); + Long2.ZERO = ZERO; + var UZERO = fromInt(0, true); + Long2.UZERO = UZERO; + var ONE = fromInt(1); + Long2.ONE = ONE; + var UONE = fromInt(1, true); + Long2.UONE = UONE; + var NEG_ONE = fromInt(-1); + Long2.NEG_ONE = NEG_ONE; + var MAX_VALUE = fromBits(4294967295 | 0, 2147483647 | 0, false); + Long2.MAX_VALUE = MAX_VALUE; + var MAX_UNSIGNED_VALUE = fromBits(4294967295 | 0, 4294967295 | 0, true); + Long2.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; + var MIN_VALUE = fromBits(0, 2147483648 | 0, false); + Long2.MIN_VALUE = MIN_VALUE; + var LongPrototype = Long2.prototype; + LongPrototype.toInt = function toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + }; + LongPrototype.toNumber = function toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + }; + LongPrototype.toString = function toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw RangeError("radix"); + if (this.isZero()) + return "0"; + if (this.isNegative()) { + if (this.eq(MIN_VALUE)) { + var radixLong = fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this); + return div.toString(radix) + rem1.toInt().toString(radix); + } else + return "-" + this.neg().toString(radix); + } + var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), rem = this; + var result = ""; + while (true) { + var remDiv = rem.div(radixToPower), intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, digits = intval.toString(radix); + rem = remDiv; + if (rem.isZero()) + return digits + result; + else { + while (digits.length < 6) + digits = "0" + digits; + result = "" + digits + result; + } + } + }; + LongPrototype.getHighBits = function getHighBits() { + return this.high; + }; + LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { + return this.high >>> 0; + }; + LongPrototype.getLowBits = function getLowBits() { + return this.low; + }; + LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { + return this.low >>> 0; + }; + LongPrototype.getNumBitsAbs = function getNumBitsAbs() { + if (this.isNegative()) + return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + var val = this.high != 0 ? this.high : this.low; + for (var bit = 31;bit > 0; bit--) + if ((val & 1 << bit) != 0) + break; + return this.high != 0 ? bit + 33 : bit + 1; + }; + LongPrototype.isZero = function isZero() { + return this.high === 0 && this.low === 0; + }; + LongPrototype.eqz = LongPrototype.isZero; + LongPrototype.isNegative = function isNegative() { + return !this.unsigned && this.high < 0; + }; + LongPrototype.isPositive = function isPositive() { + return this.unsigned || this.high >= 0; + }; + LongPrototype.isOdd = function isOdd() { + return (this.low & 1) === 1; + }; + LongPrototype.isEven = function isEven() { + return (this.low & 1) === 0; + }; + LongPrototype.equals = function equals(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1) + return false; + return this.high === other.high && this.low === other.low; + }; + LongPrototype.eq = LongPrototype.equals; + LongPrototype.notEquals = function notEquals(other) { + return !this.eq(other); + }; + LongPrototype.neq = LongPrototype.notEquals; + LongPrototype.ne = LongPrototype.notEquals; + LongPrototype.lessThan = function lessThan(other) { + return this.comp(other) < 0; + }; + LongPrototype.lt = LongPrototype.lessThan; + LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { + return this.comp(other) <= 0; + }; + LongPrototype.lte = LongPrototype.lessThanOrEqual; + LongPrototype.le = LongPrototype.lessThanOrEqual; + LongPrototype.greaterThan = function greaterThan(other) { + return this.comp(other) > 0; + }; + LongPrototype.gt = LongPrototype.greaterThan; + LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { + return this.comp(other) >= 0; + }; + LongPrototype.gte = LongPrototype.greaterThanOrEqual; + LongPrototype.ge = LongPrototype.greaterThanOrEqual; + LongPrototype.compare = function compare(other) { + if (!isLong(other)) + other = fromValue(other); + if (this.eq(other)) + return 0; + var thisNeg = this.isNegative(), otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) + return -1; + if (!thisNeg && otherNeg) + return 1; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1; + }; + LongPrototype.comp = LongPrototype.compare; + LongPrototype.negate = function negate() { + if (!this.unsigned && this.eq(MIN_VALUE)) + return MIN_VALUE; + return this.not().add(ONE); + }; + LongPrototype.neg = LongPrototype.negate; + LongPrototype.add = function add(addend) { + if (!isLong(addend)) + addend = fromValue(addend); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = addend.high >>> 16; + var b32 = addend.high & 65535; + var b16 = addend.low >>> 16; + var b00 = addend.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 + b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.subtract = function subtract(subtrahend) { + if (!isLong(subtrahend)) + subtrahend = fromValue(subtrahend); + return this.add(subtrahend.neg()); + }; + LongPrototype.sub = LongPrototype.subtract; + LongPrototype.multiply = function multiply(multiplier) { + if (this.isZero()) + return this; + if (!isLong(multiplier)) + multiplier = fromValue(multiplier); + if (wasm) { + var low = wasm["mul"](this.low, this.high, multiplier.low, multiplier.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (multiplier.isZero()) + return this.unsigned ? UZERO : ZERO; + if (this.eq(MIN_VALUE)) + return multiplier.isOdd() ? MIN_VALUE : ZERO; + if (multiplier.eq(MIN_VALUE)) + return this.isOdd() ? MIN_VALUE : ZERO; + if (this.isNegative()) { + if (multiplier.isNegative()) + return this.neg().mul(multiplier.neg()); + else + return this.neg().mul(multiplier).neg(); + } else if (multiplier.isNegative()) + return this.mul(multiplier.neg()).neg(); + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) + return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + var a48 = this.high >>> 16; + var a32 = this.high & 65535; + var a16 = this.low >>> 16; + var a00 = this.low & 65535; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 65535; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 65535; + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 65535; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 65535; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 65535; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 65535; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 65535; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 65535; + return fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned); + }; + LongPrototype.mul = LongPrototype.multiply; + LongPrototype.divide = function divide(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (divisor.isZero()) + throw Error("division by zero"); + if (wasm) { + if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) { + return this; + } + var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])(this.low, this.high, divisor.low, divisor.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + if (this.isZero()) + return this.unsigned ? UZERO : ZERO; + var approx, rem, res; + if (!this.unsigned) { + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) + return MIN_VALUE; + else if (divisor.eq(MIN_VALUE)) + return ONE; + else { + var halfThis = this.shr(1); + approx = halfThis.div(divisor).shl(1); + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE; + } else { + rem = this.sub(divisor.mul(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.eq(MIN_VALUE)) + return this.unsigned ? UZERO : ZERO; + if (this.isNegative()) { + if (divisor.isNegative()) + return this.neg().div(divisor.neg()); + return this.neg().div(divisor).neg(); + } else if (divisor.isNegative()) + return this.div(divisor.neg()).neg(); + res = ZERO; + } else { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return UZERO; + if (divisor.gt(this.shru(1))) + return UONE; + res = UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + var log2 = Math.ceil(Math.log(approx) / Math.LN2), delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), approxRes = fromNumber(approx), approxRem = approxRes.mul(divisor); + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta; + approxRes = fromNumber(approx, this.unsigned); + approxRem = approxRes.mul(divisor); + } + if (approxRes.isZero()) + approxRes = ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + }; + LongPrototype.div = LongPrototype.divide; + LongPrototype.modulo = function modulo(divisor) { + if (!isLong(divisor)) + divisor = fromValue(divisor); + if (wasm) { + var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])(this.low, this.high, divisor.low, divisor.high); + return fromBits(low, wasm["get_high"](), this.unsigned); + } + return this.sub(this.div(divisor).mul(divisor)); + }; + LongPrototype.mod = LongPrototype.modulo; + LongPrototype.rem = LongPrototype.modulo; + LongPrototype.not = function not() { + return fromBits(~this.low, ~this.high, this.unsigned); + }; + LongPrototype.countLeadingZeros = function countLeadingZeros() { + return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; + }; + LongPrototype.clz = LongPrototype.countLeadingZeros; + LongPrototype.countTrailingZeros = function countTrailingZeros() { + return this.low ? ctz32(this.low) : ctz32(this.high) + 32; + }; + LongPrototype.ctz = LongPrototype.countTrailingZeros; + LongPrototype.and = function and(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low & other.low, this.high & other.high, this.unsigned); + }; + LongPrototype.or = function or(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low | other.low, this.high | other.high, this.unsigned); + }; + LongPrototype.xor = function xor(other) { + if (!isLong(other)) + other = fromValue(other); + return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + }; + LongPrototype.shiftLeft = function shiftLeft(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned); + else + return fromBits(0, this.low << numBits - 32, this.unsigned); + }; + LongPrototype.shl = LongPrototype.shiftLeft; + LongPrototype.shiftRight = function shiftRight(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + else if (numBits < 32) + return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned); + else + return fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned); + }; + LongPrototype.shr = LongPrototype.shiftRight; + LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + if (numBits < 32) + return fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >>> numBits, this.unsigned); + if (numBits === 32) + return fromBits(this.high, 0, this.unsigned); + return fromBits(this.high >>> numBits - 32, 0, this.unsigned); + }; + LongPrototype.shru = LongPrototype.shiftRightUnsigned; + LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; + LongPrototype.rotateLeft = function rotateLeft(numBits) { + var b; + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + if (numBits === 32) + return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits(this.low << numBits | this.high >>> b, this.high << numBits | this.low >>> b, this.unsigned); + } + numBits -= 32; + b = 32 - numBits; + return fromBits(this.high << numBits | this.low >>> b, this.low << numBits | this.high >>> b, this.unsigned); + }; + LongPrototype.rotl = LongPrototype.rotateLeft; + LongPrototype.rotateRight = function rotateRight(numBits) { + var b; + if (isLong(numBits)) + numBits = numBits.toInt(); + if ((numBits &= 63) === 0) + return this; + if (numBits === 32) + return fromBits(this.high, this.low, this.unsigned); + if (numBits < 32) { + b = 32 - numBits; + return fromBits(this.high << b | this.low >>> numBits, this.low << b | this.high >>> numBits, this.unsigned); + } + numBits -= 32; + b = 32 - numBits; + return fromBits(this.low << b | this.high >>> numBits, this.high << b | this.low >>> numBits, this.unsigned); + }; + LongPrototype.rotr = LongPrototype.rotateRight; + LongPrototype.toSigned = function toSigned() { + if (!this.unsigned) + return this; + return fromBits(this.low, this.high, false); + }; + LongPrototype.toUnsigned = function toUnsigned() { + if (this.unsigned) + return this; + return fromBits(this.low, this.high, true); + }; + LongPrototype.toBytes = function toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + }; + LongPrototype.toBytesLE = function toBytesLE() { + var hi = this.high, lo = this.low; + return [lo & 255, lo >>> 8 & 255, lo >>> 16 & 255, lo >>> 24, hi & 255, hi >>> 8 & 255, hi >>> 16 & 255, hi >>> 24]; + }; + LongPrototype.toBytesBE = function toBytesBE() { + var hi = this.high, lo = this.low; + return [hi >>> 24, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255, lo >>> 24, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255]; + }; + Long2.fromBytes = function fromBytes(bytes, unsigned, le) { + return le ? Long2.fromBytesLE(bytes, unsigned) : Long2.fromBytesBE(bytes, unsigned); + }; + Long2.fromBytesLE = function fromBytesLE(bytes, unsigned) { + return new Long2(bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, unsigned); + }; + Long2.fromBytesBE = function fromBytesBE(bytes, unsigned) { + return new Long2(bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7], bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], unsigned); + }; + var _default = Long2; + exports2.default = _default; + return "default" in exports2 ? exports2.default : exports2; + }({}); + if (typeof define === "function" && define.amd) + define([], function() { + return Long; + }); + else if (typeof module === "object" && typeof exports === "object") + module.exports = Long; +}); + +// node_modules/@grpc/proto-loader/build/src/index.js +var require_src18 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = undefined; + var camelCase = require_lodash(); + var Protobuf = require_src17(); + var descriptor = require_descriptor2(); + var util_1 = require_util4(); + var Long = require_umd2(); + exports.Long = Long; + function isAnyExtension(obj) { + return "@type" in obj && typeof obj["@type"] === "string"; + } + exports.isAnyExtension = isAnyExtension; + var IdempotencyLevel; + (function(IdempotencyLevel2) { + IdempotencyLevel2["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + IdempotencyLevel2["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + IdempotencyLevel2["IDEMPOTENT"] = "IDEMPOTENT"; + })(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {})); + var descriptorOptions = { + longs: String, + enums: String, + bytes: String, + defaults: true, + oneofs: true, + json: true + }; + function joinName(baseName, name) { + if (baseName === "") { + return name; + } else { + return baseName + "." + name; + } + } + function isHandledReflectionObject(obj) { + return obj instanceof Protobuf.Service || obj instanceof Protobuf.Type || obj instanceof Protobuf.Enum; + } + function isNamespaceBase(obj) { + return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; + } + function getAllHandledReflectionObjects(obj, parentName) { + const objName = joinName(parentName, obj.name); + if (isHandledReflectionObject(obj)) { + return [[objName, obj]]; + } else { + if (isNamespaceBase(obj) && typeof obj.nested !== "undefined") { + return Object.keys(obj.nested).map((name) => { + return getAllHandledReflectionObjects(obj.nested[name], objName); + }).reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + } + } + return []; + } + function createDeserializer(cls, options) { + return function deserialize(argBuf) { + return cls.toObject(cls.decode(argBuf), options); + }; + } + function createSerializer(cls) { + return function serialize(arg) { + if (Array.isArray(arg)) { + throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); + } + const message = cls.fromObject(arg); + return cls.encode(message).finish(); + }; + } + function mapMethodOptions(options) { + return (options || []).reduce((obj, item) => { + for (const [key, value] of Object.entries(item)) { + switch (key) { + case "uninterpreted_option": + obj.uninterpreted_option.push(item.uninterpreted_option); + break; + default: + obj[key] = value; + } + } + return obj; + }, { + deprecated: false, + idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, + uninterpreted_option: [] + }); + } + function createMethodDefinition(method, serviceName, options, fileDescriptors) { + const requestType = method.resolvedRequestType; + const responseType = method.resolvedResponseType; + return { + path: "/" + serviceName + "/" + method.name, + requestStream: !!method.requestStream, + responseStream: !!method.responseStream, + requestSerialize: createSerializer(requestType), + requestDeserialize: createDeserializer(requestType, options), + responseSerialize: createSerializer(responseType), + responseDeserialize: createDeserializer(responseType, options), + originalName: camelCase(method.name), + requestType: createMessageDefinition(requestType, options, fileDescriptors), + responseType: createMessageDefinition(responseType, options, fileDescriptors), + options: mapMethodOptions(method.parsedOptions) + }; + } + function createServiceDefinition(service, name, options, fileDescriptors) { + const def = {}; + for (const method of service.methodsArray) { + def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); + } + return def; + } + function createMessageDefinition(message, options, fileDescriptors) { + const messageDescriptor = message.toDescriptor("proto3"); + return { + format: "Protocol Buffer 3 DescriptorProto", + type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + serialize: createSerializer(message), + deserialize: createDeserializer(message, options) + }; + } + function createEnumDefinition(enumType, fileDescriptors) { + const enumDescriptor = enumType.toDescriptor("proto3"); + return { + format: "Protocol Buffer 3 EnumDescriptorProto", + type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors + }; + } + function createDefinition(obj, name, options, fileDescriptors) { + if (obj instanceof Protobuf.Service) { + return createServiceDefinition(obj, name, options, fileDescriptors); + } else if (obj instanceof Protobuf.Type) { + return createMessageDefinition(obj, options, fileDescriptors); + } else if (obj instanceof Protobuf.Enum) { + return createEnumDefinition(obj, fileDescriptors); + } else { + throw new Error("Type mismatch in reflection object handling"); + } + } + function createPackageDefinition(root, options) { + const def = {}; + root.resolveAll(); + const descriptorList = root.toDescriptor("proto3").file; + const bufferList = descriptorList.map((value) => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); + for (const [name, obj] of getAllHandledReflectionObjects(root, "")) { + def[name] = createDefinition(obj, name, options, bufferList); + } + return def; + } + function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { + options = options || {}; + const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); + root.resolveAll(); + return createPackageDefinition(root, options); + } + function load(filename, options) { + return (0, util_1.loadProtosWithOptions)(filename, options).then((loadedRoot) => { + return createPackageDefinition(loadedRoot, options); + }); + } + exports.load = load; + function loadSync(filename, options) { + const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); + return createPackageDefinition(loadedRoot, options); + } + exports.loadSync = loadSync; + function fromJSON(json, options) { + options = options || {}; + const loadedRoot = Protobuf.Root.fromJSON(json); + loadedRoot.resolveAll(); + return createPackageDefinition(loadedRoot, options); + } + exports.fromJSON = fromJSON; + function loadFileDescriptorSetFromBuffer(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); + } + exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; + function loadFileDescriptorSetFromObject(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); + } + exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; + (0, util_1.addCommonProtos)(); +}); + +// node_modules/@grpc/grpc-js/build/src/channelz.js +var require_channelz = __commonJS((exports) => { + var __dirname = "/src/node_modules/@grpc/grpc-js/build/src"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.registerChannelzSocket = exports.registerChannelzServer = exports.registerChannelzSubchannel = exports.registerChannelzChannel = exports.ChannelzCallTrackerStub = exports.ChannelzCallTracker = exports.ChannelzChildrenTrackerStub = exports.ChannelzChildrenTracker = exports.ChannelzTrace = exports.ChannelzTraceStub = undefined; + exports.unregisterChannelzRef = unregisterChannelzRef; + exports.getChannelzHandlers = getChannelzHandlers; + exports.getChannelzServiceDefinition = getChannelzServiceDefinition; + exports.setup = setup; + var net_1 = __require("net"); + var ordered_map_1 = require_cjs(); + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants2(); + var subchannel_address_1 = require_subchannel_address(); + var admin_1 = require_admin(); + var make_client_1 = require_make_client(); + function channelRefToMessage(ref) { + return { + channel_id: ref.id, + name: ref.name + }; + } + function subchannelRefToMessage(ref) { + return { + subchannel_id: ref.id, + name: ref.name + }; + } + function serverRefToMessage(ref) { + return { + server_id: ref.id + }; + } + function socketRefToMessage(ref) { + return { + socket_id: ref.id, + name: ref.name + }; + } + var TARGET_RETAINED_TRACES = 32; + var DEFAULT_MAX_RESULTS = 100; + + class ChannelzTraceStub { + constructor() { + this.events = []; + this.creationTimestamp = new Date; + this.eventsLogged = 0; + } + addTrace() {} + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: [] + }; + } + } + exports.ChannelzTraceStub = ChannelzTraceStub; + + class ChannelzTrace { + constructor() { + this.events = []; + this.eventsLogged = 0; + this.creationTimestamp = new Date; + } + addTrace(severity, description, child) { + const timestamp = new Date; + this.events.push({ + description, + severity, + timestamp, + childChannel: (child === null || child === undefined ? undefined : child.kind) === "channel" ? child : undefined, + childSubchannel: (child === null || child === undefined ? undefined : child.kind) === "subchannel" ? child : undefined + }); + if (this.events.length >= TARGET_RETAINED_TRACES * 2) { + this.events = this.events.slice(TARGET_RETAINED_TRACES); + } + this.eventsLogged += 1; + } + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: this.events.map((event) => { + return { + description: event.description, + severity: event.severity, + timestamp: dateToProtoTimestamp(event.timestamp), + channel_ref: event.childChannel ? channelRefToMessage(event.childChannel) : null, + subchannel_ref: event.childSubchannel ? subchannelRefToMessage(event.childSubchannel) : null + }; + }) + }; + } + } + exports.ChannelzTrace = ChannelzTrace; + + class ChannelzChildrenTracker { + constructor() { + this.channelChildren = new ordered_map_1.OrderedMap; + this.subchannelChildren = new ordered_map_1.OrderedMap; + this.socketChildren = new ordered_map_1.OrderedMap; + this.trackerMap = { + ["channel"]: this.channelChildren, + ["subchannel"]: this.subchannelChildren, + ["socket"]: this.socketChildren + }; + } + refChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.find(child.id); + if (trackedChild.equals(tracker.end())) { + tracker.setElement(child.id, { + ref: child, + count: 1 + }, trackedChild); + } else { + trackedChild.pointer[1].count += 1; + } + } + unrefChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.getElementByKey(child.id); + if (trackedChild !== undefined) { + trackedChild.count -= 1; + if (trackedChild.count === 0) { + tracker.eraseElementByKey(child.id); + } + } + } + getChildLists() { + return { + channels: this.channelChildren, + subchannels: this.subchannelChildren, + sockets: this.socketChildren + }; + } + } + exports.ChannelzChildrenTracker = ChannelzChildrenTracker; + + class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { + refChild() {} + unrefChild() {} + } + exports.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; + + class ChannelzCallTracker { + constructor() { + this.callsStarted = 0; + this.callsSucceeded = 0; + this.callsFailed = 0; + this.lastCallStartedTimestamp = null; + } + addCallStarted() { + this.callsStarted += 1; + this.lastCallStartedTimestamp = new Date; + } + addCallSucceeded() { + this.callsSucceeded += 1; + } + addCallFailed() { + this.callsFailed += 1; + } + } + exports.ChannelzCallTracker = ChannelzCallTracker; + + class ChannelzCallTrackerStub extends ChannelzCallTracker { + addCallStarted() {} + addCallSucceeded() {} + addCallFailed() {} + } + exports.ChannelzCallTrackerStub = ChannelzCallTrackerStub; + var entityMaps = { + ["channel"]: new ordered_map_1.OrderedMap, + ["subchannel"]: new ordered_map_1.OrderedMap, + ["server"]: new ordered_map_1.OrderedMap, + ["socket"]: new ordered_map_1.OrderedMap + }; + var generateRegisterFn = (kind2) => { + let nextId = 1; + function getNextId() { + return nextId++; + } + const entityMap = entityMaps[kind2]; + return (name, getInfo, channelzEnabled) => { + const id = getNextId(); + const ref = { id, name, kind: kind2 }; + if (channelzEnabled) { + entityMap.setElement(id, { ref, getInfo }); + } + return ref; + }; + }; + exports.registerChannelzChannel = generateRegisterFn("channel"); + exports.registerChannelzSubchannel = generateRegisterFn("subchannel"); + exports.registerChannelzServer = generateRegisterFn("server"); + exports.registerChannelzSocket = generateRegisterFn("socket"); + function unregisterChannelzRef(ref) { + entityMaps[ref.kind].eraseElementByKey(ref.id); + } + function parseIPv6Section(addressSection) { + const numberValue = Number.parseInt(addressSection, 16); + return [numberValue / 256 | 0, numberValue % 256]; + } + function parseIPv6Chunk(addressChunk) { + if (addressChunk === "") { + return []; + } + const bytePairs = addressChunk.split(":").map((section) => parseIPv6Section(section)); + const result = []; + return result.concat(...bytePairs); + } + function isIPv6MappedIPv4(ipAddress) { + return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith("::ffff:") && (0, net_1.isIPv4)(ipAddress.substring(7)); + } + function ipv4AddressStringToBuffer(ipAddress) { + return Buffer.from(Uint8Array.from(ipAddress.split(".").map((segment) => Number.parseInt(segment)))); + } + function ipAddressStringToBuffer(ipAddress) { + if ((0, net_1.isIPv4)(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress); + } else if (isIPv6MappedIPv4(ipAddress)) { + return ipv4AddressStringToBuffer(ipAddress.substring(7)); + } else if ((0, net_1.isIPv6)(ipAddress)) { + let leftSection; + let rightSection; + const doubleColonIndex = ipAddress.indexOf("::"); + if (doubleColonIndex === -1) { + leftSection = ipAddress; + rightSection = ""; + } else { + leftSection = ipAddress.substring(0, doubleColonIndex); + rightSection = ipAddress.substring(doubleColonIndex + 2); + } + const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); + const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); + const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); + return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); + } else { + return null; + } + } + function connectivityStateToMessage(state) { + switch (state) { + case connectivity_state_1.ConnectivityState.CONNECTING: + return { + state: "CONNECTING" + }; + case connectivity_state_1.ConnectivityState.IDLE: + return { + state: "IDLE" + }; + case connectivity_state_1.ConnectivityState.READY: + return { + state: "READY" + }; + case connectivity_state_1.ConnectivityState.SHUTDOWN: + return { + state: "SHUTDOWN" + }; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + return { + state: "TRANSIENT_FAILURE" + }; + default: + return { + state: "UNKNOWN" + }; + } + } + function dateToProtoTimestamp(date) { + if (!date) { + return null; + } + const millisSinceEpoch = date.getTime(); + return { + seconds: millisSinceEpoch / 1000 | 0, + nanos: millisSinceEpoch % 1000 * 1e6 + }; + } + function getChannelMessage(channelEntry) { + const resolvedInfo = channelEntry.getInfo(); + const channelRef = []; + const subchannelRef = []; + resolvedInfo.children.channels.forEach((el) => { + channelRef.push(channelRefToMessage(el[1].ref)); + }); + resolvedInfo.children.subchannels.forEach((el) => { + subchannelRef.push(subchannelRefToMessage(el[1].ref)); + }); + return { + ref: channelRefToMessage(channelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage() + }, + channel_ref: channelRef, + subchannel_ref: subchannelRef + }; + } + function GetChannel(call, callback) { + const channelId = parseInt(call.request.channel_id, 10); + const channelEntry = entityMaps["channel"].getElementByKey(channelId); + if (channelEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No channel data found for id " + channelId + }); + return; + } + callback(null, { channel: getChannelMessage(channelEntry) }); + } + function GetTopChannels(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resultList = []; + const startId = parseInt(call.request.start_channel_id, 10); + const channelEntries = entityMaps["channel"]; + let i; + for (i = channelEntries.lowerBound(startId);!i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getChannelMessage(i.pointer[1])); + } + callback(null, { + channel: resultList, + end: i.equals(channelEntries.end()) + }); + } + function getServerMessage(serverEntry) { + const resolvedInfo = serverEntry.getInfo(); + const listenSocket = []; + resolvedInfo.listenerChildren.sockets.forEach((el) => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + return { + ref: serverRefToMessage(serverEntry.ref), + data: { + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage() + }, + listen_socket: listenSocket + }; + } + function GetServer(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntries = entityMaps["server"]; + const serverEntry = serverEntries.getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No server data found for id " + serverId + }); + return; + } + callback(null, { server: getServerMessage(serverEntry) }); + } + function GetServers(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const startId = parseInt(call.request.start_server_id, 10); + const serverEntries = entityMaps["server"]; + const resultList = []; + let i; + for (i = serverEntries.lowerBound(startId);!i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getServerMessage(i.pointer[1])); + } + callback(null, { + server: resultList, + end: i.equals(serverEntries.end()) + }); + } + function GetSubchannel(call, callback) { + const subchannelId = parseInt(call.request.subchannel_id, 10); + const subchannelEntry = entityMaps["subchannel"].getElementByKey(subchannelId); + if (subchannelEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No subchannel data found for id " + subchannelId + }); + return; + } + const resolvedInfo = subchannelEntry.getInfo(); + const listenSocket = []; + resolvedInfo.children.sockets.forEach((el) => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + const subchannelMessage = { + ref: subchannelRefToMessage(subchannelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage() + }, + socket_ref: listenSocket + }; + callback(null, { subchannel: subchannelMessage }); + } + function subchannelAddressToAddressMessage(subchannelAddress) { + var _a; + if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { + return { + address: "tcpip_address", + tcpip_address: { + ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== undefined ? _a : undefined, + port: subchannelAddress.port + } + }; + } else { + return { + address: "uds_address", + uds_address: { + filename: subchannelAddress.path + } + }; + } + } + function GetSocket(call, callback) { + var _a, _b, _c, _d, _e; + const socketId = parseInt(call.request.socket_id, 10); + const socketEntry = entityMaps["socket"].getElementByKey(socketId); + if (socketEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No socket data found for id " + socketId + }); + return; + } + const resolvedInfo = socketEntry.getInfo(); + const securityMessage = resolvedInfo.security ? { + model: "tls", + tls: { + cipher_suite: resolvedInfo.security.cipherSuiteStandardName ? "standard_name" : "other_name", + standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== undefined ? _a : undefined, + other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== undefined ? _b : undefined, + local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== undefined ? _c : undefined, + remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== undefined ? _d : undefined + } + } : null; + const socketMessage = { + ref: socketRefToMessage(socketEntry.ref), + local: resolvedInfo.localAddress ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) : null, + remote: resolvedInfo.remoteAddress ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) : null, + remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== undefined ? _e : undefined, + security: securityMessage, + data: { + keep_alives_sent: resolvedInfo.keepAlivesSent, + streams_started: resolvedInfo.streamsStarted, + streams_succeeded: resolvedInfo.streamsSucceeded, + streams_failed: resolvedInfo.streamsFailed, + last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), + last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), + messages_received: resolvedInfo.messagesReceived, + messages_sent: resolvedInfo.messagesSent, + last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), + last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), + local_flow_control_window: resolvedInfo.localFlowControlWindow ? { value: resolvedInfo.localFlowControlWindow } : null, + remote_flow_control_window: resolvedInfo.remoteFlowControlWindow ? { value: resolvedInfo.remoteFlowControlWindow } : null + } + }; + callback(null, { socket: socketMessage }); + } + function GetServerSockets(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntry = entityMaps["server"].getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: "No server data found for id " + serverId + }); + return; + } + const startId = parseInt(call.request.start_socket_id, 10); + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resolvedInfo = serverEntry.getInfo(); + const allSockets = resolvedInfo.sessionChildren.sockets; + const resultList = []; + let i; + for (i = allSockets.lowerBound(startId);!i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(socketRefToMessage(i.pointer[1].ref)); + } + callback(null, { + socket_ref: resultList, + end: i.equals(allSockets.end()) + }); + } + function getChannelzHandlers() { + return { + GetChannel, + GetTopChannels, + GetServer, + GetServers, + GetSubchannel, + GetSocket, + GetServerSockets + }; + } + var loadedChannelzDefinition = null; + function getChannelzServiceDefinition() { + if (loadedChannelzDefinition) { + return loadedChannelzDefinition; + } + const loaderLoadSync = require_src18().loadSync; + const loadedProto = loaderLoadSync("channelz.proto", { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [`${__dirname}/../../proto`] + }); + const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); + loadedChannelzDefinition = channelzGrpcObject.grpc.channelz.v1.Channelz.service; + return loadedChannelzDefinition; + } + function setup() { + (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); + } +}); + +// node_modules/@grpc/grpc-js/build/src/call-number.js +var require_call_number = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getNextCallNumber = getNextCallNumber; + var nextCallNumber = 0; + function getNextCallNumber() { + return nextCallNumber++; + } +}); + +// node_modules/@grpc/grpc-js/build/src/compression-algorithms.js +var require_compression_algorithms = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompressionAlgorithms = undefined; + var CompressionAlgorithms; + (function(CompressionAlgorithms2) { + CompressionAlgorithms2[CompressionAlgorithms2["identity"] = 0] = "identity"; + CompressionAlgorithms2[CompressionAlgorithms2["deflate"] = 1] = "deflate"; + CompressionAlgorithms2[CompressionAlgorithms2["gzip"] = 2] = "gzip"; + })(CompressionAlgorithms || (exports.CompressionAlgorithms = CompressionAlgorithms = {})); +}); + +// node_modules/@grpc/grpc-js/build/src/filter.js +var require_filter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaseFilter = undefined; + + class BaseFilter { + async sendMetadata(metadata) { + return metadata; + } + receiveMetadata(metadata) { + return metadata; + } + async sendMessage(message) { + return message; + } + async receiveMessage(message) { + return message; + } + receiveTrailers(status) { + return status; + } + } + exports.BaseFilter = BaseFilter; +}); + +// node_modules/@grpc/grpc-js/build/src/compression-filter.js +var require_compression_filter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompressionFilterFactory = exports.CompressionFilter = undefined; + var zlib = __require("zlib"); + var compression_algorithms_1 = require_compression_algorithms(); + var constants_1 = require_constants2(); + var filter_1 = require_filter(); + var logging = require_logging(); + var isCompressionAlgorithmKey = (key) => { + return typeof key === "number" && typeof compression_algorithms_1.CompressionAlgorithms[key] === "string"; + }; + + class CompressionHandler { + async writeMessage(message, compress) { + let messageBuffer = message; + if (compress) { + messageBuffer = await this.compressMessage(messageBuffer); + } + const output = Buffer.allocUnsafe(messageBuffer.length + 5); + output.writeUInt8(compress ? 1 : 0, 0); + output.writeUInt32BE(messageBuffer.length, 1); + messageBuffer.copy(output, 5); + return output; + } + async readMessage(data) { + const compressed = data.readUInt8(0) === 1; + let messageBuffer = data.slice(5); + if (compressed) { + messageBuffer = await this.decompressMessage(messageBuffer); + } + return messageBuffer; + } + } + + class IdentityHandler extends CompressionHandler { + async compressMessage(message) { + return message; + } + async writeMessage(message, compress) { + const output = Buffer.allocUnsafe(message.length + 5); + output.writeUInt8(0, 0); + output.writeUInt32BE(message.length, 1); + message.copy(output, 5); + return output; + } + decompressMessage(message) { + return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); + } + } + + class DeflateHandler extends CompressionHandler { + constructor(maxRecvMessageLength) { + super(); + this.maxRecvMessageLength = maxRecvMessageLength; + } + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.deflate(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + const decompresser = zlib.createInflate(); + decompresser.on("error", (error) => { + reject({ + code: constants_1.Status.INTERNAL, + details: "Failed to decompress deflate-encoded message" + }); + }); + decompresser.on("data", (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on("end", () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } + } + + class GzipHandler extends CompressionHandler { + constructor(maxRecvMessageLength) { + super(); + this.maxRecvMessageLength = maxRecvMessageLength; + } + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.gzip(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + const decompresser = zlib.createGunzip(); + decompresser.on("error", (error) => { + reject({ + code: constants_1.Status.INTERNAL, + details: "Failed to decompress gzip-encoded message" + }); + }); + decompresser.on("data", (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` + }); + } + }); + decompresser.on("end", () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(message); + decompresser.end(); + }); + } + } + + class UnknownHandler extends CompressionHandler { + constructor(compressionName) { + super(); + this.compressionName = compressionName; + } + compressMessage(message) { + return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); + } + decompressMessage(message) { + return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); + } + } + function getCompressionHandler(compressionName, maxReceiveMessageSize) { + switch (compressionName) { + case "identity": + return new IdentityHandler; + case "deflate": + return new DeflateHandler(maxReceiveMessageSize); + case "gzip": + return new GzipHandler(maxReceiveMessageSize); + default: + return new UnknownHandler(compressionName); + } + } + + class CompressionFilter extends filter_1.BaseFilter { + constructor(channelOptions, sharedFilterConfig) { + var _a, _b, _c; + super(); + this.sharedFilterConfig = sharedFilterConfig; + this.sendCompression = new IdentityHandler; + this.receiveCompression = new IdentityHandler; + this.currentCompressionAlgorithm = "identity"; + const compressionAlgorithmKey = channelOptions["grpc.default_compression_algorithm"]; + this.maxReceiveMessageLength = (_a = channelOptions["grpc.max_receive_message_length"]) !== null && _a !== undefined ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.maxSendMessageLength = (_b = channelOptions["grpc.max_send_message_length"]) !== null && _b !== undefined ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + if (compressionAlgorithmKey !== undefined) { + if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { + const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; + const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === undefined ? undefined : _c.split(","); + if (!serverSupportedEncodings || serverSupportedEncodings.includes(clientSelectedEncoding)) { + this.currentCompressionAlgorithm = clientSelectedEncoding; + this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1); + } + } else { + logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); + } + } + } + async sendMetadata(metadata) { + const headers = await metadata; + headers.set("grpc-accept-encoding", "identity,deflate,gzip"); + headers.set("accept-encoding", "identity"); + if (this.currentCompressionAlgorithm === "identity") { + headers.remove("grpc-encoding"); + } else { + headers.set("grpc-encoding", this.currentCompressionAlgorithm); + } + return headers; + } + receiveMetadata(metadata) { + const receiveEncoding = metadata.get("grpc-encoding"); + if (receiveEncoding.length > 0) { + const encoding = receiveEncoding[0]; + if (typeof encoding === "string") { + this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); + } + } + metadata.remove("grpc-encoding"); + const serverSupportedEncodingsHeader = metadata.get("grpc-accept-encoding")[0]; + if (serverSupportedEncodingsHeader) { + this.sharedFilterConfig.serverSupportedEncodingHeader = serverSupportedEncodingsHeader; + const serverSupportedEncodings = serverSupportedEncodingsHeader.split(","); + if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { + this.sendCompression = new IdentityHandler; + this.currentCompressionAlgorithm = "identity"; + } + } + metadata.remove("grpc-accept-encoding"); + return metadata; + } + async sendMessage(message) { + var _a; + const resolvedMessage = await message; + if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { + throw { + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` + }; + } + let compress; + if (this.sendCompression instanceof IdentityHandler) { + compress = false; + } else { + compress = (((_a = resolvedMessage.flags) !== null && _a !== undefined ? _a : 0) & 2) === 0; + } + return { + message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), + flags: resolvedMessage.flags + }; + } + async receiveMessage(message) { + return this.receiveCompression.readMessage(await message); + } + } + exports.CompressionFilter = CompressionFilter; + + class CompressionFilterFactory { + constructor(channel, options) { + this.options = options; + this.sharedFilterConfig = {}; + } + createFilter() { + return new CompressionFilter(this.options, this.sharedFilterConfig); + } + } + exports.CompressionFilterFactory = CompressionFilterFactory; +}); + +// node_modules/@grpc/grpc-js/build/src/control-plane-status.js +var require_control_plane_status = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; + var constants_1 = require_constants2(); + var INAPPROPRIATE_CONTROL_PLANE_CODES = [ + constants_1.Status.OK, + constants_1.Status.INVALID_ARGUMENT, + constants_1.Status.NOT_FOUND, + constants_1.Status.ALREADY_EXISTS, + constants_1.Status.FAILED_PRECONDITION, + constants_1.Status.ABORTED, + constants_1.Status.OUT_OF_RANGE, + constants_1.Status.DATA_LOSS + ]; + function restrictControlPlaneStatusCode(code, details) { + if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { + return { + code: constants_1.Status.INTERNAL, + details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}` + }; + } else { + return { code, details }; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/deadline.js +var require_deadline = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.minDeadline = minDeadline; + exports.getDeadlineTimeoutString = getDeadlineTimeoutString; + exports.getRelativeTimeout = getRelativeTimeout; + exports.deadlineToString = deadlineToString; + exports.formatDateDifference = formatDateDifference; + function minDeadline(...deadlineList) { + let minValue = Infinity; + for (const deadline of deadlineList) { + const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; + if (deadlineMsecs < minValue) { + minValue = deadlineMsecs; + } + } + return minValue; + } + var units = [ + ["m", 1], + ["S", 1000], + ["M", 60 * 1000], + ["H", 60 * 60 * 1000] + ]; + function getDeadlineTimeoutString(deadline) { + const now = new Date().getTime(); + if (deadline instanceof Date) { + deadline = deadline.getTime(); + } + const timeoutMs = Math.max(deadline - now, 0); + for (const [unit, factor] of units) { + const amount = timeoutMs / factor; + if (amount < 1e8) { + return String(Math.ceil(amount)) + unit; + } + } + throw new Error("Deadline is too far in the future"); + } + var MAX_TIMEOUT_TIME = 2147483647; + function getRelativeTimeout(deadline) { + const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; + const now = new Date().getTime(); + const timeout = deadlineMs - now; + if (timeout < 0) { + return 0; + } else if (timeout > MAX_TIMEOUT_TIME) { + return Infinity; + } else { + return timeout; + } + } + function deadlineToString(deadline) { + if (deadline instanceof Date) { + return deadline.toISOString(); + } else { + const dateDeadline = new Date(deadline); + if (Number.isNaN(dateDeadline.getTime())) { + return "" + deadline; + } else { + return dateDeadline.toISOString(); + } + } + } + function formatDateDifference(startDate, endDate) { + return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + "s"; + } +}); + +// node_modules/@grpc/grpc-js/build/src/filter-stack.js +var require_filter_stack = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilterStackFactory = exports.FilterStack = undefined; + + class FilterStack { + constructor(filters) { + this.filters = filters; + } + sendMetadata(metadata) { + let result = metadata; + for (let i = 0;i < this.filters.length; i++) { + result = this.filters[i].sendMetadata(result); + } + return result; + } + receiveMetadata(metadata) { + let result = metadata; + for (let i = this.filters.length - 1;i >= 0; i--) { + result = this.filters[i].receiveMetadata(result); + } + return result; + } + sendMessage(message) { + let result = message; + for (let i = 0;i < this.filters.length; i++) { + result = this.filters[i].sendMessage(result); + } + return result; + } + receiveMessage(message) { + let result = message; + for (let i = this.filters.length - 1;i >= 0; i--) { + result = this.filters[i].receiveMessage(result); + } + return result; + } + receiveTrailers(status) { + let result = status; + for (let i = this.filters.length - 1;i >= 0; i--) { + result = this.filters[i].receiveTrailers(result); + } + return result; + } + push(filters) { + this.filters.unshift(...filters); + } + getFilters() { + return this.filters; + } + } + exports.FilterStack = FilterStack; + + class FilterStackFactory { + constructor(factories) { + this.factories = factories; + } + push(filterFactories) { + this.factories.unshift(...filterFactories); + } + clone() { + return new FilterStackFactory([...this.factories]); + } + createFilter() { + return new FilterStack(this.factories.map((factory) => factory.createFilter())); + } + } + exports.FilterStackFactory = FilterStackFactory; +}); + +// node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js +var require_single_subchannel_channel = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SingleSubchannelChannel = undefined; + var call_number_1 = require_call_number(); + var channelz_1 = require_channelz(); + var compression_filter_1 = require_compression_filter(); + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants2(); + var control_plane_status_1 = require_control_plane_status(); + var deadline_1 = require_deadline(); + var filter_stack_1 = require_filter_stack(); + var metadata_1 = require_metadata(); + var resolver_1 = require_resolver(); + var uri_parser_1 = require_uri_parser(); + + class SubchannelCallWrapper { + constructor(subchannel, method, filterStackFactory, options, callNumber) { + var _a, _b; + this.subchannel = subchannel; + this.method = method; + this.options = options; + this.callNumber = callNumber; + this.childCall = null; + this.pendingMessage = null; + this.readPending = false; + this.halfClosePending = false; + this.pendingStatus = null; + this.readFilterPending = false; + this.writeFilterPending = false; + const splitPath = this.method.split("/"); + let serviceName = ""; + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === undefined ? undefined : _a.host) !== null && _b !== undefined ? _b : "localhost"; + this.serviceUrl = `https://${hostname}/${serviceName}`; + const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); + if (timeout !== Infinity) { + if (timeout <= 0) { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); + } else { + setTimeout(() => { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); + }, timeout); + } + } + this.filterStack = filterStackFactory.createFilter(); + } + cancelWithStatus(status, details) { + if (this.childCall) { + this.childCall.cancelWithStatus(status, details); + } else { + this.pendingStatus = { + code: status, + details, + metadata: new metadata_1.Metadata + }; + } + } + getPeer() { + var _a, _b; + return (_b = (_a = this.childCall) === null || _a === undefined ? undefined : _a.getPeer()) !== null && _b !== undefined ? _b : this.subchannel.getAddress(); + } + async start(metadata, listener) { + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + return; + } + if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + listener.onReceiveStatus({ + code: constants_1.Status.UNAVAILABLE, + details: "Subchannel not ready", + metadata: new metadata_1.Metadata + }); + return; + } + const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); + let credsMetadata; + try { + credsMetadata = await this.subchannel.getCallCredentials().generateMetadata({ method_name: this.method, service_url: this.serviceUrl }); + } catch (e) { + const error = e; + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === "number" ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); + listener.onReceiveStatus({ + code, + details, + metadata: new metadata_1.Metadata + }); + return; + } + credsMetadata.merge(filteredMetadata); + const childListener = { + onReceiveMetadata: async (metadata2) => { + listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata2)); + }, + onReceiveMessage: async (message) => { + this.readFilterPending = true; + const filteredMessage = await this.filterStack.receiveMessage(message); + this.readFilterPending = false; + listener.onReceiveMessage(filteredMessage); + if (this.pendingStatus) { + listener.onReceiveStatus(this.pendingStatus); + } + }, + onReceiveStatus: async (status) => { + const filteredStatus = await this.filterStack.receiveTrailers(status); + if (this.readFilterPending) { + this.pendingStatus = filteredStatus; + } else { + listener.onReceiveStatus(filteredStatus); + } + } + }; + this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); + if (this.readPending) { + this.childCall.startRead(); + } + if (this.pendingMessage) { + this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.halfClosePending && !this.writeFilterPending) { + this.childCall.halfClose(); + } + } + async sendMessageWithContext(context, message) { + this.writeFilterPending = true; + const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message, flags: context.flags })); + this.writeFilterPending = false; + if (this.childCall) { + this.childCall.sendMessageWithContext(context, filteredMessage.message); + if (this.halfClosePending) { + this.childCall.halfClose(); + } + } else { + this.pendingMessage = { context, message: filteredMessage.message }; + } + } + startRead() { + if (this.childCall) { + this.childCall.startRead(); + } else { + this.readPending = true; + } + } + halfClose() { + if (this.childCall && !this.writeFilterPending) { + this.childCall.halfClose(); + } else { + this.halfClosePending = true; + } + } + getCallNumber() { + return this.callNumber; + } + setCredentials(credentials) { + throw new Error("Method not implemented."); + } + getAuthContext() { + if (this.childCall) { + return this.childCall.getAuthContext(); + } else { + return null; + } + } + } + + class SingleSubchannelChannel { + constructor(subchannel, target, options) { + this.subchannel = subchannel; + this.target = target; + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTrace; + this.callTracker = new channelz_1.ChannelzCallTracker; + this.childrenTracker = new channelz_1.ChannelzChildrenTracker; + this.channelzEnabled = options["grpc.enable_channelz"] !== 0; + this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({ + target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`, + state: this.subchannel.getConnectivityState(), + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }), this.channelzEnabled); + if (this.channelzEnabled) { + this.childrenTracker.refChild(subchannel.getChannelzRef()); + } + this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]); + } + close() { + if (this.channelzEnabled) { + this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); + } + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + getTarget() { + return (0, uri_parser_1.uriToString)(this.target); + } + getConnectivityState(tryToConnect) { + throw new Error("Method not implemented."); + } + watchConnectivityState(currentState, deadline, callback) { + throw new Error("Method not implemented."); + } + getChannelzRef() { + return this.channelzRef; + } + createCall(method, deadline) { + const callOptions = { + deadline, + host: (0, resolver_1.getDefaultAuthority)(this.target), + flags: constants_1.Propagate.DEFAULTS, + parentCall: null + }; + return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)()); + } + } + exports.SingleSubchannelChannel = SingleSubchannelChannel; +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel.js +var require_subchannel = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Subchannel = undefined; + var connectivity_state_1 = require_connectivity_state(); + var backoff_timeout_1 = require_backoff_timeout(); + var logging = require_logging(); + var constants_1 = require_constants2(); + var uri_parser_1 = require_uri_parser(); + var subchannel_address_1 = require_subchannel_address(); + var channelz_1 = require_channelz(); + var single_subchannel_channel_1 = require_single_subchannel_channel(); + var TRACER_NAME = "subchannel"; + var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); + + class Subchannel { + constructor(channelTarget, subchannelAddress, options, credentials, connector) { + var _a; + this.channelTarget = channelTarget; + this.subchannelAddress = subchannelAddress; + this.options = options; + this.connector = connector; + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + this.transport = null; + this.continueConnecting = false; + this.stateListeners = new Set; + this.refcount = 0; + this.channelzEnabled = true; + this.dataProducers = new Map; + this.subchannelChannel = null; + const backoffOptions = { + initialDelay: options["grpc.initial_reconnect_backoff_ms"], + maxDelay: options["grpc.max_reconnect_backoff_ms"] + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + this.handleBackoffTimer(); + }, backoffOptions); + this.backoffTimeout.unref(); + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + this.keepaliveTime = (_a = options["grpc.keepalive_time_ms"]) !== null && _a !== undefined ? _a : -1; + if (options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub; + this.callTracker = new channelz_1.ChannelzCallTrackerStub; + this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub; + this.streamTracker = new channelz_1.ChannelzCallTrackerStub; + } else { + this.channelzTrace = new channelz_1.ChannelzTrace; + this.callTracker = new channelz_1.ChannelzCallTracker; + this.childrenTracker = new channelz_1.ChannelzChildrenTracker; + this.streamTracker = new channelz_1.ChannelzCallTracker; + } + this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace("CT_INFO", "Subchannel created"); + this.trace("Subchannel constructed with options " + JSON.stringify(options, undefined, 2)); + this.secureConnector = credentials._createSecureConnector(channelTarget, options); + } + getChannelzInfo() { + return { + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + target: this.subchannelAddressString + }; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + refTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + handleBackoffTimer() { + if (this.continueConnecting) { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + } else { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); + } + } + startBackoff() { + this.backoffTimeout.runOnce(); + } + stopBackoff() { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + } + startConnectingInternal() { + let options = this.options; + if (options["grpc.keepalive_time_ms"]) { + const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); + options = Object.assign(Object.assign({}, options), { "grpc.keepalive_time_ms": adjustedKeepaliveTime }); + } + this.connector.connect(this.subchannelAddress, this.secureConnector, options).then((transport) => { + if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { + this.transport = transport; + if (this.channelzEnabled) { + this.childrenTracker.refChild(transport.getChannelzRef()); + } + transport.addDisconnectListener((tooManyPings) => { + this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + if (tooManyPings && this.keepaliveTime > 0) { + this.keepaliveTime *= 2; + logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); + } + }); + } else { + transport.shutdown(); + } + }, (error) => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`); + }); + } + transitionToState(oldStates, newState, errorMessage) { + var _a, _b; + if (oldStates.indexOf(this.connectivityState) === -1) { + return false; + } + if (errorMessage) { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"'); + } else { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + } + if (this.channelzEnabled) { + this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); + } + const previousState = this.connectivityState; + this.connectivityState = newState; + switch (newState) { + case connectivity_state_1.ConnectivityState.READY: + this.stopBackoff(); + break; + case connectivity_state_1.ConnectivityState.CONNECTING: + this.startBackoff(); + this.startConnectingInternal(); + this.continueConnecting = false; + break; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_a = this.transport) === null || _a === undefined || _a.shutdown(); + this.transport = null; + if (!this.backoffTimeout.isRunning()) { + process.nextTick(() => { + this.handleBackoffTimer(); + }); + } + break; + case connectivity_state_1.ConnectivityState.IDLE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_b = this.transport) === null || _b === undefined || _b.shutdown(); + this.transport = null; + break; + default: + throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); + } + for (const listener of this.stateListeners) { + listener(this, previousState, newState, this.keepaliveTime, errorMessage); + } + return true; + } + ref() { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1)); + this.refcount += 1; + } + unref() { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1)); + this.refcount -= 1; + if (this.refcount === 0) { + this.channelzTrace.addTrace("CT_INFO", "Shutting down"); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + this.secureConnector.destroy(); + process.nextTick(() => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + }); + } + } + unrefIfOneRef() { + if (this.refcount === 1) { + this.unref(); + return true; + } + return false; + } + createCall(metadata, host, method, listener) { + if (!this.transport) { + throw new Error("Cannot create call, subchannel not READY"); + } + let statsTracker; + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + this.streamTracker.addCallStarted(); + statsTracker = { + onCallEnd: (status) => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + } + }; + } else { + statsTracker = {}; + } + return this.transport.createCall(metadata, host, method, listener, statsTracker); + } + startConnecting() { + process.nextTick(() => { + if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.continueConnecting = true; + } + } + }); + } + getConnectivityState() { + return this.connectivityState; + } + addConnectivityStateListener(listener) { + this.stateListeners.add(listener); + } + removeConnectivityStateListener(listener) { + this.stateListeners.delete(listener); + } + resetBackoff() { + process.nextTick(() => { + this.backoffTimeout.reset(); + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + }); + } + getAddress() { + return this.subchannelAddressString; + } + getChannelzRef() { + return this.channelzRef; + } + isHealthy() { + return true; + } + addHealthStateWatcher(listener) {} + removeHealthStateWatcher(listener) {} + getRealSubchannel() { + return this; + } + realSubchannelEquals(other) { + return other.getRealSubchannel() === this; + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + } + } + getCallCredentials() { + return this.secureConnector.getCallCredentials(); + } + getChannel() { + if (!this.subchannelChannel) { + this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options); + } + return this.subchannelChannel; + } + addDataWatcher(dataWatcher) { + throw new Error("Not implemented"); + } + getOrCreateDataProducer(name, createDataProducer) { + const existingProducer = this.dataProducers.get(name); + if (existingProducer) { + return existingProducer; + } + const newProducer = createDataProducer(this); + this.dataProducers.set(name, newProducer); + return newProducer; + } + removeDataProducer(name) { + this.dataProducers.delete(name); + } + } + exports.Subchannel = Subchannel; +}); + +// node_modules/@grpc/grpc-js/build/src/environment.js +var require_environment2 = __commonJS((exports) => { + var _a; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = undefined; + exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== undefined ? _a : "false") === "true"; +}); + +// node_modules/@grpc/grpc-js/build/src/resolver-dns.js +var require_resolver_dns = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DEFAULT_PORT = undefined; + exports.setup = setup; + var resolver_1 = require_resolver(); + var dns_1 = __require("dns"); + var service_config_1 = require_service_config(); + var constants_1 = require_constants2(); + var call_interface_1 = require_call_interface(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var constants_2 = require_constants2(); + var uri_parser_1 = require_uri_parser(); + var net_1 = __require("net"); + var backoff_timeout_1 = require_backoff_timeout(); + var environment_1 = require_environment2(); + var TRACER_NAME = "dns_resolver"; + function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); + } + exports.DEFAULT_PORT = 443; + var DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30000; + + class DnsResolver { + constructor(target, listener, channelOptions) { + var _a, _b, _c; + this.target = target; + this.listener = listener; + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfigResult = null; + this.continueResolving = false; + this.isNextResolutionTimerRunning = false; + this.isServiceConfigEnabled = true; + this.returnedIpResult = false; + this.alternativeResolver = new dns_1.promises.Resolver; + trace("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target)); + if (target.authority) { + this.alternativeResolver.setServers([target.authority]); + } + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (hostPort === null) { + this.ipResult = null; + this.dnsHostname = null; + this.port = null; + } else { + if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { + this.ipResult = [ + { + addresses: [ + { + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== undefined ? _a : exports.DEFAULT_PORT + } + ] + } + ]; + this.dnsHostname = null; + this.port = null; + } else { + this.ipResult = null; + this.dnsHostname = hostPort.host; + this.port = (_b = hostPort.port) !== null && _b !== undefined ? _b : exports.DEFAULT_PORT; + } + } + this.percentage = Math.random() * 100; + if (channelOptions["grpc.service_config_disable_resolution"] === 1) { + this.isServiceConfigEnabled = false; + } + this.defaultResolutionError = { + code: constants_1.Status.UNAVAILABLE, + details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, + metadata: new metadata_1.Metadata + }; + const backoffOptions = { + initialDelay: channelOptions["grpc.initial_reconnect_backoff_ms"], + maxDelay: channelOptions["grpc.max_reconnect_backoff_ms"] + }; + this.backoff = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, backoffOptions); + this.backoff.unref(); + this.minTimeBetweenResolutionsMs = (_c = channelOptions["grpc.dns_min_time_between_resolutions_ms"]) !== null && _c !== undefined ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; + this.nextResolutionTimer = setTimeout(() => {}, 0); + clearTimeout(this.nextResolutionTimer); + } + startResolution() { + if (this.ipResult !== null) { + if (!this.returnedIpResult) { + trace("Returning IP address for target " + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, ""); + }); + this.returnedIpResult = true; + } + this.backoff.stop(); + this.backoff.reset(); + this.stopNextResolutionTimer(); + return; + } + if (this.dnsHostname === null) { + trace("Failed to parse DNS address " + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener((0, call_interface_1.statusOrFromError)({ + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}` + }), {}, null, ""); + }); + this.stopNextResolutionTimer(); + } else { + if (this.pendingLookupPromise !== null) { + return; + } + trace("Looking up DNS hostname " + this.dnsHostname); + this.latestLookupResult = null; + const hostname = this.dnsHostname; + this.pendingLookupPromise = this.lookup(hostname); + this.pendingLookupPromise.then((addressList) => { + if (this.pendingLookupPromise === null) { + return; + } + this.pendingLookupPromise = null; + this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map((address) => ({ + addresses: [address] + }))); + const allAddressesString = "[" + addressList.map((addr) => addr.host + ":" + addr.port).join(",") + "]"; + trace("Resolved addresses for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + allAddressesString); + const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ""); + this.handleHealthStatus(healthStatus); + }, (err) => { + if (this.pendingLookupPromise === null) { + return; + } + trace("Resolution error for target " + (0, uri_parser_1.uriToString)(this.target) + ": " + err.message); + this.pendingLookupPromise = null; + this.stopNextResolutionTimer(); + this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, ""); + }); + if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { + this.pendingTxtPromise = this.resolveTxt(hostname); + this.pendingTxtPromise.then((txtRecord) => { + if (this.pendingTxtPromise === null) { + return; + } + this.pendingTxtPromise = null; + let serviceConfig; + try { + serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); + if (serviceConfig) { + this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig); + } else { + this.latestServiceConfigResult = null; + } + } catch (err) { + this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({ + code: constants_1.Status.UNAVAILABLE, + details: `Parsing service config failed with error ${err.message}` + }); + } + if (this.latestLookupResult !== null) { + this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ""); + } + }, (err) => {}); + } + } + } + handleHealthStatus(healthStatus) { + if (healthStatus) { + this.backoff.stop(); + this.backoff.reset(); + } else { + this.continueResolving = true; + } + } + async lookup(hostname) { + if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace("Using alternative DNS resolver."); + const records = await Promise.allSettled([ + this.alternativeResolver.resolve4(hostname), + this.alternativeResolver.resolve6(hostname) + ]); + if (records.every((result) => result.status === "rejected")) { + throw new Error(records[0].reason); + } + return records.reduce((acc, result) => { + return result.status === "fulfilled" ? [...acc, ...result.value] : acc; + }, []).map((addr) => ({ + host: addr, + port: +this.port + })); + } + const addressList = await dns_1.promises.lookup(hostname, { all: true }); + return addressList.map((addr) => ({ host: addr.address, port: +this.port })); + } + async resolveTxt(hostname) { + if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { + trace("Using alternative DNS resolver."); + return this.alternativeResolver.resolveTxt(hostname); + } + return dns_1.promises.resolveTxt(hostname); + } + startNextResolutionTimer() { + var _a, _b; + clearTimeout(this.nextResolutionTimer); + this.nextResolutionTimer = setTimeout(() => { + this.stopNextResolutionTimer(); + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, this.minTimeBetweenResolutionsMs); + (_b = (_a = this.nextResolutionTimer).unref) === null || _b === undefined || _b.call(_a); + this.isNextResolutionTimerRunning = true; + } + stopNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.isNextResolutionTimerRunning = false; + } + startResolutionWithBackoff() { + if (this.pendingLookupPromise === null) { + this.continueResolving = false; + this.backoff.runOnce(); + this.startNextResolutionTimer(); + this.startResolution(); + } + } + updateResolution() { + if (this.pendingLookupPromise === null) { + if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { + if (this.isNextResolutionTimerRunning) { + trace('resolution update delayed by "min time between resolutions" rate limit'); + } else { + trace("resolution update delayed by backoff timer until " + this.backoff.getEndTime().toISOString()); + } + this.continueResolving = true; + } else { + this.startResolutionWithBackoff(); + } + } + } + destroy() { + this.continueResolving = false; + this.backoff.reset(); + this.backoff.stop(); + this.stopNextResolutionTimer(); + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfigResult = null; + this.returnedIpResult = false; + } + static getDefaultAuthority(target) { + return target.path; + } + } + function setup() { + (0, resolver_1.registerResolver)("dns", DnsResolver); + (0, resolver_1.registerDefaultScheme)("dns"); + } +}); + +// node_modules/@grpc/grpc-js/build/src/http_proxy.js +var require_http_proxy = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseCIDR = parseCIDR; + exports.mapProxyName = mapProxyName; + exports.getProxiedConnection = getProxiedConnection; + var logging_1 = require_logging(); + var constants_1 = require_constants2(); + var net_1 = __require("net"); + var http = __require("http"); + var logging = require_logging(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var url_1 = __require("url"); + var resolver_dns_1 = require_resolver_dns(); + var TRACER_NAME = "proxy"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + function getProxyInfo() { + let proxyEnv = ""; + let envVar = ""; + if (process.env.grpc_proxy) { + envVar = "grpc_proxy"; + proxyEnv = process.env.grpc_proxy; + } else if (process.env.https_proxy) { + envVar = "https_proxy"; + proxyEnv = process.env.https_proxy; + } else if (process.env.http_proxy) { + envVar = "http_proxy"; + proxyEnv = process.env.http_proxy; + } else { + return {}; + } + let proxyUrl; + try { + proxyUrl = new url_1.URL(proxyEnv); + } catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); + return {}; + } + if (proxyUrl.protocol !== "http:") { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); + return {}; + } + let userCred = null; + if (proxyUrl.username) { + if (proxyUrl.password) { + (0, logging_1.log)(constants_1.LogVerbosity.INFO, "userinfo found in proxy URI"); + userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); + } else { + userCred = proxyUrl.username; + } + } + const hostname = proxyUrl.hostname; + let port = proxyUrl.port; + if (port === "") { + port = "80"; + } + const result = { + address: `${hostname}:${port}` + }; + if (userCred) { + result.creds = userCred; + } + trace("Proxy server " + result.address + " set by environment variable " + envVar); + return result; + } + function getNoProxyHostList() { + let noProxyStr = process.env.no_grpc_proxy; + let envVar = "no_grpc_proxy"; + if (!noProxyStr) { + noProxyStr = process.env.no_proxy; + envVar = "no_proxy"; + } + if (noProxyStr) { + trace("No proxy server list set by environment variable " + envVar); + return noProxyStr.split(","); + } else { + return []; + } + } + function parseCIDR(cidrString) { + const splitRange = cidrString.split("/"); + if (splitRange.length !== 2) { + return null; + } + const prefixLength = parseInt(splitRange[1], 10); + if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { + return null; + } + return { + ip: ipToInt(splitRange[0]), + prefixLength + }; + } + function ipToInt(ip) { + return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); + } + function isIpInCIDR(cidr, serverHost) { + const ip = cidr.ip; + const mask = -1 << 32 - cidr.prefixLength; + const hostIP = ipToInt(serverHost); + return (hostIP & mask) === (ip & mask); + } + function hostMatchesNoProxyList(serverHost) { + for (const host of getNoProxyHostList()) { + const parsedCIDR = parseCIDR(host); + if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { + return true; + } else if (serverHost.endsWith(host)) { + return true; + } + } + return false; + } + function mapProxyName(target, options) { + var _a; + const noProxyResult = { + target, + extraOptions: {} + }; + if (((_a = options["grpc.enable_http_proxy"]) !== null && _a !== undefined ? _a : 1) === 0) { + return noProxyResult; + } + if (target.scheme === "unix") { + return noProxyResult; + } + const proxyInfo = getProxyInfo(); + if (!proxyInfo.address) { + return noProxyResult; + } + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (!hostPort) { + return noProxyResult; + } + const serverHost = hostPort.host; + if (hostMatchesNoProxyList(serverHost)) { + trace("Not using proxy for target in no_proxy list: " + (0, uri_parser_1.uriToString)(target)); + return noProxyResult; + } + const extraOptions = { + "grpc.http_connect_target": (0, uri_parser_1.uriToString)(target) + }; + if (proxyInfo.creds) { + extraOptions["grpc.http_connect_creds"] = proxyInfo.creds; + } + return { + target: { + scheme: "dns", + path: proxyInfo.address + }, + extraOptions + }; + } + function getProxiedConnection(address, channelOptions) { + var _a; + if (!("grpc.http_connect_target" in channelOptions)) { + return Promise.resolve(null); + } + const realTarget = channelOptions["grpc.http_connect_target"]; + const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); + if (parsedTarget === null) { + return Promise.resolve(null); + } + const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); + if (splitHostPost === null) { + return Promise.resolve(null); + } + const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== undefined ? _a : resolver_dns_1.DEFAULT_PORT}`; + const options = { + method: "CONNECT", + path: hostPort + }; + const headers = { + Host: hostPort + }; + if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { + options.host = address.host; + options.port = address.port; + } else { + options.socketPath = address.path; + } + if ("grpc.http_connect_creds" in channelOptions) { + headers["Proxy-Authorization"] = "Basic " + Buffer.from(channelOptions["grpc.http_connect_creds"]).toString("base64"); + } + options.headers = headers; + const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); + trace("Using proxy " + proxyAddressString + " to connect to " + options.path); + return new Promise((resolve, reject) => { + const request2 = http.request(options); + request2.once("connect", (res, socket, head) => { + request2.removeAllListeners(); + socket.removeAllListeners(); + if (res.statusCode === 200) { + trace("Successfully connected to " + options.path + " through proxy " + proxyAddressString); + if (head.length > 0) { + socket.unshift(head); + } + trace("Successfully established a plaintext connection to " + options.path + " through proxy " + proxyAddressString); + resolve(socket); + } else { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to " + options.path + " through proxy " + proxyAddressString + " with status " + res.statusCode); + reject(); + } + }); + request2.once("error", (err) => { + request2.removeAllListeners(); + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, "Failed to connect to proxy " + proxyAddressString + " with error " + err.message); + reject(); + }); + request2.end(); + }); + } +}); + +// node_modules/@grpc/grpc-js/build/src/stream-decoder.js +var require_stream_decoder = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StreamDecoder = undefined; + var ReadState; + (function(ReadState2) { + ReadState2[ReadState2["NO_DATA"] = 0] = "NO_DATA"; + ReadState2[ReadState2["READING_SIZE"] = 1] = "READING_SIZE"; + ReadState2[ReadState2["READING_MESSAGE"] = 2] = "READING_MESSAGE"; + })(ReadState || (ReadState = {})); + + class StreamDecoder { + constructor(maxReadMessageLength) { + this.maxReadMessageLength = maxReadMessageLength; + this.readState = ReadState.NO_DATA; + this.readCompressFlag = Buffer.alloc(1); + this.readPartialSize = Buffer.alloc(4); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readPartialMessage = []; + this.readMessageRemaining = 0; + } + write(data) { + let readHead = 0; + let toRead; + const result = []; + while (readHead < data.length) { + switch (this.readState) { + case ReadState.NO_DATA: + this.readCompressFlag = data.slice(readHead, readHead + 1); + readHead += 1; + this.readState = ReadState.READING_SIZE; + this.readPartialSize.fill(0); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readMessageRemaining = 0; + this.readPartialMessage = []; + break; + case ReadState.READING_SIZE: + toRead = Math.min(data.length - readHead, this.readSizeRemaining); + data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); + this.readSizeRemaining -= toRead; + readHead += toRead; + if (this.readSizeRemaining === 0) { + this.readMessageSize = this.readPartialSize.readUInt32BE(0); + if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { + throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); + } + this.readMessageRemaining = this.readMessageSize; + if (this.readMessageRemaining > 0) { + this.readState = ReadState.READING_MESSAGE; + } else { + const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); + this.readState = ReadState.NO_DATA; + result.push(message); + } + } + break; + case ReadState.READING_MESSAGE: + toRead = Math.min(data.length - readHead, this.readMessageRemaining); + this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); + this.readMessageRemaining -= toRead; + readHead += toRead; + if (this.readMessageRemaining === 0) { + const framedMessageBuffers = [ + this.readCompressFlag, + this.readPartialSize + ].concat(this.readPartialMessage); + const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); + this.readState = ReadState.NO_DATA; + result.push(framedMessage); + } + break; + default: + throw new Error("Unexpected read state"); + } + } + return result; + } + } + exports.StreamDecoder = StreamDecoder; +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-call.js +var require_subchannel_call = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Http2SubchannelCall = undefined; + var http2 = __require("http2"); + var os = __require("os"); + var constants_1 = require_constants2(); + var metadata_1 = require_metadata(); + var stream_decoder_1 = require_stream_decoder(); + var logging = require_logging(); + var constants_2 = require_constants2(); + var TRACER_NAME = "subchannel_call"; + function getSystemErrorName(errno) { + for (const [name, num] of Object.entries(os.constants.errno)) { + if (num === errno) { + return name; + } + } + return "Unknown system error " + errno; + } + function mapHttpStatusCode(code) { + const details = `Received HTTP status code ${code}`; + let mappedStatusCode; + switch (code) { + case 400: + mappedStatusCode = constants_1.Status.INTERNAL; + break; + case 401: + mappedStatusCode = constants_1.Status.UNAUTHENTICATED; + break; + case 403: + mappedStatusCode = constants_1.Status.PERMISSION_DENIED; + break; + case 404: + mappedStatusCode = constants_1.Status.UNIMPLEMENTED; + break; + case 429: + case 502: + case 503: + case 504: + mappedStatusCode = constants_1.Status.UNAVAILABLE; + break; + default: + mappedStatusCode = constants_1.Status.UNKNOWN; + } + return { + code: mappedStatusCode, + details, + metadata: new metadata_1.Metadata + }; + } + + class Http2SubchannelCall { + constructor(http2Stream, callEventTracker, listener, transport, callId) { + var _a; + this.http2Stream = http2Stream; + this.callEventTracker = callEventTracker; + this.listener = listener; + this.transport = transport; + this.callId = callId; + this.isReadFilterPending = false; + this.isPushPending = false; + this.canPush = false; + this.readsClosed = false; + this.statusOutput = false; + this.unpushedReadMessages = []; + this.finalStatus = null; + this.internalError = null; + this.serverEndedCall = false; + this.connectionDropped = false; + const maxReceiveMessageLength = (_a = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a !== undefined ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); + http2Stream.on("response", (headers, flags) => { + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += "\t\t" + header + ": " + headers[header] + ` +`; + } + this.trace(`Received server headers: +` + headersString); + this.httpStatusCode = headers[":status"]; + if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { + this.handleTrailers(headers); + } else { + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } catch (error) { + this.endCall({ + code: constants_1.Status.UNKNOWN, + details: error.message, + metadata: new metadata_1.Metadata + }); + return; + } + this.listener.onReceiveMetadata(metadata); + } + }); + http2Stream.on("trailers", (headers) => { + this.handleTrailers(headers); + }); + http2Stream.on("data", (data) => { + if (this.statusOutput) { + return; + } + this.trace("receive HTTP/2 data frame of length " + data.length); + let messages; + try { + messages = this.decoder.write(data); + } catch (e) { + if (this.httpStatusCode !== undefined && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + this.cancelWithStatus(mappedStatus.code, mappedStatus.details); + } else { + this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message); + } + return; + } + for (const message of messages) { + this.trace("parsed message of length " + message.length); + this.callEventTracker.addMessageReceived(); + this.tryPush(message); + } + }); + http2Stream.on("end", () => { + this.readsClosed = true; + this.maybeOutputStatus(); + }); + http2Stream.on("close", () => { + this.serverEndedCall = true; + process.nextTick(() => { + var _a2; + this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode); + if (((_a2 = this.finalStatus) === null || _a2 === undefined ? undefined : _a2.code) === constants_1.Status.OK) { + return; + } + let code; + let details = ""; + switch (http2Stream.rstCode) { + case http2.constants.NGHTTP2_NO_ERROR: + if (this.finalStatus !== null) { + return; + } + if (this.httpStatusCode && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + code = mappedStatus.code; + details = mappedStatus.details; + } else { + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; + } + break; + case http2.constants.NGHTTP2_REFUSED_STREAM: + code = constants_1.Status.UNAVAILABLE; + details = "Stream refused by server"; + break; + case http2.constants.NGHTTP2_CANCEL: + if (this.connectionDropped) { + code = constants_1.Status.UNAVAILABLE; + details = "Connection dropped"; + } else { + code = constants_1.Status.CANCELLED; + details = "Call cancelled"; + } + break; + case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: + code = constants_1.Status.RESOURCE_EXHAUSTED; + details = "Bandwidth exhausted or memory limit exceeded"; + break; + case http2.constants.NGHTTP2_INADEQUATE_SECURITY: + code = constants_1.Status.PERMISSION_DENIED; + details = "Protocol not secure enough"; + break; + case http2.constants.NGHTTP2_INTERNAL_ERROR: + code = constants_1.Status.INTERNAL; + if (this.internalError === null) { + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; + } else { + if (this.internalError.code === "ECONNRESET" || this.internalError.code === "ETIMEDOUT") { + code = constants_1.Status.UNAVAILABLE; + details = this.internalError.message; + } else { + details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; + } + } + break; + default: + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode}`; + } + this.endCall({ + code, + details, + metadata: new metadata_1.Metadata, + rstCode: http2Stream.rstCode + }); + }); + }); + http2Stream.on("error", (err) => { + if (err.code !== "ERR_HTTP2_STREAM_ERROR") { + this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall); + this.internalError = err; + } + this.callEventTracker.onStreamEnd(false); + }); + } + getDeadlineInfo() { + return [`remote_addr=${this.getPeer()}`]; + } + onDisconnect() { + this.connectionDropped = true; + setImmediate(() => { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: "Connection dropped", + metadata: new metadata_1.Metadata + }); + }); + } + outputStatus() { + if (!this.statusOutput) { + this.statusOutput = true; + this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"'); + this.callEventTracker.onCallEnd(this.finalStatus); + process.nextTick(() => { + this.listener.onReceiveStatus(this.finalStatus); + }); + this.http2Stream.resume(); + } + } + trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text); + } + endCall(status) { + if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { + this.finalStatus = status; + this.maybeOutputStatus(); + } + this.destroyHttp2Stream(); + } + maybeOutputStatus() { + if (this.finalStatus !== null) { + if (this.finalStatus.code !== constants_1.Status.OK || this.readsClosed && this.unpushedReadMessages.length === 0 && !this.isReadFilterPending && !this.isPushPending) { + this.outputStatus(); + } + } + } + push(message) { + this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null)); + this.canPush = false; + this.isPushPending = true; + process.nextTick(() => { + this.isPushPending = false; + if (this.statusOutput) { + return; + } + this.listener.onReceiveMessage(message); + this.maybeOutputStatus(); + }); + } + tryPush(messageBytes) { + if (this.canPush) { + this.http2Stream.pause(); + this.push(messageBytes); + } else { + this.trace("unpushedReadMessages.push message of length " + messageBytes.length); + this.unpushedReadMessages.push(messageBytes); + } + } + handleTrailers(headers) { + this.serverEndedCall = true; + this.callEventTracker.onStreamEnd(true); + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += "\t\t" + header + ": " + headers[header] + ` +`; + } + this.trace(`Received server trailers: +` + headersString); + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } catch (e) { + metadata = new metadata_1.Metadata; + } + const metadataMap = metadata.getMap(); + let status; + if (typeof metadataMap["grpc-status"] === "string") { + const receivedStatus = Number(metadataMap["grpc-status"]); + this.trace("received status code " + receivedStatus + " from server"); + metadata.remove("grpc-status"); + let details = ""; + if (typeof metadataMap["grpc-message"] === "string") { + try { + details = decodeURI(metadataMap["grpc-message"]); + } catch (e) { + details = metadataMap["grpc-message"]; + } + metadata.remove("grpc-message"); + this.trace('received status details string "' + details + '" from server'); + } + status = { + code: receivedStatus, + details, + metadata + }; + } else if (this.httpStatusCode) { + status = mapHttpStatusCode(this.httpStatusCode); + status.metadata = metadata; + } else { + status = { + code: constants_1.Status.UNKNOWN, + details: "No status information received", + metadata + }; + } + this.endCall(status); + } + destroyHttp2Stream() { + var _a; + if (this.http2Stream.destroyed) { + return; + } + if (this.serverEndedCall) { + this.http2Stream.end(); + } else { + let code; + if (((_a = this.finalStatus) === null || _a === undefined ? undefined : _a.code) === constants_1.Status.OK) { + code = http2.constants.NGHTTP2_NO_ERROR; + } else { + code = http2.constants.NGHTTP2_CANCEL; + } + this.trace("close http2 stream with code " + code); + this.http2Stream.close(code); + } + } + cancelWithStatus(status, details) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + this.endCall({ code: status, details, metadata: new metadata_1.Metadata }); + } + getStatus() { + return this.finalStatus; + } + getPeer() { + return this.transport.getPeerName(); + } + getCallNumber() { + return this.callId; + } + getAuthContext() { + return this.transport.getAuthContext(); + } + startRead() { + if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { + this.readsClosed = true; + this.maybeOutputStatus(); + return; + } + this.canPush = true; + if (this.unpushedReadMessages.length > 0) { + const nextMessage = this.unpushedReadMessages.shift(); + this.push(nextMessage); + return; + } + this.http2Stream.resume(); + } + sendMessageWithContext(context, message) { + this.trace("write() called with message of length " + message.length); + const cb = (error) => { + process.nextTick(() => { + var _a; + let code = constants_1.Status.UNAVAILABLE; + if ((error === null || error === undefined ? undefined : error.code) === "ERR_STREAM_WRITE_AFTER_END") { + code = constants_1.Status.INTERNAL; + } + if (error) { + this.cancelWithStatus(code, `Write error: ${error.message}`); + } + (_a = context.callback) === null || _a === undefined || _a.call(context); + }); + }; + this.trace("sending data chunk of length " + message.length); + this.callEventTracker.addMessageSent(); + try { + this.http2Stream.write(message, cb); + } catch (error) { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: `Write failed with error ${error.message}`, + metadata: new metadata_1.Metadata + }); + } + } + halfClose() { + this.trace("end() called"); + this.trace("calling end() on HTTP/2 stream"); + this.http2Stream.end(); + } + } + exports.Http2SubchannelCall = Http2SubchannelCall; +}); + +// node_modules/@grpc/grpc-js/build/src/transport.js +var require_transport = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Http2SubchannelConnector = undefined; + var http2 = __require("http2"); + var tls_1 = __require("tls"); + var channelz_1 = require_channelz(); + var constants_1 = require_constants2(); + var http_proxy_1 = require_http_proxy(); + var logging = require_logging(); + var resolver_1 = require_resolver(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var net = __require("net"); + var subchannel_call_1 = require_subchannel_call(); + var call_number_1 = require_call_number(); + var TRACER_NAME = "transport"; + var FLOW_CONTROL_TRACER_NAME = "transport_flowctrl"; + var clientVersion = require_package().version; + var { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT } = http2.constants; + var KEEPALIVE_TIMEOUT_MS = 20000; + var tooManyPingsData = Buffer.from("too_many_pings", "ascii"); + + class Http2Transport { + constructor(session, subchannelAddress, options, remoteName) { + this.session = session; + this.options = options; + this.remoteName = remoteName; + this.keepaliveTimer = null; + this.pendingSendKeepalivePing = false; + this.activeCalls = new Set; + this.disconnectListeners = []; + this.disconnectHandled = false; + this.channelzEnabled = true; + this.keepalivesSent = 0; + this.messagesSent = 0; + this.messagesReceived = 0; + this.lastMessageSentTimestamp = null; + this.lastMessageReceivedTimestamp = null; + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + if (options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + this.streamTracker = new channelz_1.ChannelzCallTrackerStub; + } else { + this.streamTracker = new channelz_1.ChannelzCallTracker; + } + this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + this.userAgent = [ + options["grpc.primary_user_agent"], + `grpc-node-js/${clientVersion}`, + options["grpc.secondary_user_agent"] + ].filter((e) => e).join(" "); + if ("grpc.keepalive_time_ms" in options) { + this.keepaliveTimeMs = options["grpc.keepalive_time_ms"]; + } else { + this.keepaliveTimeMs = -1; + } + if ("grpc.keepalive_timeout_ms" in options) { + this.keepaliveTimeoutMs = options["grpc.keepalive_timeout_ms"]; + } else { + this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; + } + if ("grpc.keepalive_permit_without_calls" in options) { + this.keepaliveWithoutCalls = options["grpc.keepalive_permit_without_calls"] === 1; + } else { + this.keepaliveWithoutCalls = false; + } + session.once("close", () => { + this.trace("session closed"); + this.handleDisconnect(); + }); + session.once("goaway", (errorCode, lastStreamID, opaqueData) => { + let tooManyPings = false; + if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && opaqueData && opaqueData.equals(tooManyPingsData)) { + tooManyPings = true; + } + this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === undefined ? undefined : opaqueData.toString())); + this.reportDisconnectToOwner(tooManyPings); + }); + session.once("error", (error) => { + this.trace("connection closed with error " + error.message); + this.handleDisconnect(); + }); + session.socket.once("close", (hadError) => { + this.trace("connection closed. hadError=" + hadError); + this.handleDisconnect(); + }); + if (logging.isTracerEnabled(TRACER_NAME)) { + session.on("remoteSettings", (settings) => { + this.trace("new settings received" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); + }); + session.on("localSettings", (settings) => { + this.trace("local settings acknowledged by remote" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); + }); + } + if (this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + if (session.socket instanceof tls_1.TLSSocket) { + this.authContext = { + transportSecurityType: "ssl", + sslPeerCertificate: session.socket.getPeerCertificate() + }; + } else { + this.authContext = {}; + } + } + getChannelzInfo() { + var _a, _b, _c; + const sessionSocket = this.session.socket; + const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null; + const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null; + let tlsInfo; + if (this.session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== undefined ? _a : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && "raw" in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null + }; + } else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress, + localAddress, + security: tlsInfo, + remoteName: this.remoteName, + streamsStarted: this.streamTracker.callsStarted, + streamsSucceeded: this.streamTracker.callsSucceeded, + streamsFailed: this.streamTracker.callsFailed, + messagesSent: this.messagesSent, + messagesReceived: this.messagesReceived, + keepAlivesSent: this.keepalivesSent, + lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: this.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, + localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== undefined ? _b : null, + remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== undefined ? _c : null + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + keepaliveTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + flowControlTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + internalsTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } + reportDisconnectToOwner(tooManyPings) { + if (this.disconnectHandled) { + return; + } + this.disconnectHandled = true; + this.disconnectListeners.forEach((listener) => listener(tooManyPings)); + } + handleDisconnect() { + this.clearKeepaliveTimeout(); + this.reportDisconnectToOwner(false); + for (const call of this.activeCalls) { + call.onDisconnect(); + } + setImmediate(() => { + this.session.destroy(); + }); + } + addDisconnectListener(listener) { + this.disconnectListeners.push(listener); + } + canSendPing() { + return !this.session.destroyed && this.keepaliveTimeMs > 0 && (this.keepaliveWithoutCalls || this.activeCalls.size > 0); + } + maybeSendPing() { + var _a, _b; + if (!this.canSendPing()) { + this.pendingSendKeepalivePing = true; + return; + } + if (this.keepaliveTimer) { + console.error("keepaliveTimeout is not null"); + return; + } + if (this.channelzEnabled) { + this.keepalivesSent += 1; + } + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.keepaliveTrace("Ping timeout passed without response"); + this.handleDisconnect(); + }, this.keepaliveTimeoutMs); + (_b = (_a = this.keepaliveTimer).unref) === null || _b === undefined || _b.call(_a); + let pingSendError = ""; + try { + const pingSentSuccessfully = this.session.ping((err, duration, payload) => { + this.clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace("Ping failed with error " + err.message); + this.handleDisconnect(); + } else { + this.keepaliveTrace("Received ping response"); + this.maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = "Ping returned false"; + } + } catch (e) { + pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; + } + if (pingSendError) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + this.handleDisconnect(); + } + } + maybeStartKeepalivePingTimer() { + var _a, _b; + if (!this.canSendPing()) { + return; + } + if (this.pendingSendKeepalivePing) { + this.pendingSendKeepalivePing = false; + this.maybeSendPing(); + } else if (!this.keepaliveTimer) { + this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); + this.keepaliveTimer = setTimeout(() => { + this.keepaliveTimer = null; + this.maybeSendPing(); + }, this.keepaliveTimeMs); + (_b = (_a = this.keepaliveTimer).unref) === null || _b === undefined || _b.call(_a); + } + } + clearKeepaliveTimeout() { + if (this.keepaliveTimer) { + clearTimeout(this.keepaliveTimer); + this.keepaliveTimer = null; + } + } + removeActiveCall(call) { + this.activeCalls.delete(call); + if (this.activeCalls.size === 0) { + this.session.unref(); + } + } + addActiveCall(call) { + this.activeCalls.add(call); + if (this.activeCalls.size === 1) { + this.session.ref(); + if (!this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + } + createCall(metadata, host, method, listener, subchannelCallStatsTracker) { + const headers = metadata.toHttp2Headers(); + headers[HTTP2_HEADER_AUTHORITY] = host; + headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; + headers[HTTP2_HEADER_CONTENT_TYPE] = "application/grpc"; + headers[HTTP2_HEADER_METHOD] = "POST"; + headers[HTTP2_HEADER_PATH] = method; + headers[HTTP2_HEADER_TE] = "trailers"; + let http2Stream; + try { + http2Stream = this.session.request(headers); + } catch (e) { + this.handleDisconnect(); + throw e; + } + this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize); + this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed); + let eventTracker; + let call; + if (this.channelzEnabled) { + this.streamTracker.addCallStarted(); + eventTracker = { + addMessageSent: () => { + var _a; + this.messagesSent += 1; + this.lastMessageSentTimestamp = new Date; + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === undefined || _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + this.messagesReceived += 1; + this.lastMessageReceivedTimestamp = new Date; + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === undefined || _a.call(subchannelCallStatsTracker); + }, + onCallEnd: (status) => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === undefined || _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: (success) => { + var _a; + if (success) { + this.streamTracker.addCallSucceeded(); + } else { + this.streamTracker.addCallFailed(); + } + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === undefined || _a.call(subchannelCallStatsTracker, success); + } + }; + } else { + eventTracker = { + addMessageSent: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === undefined || _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === undefined || _a.call(subchannelCallStatsTracker); + }, + onCallEnd: (status) => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === undefined || _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: (success) => { + var _a; + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === undefined || _a.call(subchannelCallStatsTracker, success); + } + }; + } + call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); + this.addActiveCall(call); + return call; + } + getChannelzRef() { + return this.channelzRef; + } + getPeerName() { + return this.subchannelAddressString; + } + getOptions() { + return this.options; + } + getAuthContext() { + return this.authContext; + } + shutdown() { + this.session.close(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + } + + class Http2SubchannelConnector { + constructor(channelTarget) { + this.channelTarget = channelTarget; + this.session = null; + this.isShutdown = false; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text); + } + createSession(secureConnectResult, address, options) { + if (this.isShutdown) { + return Promise.reject(); + } + if (secureConnectResult.socket.closed) { + return Promise.reject("Connection closed before starting HTTP/2 handshake"); + } + return new Promise((resolve, reject) => { + var _a, _b, _c, _d, _e, _f, _g, _h; + let remoteName = null; + let realTarget = this.channelTarget; + if ("grpc.http_connect_target" in options) { + const parsedTarget = (0, uri_parser_1.parseUri)(options["grpc.http_connect_target"]); + if (parsedTarget) { + realTarget = parsedTarget; + remoteName = (0, uri_parser_1.uriToString)(parsedTarget); + } + } + const scheme = secureConnectResult.secure ? "https" : "http"; + const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); + const closeHandler = () => { + var _a2; + (_a2 = this.session) === null || _a2 === undefined || _a2.destroy(); + this.session = null; + setImmediate(() => { + if (!reportedError) { + reportedError = true; + reject(`${errorMessage.trim()} (${new Date().toISOString()})`); + } + }); + }; + const errorHandler = (error) => { + var _a2; + (_a2 = this.session) === null || _a2 === undefined || _a2.destroy(); + errorMessage = error.message; + this.trace("connection failed with error " + errorMessage); + if (!reportedError) { + reportedError = true; + reject(`${errorMessage} (${new Date().toISOString()})`); + } + }; + const sessionOptions = { + createConnection: (authority, option) => { + return secureConnectResult.socket; + }, + settings: { + initialWindowSize: (_d = (_a = options["grpc-node.flow_control_window"]) !== null && _a !== undefined ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === undefined ? undefined : _b.call(http2)) === null || _c === undefined ? undefined : _c.initialWindowSize) !== null && _d !== undefined ? _d : 65535 + }, + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + maxSessionMemory: (_e = options["grpc-node.max_session_memory"]) !== null && _e !== undefined ? _e : Number.MAX_SAFE_INTEGER + }; + const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); + const defaultWin = (_h = (_g = (_f = http2.getDefaultSettings) === null || _f === undefined ? undefined : _f.call(http2)) === null || _g === undefined ? undefined : _g.initialWindowSize) !== null && _h !== undefined ? _h : 65535; + const connWin = options["grpc-node.flow_control_window"]; + this.session = session; + let errorMessage = "Failed to connect"; + let reportedError = false; + session.unref(); + session.once("remoteSettings", () => { + var _a2; + if (connWin && connWin > defaultWin) { + try { + session.setLocalWindowSize(connWin); + } catch (_b2) { + const delta = connWin - ((_a2 = session.state.localWindowSize) !== null && _a2 !== undefined ? _a2 : defaultWin); + if (delta > 0) + session.incrementWindowSize(delta); + } + } + session.removeAllListeners(); + secureConnectResult.socket.removeListener("close", closeHandler); + secureConnectResult.socket.removeListener("error", errorHandler); + resolve(new Http2Transport(session, address, options, remoteName)); + this.session = null; + }); + session.once("close", closeHandler); + session.once("error", errorHandler); + secureConnectResult.socket.once("close", closeHandler); + secureConnectResult.socket.once("error", errorHandler); + }); + } + tcpConnect(address, options) { + return (0, http_proxy_1.getProxiedConnection)(address, options).then((proxiedSocket) => { + if (proxiedSocket) { + return proxiedSocket; + } else { + return new Promise((resolve, reject) => { + const closeCallback = () => { + reject(new Error("Socket closed")); + }; + const errorCallback = (error) => { + reject(error); + }; + const socket = net.connect(address, () => { + socket.removeListener("close", closeCallback); + socket.removeListener("error", errorCallback); + resolve(socket); + }); + socket.once("close", closeCallback); + socket.once("error", errorCallback); + }); + } + }); + } + async connect(address, secureConnector, options) { + if (this.isShutdown) { + return Promise.reject(); + } + let tcpConnection = null; + let secureConnectResult = null; + const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); + try { + this.trace(addressString + " Waiting for secureConnector to be ready"); + await secureConnector.waitForReady(); + this.trace(addressString + " secureConnector is ready"); + tcpConnection = await this.tcpConnect(address, options); + tcpConnection.setNoDelay(); + this.trace(addressString + " Established TCP connection"); + secureConnectResult = await secureConnector.connect(tcpConnection); + this.trace(addressString + " Established secure connection"); + return this.createSession(secureConnectResult, address, options); + } catch (e) { + tcpConnection === null || tcpConnection === undefined || tcpConnection.destroy(); + secureConnectResult === null || secureConnectResult === undefined || secureConnectResult.socket.destroy(); + throw e; + } + } + shutdown() { + var _a; + this.isShutdown = true; + (_a = this.session) === null || _a === undefined || _a.close(); + this.session = null; + } + } + exports.Http2SubchannelConnector = Http2SubchannelConnector; +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-pool.js +var require_subchannel_pool = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SubchannelPool = undefined; + exports.getSubchannelPool = getSubchannelPool; + var channel_options_1 = require_channel_options(); + var subchannel_1 = require_subchannel(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var transport_1 = require_transport(); + var REF_CHECK_INTERVAL = 1e4; + + class SubchannelPool { + constructor() { + this.pool = Object.create(null); + this.cleanupTimer = null; + } + unrefUnusedSubchannels() { + let allSubchannelsUnrefed = true; + for (const channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + const refedSubchannels = subchannelObjArray.filter((value) => !value.subchannel.unrefIfOneRef()); + if (refedSubchannels.length > 0) { + allSubchannelsUnrefed = false; + } + this.pool[channelTarget] = refedSubchannels; + } + if (allSubchannelsUnrefed && this.cleanupTimer !== null) { + clearInterval(this.cleanupTimer); + this.cleanupTimer = null; + } + } + ensureCleanupTask() { + var _a, _b; + if (this.cleanupTimer === null) { + this.cleanupTimer = setInterval(() => { + this.unrefUnusedSubchannels(); + }, REF_CHECK_INTERVAL); + (_b = (_a = this.cleanupTimer).unref) === null || _b === undefined || _b.call(_a); + } + } + getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { + this.ensureCleanupTask(); + const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); + if (channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + for (const subchannelObj of subchannelObjArray) { + if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && channelCredentials._equals(subchannelObj.channelCredentials)) { + return subchannelObj.subchannel; + } + } + } + const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); + if (!(channelTarget in this.pool)) { + this.pool[channelTarget] = []; + } + this.pool[channelTarget].push({ + subchannelAddress: subchannelTarget, + channelArguments, + channelCredentials, + subchannel + }); + subchannel.ref(); + return subchannel; + } + } + exports.SubchannelPool = SubchannelPool; + var globalSubchannelPool = new SubchannelPool; + function getSubchannelPool(global2) { + if (global2) { + return globalSubchannelPool; + } else { + return new SubchannelPool; + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancing-call.js +var require_load_balancing_call = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LoadBalancingCall = undefined; + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants2(); + var deadline_1 = require_deadline(); + var metadata_1 = require_metadata(); + var picker_1 = require_picker(); + var uri_parser_1 = require_uri_parser(); + var logging = require_logging(); + var control_plane_status_1 = require_control_plane_status(); + var http2 = __require("http2"); + var TRACER_NAME = "load_balancing_call"; + + class LoadBalancingCall { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { + var _a, _b; + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.metadata = null; + this.listener = null; + this.onCallEnded = null; + this.childStartTime = null; + const splitPath = this.methodName.split("/"); + let serviceName = ""; + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === undefined ? undefined : _a.host) !== null && _b !== undefined ? _b : "localhost"; + this.serviceUrl = `https://${hostname}/${serviceName}`; + this.startTime = new Date; + } + getDeadlineInfo() { + var _a, _b; + const deadlineInfo = []; + if (this.childStartTime) { + if (this.childStartTime > this.startTime) { + if ((_a = this.metadata) === null || _a === undefined ? undefined : _a.getOptions().waitForReady) { + deadlineInfo.push("wait_for_ready"); + } + deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); + } + deadlineInfo.push(...this.child.getDeadlineInfo()); + return deadlineInfo; + } else { + if ((_b = this.metadata) === null || _b === undefined ? undefined : _b.getOptions().waitForReady) { + deadlineInfo.push("wait_for_ready"); + } + deadlineInfo.push("Waiting for LB pick"); + } + return deadlineInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + outputStatus(status, progress) { + var _a, _b; + if (!this.ended) { + this.ended = true; + this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + this.startTime.toISOString()); + const finalStatus = Object.assign(Object.assign({}, status), { progress }); + (_a = this.listener) === null || _a === undefined || _a.onReceiveStatus(finalStatus); + (_b = this.onCallEnded) === null || _b === undefined || _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); + } + } + doPick() { + var _a, _b; + if (this.ended) { + return; + } + if (!this.metadata) { + throw new Error("doPick called before start"); + } + this.trace("Pick called"); + const finalMetadata = this.metadata.clone(); + const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); + const subchannelString = pickResult.subchannel ? "(" + pickResult.subchannel.getChannelzRef().id + ") " + pickResult.subchannel.getAddress() : "" + pickResult.subchannel; + this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + subchannelString + " status: " + ((_a = pickResult.status) === null || _a === undefined ? undefined : _a.code) + " " + ((_b = pickResult.status) === null || _b === undefined ? undefined : _b.details)); + switch (pickResult.pickResultType) { + case picker_1.PickResultType.COMPLETE: + const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); + combinedCallCredentials.generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }).then((credsMetadata) => { + var _a2; + if (this.ended) { + this.trace("Credentials metadata generation finished after call ended"); + return; + } + finalMetadata.merge(credsMetadata); + if (finalMetadata.get("authorization").length > 1) { + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: '"authorization" metadata cannot have multiple values', + metadata: new metadata_1.Metadata + }, "PROCESSED"); + } + if (pickResult.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + this.trace("Picked subchannel " + subchannelString + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick"); + this.doPick(); + return; + } + if (this.deadline !== Infinity) { + finalMetadata.set("grpc-timeout", (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); + } + try { + this.child = pickResult.subchannel.getRealSubchannel().createCall(finalMetadata, this.host, this.methodName, { + onReceiveMetadata: (metadata) => { + this.trace("Received metadata"); + this.listener.onReceiveMetadata(metadata); + }, + onReceiveMessage: (message) => { + this.trace("Received message"); + this.listener.onReceiveMessage(message); + }, + onReceiveStatus: (status) => { + this.trace("Received status"); + if (status.rstCode === http2.constants.NGHTTP2_REFUSED_STREAM) { + this.outputStatus(status, "REFUSED"); + } else { + this.outputStatus(status, "PROCESSED"); + } + } + }); + this.childStartTime = new Date; + } catch (error) { + this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error.message); + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: "Failed to start HTTP/2 stream with error " + error.message, + metadata: new metadata_1.Metadata + }, "NOT_STARTED"); + return; + } + (_a2 = pickResult.onCallStarted) === null || _a2 === undefined || _a2.call(pickResult); + this.onCallEnded = pickResult.onCallEnded; + this.trace("Created child call [" + this.child.getCallNumber() + "]"); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (error) => { + const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === "number" ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); + this.outputStatus({ + code: code2, + details: details2, + metadata: new metadata_1.Metadata + }, "PROCESSED"); + }); + break; + case picker_1.PickResultType.DROP: + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code, details, metadata: pickResult.status.metadata }, "DROP"); + }); + break; + case picker_1.PickResultType.TRANSIENT_FAILURE: + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForPick(this); + } else { + const { code: code2, details: details2 } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code: code2, details: details2, metadata: pickResult.status.metadata }, "PROCESSED"); + }); + } + break; + case picker_1.PickResultType.QUEUE: + this.channel.queueCallForPick(this); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === undefined || _a.cancelWithStatus(status, details); + this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata }, "PROCESSED"); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === undefined ? undefined : _a.getPeer()) !== null && _b !== undefined ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace("start called"); + this.listener = listener; + this.metadata = metadata; + this.doPick(); + } + sendMessageWithContext(context, message) { + this.trace("write() called with message of length " + message.length); + if (this.child) { + this.child.sendMessageWithContext(context, message); + } else { + this.pendingMessage = { context, message }; + } + } + startRead() { + this.trace("startRead called"); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose() { + this.trace("halfClose called"); + if (this.child) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + throw new Error("Method not implemented."); + } + getCallNumber() { + return this.callNumber; + } + getAuthContext() { + if (this.child) { + return this.child.getAuthContext(); + } else { + return null; + } + } + } + exports.LoadBalancingCall = LoadBalancingCall; +}); + +// node_modules/@grpc/grpc-js/build/src/resolving-call.js +var require_resolving_call = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResolvingCall = undefined; + var call_credentials_1 = require_call_credentials(); + var constants_1 = require_constants2(); + var deadline_1 = require_deadline(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var control_plane_status_1 = require_control_plane_status(); + var TRACER_NAME = "resolving_call"; + + class ResolvingCall { + constructor(channel, method, options, filterStackFactory, callNumber) { + this.channel = channel; + this.method = method; + this.filterStackFactory = filterStackFactory; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.readFilterPending = false; + this.writeFilterPending = false; + this.pendingChildStatus = null; + this.metadata = null; + this.listener = null; + this.statusWatchers = []; + this.deadlineTimer = setTimeout(() => {}, 0); + this.filterStack = null; + this.deadlineStartTime = null; + this.configReceivedTime = null; + this.childStartTime = null; + this.credentials = call_credentials_1.CallCredentials.createEmpty(); + this.deadline = options.deadline; + this.host = options.host; + if (options.parentCall) { + if (options.flags & constants_1.Propagate.CANCELLATION) { + options.parentCall.on("cancelled", () => { + this.cancelWithStatus(constants_1.Status.CANCELLED, "Cancelled by parent call"); + }); + } + if (options.flags & constants_1.Propagate.DEADLINE) { + this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline()); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); + } + } + this.trace("Created"); + this.runDeadlineTimer(); + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + runDeadlineTimer() { + clearTimeout(this.deadlineTimer); + this.deadlineStartTime = new Date; + this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline)); + const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); + if (timeout !== Infinity) { + this.trace("Deadline will be reached in " + timeout + "ms"); + const handleDeadline = () => { + if (!this.deadlineStartTime) { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); + return; + } + const deadlineInfo = []; + const deadlineEndTime = new Date; + deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); + if (this.configReceivedTime) { + if (this.configReceivedTime > this.deadlineStartTime) { + deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); + } + if (this.childStartTime) { + if (this.childStartTime > this.configReceivedTime) { + deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); + } + } else { + deadlineInfo.push("waiting for metadata filters"); + } + } else { + deadlineInfo.push("waiting for name resolution"); + } + if (this.child) { + deadlineInfo.push(...this.child.getDeadlineInfo()); + } + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(",")); + }; + if (timeout <= 0) { + process.nextTick(handleDeadline); + } else { + this.deadlineTimer = setTimeout(handleDeadline, timeout); + } + } + } + outputStatus(status) { + if (!this.ended) { + this.ended = true; + if (!this.filterStack) { + this.filterStack = this.filterStackFactory.createFilter(); + } + clearTimeout(this.deadlineTimer); + const filteredStatus = this.filterStack.receiveTrailers(status); + this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"'); + this.statusWatchers.forEach((watcher) => watcher(filteredStatus)); + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === undefined || _a.onReceiveStatus(filteredStatus); + }); + } + } + sendMessageOnChild(context, message) { + if (!this.child) { + throw new Error("sendMessageonChild called with child not populated"); + } + const child = this.child; + this.writeFilterPending = true; + this.filterStack.sendMessage(Promise.resolve({ message, flags: context.flags })).then((filteredMessage) => { + this.writeFilterPending = false; + child.sendMessageWithContext(context, filteredMessage.message); + if (this.pendingHalfClose) { + child.halfClose(); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + } + getConfig() { + if (this.ended) { + return; + } + if (!this.metadata || !this.listener) { + throw new Error("getConfig called before start"); + } + const configResult = this.channel.getConfig(this.method, this.metadata); + if (configResult.type === "NONE") { + this.channel.queueCallForConfig(this); + return; + } else if (configResult.type === "ERROR") { + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(configResult.error); + } + return; + } + this.configReceivedTime = new Date; + const config = configResult.config; + if (config.status !== constants_1.Status.OK) { + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, "Failed to route call to method " + this.method); + this.outputStatus({ + code, + details, + metadata: new metadata_1.Metadata + }); + return; + } + if (config.methodConfig.timeout) { + const configDeadline = new Date; + configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); + configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config.methodConfig.timeout.nanos / 1e6); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); + this.runDeadlineTimer(); + } + this.filterStackFactory.push(config.dynamicFilterFactories); + this.filterStack = this.filterStackFactory.createFilter(); + this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => { + this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); + this.trace("Created child [" + this.child.getCallNumber() + "]"); + this.childStartTime = new Date; + this.child.start(filteredMetadata, { + onReceiveMetadata: (metadata) => { + this.trace("Received metadata"); + this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); + }, + onReceiveMessage: (message) => { + this.trace("Received message"); + this.readFilterPending = true; + this.filterStack.receiveMessage(message).then((filteredMesssage) => { + this.trace("Finished filtering received message"); + this.readFilterPending = false; + this.listener.onReceiveMessage(filteredMesssage); + if (this.pendingChildStatus) { + this.outputStatus(this.pendingChildStatus); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + }, + onReceiveStatus: (status) => { + this.trace("Received status"); + if (this.readFilterPending) { + this.pendingChildStatus = status; + } else { + this.outputStatus(status); + } + } + }); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); + } else if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (status) => { + this.outputStatus(status); + }); + } + reportResolverError(status) { + var _a; + if ((_a = this.metadata) === null || _a === undefined ? undefined : _a.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(status); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === undefined || _a.cancelWithStatus(status, details); + this.outputStatus({ + code: status, + details, + metadata: new metadata_1.Metadata + }); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === undefined ? undefined : _a.getPeer()) !== null && _b !== undefined ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace("start called"); + this.metadata = metadata.clone(); + this.listener = listener; + this.getConfig(); + } + sendMessageWithContext(context, message) { + this.trace("write() called with message of length " + message.length); + if (this.child) { + this.sendMessageOnChild(context, message); + } else { + this.pendingMessage = { context, message }; + } + } + startRead() { + this.trace("startRead called"); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose() { + this.trace("halfClose called"); + if (this.child && !this.writeFilterPending) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + this.credentials = credentials; + } + addStatusWatcher(watcher) { + this.statusWatchers.push(watcher); + } + getCallNumber() { + return this.callNumber; + } + getAuthContext() { + if (this.child) { + return this.child.getAuthContext(); + } else { + return null; + } + } + } + exports.ResolvingCall = ResolvingCall; +}); + +// node_modules/@grpc/grpc-js/build/src/retrying-call.js +var require_retrying_call = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RetryingCall = exports.MessageBufferTracker = exports.RetryThrottler = undefined; + var constants_1 = require_constants2(); + var deadline_1 = require_deadline(); + var metadata_1 = require_metadata(); + var logging = require_logging(); + var TRACER_NAME = "retrying_call"; + + class RetryThrottler { + constructor(maxTokens, tokenRatio, previousRetryThrottler) { + this.maxTokens = maxTokens; + this.tokenRatio = tokenRatio; + if (previousRetryThrottler) { + this.tokens = previousRetryThrottler.tokens * (maxTokens / previousRetryThrottler.maxTokens); + } else { + this.tokens = maxTokens; + } + } + addCallSucceeded() { + this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); + } + addCallFailed() { + this.tokens = Math.max(this.tokens - 1, 0); + } + canRetryCall() { + return this.tokens > this.maxTokens / 2; + } + } + exports.RetryThrottler = RetryThrottler; + + class MessageBufferTracker { + constructor(totalLimit, limitPerCall) { + this.totalLimit = totalLimit; + this.limitPerCall = limitPerCall; + this.totalAllocated = 0; + this.allocatedPerCall = new Map; + } + allocate(size, callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== undefined ? _a : 0; + if (this.limitPerCall - currentPerCall < size || this.totalLimit - this.totalAllocated < size) { + return false; + } + this.allocatedPerCall.set(callId, currentPerCall + size); + this.totalAllocated += size; + return true; + } + free(size, callId) { + var _a; + if (this.totalAllocated < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= size; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== undefined ? _a : 0; + if (currentPerCall < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); + } + this.allocatedPerCall.set(callId, currentPerCall - size); + } + freeAll(callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== undefined ? _a : 0; + if (this.totalAllocated < currentPerCall) { + throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= currentPerCall; + this.allocatedPerCall.delete(callId); + } + } + exports.MessageBufferTracker = MessageBufferTracker; + var PREVIONS_RPC_ATTEMPTS_METADATA_KEY = "grpc-previous-rpc-attempts"; + var DEFAULT_MAX_ATTEMPTS_LIMIT = 5; + + class RetryingCall { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { + var _a; + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.bufferTracker = bufferTracker; + this.retryThrottler = retryThrottler; + this.listener = null; + this.initialMetadata = null; + this.underlyingCalls = []; + this.writeBuffer = []; + this.writeBufferOffset = 0; + this.readStarted = false; + this.transparentRetryUsed = false; + this.attempts = 0; + this.hedgingTimer = null; + this.committedCallIndex = null; + this.initialRetryBackoffSec = 0; + this.nextRetryBackoffSec = 0; + const maxAttemptsLimit = (_a = channel.getOptions()["grpc-node.retry_max_attempts_limit"]) !== null && _a !== undefined ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT; + if (channel.getOptions()["grpc.enable_retries"] === 0) { + this.state = "NO_RETRY"; + this.maxAttempts = 1; + } else if (callConfig.methodConfig.retryPolicy) { + this.state = "RETRY"; + const retryPolicy = callConfig.methodConfig.retryPolicy; + this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); + this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); + } else if (callConfig.methodConfig.hedgingPolicy) { + this.state = "HEDGING"; + this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit); + } else { + this.state = "TRANSPARENT_ONLY"; + this.maxAttempts = 1; + } + this.startTime = new Date; + } + getDeadlineInfo() { + if (this.underlyingCalls.length === 0) { + return []; + } + const deadlineInfo = []; + const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; + if (this.underlyingCalls.length > 1) { + deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); + } + if (latestCall.startTime > this.startTime) { + deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); + } + deadlineInfo.push(...latestCall.call.getDeadlineInfo()); + return deadlineInfo; + } + getCallNumber() { + return this.callNumber; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + reportStatus(statusObject) { + this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + this.startTime.toISOString()); + this.bufferTracker.freeAll(this.callNumber); + this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; + this.writeBuffer = []; + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === undefined || _a.onReceiveStatus({ + code: statusObject.code, + details: statusObject.details, + metadata: statusObject.metadata + }); + }); + } + cancelWithStatus(status, details) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata }); + for (const { call } of this.underlyingCalls) { + call.cancelWithStatus(status, details); + } + } + getPeer() { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getPeer(); + } else { + return "unknown"; + } + } + getBufferEntry(messageIndex) { + var _a; + return (_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== undefined ? _a : { + entryType: "FREED", + allocated: false + }; + } + getNextBufferIndex() { + return this.writeBufferOffset + this.writeBuffer.length; + } + clearSentMessages() { + if (this.state !== "COMMITTED") { + return; + } + let earliestNeededMessageIndex; + if (this.underlyingCalls[this.committedCallIndex].state === "COMPLETED") { + earliestNeededMessageIndex = this.getNextBufferIndex(); + } else { + earliestNeededMessageIndex = this.underlyingCalls[this.committedCallIndex].nextMessageToSend; + } + for (let messageIndex = this.writeBufferOffset;messageIndex < earliestNeededMessageIndex; messageIndex++) { + const bufferEntry = this.getBufferEntry(messageIndex); + if (bufferEntry.allocated) { + this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); + } + } + this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); + this.writeBufferOffset = earliestNeededMessageIndex; + } + commitCall(index) { + var _a, _b; + if (this.state === "COMMITTED") { + return; + } + this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index); + this.state = "COMMITTED"; + (_b = (_a = this.callConfig).onCommitted) === null || _b === undefined || _b.call(_a); + this.committedCallIndex = index; + for (let i = 0;i < this.underlyingCalls.length; i++) { + if (i === index) { + continue; + } + if (this.underlyingCalls[i].state === "COMPLETED") { + continue; + } + this.underlyingCalls[i].state = "COMPLETED"; + this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, "Discarded in favor of other hedged attempt"); + } + this.clearSentMessages(); + } + commitCallWithMostMessages() { + if (this.state === "COMMITTED") { + return; + } + let mostMessages = -1; + let callWithMostMessages = -1; + for (const [index, childCall] of this.underlyingCalls.entries()) { + if (childCall.state === "ACTIVE" && childCall.nextMessageToSend > mostMessages) { + mostMessages = childCall.nextMessageToSend; + callWithMostMessages = index; + } + } + if (callWithMostMessages === -1) { + this.state = "TRANSPARENT_ONLY"; + } else { + this.commitCall(callWithMostMessages); + } + } + isStatusCodeInList(list, code) { + return list.some((value) => { + var _a; + return value === code || value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === undefined ? undefined : _a.toLowerCase()); + }); + } + getNextRetryJitter() { + return Math.random() * (1.2 - 0.8) + 0.8; + } + getNextRetryBackoffMs() { + var _a; + const retryPolicy = (_a = this.callConfig) === null || _a === undefined ? undefined : _a.methodConfig.retryPolicy; + if (!retryPolicy) { + return 0; + } + const jitter = this.getNextRetryJitter(); + const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1000; + const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); + this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); + return nextBackoffMs; + } + maybeRetryCall(pushback, callback) { + if (this.state !== "RETRY") { + callback(false); + return; + } + if (this.attempts >= this.maxAttempts) { + callback(false); + return; + } + let retryDelayMs; + if (pushback === null) { + retryDelayMs = this.getNextRetryBackoffMs(); + } else if (pushback < 0) { + this.state = "TRANSPARENT_ONLY"; + callback(false); + return; + } else { + retryDelayMs = pushback; + this.nextRetryBackoffSec = this.initialRetryBackoffSec; + } + setTimeout(() => { + var _a, _b; + if (this.state !== "RETRY") { + callback(false); + return; + } + if ((_b = (_a = this.retryThrottler) === null || _a === undefined ? undefined : _a.canRetryCall()) !== null && _b !== undefined ? _b : true) { + callback(true); + this.attempts += 1; + this.startNewAttempt(); + } else { + this.trace("Retry attempt denied by throttling policy"); + callback(false); + } + }, retryDelayMs); + } + countActiveCalls() { + let count = 0; + for (const call of this.underlyingCalls) { + if ((call === null || call === undefined ? undefined : call.state) === "ACTIVE") { + count += 1; + } + } + return count; + } + handleProcessedStatus(status, callIndex, pushback) { + var _a, _b, _c; + switch (this.state) { + case "COMMITTED": + case "NO_RETRY": + case "TRANSPARENT_ONLY": + this.commitCall(callIndex); + this.reportStatus(status); + break; + case "HEDGING": + if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== undefined ? _a : [], status.code)) { + (_b = this.retryThrottler) === null || _b === undefined || _b.addCallFailed(); + let delayMs; + if (pushback === null) { + delayMs = 0; + } else if (pushback < 0) { + this.state = "TRANSPARENT_ONLY"; + this.commitCall(callIndex); + this.reportStatus(status); + return; + } else { + delayMs = pushback; + } + setTimeout(() => { + this.maybeStartHedgingAttempt(); + if (this.countActiveCalls() === 0) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }, delayMs); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + case "RETRY": + if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { + (_c = this.retryThrottler) === null || _c === undefined || _c.addCallFailed(); + this.maybeRetryCall(pushback, (retried) => { + if (!retried) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + } + } + getPushback(metadata) { + const mdValue = metadata.get("grpc-retry-pushback-ms"); + if (mdValue.length === 0) { + return null; + } + try { + return parseInt(mdValue[0]); + } catch (e) { + return -1; + } + } + handleChildStatus(status, callIndex) { + var _a; + if (this.underlyingCalls[callIndex].state === "COMPLETED") { + return; + } + this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state); + this.underlyingCalls[callIndex].state = "COMPLETED"; + if (status.code === constants_1.Status.OK) { + (_a = this.retryThrottler) === null || _a === undefined || _a.addCallSucceeded(); + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === "NO_RETRY") { + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === "COMMITTED") { + this.reportStatus(status); + return; + } + const pushback = this.getPushback(status.metadata); + switch (status.progress) { + case "NOT_STARTED": + this.startNewAttempt(); + break; + case "REFUSED": + if (this.transparentRetryUsed) { + this.handleProcessedStatus(status, callIndex, pushback); + } else { + this.transparentRetryUsed = true; + this.startNewAttempt(); + } + break; + case "DROP": + this.commitCall(callIndex); + this.reportStatus(status); + break; + case "PROCESSED": + this.handleProcessedStatus(status, callIndex, pushback); + break; + } + } + maybeStartHedgingAttempt() { + if (this.state !== "HEDGING") { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + if (this.attempts >= this.maxAttempts) { + return; + } + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + maybeStartHedgingTimer() { + var _a, _b, _c; + if (this.hedgingTimer) { + clearTimeout(this.hedgingTimer); + } + if (this.state !== "HEDGING") { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= this.maxAttempts) { + return; + } + const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== undefined ? _a : "0s"; + const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); + this.hedgingTimer = setTimeout(() => { + this.maybeStartHedgingAttempt(); + }, hedgingDelaySec * 1000); + (_c = (_b = this.hedgingTimer).unref) === null || _c === undefined || _c.call(_b); + } + startNewAttempt() { + const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); + this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts); + const index = this.underlyingCalls.length; + this.underlyingCalls.push({ + state: "ACTIVE", + call: child, + nextMessageToSend: 0, + startTime: new Date + }); + const previousAttempts = this.attempts - 1; + const initialMetadata = this.initialMetadata.clone(); + if (previousAttempts > 0) { + initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + let receivedMetadata = false; + child.start(initialMetadata, { + onReceiveMetadata: (metadata) => { + this.trace("Received metadata from child [" + child.getCallNumber() + "]"); + this.commitCall(index); + receivedMetadata = true; + if (previousAttempts > 0) { + metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + if (this.underlyingCalls[index].state === "ACTIVE") { + this.listener.onReceiveMetadata(metadata); + } + }, + onReceiveMessage: (message) => { + this.trace("Received message from child [" + child.getCallNumber() + "]"); + this.commitCall(index); + if (this.underlyingCalls[index].state === "ACTIVE") { + this.listener.onReceiveMessage(message); + } + }, + onReceiveStatus: (status) => { + this.trace("Received status from child [" + child.getCallNumber() + "]"); + if (!receivedMetadata && previousAttempts > 0) { + status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + this.handleChildStatus(status, index); + } + }); + this.sendNextChildMessage(index); + if (this.readStarted) { + child.startRead(); + } + } + start(metadata, listener) { + this.trace("start called"); + this.listener = listener; + this.initialMetadata = metadata; + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + handleChildWriteCompleted(childIndex, messageIndex) { + var _a, _b; + (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === undefined || _b.call(_a); + this.clearSentMessages(); + const childCall = this.underlyingCalls[childIndex]; + childCall.nextMessageToSend += 1; + this.sendNextChildMessage(childIndex); + } + sendNextChildMessage(childIndex) { + const childCall = this.underlyingCalls[childIndex]; + if (childCall.state === "COMPLETED") { + return; + } + const messageIndex = childCall.nextMessageToSend; + if (this.getBufferEntry(messageIndex)) { + const bufferEntry = this.getBufferEntry(messageIndex); + switch (bufferEntry.entryType) { + case "MESSAGE": + childCall.call.sendMessageWithContext({ + callback: (error) => { + this.handleChildWriteCompleted(childIndex, messageIndex); + } + }, bufferEntry.message.message); + const nextEntry = this.getBufferEntry(messageIndex + 1); + if (nextEntry.entryType === "HALF_CLOSE") { + this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message"); + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + } + break; + case "HALF_CLOSE": + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + break; + case "FREED": + break; + } + } + } + sendMessageWithContext(context, message) { + this.trace("write() called with message of length " + message.length); + const writeObj = { + message, + flags: context.flags + }; + const messageIndex = this.getNextBufferIndex(); + const bufferEntry = { + entryType: "MESSAGE", + message: writeObj, + allocated: this.bufferTracker.allocate(message.length, this.callNumber) + }; + this.writeBuffer.push(bufferEntry); + if (bufferEntry.allocated) { + process.nextTick(() => { + var _a; + (_a = context.callback) === null || _a === undefined || _a.call(context); + }); + for (const [callIndex, call] of this.underlyingCalls.entries()) { + if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: (error) => { + this.handleChildWriteCompleted(callIndex, messageIndex); + } + }, message); + } + } + } else { + this.commitCallWithMostMessages(); + if (this.committedCallIndex === null) { + return; + } + const call = this.underlyingCalls[this.committedCallIndex]; + bufferEntry.callback = context.callback; + if (call.state === "ACTIVE" && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: (error) => { + this.handleChildWriteCompleted(this.committedCallIndex, messageIndex); + } + }, message); + } + } + } + startRead() { + this.trace("startRead called"); + this.readStarted = true; + for (const underlyingCall of this.underlyingCalls) { + if ((underlyingCall === null || underlyingCall === undefined ? undefined : underlyingCall.state) === "ACTIVE") { + underlyingCall.call.startRead(); + } + } + } + halfClose() { + this.trace("halfClose called"); + const halfCloseIndex = this.getNextBufferIndex(); + this.writeBuffer.push({ + entryType: "HALF_CLOSE", + allocated: false + }); + for (const call of this.underlyingCalls) { + if ((call === null || call === undefined ? undefined : call.state) === "ACTIVE") { + if (call.nextMessageToSend === halfCloseIndex || call.nextMessageToSend === halfCloseIndex - 1) { + this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent"); + call.nextMessageToSend += 1; + call.call.halfClose(); + } + } + } + } + setCredentials(newCredentials) { + throw new Error("Method not implemented."); + } + getMethod() { + return this.methodName; + } + getHost() { + return this.host; + } + getAuthContext() { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getAuthContext(); + } else { + return null; + } + } + } + exports.RetryingCall = RetryingCall; +}); + +// node_modules/@grpc/grpc-js/build/src/subchannel-interface.js +var require_subchannel_interface = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaseSubchannelWrapper = undefined; + + class BaseSubchannelWrapper { + constructor(child) { + this.child = child; + this.healthy = true; + this.healthListeners = new Set; + this.refcount = 0; + this.dataWatchers = new Set; + child.addHealthStateWatcher((childHealthy) => { + if (this.healthy) { + this.updateHealthListeners(); + } + }); + } + updateHealthListeners() { + for (const listener of this.healthListeners) { + listener(this.isHealthy()); + } + } + getConnectivityState() { + return this.child.getConnectivityState(); + } + addConnectivityStateListener(listener) { + this.child.addConnectivityStateListener(listener); + } + removeConnectivityStateListener(listener) { + this.child.removeConnectivityStateListener(listener); + } + startConnecting() { + this.child.startConnecting(); + } + getAddress() { + return this.child.getAddress(); + } + throttleKeepalive(newKeepaliveTime) { + this.child.throttleKeepalive(newKeepaliveTime); + } + ref() { + this.child.ref(); + this.refcount += 1; + } + unref() { + this.child.unref(); + this.refcount -= 1; + if (this.refcount === 0) { + this.destroy(); + } + } + destroy() { + for (const watcher of this.dataWatchers) { + watcher.destroy(); + } + } + getChannelzRef() { + return this.child.getChannelzRef(); + } + isHealthy() { + return this.healthy && this.child.isHealthy(); + } + addHealthStateWatcher(listener) { + this.healthListeners.add(listener); + } + removeHealthStateWatcher(listener) { + this.healthListeners.delete(listener); + } + addDataWatcher(dataWatcher) { + dataWatcher.setSubchannel(this.getRealSubchannel()); + this.dataWatchers.add(dataWatcher); + } + setHealthy(healthy) { + if (healthy !== this.healthy) { + this.healthy = healthy; + if (this.child.isHealthy()) { + this.updateHealthListeners(); + } + } + } + getRealSubchannel() { + return this.child.getRealSubchannel(); + } + realSubchannelEquals(other) { + return this.getRealSubchannel() === other.getRealSubchannel(); + } + getCallCredentials() { + return this.child.getCallCredentials(); + } + getChannel() { + return this.child.getChannel(); + } + } + exports.BaseSubchannelWrapper = BaseSubchannelWrapper; +}); + +// node_modules/@grpc/grpc-js/build/src/internal-channel.js +var require_internal_channel = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InternalChannel = exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = undefined; + var channel_credentials_1 = require_channel_credentials(); + var resolving_load_balancer_1 = require_resolving_load_balancer(); + var subchannel_pool_1 = require_subchannel_pool(); + var picker_1 = require_picker(); + var metadata_1 = require_metadata(); + var constants_1 = require_constants2(); + var filter_stack_1 = require_filter_stack(); + var compression_filter_1 = require_compression_filter(); + var resolver_1 = require_resolver(); + var logging_1 = require_logging(); + var http_proxy_1 = require_http_proxy(); + var uri_parser_1 = require_uri_parser(); + var connectivity_state_1 = require_connectivity_state(); + var channelz_1 = require_channelz(); + var load_balancing_call_1 = require_load_balancing_call(); + var deadline_1 = require_deadline(); + var resolving_call_1 = require_resolving_call(); + var call_number_1 = require_call_number(); + var control_plane_status_1 = require_control_plane_status(); + var retrying_call_1 = require_retrying_call(); + var subchannel_interface_1 = require_subchannel_interface(); + var MAX_TIMEOUT_TIME = 2147483647; + var MIN_IDLE_TIMEOUT_MS = 1000; + var DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; + var RETRY_THROTTLER_MAP = new Map; + var DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; + var DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; + + class ChannelSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, channel) { + super(childSubchannel); + this.channel = channel; + this.refCount = 0; + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { + channel.throttleKeepalive(keepaliveTime); + }; + } + ref() { + if (this.refCount === 0) { + this.child.addConnectivityStateListener(this.subchannelStateListener); + this.channel.addWrappedSubchannel(this); + } + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + this.child.removeConnectivityStateListener(this.subchannelStateListener); + this.channel.removeWrappedSubchannel(this); + } + } + } + + class ShutdownPicker { + pick(pickArgs) { + return { + pickResultType: picker_1.PickResultType.DROP, + status: { + code: constants_1.Status.UNAVAILABLE, + details: "Channel closed before call started", + metadata: new metadata_1.Metadata + }, + subchannel: null, + onCallStarted: null, + onCallEnded: null + }; + } + } + exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = "grpc.internal.no_subchannel"; + + class ChannelzInfoTracker { + constructor(target) { + this.target = target; + this.trace = new channelz_1.ChannelzTrace; + this.callTracker = new channelz_1.ChannelzCallTracker; + this.childrenTracker = new channelz_1.ChannelzChildrenTracker; + this.state = connectivity_state_1.ConnectivityState.IDLE; + } + getChannelzInfoCallback() { + return () => { + return { + target: this.target, + state: this.state, + trace: this.trace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists() + }; + }; + } + } + + class InternalChannel { + constructor(target, credentials, options) { + var _a, _b, _c, _d, _e, _f; + this.credentials = credentials; + this.options = options; + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + this.currentPicker = new picker_1.UnavailablePicker; + this.configSelectionQueue = []; + this.pickQueue = []; + this.connectivityStateWatchers = []; + this.callRefTimer = null; + this.configSelector = null; + this.currentResolutionError = null; + this.wrappedSubchannels = new Set; + this.callCount = 0; + this.idleTimer = null; + this.channelzEnabled = true; + this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + if (typeof target !== "string") { + throw new TypeError("Channel target must be a string"); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError("Channel credentials must be a ChannelCredentials object"); + } + if (options) { + if (typeof options !== "object") { + throw new TypeError("Channel options must be an object"); + } + } + this.channelzInfoTracker = new ChannelzInfoTracker(target); + const originalTargetUri = (0, uri_parser_1.parseUri)(target); + if (originalTargetUri === null) { + throw new Error(`Could not parse target name "${target}"`); + } + const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); + if (defaultSchemeMapResult === null) { + throw new Error(`Could not find a default scheme for target name "${target}"`); + } + if (this.options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + } + this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Channel created"); + } + if (this.options["grpc.default_authority"]) { + this.defaultAuthority = this.options["grpc.default_authority"]; + } else { + this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); + } + const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); + this.target = proxyMapResult.target; + this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); + this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options["grpc.use_local_subchannel_pool"]) !== null && _a !== undefined ? _a : 0) === 0); + this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options["grpc.retry_buffer_size"]) !== null && _b !== undefined ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options["grpc.per_rpc_retry_buffer_size"]) !== null && _c !== undefined ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); + this.keepaliveTime = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== undefined ? _d : -1; + this.idleTimeoutMs = Math.max((_e = this.options["grpc.client_idle_timeout_ms"]) !== null && _e !== undefined ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); + const channelControlHelper = { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const finalSubchannelArgs = {}; + for (const [key, value] of Object.entries(subchannelArgs)) { + if (!key.startsWith(exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { + finalSubchannelArgs[key] = value; + } + } + const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials); + subchannel.throttleKeepalive(this.keepaliveTime); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Created subchannel or used existing subchannel", subchannel.getChannelzRef()); + } + const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); + return wrappedSubchannel; + }, + updateState: (connectivityState, picker) => { + this.currentPicker = picker; + const queueCopy = this.pickQueue.slice(); + this.pickQueue = []; + if (queueCopy.length > 0) { + this.callRefTimerUnref(); + } + for (const call of queueCopy) { + call.doPick(); + } + this.updateState(connectivityState); + }, + requestReresolution: () => { + throw new Error("Resolving load balancer should never call requestReresolution"); + }, + addChannelzChild: (child) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.refChild(child); + } + }, + removeChannelzChild: (child) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.childrenTracker.unrefChild(child); + } + } + }; + this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => { + var _a2; + if (serviceConfig.retryThrottling) { + RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); + } else { + RETRY_THROTTLER_MAP.delete(this.getTarget()); + } + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Address resolution succeeded"); + } + (_a2 = this.configSelector) === null || _a2 === undefined || _a2.unref(); + this.configSelector = configSelector; + this.currentResolutionError = null; + process.nextTick(() => { + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.getConfig(); + } + }); + }, (status) => { + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_WARNING", "Address resolution failed with code " + status.code + ' and details "' + status.details + '"'); + } + if (this.configSelectionQueue.length > 0) { + this.trace("Name resolution failed with calls queued for config selection"); + } + if (this.configSelector === null) { + this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); + } + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.reportResolverError(status); + } + }); + this.filterStackFactory = new filter_stack_1.FilterStackFactory([ + new compression_filter_1.CompressionFilterFactory(this, this.options) + ]); + this.trace("Channel constructed with options " + JSON.stringify(options, undefined, 2)); + const error = new Error; + if ((0, logging_1.isTracerEnabled)("channel_stacktrace")) { + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") " + `Channel constructed +` + ((_f = error.stack) === null || _f === undefined ? undefined : _f.substring(error.stack.indexOf(` +`) + 1))); + } + this.lastActivityTimestamp = new Date; + } + trace(text, verbosityOverride) { + (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== undefined ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text); + } + callRefTimerRef() { + var _a, _b, _c, _d; + if (!this.callRefTimer) { + this.callRefTimer = setInterval(() => {}, MAX_TIMEOUT_TIME); + } + if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === undefined ? undefined : _b.call(_a))) { + this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + (_d = (_c = this.callRefTimer).ref) === null || _d === undefined || _d.call(_c); + } + } + callRefTimerUnref() { + var _a, _b, _c; + if (!((_a = this.callRefTimer) === null || _a === undefined ? undefined : _a.hasRef) || this.callRefTimer.hasRef()) { + this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + (_c = (_b = this.callRefTimer) === null || _b === undefined ? undefined : _b.unref) === null || _c === undefined || _c.call(_b); + } + } + removeConnectivityStateWatcher(watcherObject) { + const watcherIndex = this.connectivityStateWatchers.findIndex((value) => value === watcherObject); + if (watcherIndex >= 0) { + this.connectivityStateWatchers.splice(watcherIndex, 1); + } + } + updateState(newState) { + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "connectivity_state", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + if (this.channelzEnabled) { + this.channelzInfoTracker.trace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); + } + this.connectivityState = newState; + this.channelzInfoTracker.state = newState; + const watchersCopy = this.connectivityStateWatchers.slice(); + for (const watcherObject of watchersCopy) { + if (newState !== watcherObject.currentState) { + if (watcherObject.timer) { + clearTimeout(watcherObject.timer); + } + this.removeConnectivityStateWatcher(watcherObject); + watcherObject.callback(); + } + } + if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.currentResolutionError = null; + } + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + for (const wrappedSubchannel of this.wrappedSubchannels) { + wrappedSubchannel.throttleKeepalive(newKeepaliveTime); + } + } + } + addWrappedSubchannel(wrappedSubchannel) { + this.wrappedSubchannels.add(wrappedSubchannel); + } + removeWrappedSubchannel(wrappedSubchannel) { + this.wrappedSubchannels.delete(wrappedSubchannel); + } + doPick(metadata, extraPickInfo) { + return this.currentPicker.pick({ + metadata, + extraPickInfo + }); + } + queueCallForPick(call) { + this.pickQueue.push(call); + this.callRefTimerRef(); + } + getConfig(method, metadata) { + if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { + this.resolvingLoadBalancer.exitIdle(); + } + if (this.configSelector) { + return { + type: "SUCCESS", + config: this.configSelector.invoke(method, metadata, this.randomChannelId) + }; + } else { + if (this.currentResolutionError) { + return { + type: "ERROR", + error: this.currentResolutionError + }; + } else { + return { + type: "NONE" + }; + } + } + } + queueCallForConfig(call) { + this.configSelectionQueue.push(call); + this.callRefTimerRef(); + } + enterIdle() { + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.IDLE); + this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + this.callRefTimer = null; + } + } + startIdleTimeout(timeoutMs) { + var _a, _b; + this.idleTimer = setTimeout(() => { + if (this.callCount > 0) { + this.startIdleTimeout(this.idleTimeoutMs); + return; + } + const now = new Date; + const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); + if (timeSinceLastActivity >= this.idleTimeoutMs) { + this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity"); + this.enterIdle(); + } else { + this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); + } + }, timeoutMs); + (_b = (_a = this.idleTimer).unref) === null || _b === undefined || _b.call(_a); + } + maybeStartIdleTimer() { + if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && !this.idleTimer) { + this.startIdleTimeout(this.idleTimeoutMs); + } + } + onCallStart() { + if (this.channelzEnabled) { + this.channelzInfoTracker.callTracker.addCallStarted(); + } + this.callCount += 1; + } + onCallEnd(status) { + if (this.channelzEnabled) { + if (status.code === constants_1.Status.OK) { + this.channelzInfoTracker.callTracker.addCallSucceeded(); + } else { + this.channelzInfoTracker.callTracker.addCallFailed(); + } + } + this.callCount -= 1; + this.lastActivityTimestamp = new Date; + this.maybeStartIdleTimer(); + } + createLoadBalancingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace("createLoadBalancingCall [" + callNumber + '] method="' + method + '"'); + return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); + } + createRetryingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace("createRetryingCall [" + callNumber + '] method="' + method + '"'); + return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); + } + createResolvingCall(method, deadline, host, parentCall, propagateFlags) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline)); + const finalOptions = { + deadline, + flags: propagateFlags !== null && propagateFlags !== undefined ? propagateFlags : constants_1.Propagate.DEFAULTS, + host: host !== null && host !== undefined ? host : this.defaultAuthority, + parentCall + }; + const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber); + this.onCallStart(); + call.addStatusWatcher((status) => { + this.onCallEnd(status); + }); + return call; + } + close() { + var _a; + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); + this.currentPicker = new ShutdownPicker; + for (const call of this.configSelectionQueue) { + call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); + } + this.configSelectionQueue = []; + for (const call of this.pickQueue) { + call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); + } + this.pickQueue = []; + if (this.callRefTimer) { + clearInterval(this.callRefTimer); + } + if (this.idleTimer) { + clearTimeout(this.idleTimer); + } + if (this.channelzEnabled) { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + this.subchannelPool.unrefUnusedSubchannels(); + (_a = this.configSelector) === null || _a === undefined || _a.unref(); + this.configSelector = null; + } + getTarget() { + return (0, uri_parser_1.uriToString)(this.target); + } + getConnectivityState(tryToConnect) { + const connectivityState = this.connectivityState; + if (tryToConnect) { + this.resolvingLoadBalancer.exitIdle(); + this.lastActivityTimestamp = new Date; + this.maybeStartIdleTimer(); + } + return connectivityState; + } + watchConnectivityState(currentState, deadline, callback) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error("Channel has been shut down"); + } + let timer = null; + if (deadline !== Infinity) { + const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); + const now = new Date; + if (deadline === -Infinity || deadlineDate <= now) { + process.nextTick(callback, new Error("Deadline passed without connectivity state change")); + return; + } + timer = setTimeout(() => { + this.removeConnectivityStateWatcher(watcherObject); + callback(new Error("Deadline passed without connectivity state change")); + }, deadlineDate.getTime() - now.getTime()); + } + const watcherObject = { + currentState, + callback, + timer + }; + this.connectivityStateWatchers.push(watcherObject); + } + getChannelzRef() { + return this.channelzRef; + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== "string") { + throw new TypeError("Channel#createCall: method must be a string"); + } + if (!(typeof deadline === "number" || deadline instanceof Date)) { + throw new TypeError("Channel#createCall: deadline must be a number or Date"); + } + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error("Channel has been shut down"); + } + return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); + } + getOptions() { + return this.options; + } + } + exports.InternalChannel = InternalChannel; +}); + +// node_modules/@grpc/grpc-js/build/src/channel.js +var require_channel = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChannelImplementation = undefined; + var channel_credentials_1 = require_channel_credentials(); + var internal_channel_1 = require_internal_channel(); + + class ChannelImplementation { + constructor(target, credentials, options) { + if (typeof target !== "string") { + throw new TypeError("Channel target must be a string"); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError("Channel credentials must be a ChannelCredentials object"); + } + if (options) { + if (typeof options !== "object") { + throw new TypeError("Channel options must be an object"); + } + } + this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); + } + close() { + this.internalChannel.close(); + } + getTarget() { + return this.internalChannel.getTarget(); + } + getConnectivityState(tryToConnect) { + return this.internalChannel.getConnectivityState(tryToConnect); + } + watchConnectivityState(currentState, deadline, callback) { + this.internalChannel.watchConnectivityState(currentState, deadline, callback); + } + getChannelzRef() { + return this.internalChannel.getChannelzRef(); + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== "string") { + throw new TypeError("Channel#createCall: method must be a string"); + } + if (!(typeof deadline === "number" || deadline instanceof Date)) { + throw new TypeError("Channel#createCall: deadline must be a number or Date"); + } + return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); + } + } + exports.ChannelImplementation = ChannelImplementation; +}); + +// node_modules/@grpc/grpc-js/build/src/server-call.js +var require_server_call = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = undefined; + exports.serverErrorToStatus = serverErrorToStatus; + var events_1 = __require("events"); + var stream_1 = __require("stream"); + var constants_1 = require_constants2(); + var metadata_1 = require_metadata(); + function serverErrorToStatus(error, overrideTrailers) { + var _a; + const status = { + code: constants_1.Status.UNKNOWN, + details: "message" in error ? error.message : "Unknown Error", + metadata: (_a = overrideTrailers !== null && overrideTrailers !== undefined ? overrideTrailers : error.metadata) !== null && _a !== undefined ? _a : null + }; + if ("code" in error && typeof error.code === "number" && Number.isInteger(error.code)) { + status.code = error.code; + if ("details" in error && typeof error.details === "string") { + status.details = error.details; + } + } + return status; + } + + class ServerUnaryCallImpl extends events_1.EventEmitter { + constructor(path, call, metadata, request2) { + super(); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request2; + this.cancelled = false; + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + } + exports.ServerUnaryCallImpl = ServerUnaryCallImpl; + + class ServerReadableStreamImpl extends stream_1.Readable { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.cancelled = false; + } + _read(size) { + this.call.startRead(); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + } + exports.ServerReadableStreamImpl = ServerReadableStreamImpl; + + class ServerWritableStreamImpl extends stream_1.Writable { + constructor(path, call, metadata, request2) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request2; + this.pendingStatus = { + code: constants_1.Status.OK, + details: "OK" + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata; + this.on("error", (err) => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + _write(chunk, encoding, callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== undefined ? _a : this.trailingMetadata })); + } + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } + } + exports.ServerWritableStreamImpl = ServerWritableStreamImpl; + + class ServerDuplexStreamImpl extends stream_1.Duplex { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.pendingStatus = { + code: constants_1.Status.OK, + details: "OK" + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata; + this.on("error", (err) => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + getHost() { + return this.call.getHost(); + } + getAuthContext() { + return this.call.getAuthContext(); + } + getMetricsRecorder() { + return this.call.getMetricsRecorder(); + } + _read(size) { + this.call.startRead(); + } + _write(chunk, encoding, callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== undefined ? _a : this.trailingMetadata })); + } + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } + } + exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl; +}); + +// node_modules/@grpc/grpc-js/build/src/server-credentials.js +var require_server_credentials = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ServerCredentials = undefined; + exports.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials; + exports.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors; + var tls_helpers_1 = require_tls_helpers(); + + class ServerCredentials { + constructor(serverConstructorOptions, contextOptions) { + this.serverConstructorOptions = serverConstructorOptions; + this.watchers = new Set; + this.latestContextOptions = null; + this.latestContextOptions = contextOptions !== null && contextOptions !== undefined ? contextOptions : null; + } + _addWatcher(watcher) { + this.watchers.add(watcher); + } + _removeWatcher(watcher) { + this.watchers.delete(watcher); + } + getWatcherCount() { + return this.watchers.size; + } + updateSecureContextOptions(options) { + this.latestContextOptions = options; + for (const watcher of this.watchers) { + watcher(this.latestContextOptions); + } + } + _isSecure() { + return this.serverConstructorOptions !== null; + } + _getSecureContextOptions() { + return this.latestContextOptions; + } + _getConstructorOptions() { + return this.serverConstructorOptions; + } + _getInterceptors() { + return []; + } + static createInsecure() { + return new InsecureServerCredentials; + } + static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { + var _a; + if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { + throw new TypeError("rootCerts must be null or a Buffer"); + } + if (!Array.isArray(keyCertPairs)) { + throw new TypeError("keyCertPairs must be an array"); + } + if (typeof checkClientCertificate !== "boolean") { + throw new TypeError("checkClientCertificate must be a boolean"); + } + const cert = []; + const key = []; + for (let i = 0;i < keyCertPairs.length; i++) { + const pair = keyCertPairs[i]; + if (pair === null || typeof pair !== "object") { + throw new TypeError(`keyCertPair[${i}] must be an object`); + } + if (!Buffer.isBuffer(pair.private_key)) { + throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); + } + if (!Buffer.isBuffer(pair.cert_chain)) { + throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); + } + cert.push(pair.cert_chain); + key.push(pair.private_key); + } + return new SecureServerCredentials({ + requestCert: checkClientCertificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }, { + ca: (_a = rootCerts !== null && rootCerts !== undefined ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== undefined ? _a : undefined, + cert, + key + }); + } + } + exports.ServerCredentials = ServerCredentials; + + class InsecureServerCredentials extends ServerCredentials { + constructor() { + super(null); + } + _getSettings() { + return null; + } + _equals(other) { + return other instanceof InsecureServerCredentials; + } + } + + class SecureServerCredentials extends ServerCredentials { + constructor(constructorOptions, contextOptions) { + super(constructorOptions, contextOptions); + this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions); + } + _equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof SecureServerCredentials)) { + return false; + } + if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { + if (!this.options.ca.equals(other.options.ca)) { + return false; + } + } else { + if (this.options.ca !== other.options.ca) { + return false; + } + } + if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { + if (this.options.cert.length !== other.options.cert.length) { + return false; + } + for (let i = 0;i < this.options.cert.length; i++) { + const thisCert = this.options.cert[i]; + const otherCert = other.options.cert[i]; + if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { + if (!thisCert.equals(otherCert)) { + return false; + } + } else { + if (thisCert !== otherCert) { + return false; + } + } + } + } else { + if (this.options.cert !== other.options.cert) { + return false; + } + } + if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { + if (this.options.key.length !== other.options.key.length) { + return false; + } + for (let i = 0;i < this.options.key.length; i++) { + const thisKey = this.options.key[i]; + const otherKey = other.options.key[i]; + if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { + if (!thisKey.equals(otherKey)) { + return false; + } + } else { + if (thisKey !== otherKey) { + return false; + } + } + } + } else { + if (this.options.key !== other.options.key) { + return false; + } + } + if (this.options.requestCert !== other.options.requestCert) { + return false; + } + return true; + } + } + + class CertificateProviderServerCredentials extends ServerCredentials { + constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) { + super({ + requestCert: caCertificateProvider !== null, + rejectUnauthorized: requireClientCertificate, + ciphers: tls_helpers_1.CIPHER_SUITES + }); + this.identityCertificateProvider = identityCertificateProvider; + this.caCertificateProvider = caCertificateProvider; + this.requireClientCertificate = requireClientCertificate; + this.latestCaUpdate = null; + this.latestIdentityUpdate = null; + this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); + this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); + } + _addWatcher(watcher) { + var _a; + if (this.getWatcherCount() === 0) { + (_a = this.caCertificateProvider) === null || _a === undefined || _a.addCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); + } + super._addWatcher(watcher); + } + _removeWatcher(watcher) { + var _a; + super._removeWatcher(watcher); + if (this.getWatcherCount() === 0) { + (_a = this.caCertificateProvider) === null || _a === undefined || _a.removeCaCertificateListener(this.caCertificateUpdateListener); + this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); + } + } + _equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof CertificateProviderServerCredentials)) { + return false; + } + return this.caCertificateProvider === other.caCertificateProvider && this.identityCertificateProvider === other.identityCertificateProvider && this.requireClientCertificate === other.requireClientCertificate; + } + calculateSecureContextOptions() { + var _a; + if (this.latestIdentityUpdate === null) { + return null; + } + if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { + return null; + } + return { + ca: (_a = this.latestCaUpdate) === null || _a === undefined ? undefined : _a.caCertificate, + cert: [this.latestIdentityUpdate.certificate], + key: [this.latestIdentityUpdate.privateKey] + }; + } + finalizeUpdate() { + const secureContextOptions = this.calculateSecureContextOptions(); + this.updateSecureContextOptions(secureContextOptions); + } + handleCaCertificateUpdate(update) { + this.latestCaUpdate = update; + this.finalizeUpdate(); + } + handleIdentityCertitificateUpdate(update) { + this.latestIdentityUpdate = update; + this.finalizeUpdate(); + } + } + function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) { + return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate); + } + + class InterceptorServerCredentials extends ServerCredentials { + constructor(childCredentials, interceptors) { + super({}); + this.childCredentials = childCredentials; + this.interceptors = interceptors; + } + _isSecure() { + return this.childCredentials._isSecure(); + } + _equals(other) { + if (!(other instanceof InterceptorServerCredentials)) { + return false; + } + if (!this.childCredentials._equals(other.childCredentials)) { + return false; + } + if (this.interceptors.length !== other.interceptors.length) { + return false; + } + for (let i = 0;i < this.interceptors.length; i++) { + if (this.interceptors[i] !== other.interceptors[i]) { + return false; + } + } + return true; + } + _getInterceptors() { + return this.interceptors; + } + _addWatcher(watcher) { + this.childCredentials._addWatcher(watcher); + } + _removeWatcher(watcher) { + this.childCredentials._removeWatcher(watcher); + } + _getConstructorOptions() { + return this.childCredentials._getConstructorOptions(); + } + _getSecureContextOptions() { + return this.childCredentials._getSecureContextOptions(); + } + } + function createServerCredentialsWithInterceptors(credentials, interceptors) { + return new InterceptorServerCredentials(credentials, interceptors); + } +}); + +// node_modules/@grpc/grpc-js/build/src/duration.js +var require_duration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.durationMessageToDuration = durationMessageToDuration; + exports.msToDuration = msToDuration; + exports.durationToMs = durationToMs; + exports.isDuration = isDuration; + exports.isDurationMessage = isDurationMessage; + exports.parseDuration = parseDuration; + exports.durationToString = durationToString; + function durationMessageToDuration(message) { + return { + seconds: Number.parseInt(message.seconds), + nanos: message.nanos + }; + } + function msToDuration(millis) { + return { + seconds: millis / 1000 | 0, + nanos: millis % 1000 * 1e6 | 0 + }; + } + function durationToMs(duration) { + return duration.seconds * 1000 + duration.nanos / 1e6 | 0; + } + function isDuration(value) { + return typeof value.seconds === "number" && typeof value.nanos === "number"; + } + function isDurationMessage(value) { + return typeof value.seconds === "string" && typeof value.nanos === "number"; + } + var durationRegex = /^(\d+)(?:\.(\d+))?s$/; + function parseDuration(value) { + const match = value.match(durationRegex); + if (!match) { + return null; + } + return { + seconds: Number.parseInt(match[1], 10), + nanos: match[2] ? Number.parseInt(match[2].padEnd(9, "0"), 10) : 0 + }; + } + function durationToString(duration) { + if (duration.nanos === 0) { + return `${duration.seconds}s`; + } + let scaleFactor; + if (duration.nanos % 1e6 === 0) { + scaleFactor = 1e6; + } else if (duration.nanos % 1000 === 0) { + scaleFactor = 1000; + } else { + scaleFactor = 1; + } + return `${duration.seconds}.${duration.nanos / scaleFactor}s`; + } +}); + +// node_modules/@grpc/grpc-js/build/src/orca.js +var require_orca = __commonJS((exports) => { + var __dirname = "/src/node_modules/@grpc/grpc-js/build/src"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OrcaOobMetricsSubchannelWrapper = exports.GRPC_METRICS_HEADER = exports.ServerMetricRecorder = exports.PerRequestMetricRecorder = undefined; + exports.createOrcaClient = createOrcaClient; + exports.createMetricsReader = createMetricsReader; + var make_client_1 = require_make_client(); + var duration_1 = require_duration(); + var channel_credentials_1 = require_channel_credentials(); + var subchannel_interface_1 = require_subchannel_interface(); + var constants_1 = require_constants2(); + var backoff_timeout_1 = require_backoff_timeout(); + var connectivity_state_1 = require_connectivity_state(); + var loadedOrcaProto = null; + function loadOrcaProto() { + if (loadedOrcaProto) { + return loadedOrcaProto; + } + const loaderLoadSync = require_src18().loadSync; + const loadedProto = loaderLoadSync("xds/service/orca/v3/orca.proto", { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [ + `${__dirname}/../../proto/xds`, + `${__dirname}/../../proto/protoc-gen-validate` + ] + }); + return (0, make_client_1.loadPackageDefinition)(loadedProto); + } + + class PerRequestMetricRecorder { + constructor() { + this.message = {}; + } + recordRequestCostMetric(name, value) { + if (!this.message.request_cost) { + this.message.request_cost = {}; + } + this.message.request_cost[name] = value; + } + recordUtilizationMetric(name, value) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + recordNamedMetric(name, value) { + if (!this.message.named_metrics) { + this.message.named_metrics = {}; + } + this.message.named_metrics[name] = value; + } + recordCPUUtilizationMetric(value) { + this.message.cpu_utilization = value; + } + recordMemoryUtilizationMetric(value) { + this.message.mem_utilization = value; + } + recordApplicationUtilizationMetric(value) { + this.message.application_utilization = value; + } + recordQpsMetric(value) { + this.message.rps_fractional = value; + } + recordEpsMetric(value) { + this.message.eps = value; + } + serialize() { + const orcaProto = loadOrcaProto(); + return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); + } + } + exports.PerRequestMetricRecorder = PerRequestMetricRecorder; + var DEFAULT_REPORT_INTERVAL_MS = 30000; + + class ServerMetricRecorder { + constructor() { + this.message = {}; + this.serviceImplementation = { + StreamCoreMetrics: (call) => { + const reportInterval = call.request.report_interval ? (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : DEFAULT_REPORT_INTERVAL_MS; + const reportTimer = setInterval(() => { + call.write(this.message); + }, reportInterval); + call.on("cancelled", () => { + clearInterval(reportTimer); + }); + } + }; + } + putUtilizationMetric(name, value) { + if (!this.message.utilization) { + this.message.utilization = {}; + } + this.message.utilization[name] = value; + } + setAllUtilizationMetrics(metrics) { + this.message.utilization = Object.assign({}, metrics); + } + deleteUtilizationMetric(name) { + var _a; + (_a = this.message.utilization) === null || _a === undefined || delete _a[name]; + } + setCpuUtilizationMetric(value) { + this.message.cpu_utilization = value; + } + deleteCpuUtilizationMetric() { + delete this.message.cpu_utilization; + } + setApplicationUtilizationMetric(value) { + this.message.application_utilization = value; + } + deleteApplicationUtilizationMetric() { + delete this.message.application_utilization; + } + setQpsMetric(value) { + this.message.rps_fractional = value; + } + deleteQpsMetric() { + delete this.message.rps_fractional; + } + setEpsMetric(value) { + this.message.eps = value; + } + deleteEpsMetric() { + delete this.message.eps; + } + addToServer(server) { + const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; + server.addService(serviceDefinition, this.serviceImplementation); + } + } + exports.ServerMetricRecorder = ServerMetricRecorder; + function createOrcaClient(channel) { + const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; + return new ClientClass("unused", channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel }); + } + exports.GRPC_METRICS_HEADER = "endpoint-load-metrics-bin"; + var PARSED_LOAD_REPORT_KEY = "grpc_orca_load_report"; + function createMetricsReader(listener, previousOnCallEnded) { + return (code, details, metadata) => { + let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY); + if (parsedLoadReport) { + listener(parsedLoadReport); + } else { + const serializedLoadReport = metadata.get(exports.GRPC_METRICS_HEADER); + if (serializedLoadReport.length > 0) { + const orcaProto = loadOrcaProto(); + parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]); + listener(parsedLoadReport); + metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); + } + } + if (previousOnCallEnded) { + previousOnCallEnded(code, details, metadata); + } + }; + } + var DATA_PRODUCER_KEY = "orca_oob_metrics"; + + class OobMetricsDataWatcher { + constructor(metricsListener, intervalMs) { + this.metricsListener = metricsListener; + this.intervalMs = intervalMs; + this.dataProducer = null; + } + setSubchannel(subchannel) { + const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); + this.dataProducer = producer; + producer.addDataWatcher(this); + } + destroy() { + var _a; + (_a = this.dataProducer) === null || _a === undefined || _a.removeDataWatcher(this); + } + getInterval() { + return this.intervalMs; + } + onMetricsUpdate(metrics) { + this.metricsListener(metrics); + } + } + + class OobMetricsDataProducer { + constructor(subchannel) { + this.subchannel = subchannel; + this.dataWatchers = new Set; + this.orcaSupported = true; + this.metricsCall = null; + this.currentInterval = Infinity; + this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription()); + this.subchannelStateListener = () => this.updateMetricsSubscription(); + const channel = subchannel.getChannel(); + this.client = createOrcaClient(channel); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + addDataWatcher(dataWatcher) { + this.dataWatchers.add(dataWatcher); + this.updateMetricsSubscription(); + } + removeDataWatcher(dataWatcher) { + var _a; + this.dataWatchers.delete(dataWatcher); + if (this.dataWatchers.size === 0) { + this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); + (_a = this.metricsCall) === null || _a === undefined || _a.cancel(); + this.metricsCall = null; + this.client.close(); + this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + } else { + this.updateMetricsSubscription(); + } + } + updateMetricsSubscription() { + var _a; + if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + return; + } + const newInterval = Math.min(...Array.from(this.dataWatchers).map((watcher) => watcher.getInterval())); + if (!this.metricsCall || newInterval !== this.currentInterval) { + (_a = this.metricsCall) === null || _a === undefined || _a.cancel(); + this.currentInterval = newInterval; + const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) }); + this.metricsCall = metricsCall; + metricsCall.on("data", (report) => { + this.dataWatchers.forEach((watcher) => { + watcher.onMetricsUpdate(report); + }); + }); + metricsCall.on("error", (error) => { + this.metricsCall = null; + if (error.code === constants_1.Status.UNIMPLEMENTED) { + this.orcaSupported = false; + return; + } + if (error.code === constants_1.Status.CANCELLED) { + return; + } + this.backoffTimer.runOnce(); + }); + } + } + } + + class OrcaOobMetricsSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(child, metricsListener, intervalMs) { + super(child); + this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); + } + getWrappedSubchannel() { + return this.child; + } + } + exports.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper; + function createOobMetricsDataProducer(subchannel) { + return new OobMetricsDataProducer(subchannel); + } +}); + +// node_modules/@grpc/grpc-js/build/src/server-interceptors.js +var require_server_interceptors = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaseServerInterceptingCall = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = undefined; + exports.isInterceptingServerListener = isInterceptingServerListener; + exports.getServerInterceptingCall = getServerInterceptingCall; + var metadata_1 = require_metadata(); + var constants_1 = require_constants2(); + var http2 = __require("http2"); + var error_1 = require_error2(); + var zlib = __require("zlib"); + var stream_decoder_1 = require_stream_decoder(); + var logging = require_logging(); + var tls_1 = __require("tls"); + var orca_1 = require_orca(); + var TRACER_NAME = "server_call"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + + class ServerListenerBuilder { + constructor() { + this.metadata = undefined; + this.message = undefined; + this.halfClose = undefined; + this.cancel = undefined; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveHalfClose(onReceiveHalfClose) { + this.halfClose = onReceiveHalfClose; + return this; + } + withOnCancel(onCancel) { + this.cancel = onCancel; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveHalfClose: this.halfClose, + onCancel: this.cancel + }; + } + } + exports.ServerListenerBuilder = ServerListenerBuilder; + function isInterceptingServerListener(listener) { + return listener.onReceiveMetadata !== undefined && listener.onReceiveMetadata.length === 1; + } + + class InterceptingServerListenerImpl { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + this.cancelled = false; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.pendingMessage = null; + this.processingMessage = false; + this.hasPendingHalfClose = false; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingHalfClose() { + if (this.hasPendingHalfClose) { + this.nextListener.onReceiveHalfClose(); + this.hasPendingHalfClose = false; + } + } + onReceiveMetadata(metadata) { + if (this.cancelled) { + return; + } + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, (interceptedMetadata) => { + this.processingMetadata = false; + if (this.cancelled) { + return; + } + this.nextListener.onReceiveMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + onReceiveMessage(message) { + if (this.cancelled) { + return; + } + this.processingMessage = true; + this.listener.onReceiveMessage(message, (msg) => { + this.processingMessage = false; + if (this.cancelled) { + return; + } + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingHalfClose(); + } + }); + } + onReceiveHalfClose() { + if (this.cancelled) { + return; + } + this.listener.onReceiveHalfClose(() => { + if (this.cancelled) { + return; + } + if (this.processingMetadata || this.processingMessage) { + this.hasPendingHalfClose = true; + } else { + this.nextListener.onReceiveHalfClose(); + } + }); + } + onCancel() { + this.cancelled = true; + this.listener.onCancel(); + this.nextListener.onCancel(); + } + } + + class ResponderBuilder { + constructor() { + this.start = undefined; + this.metadata = undefined; + this.message = undefined; + this.status = undefined; + } + withStart(start) { + this.start = start; + return this; + } + withSendMetadata(sendMetadata) { + this.metadata = sendMetadata; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withSendStatus(sendStatus) { + this.status = sendStatus; + return this; + } + build() { + return { + start: this.start, + sendMetadata: this.metadata, + sendMessage: this.message, + sendStatus: this.status + }; + } + } + exports.ResponderBuilder = ResponderBuilder; + var defaultServerListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveHalfClose: (next) => { + next(); + }, + onCancel: () => {} + }; + var defaultResponder = { + start: (next) => { + next(); + }, + sendMetadata: (metadata, next) => { + next(metadata); + }, + sendMessage: (message, next) => { + next(message); + }, + sendStatus: (status, next) => { + next(status); + } + }; + + class ServerInterceptingCall { + constructor(nextCall, responder) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + this.processingMetadata = false; + this.sentMetadata = false; + this.processingMessage = false; + this.pendingMessage = null; + this.pendingMessageCallback = null; + this.pendingStatus = null; + this.responder = { + start: (_a = responder === null || responder === undefined ? undefined : responder.start) !== null && _a !== undefined ? _a : defaultResponder.start, + sendMetadata: (_b = responder === null || responder === undefined ? undefined : responder.sendMetadata) !== null && _b !== undefined ? _b : defaultResponder.sendMetadata, + sendMessage: (_c = responder === null || responder === undefined ? undefined : responder.sendMessage) !== null && _c !== undefined ? _c : defaultResponder.sendMessage, + sendStatus: (_d = responder === null || responder === undefined ? undefined : responder.sendStatus) !== null && _d !== undefined ? _d : defaultResponder.sendStatus + }; + } + processPendingMessage() { + if (this.pendingMessageCallback) { + this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); + this.pendingMessage = null; + this.pendingMessageCallback = null; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextCall.sendStatus(this.pendingStatus); + this.pendingStatus = null; + } + } + start(listener) { + this.responder.start((interceptedListener) => { + var _a, _b, _c, _d; + const fullInterceptedListener = { + onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === undefined ? undefined : interceptedListener.onReceiveMetadata) !== null && _a !== undefined ? _a : defaultServerListener.onReceiveMetadata, + onReceiveMessage: (_b = interceptedListener === null || interceptedListener === undefined ? undefined : interceptedListener.onReceiveMessage) !== null && _b !== undefined ? _b : defaultServerListener.onReceiveMessage, + onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === undefined ? undefined : interceptedListener.onReceiveHalfClose) !== null && _c !== undefined ? _c : defaultServerListener.onReceiveHalfClose, + onCancel: (_d = interceptedListener === null || interceptedListener === undefined ? undefined : interceptedListener.onCancel) !== null && _d !== undefined ? _d : defaultServerListener.onCancel + }; + const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); + this.nextCall.start(finalInterceptingListener); + }); + } + sendMetadata(metadata) { + this.processingMetadata = true; + this.sentMetadata = true; + this.responder.sendMetadata(metadata, (interceptedMetadata) => { + this.processingMetadata = false; + this.nextCall.sendMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + sendMessage(message, callback) { + this.processingMessage = true; + if (!this.sentMetadata) { + this.sendMetadata(new metadata_1.Metadata); + } + this.responder.sendMessage(message, (interceptedMessage) => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = interceptedMessage; + this.pendingMessageCallback = callback; + } else { + this.nextCall.sendMessage(interceptedMessage, callback); + } + }); + } + sendStatus(status) { + this.responder.sendStatus(status, (interceptedStatus) => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = interceptedStatus; + } else { + this.nextCall.sendStatus(interceptedStatus); + } + }); + } + startRead() { + this.nextCall.startRead(); + } + getPeer() { + return this.nextCall.getPeer(); + } + getDeadline() { + return this.nextCall.getDeadline(); + } + getHost() { + return this.nextCall.getHost(); + } + getAuthContext() { + return this.nextCall.getAuthContext(); + } + getConnectionInfo() { + return this.nextCall.getConnectionInfo(); + } + getMetricsRecorder() { + return this.nextCall.getMetricsRecorder(); + } + } + exports.ServerInterceptingCall = ServerInterceptingCall; + var GRPC_ACCEPT_ENCODING_HEADER = "grpc-accept-encoding"; + var GRPC_ENCODING_HEADER = "grpc-encoding"; + var GRPC_MESSAGE_HEADER = "grpc-message"; + var GRPC_STATUS_HEADER = "grpc-status"; + var GRPC_TIMEOUT_HEADER = "grpc-timeout"; + var DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; + var deadlineUnitsToMs = { + H: 3600000, + M: 60000, + S: 1000, + m: 1, + u: 0.001, + n: 0.000001 + }; + var defaultCompressionHeaders = { + [GRPC_ACCEPT_ENCODING_HEADER]: "identity,deflate,gzip", + [GRPC_ENCODING_HEADER]: "identity" + }; + var defaultResponseHeaders = { + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" + }; + var defaultResponseOptions = { + waitForTrailers: true + }; + + class BaseServerInterceptingCall { + constructor(stream, headers, callEventTracker, handler, options) { + var _a, _b; + this.stream = stream; + this.callEventTracker = callEventTracker; + this.handler = handler; + this.listener = null; + this.deadlineTimer = null; + this.deadline = Infinity; + this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.cancelled = false; + this.metadataSent = false; + this.wantTrailers = false; + this.cancelNotified = false; + this.incomingEncoding = "identity"; + this.readQueue = []; + this.isReadPending = false; + this.receivedHalfClose = false; + this.streamEnded = false; + this.metricsRecorder = new orca_1.PerRequestMetricRecorder; + this.stream.once("close", () => { + var _a2; + trace("Request to method " + ((_a2 = this.handler) === null || _a2 === undefined ? undefined : _a2.path) + " stream closed with rstCode " + this.stream.rstCode); + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(false); + this.callEventTracker.onCallEnd({ + code: constants_1.Status.CANCELLED, + details: "Stream closed before sending status", + metadata: null + }); + } + this.notifyOnCancel(); + }); + this.stream.on("data", (data) => { + this.handleDataFrame(data); + }); + this.stream.pause(); + this.stream.on("end", () => { + this.handleEndEvent(); + }); + if ("grpc.max_send_message_length" in options) { + this.maxSendMessageSize = options["grpc.max_send_message_length"]; + } + if ("grpc.max_receive_message_length" in options) { + this.maxReceiveMessageSize = options["grpc.max_receive_message_length"]; + } + this.host = (_a = headers[":authority"]) !== null && _a !== undefined ? _a : headers.host; + this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize); + const metadata = metadata_1.Metadata.fromHttp2Headers(headers); + if (logging.isTracerEnabled(TRACER_NAME)) { + trace("Request to " + this.handler.path + " received headers " + JSON.stringify(metadata.toJSON())); + } + const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); + if (timeoutHeader.length > 0) { + this.handleTimeoutHeader(timeoutHeader[0]); + } + const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); + if (encodingHeader.length > 0) { + this.incomingEncoding = encodingHeader[0]; + } + metadata.remove(GRPC_TIMEOUT_HEADER); + metadata.remove(GRPC_ENCODING_HEADER); + metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); + metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); + metadata.remove(http2.constants.HTTP2_HEADER_TE); + metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); + this.metadata = metadata; + const socket = (_b = stream.session) === null || _b === undefined ? undefined : _b.socket; + this.connectionInfo = { + localAddress: socket === null || socket === undefined ? undefined : socket.localAddress, + localPort: socket === null || socket === undefined ? undefined : socket.localPort, + remoteAddress: socket === null || socket === undefined ? undefined : socket.remoteAddress, + remotePort: socket === null || socket === undefined ? undefined : socket.remotePort + }; + this.shouldSendMetrics = !!options["grpc.server_call_metric_recording"]; + } + handleTimeoutHeader(timeoutHeader) { + const match = timeoutHeader.toString().match(DEADLINE_REGEX); + if (match === null) { + const status = { + code: constants_1.Status.INTERNAL, + details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, + metadata: null + }; + process.nextTick(() => { + this.sendStatus(status); + }); + return; + } + const timeout = +match[1] * deadlineUnitsToMs[match[2]] | 0; + const now = new Date; + this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadlineTimer = setTimeout(() => { + const status = { + code: constants_1.Status.DEADLINE_EXCEEDED, + details: "Deadline exceeded", + metadata: null + }; + this.sendStatus(status); + }, timeout); + } + checkCancelled() { + if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { + this.notifyOnCancel(); + this.cancelled = true; + } + return this.cancelled; + } + notifyOnCancel() { + if (this.cancelNotified) { + return; + } + this.cancelNotified = true; + this.cancelled = true; + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === undefined || _a.onCancel(); + }); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + } + this.stream.resume(); + } + maybeSendMetadata() { + if (!this.metadataSent) { + this.sendMetadata(new metadata_1.Metadata); + } + } + serializeMessage(value) { + const messageBuffer = this.handler.serialize(value); + const byteLength = messageBuffer.byteLength; + const output = Buffer.allocUnsafe(byteLength + 5); + output.writeUInt8(0, 0); + output.writeUInt32BE(byteLength, 1); + messageBuffer.copy(output, 5); + return output; + } + decompressMessage(message, encoding) { + const messageContents = message.subarray(5); + if (encoding === "identity") { + return messageContents; + } else if (encoding === "deflate" || encoding === "gzip") { + let decompresser; + if (encoding === "deflate") { + decompresser = zlib.createInflate(); + } else { + decompresser = zlib.createGunzip(); + } + return new Promise((resolve, reject) => { + let totalLength = 0; + const messageParts = []; + decompresser.on("error", (error) => { + reject({ + code: constants_1.Status.INTERNAL, + details: "Failed to decompress message" + }); + }); + decompresser.on("data", (chunk) => { + messageParts.push(chunk); + totalLength += chunk.byteLength; + if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { + decompresser.destroy(); + reject({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` + }); + } + }); + decompresser.on("end", () => { + resolve(Buffer.concat(messageParts)); + }); + decompresser.write(messageContents); + decompresser.end(); + }); + } else { + return Promise.reject({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received message compressed with unsupported encoding "${encoding}"` + }); + } + } + async decompressAndMaybePush(queueEntry) { + if (queueEntry.type !== "COMPRESSED") { + throw new Error(`Invalid queue entry type: ${queueEntry.type}`); + } + const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; + const compressedMessageEncoding = compressed ? this.incomingEncoding : "identity"; + let decompressedMessage; + try { + decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); + } catch (err) { + this.sendStatus(err); + return; + } + try { + queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); + } catch (err) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error deserializing request: ${err.message}` + }); + return; + } + queueEntry.type = "READABLE"; + this.maybePushNextMessage(); + } + maybePushNextMessage() { + if (this.listener && this.isReadPending && this.readQueue.length > 0 && this.readQueue[0].type !== "COMPRESSED") { + this.isReadPending = false; + const nextQueueEntry = this.readQueue.shift(); + if (nextQueueEntry.type === "READABLE") { + this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); + } else { + this.listener.onReceiveHalfClose(); + } + } + } + handleDataFrame(data) { + var _a; + if (this.checkCancelled()) { + return; + } + trace("Request to " + this.handler.path + " received data frame of size " + data.length); + let rawMessages; + try { + rawMessages = this.decoder.write(data); + } catch (e) { + this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message }); + return; + } + for (const messageBytes of rawMessages) { + this.stream.pause(); + const queueEntry = { + type: "COMPRESSED", + compressedMessage: messageBytes, + parsedMessage: null + }; + this.readQueue.push(queueEntry); + this.decompressAndMaybePush(queueEntry); + (_a = this.callEventTracker) === null || _a === undefined || _a.addMessageReceived(); + } + } + handleEndEvent() { + this.readQueue.push({ + type: "HALF_CLOSE", + compressedMessage: null, + parsedMessage: null + }); + this.receivedHalfClose = true; + this.maybePushNextMessage(); + } + start(listener) { + trace("Request to " + this.handler.path + " start called"); + if (this.checkCancelled()) { + return; + } + this.listener = listener; + listener.onReceiveMetadata(this.metadata); + } + sendMetadata(metadata) { + if (this.checkCancelled()) { + return; + } + if (this.metadataSent) { + return; + } + this.metadataSent = true; + const custom = metadata ? metadata.toHttp2Headers() : null; + const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); + this.stream.respond(headers, defaultResponseOptions); + } + sendMessage(message, callback) { + if (this.checkCancelled()) { + return; + } + let response; + try { + response = this.serializeMessage(message); + } catch (e) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, + metadata: null + }); + return; + } + if (this.maxSendMessageSize !== -1 && response.length - 5 > this.maxSendMessageSize) { + this.sendStatus({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, + metadata: null + }); + return; + } + this.maybeSendMetadata(); + trace("Request to " + this.handler.path + " sent data frame of size " + response.length); + this.stream.write(response, (error) => { + var _a; + if (error) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`, + metadata: null + }); + return; + } + (_a = this.callEventTracker) === null || _a === undefined || _a.addMessageSent(); + callback(); + }); + } + sendStatus(status) { + var _a, _b, _c; + if (this.checkCancelled()) { + return; + } + trace("Request to method " + ((_a = this.handler) === null || _a === undefined ? undefined : _a.path) + " ended with status code: " + constants_1.Status[status.code] + " details: " + status.details); + const statusMetadata = (_c = (_b = status.metadata) === null || _b === undefined ? undefined : _b.clone()) !== null && _c !== undefined ? _c : new metadata_1.Metadata; + if (this.shouldSendMetrics) { + statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); + } + if (this.metadataSent) { + if (!this.wantTrailers) { + this.wantTrailers = true; + this.stream.once("wantTrailers", () => { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers()); + this.stream.sendTrailers(trailersToSend); + this.notifyOnCancel(); + }); + this.stream.end(); + } else { + this.notifyOnCancel(); + } + } else { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers()); + this.stream.respond(trailersToSend, { endStream: true }); + this.notifyOnCancel(); + } + } + startRead() { + trace("Request to " + this.handler.path + " startRead called"); + if (this.checkCancelled()) { + return; + } + this.isReadPending = true; + if (this.readQueue.length === 0) { + if (!this.receivedHalfClose) { + this.stream.resume(); + } + } else { + this.maybePushNextMessage(); + } + } + getPeer() { + var _a; + const socket = (_a = this.stream.session) === null || _a === undefined ? undefined : _a.socket; + if (socket === null || socket === undefined ? undefined : socket.remoteAddress) { + if (socket.remotePort) { + return `${socket.remoteAddress}:${socket.remotePort}`; + } else { + return socket.remoteAddress; + } + } else { + return "unknown"; + } + } + getDeadline() { + return this.deadline; + } + getHost() { + return this.host; + } + getAuthContext() { + var _a; + if (((_a = this.stream.session) === null || _a === undefined ? undefined : _a.socket) instanceof tls_1.TLSSocket) { + const peerCertificate = this.stream.session.socket.getPeerCertificate(); + return { + transportSecurityType: "ssl", + sslPeerCertificate: peerCertificate.raw ? peerCertificate : undefined + }; + } else { + return {}; + } + } + getConnectionInfo() { + return this.connectionInfo; + } + getMetricsRecorder() { + return this.metricsRecorder; + } + } + exports.BaseServerInterceptingCall = BaseServerInterceptingCall; + function getServerInterceptingCall(interceptors, stream, headers, callEventTracker, handler, options) { + const methodDefinition = { + path: handler.path, + requestStream: handler.type === "clientStream" || handler.type === "bidi", + responseStream: handler.type === "serverStream" || handler.type === "bidi", + requestDeserialize: handler.deserialize, + responseSerialize: handler.serialize + }; + const baseCall = new BaseServerInterceptingCall(stream, headers, callEventTracker, handler, options); + return interceptors.reduce((call, interceptor) => { + return interceptor(methodDefinition, call); + }, baseCall); + } +}); + +// node_modules/@grpc/grpc-js/build/src/server.js +var require_server = __commonJS((exports) => { + var __runInitializers = exports && exports.__runInitializers || function(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0;i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : undefined; + }; + var __esDecorate = exports && exports.__esDecorate || function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== undefined && typeof f !== "function") + throw new TypeError("Function expected"); + return f; + } + var kind2 = contextIn.kind, key = kind2 === "getter" ? "get" : kind2 === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1;i >= 0; i--) { + var context = {}; + for (var p in contextIn) + context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) + context.access[p] = contextIn.access[p]; + context.addInitializer = function(f) { + if (done) + throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind2 === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind2 === "accessor") { + if (result === undefined) + continue; + if (result === null || typeof result !== "object") + throw new TypeError("Object expected"); + if (_ = accept(result.get)) + descriptor.get = _; + if (_ = accept(result.set)) + descriptor.set = _; + if (_ = accept(result.init)) + initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind2 === "field") + initializers.unshift(_); + else + descriptor[key] = _; + } + } + if (target) + Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Server = undefined; + var http2 = __require("http2"); + var util = __require("util"); + var constants_1 = require_constants2(); + var server_call_1 = require_server_call(); + var server_credentials_1 = require_server_credentials(); + var resolver_1 = require_resolver(); + var logging = require_logging(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var channelz_1 = require_channelz(); + var server_interceptors_1 = require_server_interceptors(); + var UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); + var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); + var KEEPALIVE_TIMEOUT_MS = 20000; + var MAX_CONNECTION_IDLE_MS = ~(1 << 31); + var { HTTP2_HEADER_PATH } = http2.constants; + var TRACER_NAME = "server"; + var kMaxAge = Buffer.from("max_age"); + function serverCallTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "server_call", text); + } + function noop() {} + function deprecate(message) { + return function(target, context) { + return util.deprecate(target, message); + }; + } + function getUnimplementedStatusResponse(methodName) { + return { + code: constants_1.Status.UNIMPLEMENTED, + details: `The server does not implement the method ${methodName}` + }; + } + function getDefaultHandler(handlerType, methodName) { + const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); + switch (handlerType) { + case "unary": + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case "clientStream": + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case "serverStream": + return (call) => { + call.emit("error", unimplementedStatusResponse); + }; + case "bidi": + return (call) => { + call.emit("error", unimplementedStatusResponse); + }; + default: + throw new Error(`Invalid handlerType ${handlerType}`); + } + } + var Server = (() => { + var _a; + let _instanceExtraInitializers = []; + let _start_decorators; + return _a = class Server2 { + constructor(options) { + var _b, _c, _d, _e, _f, _g; + this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), new Map); + this.http2Servers = new Map; + this.sessionIdleTimeouts = new Map; + this.handlers = new Map; + this.sessions = new Map; + this.started = false; + this.shutdown = false; + this.serverAddressString = "null"; + this.channelzEnabled = true; + this.options = options !== null && options !== undefined ? options : {}; + if (this.options["grpc.enable_channelz"] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub; + this.callTracker = new channelz_1.ChannelzCallTrackerStub; + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub; + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub; + } else { + this.channelzTrace = new channelz_1.ChannelzTrace; + this.callTracker = new channelz_1.ChannelzCallTracker; + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker; + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker; + } + this.channelzRef = (0, channelz_1.registerChannelzServer)("server", () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace("CT_INFO", "Server created"); + this.maxConnectionAgeMs = (_b = this.options["grpc.max_connection_age_ms"]) !== null && _b !== undefined ? _b : UNLIMITED_CONNECTION_AGE_MS; + this.maxConnectionAgeGraceMs = (_c = this.options["grpc.max_connection_age_grace_ms"]) !== null && _c !== undefined ? _c : UNLIMITED_CONNECTION_AGE_MS; + this.keepaliveTimeMs = (_d = this.options["grpc.keepalive_time_ms"]) !== null && _d !== undefined ? _d : KEEPALIVE_MAX_TIME_MS; + this.keepaliveTimeoutMs = (_e = this.options["grpc.keepalive_timeout_ms"]) !== null && _e !== undefined ? _e : KEEPALIVE_TIMEOUT_MS; + this.sessionIdleTimeout = (_f = this.options["grpc.max_connection_idle_ms"]) !== null && _f !== undefined ? _f : MAX_CONNECTION_IDLE_MS; + this.commonServerOptions = { + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER + }; + if ("grpc-node.max_session_memory" in this.options) { + this.commonServerOptions.maxSessionMemory = this.options["grpc-node.max_session_memory"]; + } else { + this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + if ("grpc.max_concurrent_streams" in this.options) { + this.commonServerOptions.settings = { + maxConcurrentStreams: this.options["grpc.max_concurrent_streams"] + }; + } + this.interceptors = (_g = this.options.interceptors) !== null && _g !== undefined ? _g : []; + this.trace("Server constructed"); + } + getChannelzInfo() { + return { + trace: this.channelzTrace, + callTracker: this.callTracker, + listenerChildren: this.listenerChildrenTracker.getChildLists(), + sessionChildren: this.sessionChildrenTracker.getChildLists() + }; + } + getChannelzSessionInfo(session) { + var _b, _c, _d; + const sessionInfo = this.sessions.get(session); + const sessionSocket = session.socket; + const remoteAddress = sessionSocket.remoteAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) : null; + const localAddress = sessionSocket.localAddress ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) : null; + let tlsInfo; + if (session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== undefined ? _b : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && "raw" in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && "raw" in peerCertificate ? peerCertificate.raw : null + }; + } else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress, + localAddress, + security: tlsInfo, + remoteName: null, + streamsStarted: sessionInfo.streamTracker.callsStarted, + streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, + streamsFailed: sessionInfo.streamTracker.callsFailed, + messagesSent: sessionInfo.messagesSent, + messagesReceived: sessionInfo.messagesReceived, + keepAlivesSent: sessionInfo.keepAlivesSent, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, + lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, + localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== undefined ? _c : null, + remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== undefined ? _d : null + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + text); + } + keepaliveTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + text); + } + addProtoService() { + throw new Error("Not implemented. Use addService() instead"); + } + addService(service, implementation) { + if (service === null || typeof service !== "object" || implementation === null || typeof implementation !== "object") { + throw new Error("addService() requires two objects as arguments"); + } + const serviceKeys = Object.keys(service); + if (serviceKeys.length === 0) { + throw new Error("Cannot add an empty service to a server"); + } + serviceKeys.forEach((name) => { + const attrs = service[name]; + let methodType; + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = "bidi"; + } else { + methodType = "clientStream"; + } + } else { + if (attrs.responseStream) { + methodType = "serverStream"; + } else { + methodType = "unary"; + } + } + let implFn = implementation[name]; + let impl; + if (implFn === undefined && typeof attrs.originalName === "string") { + implFn = implementation[attrs.originalName]; + } + if (implFn !== undefined) { + impl = implFn.bind(implementation); + } else { + impl = getDefaultHandler(methodType, name); + } + const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); + if (success === false) { + throw new Error(`Method handler for ${attrs.path} already provided.`); + } + }); + } + removeService(service) { + if (service === null || typeof service !== "object") { + throw new Error("removeService() requires object as argument"); + } + const serviceKeys = Object.keys(service); + serviceKeys.forEach((name) => { + const attrs = service[name]; + this.unregister(attrs.path); + }); + } + bind(port, creds) { + throw new Error("Not implemented. Use bindAsync() instead"); + } + experimentalRegisterListenerToChannelz(boundAddress) { + return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { + return { + localAddress: boundAddress, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null + }; + }, this.channelzEnabled); + } + experimentalUnregisterListenerFromChannelz(channelzRef) { + (0, channelz_1.unregisterChannelzRef)(channelzRef); + } + createHttp2Server(credentials) { + let http2Server; + if (credentials._isSecure()) { + const constructorOptions = credentials._getConstructorOptions(); + const contextOptions = credentials._getSecureContextOptions(); + const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options["grpc-node.tls_enable_trace"] === 1 }); + let areCredentialsValid = contextOptions !== null; + this.trace("Initial credentials valid: " + areCredentialsValid); + http2Server = http2.createSecureServer(secureServerOptions); + http2Server.prependListener("connection", (socket) => { + if (!areCredentialsValid) { + this.trace("Dropped connection from " + JSON.stringify(socket.address()) + " due to unloaded credentials"); + socket.destroy(); + } + }); + http2Server.on("secureConnection", (socket) => { + socket.on("error", (e) => { + this.trace("An incoming TLS connection closed with error: " + e.message); + }); + }); + const credsWatcher = (options) => { + if (options) { + const secureServer = http2Server; + try { + secureServer.setSecureContext(options); + } catch (e) { + logging.log(constants_1.LogVerbosity.ERROR, "Failed to set secure context with error " + e.message); + options = null; + } + } + areCredentialsValid = options !== null; + this.trace("Post-update credentials valid: " + areCredentialsValid); + }; + credentials._addWatcher(credsWatcher); + http2Server.on("close", () => { + credentials._removeWatcher(credsWatcher); + }); + } else { + http2Server = http2.createServer(this.commonServerOptions); + } + http2Server.setTimeout(0, noop); + this._setupHandlers(http2Server, credentials._getInterceptors()); + return http2Server; + } + bindOneAddress(address, boundPortObject) { + this.trace("Attempting to bind " + (0, subchannel_address_1.subchannelAddressToString)(address)); + const http2Server = this.createHttp2Server(boundPortObject.credentials); + return new Promise((resolve, reject) => { + const onError = (err) => { + this.trace("Failed to bind " + (0, subchannel_address_1.subchannelAddressToString)(address) + " with error " + err.message); + resolve({ + port: "port" in address ? address.port : 1, + error: err.message + }); + }; + http2Server.once("error", onError); + http2Server.listen(address, () => { + const boundAddress = http2Server.address(); + let boundSubchannelAddress; + if (typeof boundAddress === "string") { + boundSubchannelAddress = { + path: boundAddress + }; + } else { + boundSubchannelAddress = { + host: boundAddress.address, + port: boundAddress.port + }; + } + const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress); + this.listenerChildrenTracker.refChild(channelzRef); + this.http2Servers.set(http2Server, { + channelzRef, + sessions: new Set, + ownsChannelzRef: true + }); + boundPortObject.listeningServers.add(http2Server); + this.trace("Successfully bound " + (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); + resolve({ + port: "port" in boundSubchannelAddress ? boundSubchannelAddress.port : 1 + }); + http2Server.removeListener("error", onError); + }); + }); + } + async bindManyPorts(addressList, boundPortObject) { + if (addressList.length === 0) { + return { + count: 0, + port: 0, + errors: [] + }; + } + if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { + const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); + if (firstAddressResult.error) { + const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); + return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); + } else { + const restAddresses = addressList.slice(1).map((address) => (0, subchannel_address_1.isTcpSubchannelAddress)(address) ? { host: address.host, port: firstAddressResult.port } : address); + const restAddressResult = await Promise.all(restAddresses.map((address) => this.bindOneAddress(address, boundPortObject))); + const allResults = [firstAddressResult, ...restAddressResult]; + return { + count: allResults.filter((result) => result.error === undefined).length, + port: firstAddressResult.port, + errors: allResults.filter((result) => result.error).map((result) => result.error) + }; + } + } else { + const allResults = await Promise.all(addressList.map((address) => this.bindOneAddress(address, boundPortObject))); + return { + count: allResults.filter((result) => result.error === undefined).length, + port: allResults[0].port, + errors: allResults.filter((result) => result.error).map((result) => result.error) + }; + } + } + async bindAddressList(addressList, boundPortObject) { + const bindResult = await this.bindManyPorts(addressList, boundPortObject); + if (bindResult.count > 0) { + if (bindResult.count < addressList.length) { + logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); + } + return bindResult.port; + } else { + const errorString = `No address added out of total ${addressList.length} resolved`; + logging.log(constants_1.LogVerbosity.ERROR, errorString); + throw new Error(`${errorString} errors: [${bindResult.errors.join(",")}]`); + } + } + resolvePort(port) { + return new Promise((resolve, reject) => { + let seenResolution = false; + const resolverListener = (endpointList, attributes, serviceConfig, resolutionNote) => { + if (seenResolution) { + return true; + } + seenResolution = true; + if (!endpointList.ok) { + reject(new Error(endpointList.error.details)); + return true; + } + const addressList = [].concat(...endpointList.value.map((endpoint) => endpoint.addresses)); + if (addressList.length === 0) { + reject(new Error(`No addresses resolved for port ${port}`)); + return true; + } + resolve(addressList); + return true; + }; + const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); + resolver.updateResolution(); + }); + } + async bindPort(port, boundPortObject) { + const addressList = await this.resolvePort(port); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error("bindAsync operation cancelled by unbind call"); + } + const portNumber = await this.bindAddressList(addressList, boundPortObject); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error("bindAsync operation cancelled by unbind call"); + } + return portNumber; + } + normalizePort(port) { + const initialPortUri = (0, uri_parser_1.parseUri)(port); + if (initialPortUri === null) { + throw new Error(`Could not parse port "${port}"`); + } + const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); + if (portUri === null) { + throw new Error(`Could not get a default scheme for port "${port}"`); + } + return portUri; + } + bindAsync(port, creds, callback) { + if (this.shutdown) { + throw new Error("bindAsync called after shutdown"); + } + if (typeof port !== "string") { + throw new TypeError("port must be a string"); + } + if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError("creds must be a ServerCredentials object"); + } + if (typeof callback !== "function") { + throw new TypeError("callback must be a function"); + } + this.trace("bindAsync port=" + port); + const portUri = this.normalizePort(port); + const deferredCallback = (error, port2) => { + process.nextTick(() => callback(error, port2)); + }; + let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + if (!creds._equals(boundPortObject.credentials)) { + deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); + return; + } + boundPortObject.cancelled = false; + if (boundPortObject.completionPromise) { + boundPortObject.completionPromise.then((portNum) => callback(null, portNum), (error) => callback(error, 0)); + } else { + deferredCallback(null, boundPortObject.portNumber); + } + return; + } + boundPortObject = { + mapKey: (0, uri_parser_1.uriToString)(portUri), + originalUri: portUri, + completionPromise: null, + cancelled: false, + portNumber: 0, + credentials: creds, + listeningServers: new Set + }; + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + const completionPromise = this.bindPort(portUri, boundPortObject); + boundPortObject.completionPromise = completionPromise; + if ((splitPort === null || splitPort === undefined ? undefined : splitPort.port) === 0) { + completionPromise.then((portNum) => { + const finalUri = { + scheme: portUri.scheme, + authority: portUri.authority, + path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }) + }; + boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + callback(null, portNum); + }, (error) => { + callback(error, 0); + }); + } else { + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + completionPromise.then((portNum) => { + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + callback(null, portNum); + }, (error) => { + callback(error, 0); + }); + } + } + registerInjectorToChannelz() { + return (0, channelz_1.registerChannelzSocket)("injector", () => { + return { + localAddress: null, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null + }; + }, this.channelzEnabled); + } + experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) { + if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError("creds must be a ServerCredentials object"); + } + if (this.channelzEnabled) { + this.listenerChildrenTracker.refChild(channelzRef); + } + const server = this.createHttp2Server(credentials); + const sessionsSet = new Set; + this.http2Servers.set(server, { + channelzRef, + sessions: sessionsSet, + ownsChannelzRef + }); + return { + injectConnection: (connection) => { + server.emit("connection", connection); + }, + drain: (graceTimeMs) => { + var _b, _c; + for (const session of sessionsSet) { + this.closeSession(session); + } + (_c = (_b = setTimeout(() => { + for (const session of sessionsSet) { + session.destroy(http2.constants.NGHTTP2_CANCEL); + } + }, graceTimeMs)).unref) === null || _c === undefined || _c.call(_b); + }, + destroy: () => { + this.closeServer(server); + for (const session of sessionsSet) { + this.closeSession(session); + } + } + }; + } + createConnectionInjector(credentials) { + if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError("creds must be a ServerCredentials object"); + } + const channelzRef = this.registerInjectorToChannelz(); + return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); + } + closeServer(server, callback) { + this.trace("Closing server with address " + JSON.stringify(server.address())); + const serverInfo = this.http2Servers.get(server); + server.close(() => { + if (serverInfo && serverInfo.ownsChannelzRef) { + this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); + (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); + } + this.http2Servers.delete(server); + callback === null || callback === undefined || callback(); + }); + } + closeSession(session, callback) { + var _b; + this.trace("Closing session initiated by " + ((_b = session.socket) === null || _b === undefined ? undefined : _b.remoteAddress)); + const sessionInfo = this.sessions.get(session); + const closeCallback = () => { + if (sessionInfo) { + this.sessionChildrenTracker.unrefChild(sessionInfo.ref); + (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); + } + callback === null || callback === undefined || callback(); + }; + if (session.closed) { + queueMicrotask(closeCallback); + } else { + session.close(closeCallback); + } + } + completeUnbind(boundPortObject) { + for (const server of boundPortObject.listeningServers) { + const serverInfo = this.http2Servers.get(server); + this.closeServer(server, () => { + boundPortObject.listeningServers.delete(server); + }); + if (serverInfo) { + for (const session of serverInfo.sessions) { + this.closeSession(session); + } + } + } + this.boundPorts.delete(boundPortObject.mapKey); + } + unbind(port) { + this.trace("unbind port=" + port); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === undefined ? undefined : splitPort.port) === 0) { + throw new Error("Cannot unbind port 0"); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + this.trace("unbinding " + boundPortObject.mapKey + " originally bound as " + (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); + if (boundPortObject.completionPromise) { + boundPortObject.cancelled = true; + } else { + this.completeUnbind(boundPortObject); + } + } + } + drain(port, graceTimeMs) { + var _b, _c; + this.trace("drain port=" + port + " graceTimeMs=" + graceTimeMs); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === undefined ? undefined : splitPort.port) === 0) { + throw new Error("Cannot drain port 0"); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (!boundPortObject) { + return; + } + const allSessions = new Set; + for (const http2Server of boundPortObject.listeningServers) { + const serverEntry = this.http2Servers.get(http2Server); + if (serverEntry) { + for (const session of serverEntry.sessions) { + allSessions.add(session); + this.closeSession(session, () => { + allSessions.delete(session); + }); + } + } + } + (_c = (_b = setTimeout(() => { + for (const session of allSessions) { + session.destroy(http2.constants.NGHTTP2_CANCEL); + } + }, graceTimeMs)).unref) === null || _c === undefined || _c.call(_b); + } + forceShutdown() { + for (const boundPortObject of this.boundPorts.values()) { + boundPortObject.cancelled = true; + } + this.boundPorts.clear(); + for (const server of this.http2Servers.keys()) { + this.closeServer(server); + } + this.sessions.forEach((channelzInfo, session) => { + this.closeSession(session); + session.destroy(http2.constants.NGHTTP2_CANCEL); + }); + this.sessions.clear(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + this.shutdown = true; + } + register(name, handler, serialize, deserialize, type) { + if (this.handlers.has(name)) { + return false; + } + this.handlers.set(name, { + func: handler, + serialize, + deserialize, + type, + path: name + }); + return true; + } + unregister(name) { + return this.handlers.delete(name); + } + start() { + if (this.http2Servers.size === 0 || [...this.http2Servers.keys()].every((server) => !server.listening)) { + throw new Error("server must be bound in order to start"); + } + if (this.started === true) { + throw new Error("server is already started"); + } + this.started = true; + } + tryShutdown(callback) { + var _b; + const wrappedCallback = (error) => { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + callback(error); + }; + let pendingChecks = 0; + function maybeCallback() { + pendingChecks--; + if (pendingChecks === 0) { + wrappedCallback(); + } + } + this.shutdown = true; + for (const [serverKey, server] of this.http2Servers.entries()) { + pendingChecks++; + const serverString = server.channelzRef.name; + this.trace("Waiting for server " + serverString + " to close"); + this.closeServer(serverKey, () => { + this.trace("Server " + serverString + " finished closing"); + maybeCallback(); + }); + for (const session of server.sessions.keys()) { + pendingChecks++; + const sessionString = (_b = session.socket) === null || _b === undefined ? undefined : _b.remoteAddress; + this.trace("Waiting for session " + sessionString + " to close"); + this.closeSession(session, () => { + this.trace("Session " + sessionString + " finished closing"); + maybeCallback(); + }); + } + } + if (pendingChecks === 0) { + wrappedCallback(); + } + } + addHttp2Port() { + throw new Error("Not yet implemented"); + } + getChannelzRef() { + return this.channelzRef; + } + _verifyContentType(stream, headers) { + const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; + if (typeof contentType !== "string" || !contentType.startsWith("application/grpc")) { + stream.respond({ + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE + }, { endStream: true }); + return false; + } + return true; + } + _retrieveHandler(path) { + serverCallTrace("Received call to method " + path + " at address " + this.serverAddressString); + const handler = this.handlers.get(path); + if (handler === undefined) { + serverCallTrace("No handler registered for method " + path + ". Sending UNIMPLEMENTED status."); + return null; + } + return handler; + } + _respondWithError(err, stream, channelzSessionInfo = null) { + var _b, _c; + const trailersToSend = Object.assign({ "grpc-status": (_b = err.code) !== null && _b !== undefined ? _b : constants_1.Status.INTERNAL, "grpc-message": err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: "application/grpc+proto" }, (_c = err.metadata) === null || _c === undefined ? undefined : _c.toHttp2Headers()); + stream.respond(trailersToSend, { endStream: true }); + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === undefined || channelzSessionInfo.streamTracker.addCallFailed(); + } + _channelzHandler(extraInterceptors, stream, headers) { + stream.once("error", (err) => {}); + this.onStreamOpened(stream); + const channelzSessionInfo = this.sessions.get(stream.session); + this.callTracker.addCallStarted(); + channelzSessionInfo === null || channelzSessionInfo === undefined || channelzSessionInfo.streamTracker.addCallStarted(); + if (!this._verifyContentType(stream, headers)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === undefined || channelzSessionInfo.streamTracker.addCallFailed(); + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError(getUnimplementedStatusResponse(path), stream, channelzSessionInfo); + return; + } + const callEventTracker = { + addMessageSent: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesSent += 1; + channelzSessionInfo.lastMessageSentTimestamp = new Date; + } + }, + addMessageReceived: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesReceived += 1; + channelzSessionInfo.lastMessageReceivedTimestamp = new Date; + } + }, + onCallEnd: (status) => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + }, + onStreamEnd: (success) => { + if (channelzSessionInfo) { + if (success) { + channelzSessionInfo.streamTracker.addCallSucceeded(); + } else { + channelzSessionInfo.streamTracker.addCallFailed(); + } + } + } + }; + const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, callEventTracker, handler, this.options); + if (!this._runHandlerForCall(call, handler)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === undefined || channelzSessionInfo.streamTracker.addCallFailed(); + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler.type}` + }); + } + } + _streamHandler(extraInterceptors, stream, headers) { + stream.once("error", (err) => {}); + this.onStreamOpened(stream); + if (this._verifyContentType(stream, headers) !== true) { + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError(getUnimplementedStatusResponse(path), stream, null); + return; + } + const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, null, handler, this.options); + if (!this._runHandlerForCall(call, handler)) { + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler.type}` + }); + } + } + _runHandlerForCall(call, handler) { + const { type } = handler; + if (type === "unary") { + handleUnary(call, handler); + } else if (type === "clientStream") { + handleClientStreaming(call, handler); + } else if (type === "serverStream") { + handleServerStreaming(call, handler); + } else if (type === "bidi") { + handleBidiStreaming(call, handler); + } else { + return false; + } + return true; + } + _setupHandlers(http2Server, extraInterceptors) { + if (http2Server === null) { + return; + } + const serverAddress = http2Server.address(); + let serverAddressString = "null"; + if (serverAddress) { + if (typeof serverAddress === "string") { + serverAddressString = serverAddress; + } else { + serverAddressString = serverAddress.address + ":" + serverAddress.port; + } + } + this.serverAddressString = serverAddressString; + const handler = this.channelzEnabled ? this._channelzHandler : this._streamHandler; + const sessionHandler = this.channelzEnabled ? this._channelzSessionHandler(http2Server) : this._sessionHandler(http2Server); + http2Server.on("stream", handler.bind(this, extraInterceptors)); + http2Server.on("session", sessionHandler); + } + _sessionHandler(http2Server) { + return (session) => { + var _b, _c; + (_b = this.http2Servers.get(http2Server)) === null || _b === undefined || _b.sessions.add(session); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keepaliveTimer = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b2, _c2; + sessionClosedByServer = true; + this.trace("Connection dropped by max connection age: " + ((_b2 = session.socket) === null || _b2 === undefined ? undefined : _b2.remoteAddress)); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } catch (e) { + session.destroy(); + return; + } + session.close(); + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_c2 = connectionAgeGraceTimer.unref) === null || _c2 === undefined || _c2.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_c = connectionAgeTimer.unref) === null || _c === undefined || _c.call(connectionAgeTimer); + } + const clearKeepaliveTimeout = () => { + if (keepaliveTimer) { + clearTimeout(keepaliveTimer); + keepaliveTimer = null; + } + }; + const canSendPing = () => { + return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0; + }; + let sendPing; + const maybeStartKeepalivePingTimer = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + (_b2 = keepaliveTimer.unref) === null || _b2 === undefined || _b2.call(keepaliveTimer); + }; + sendPing = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + let pingSendError = ""; + try { + const pingSentSuccessfully = session.ping((err, duration, payload) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace("Ping failed with error: " + err.message); + sessionClosedByServer = true; + session.destroy(); + } else { + this.keepaliveTrace("Received ping response"); + maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = "Ping returned false"; + } + } catch (e) { + pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; + } + if (pingSendError) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + this.trace("Connection dropped due to ping send error: " + pingSendError); + sessionClosedByServer = true; + session.destroy(); + return; + } + keepaliveTimer = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace("Ping timeout passed without response"); + this.trace("Connection dropped by keepalive timeout"); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + (_b2 = keepaliveTimer.unref) === null || _b2 === undefined || _b2.call(keepaliveTimer); + }; + maybeStartKeepalivePingTimer(); + session.on("close", () => { + var _b2, _c2; + if (!sessionClosedByServer) { + this.trace(`Connection dropped by client ${(_b2 = session.socket) === null || _b2 === undefined ? undefined : _b2.remoteAddress}`); + } + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + clearKeepaliveTimeout(); + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_c2 = this.http2Servers.get(http2Server)) === null || _c2 === undefined || _c2.sessions.delete(session); + }); + }; + } + _channelzSessionHandler(http2Server) { + return (session) => { + var _b, _c, _d, _e; + const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === undefined ? undefined : _b.remoteAddress) !== null && _c !== undefined ? _c : "unknown", this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); + const channelzSessionInfo = { + ref: channelzRef, + streamTracker: new channelz_1.ChannelzCallTracker, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null + }; + (_d = this.http2Servers.get(http2Server)) === null || _d === undefined || _d.sessions.add(session); + this.sessions.set(session, channelzSessionInfo); + const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; + this.channelzTrace.addTrace("CT_INFO", "Connection established by client " + clientAddress); + this.trace("Connection established by client " + clientAddress); + this.sessionChildrenTracker.refChild(channelzRef); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keepaliveTimeout = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b2; + sessionClosedByServer = true; + this.channelzTrace.addTrace("CT_INFO", "Connection dropped by max connection age from " + clientAddress); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } catch (e) { + session.destroy(); + return; + } + session.close(); + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_b2 = connectionAgeGraceTimer.unref) === null || _b2 === undefined || _b2.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_e = connectionAgeTimer.unref) === null || _e === undefined || _e.call(connectionAgeTimer); + } + const clearKeepaliveTimeout = () => { + if (keepaliveTimeout) { + clearTimeout(keepaliveTimeout); + keepaliveTimeout = null; + } + }; + const canSendPing = () => { + return !session.destroyed && this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && this.keepaliveTimeMs > 0; + }; + let sendPing; + const maybeStartKeepalivePingTimer = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Starting keepalive timer for " + this.keepaliveTimeMs + "ms"); + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + sendPing(); + }, this.keepaliveTimeMs); + (_b2 = keepaliveTimeout.unref) === null || _b2 === undefined || _b2.call(keepaliveTimeout); + }; + sendPing = () => { + var _b2; + if (!canSendPing()) { + return; + } + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + let pingSendError = ""; + try { + const pingSentSuccessfully = session.ping((err, duration, payload) => { + clearKeepaliveTimeout(); + if (err) { + this.keepaliveTrace("Ping failed with error: " + err.message); + this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to error of a ping frame " + err.message + " return in " + duration); + sessionClosedByServer = true; + session.destroy(); + } else { + this.keepaliveTrace("Received ping response"); + maybeStartKeepalivePingTimer(); + } + }); + if (!pingSentSuccessfully) { + pingSendError = "Ping returned false"; + } + } catch (e) { + pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; + } + if (pingSendError) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + this.channelzTrace.addTrace("CT_INFO", "Connection dropped due to ping send error: " + pingSendError); + sessionClosedByServer = true; + session.destroy(); + return; + } + channelzSessionInfo.keepAlivesSent += 1; + keepaliveTimeout = setTimeout(() => { + clearKeepaliveTimeout(); + this.keepaliveTrace("Ping timeout passed without response"); + this.channelzTrace.addTrace("CT_INFO", "Connection dropped by keepalive timeout from " + clientAddress); + sessionClosedByServer = true; + session.destroy(); + }, this.keepaliveTimeoutMs); + (_b2 = keepaliveTimeout.unref) === null || _b2 === undefined || _b2.call(keepaliveTimeout); + }; + maybeStartKeepalivePingTimer(); + session.on("close", () => { + var _b2; + if (!sessionClosedByServer) { + this.channelzTrace.addTrace("CT_INFO", "Connection dropped by client " + clientAddress); + } + this.sessionChildrenTracker.unrefChild(channelzRef); + (0, channelz_1.unregisterChannelzRef)(channelzRef); + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + clearKeepaliveTimeout(); + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_b2 = this.http2Servers.get(http2Server)) === null || _b2 === undefined || _b2.sessions.delete(session); + this.sessions.delete(session); + }); + }; + } + enableIdleTimeout(session) { + var _b, _c; + if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { + return null; + } + const idleTimeoutObj = { + activeStreams: 0, + lastIdle: Date.now(), + onClose: this.onStreamClose.bind(this, session), + timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session) + }; + (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === undefined || _c.call(_b); + this.sessionIdleTimeouts.set(session, idleTimeoutObj); + const { socket } = session; + this.trace("Enable idle timeout for " + socket.remoteAddress + ":" + socket.remotePort); + return idleTimeoutObj; + } + onIdleTimeout(ctx, session) { + const { socket } = session; + const sessionInfo = ctx.sessionIdleTimeouts.get(session); + if (sessionInfo !== undefined && sessionInfo.activeStreams === 0) { + if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { + ctx.trace("Session idle timeout triggered for " + (socket === null || socket === undefined ? undefined : socket.remoteAddress) + ":" + (socket === null || socket === undefined ? undefined : socket.remotePort) + " last idle at " + sessionInfo.lastIdle); + ctx.closeSession(session); + } else { + sessionInfo.timeout.refresh(); + } + } + } + onStreamOpened(stream) { + const session = stream.session; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams += 1; + stream.once("close", idleTimeoutObj.onClose); + } + } + onStreamClose(session) { + var _b, _c; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams -= 1; + if (idleTimeoutObj.activeStreams === 0) { + idleTimeoutObj.lastIdle = Date.now(); + idleTimeoutObj.timeout.refresh(); + this.trace("Session onStreamClose" + ((_b = session.socket) === null || _b === undefined ? undefined : _b.remoteAddress) + ":" + ((_c = session.socket) === null || _c === undefined ? undefined : _c.remotePort) + " at " + idleTimeoutObj.lastIdle); + } + } + } + }, (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : undefined; + _start_decorators = [deprecate("Calling start() is no longer necessary. It can be safely omitted.")]; + __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: (obj) => ("start" in obj), get: (obj) => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); + if (_metadata) + Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + })(), _a; + })(); + exports.Server = Server; + async function handleUnary(call, handler) { + let stream; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: "OK", + metadata: trailer !== null && trailer !== undefined ? trailer : null + }); + }); + } + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null + }); + return; + } + stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); + try { + handler.func(stream, respond); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit("cancelled", "cancelled"); + } + } + }); + } + function handleClientStreaming(call, handler) { + let stream; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: "OK", + metadata: trailer !== null && trailer !== undefined ? trailer : null + }); + }); + } + call.start({ + onReceiveMetadata(metadata) { + stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream, respond); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit("cancelled", "cancelled"); + stream.destroy(); + } + } + }); + } + function handleServerStreaming(call, handler) { + let stream; + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null + }); + return; + } + stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); + try { + handler.func(stream); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit("cancelled", "cancelled"); + stream.destroy(); + } + } + }); + } + function handleBidiStreaming(call, handler) { + let stream; + call.start({ + onReceiveMetadata(metadata) { + stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream); + } catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit("cancelled", "cancelled"); + stream.destroy(); + } + } + }); + } +}); + +// node_modules/@grpc/grpc-js/build/src/status-builder.js +var require_status_builder = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.StatusBuilder = undefined; + + class StatusBuilder { + constructor() { + this.code = null; + this.details = null; + this.metadata = null; + } + withCode(code) { + this.code = code; + return this; + } + withDetails(details) { + this.details = details; + return this; + } + withMetadata(metadata) { + this.metadata = metadata; + return this; + } + build() { + const status = {}; + if (this.code !== null) { + status.code = this.code; + } + if (this.details !== null) { + status.details = this.details; + } + if (this.metadata !== null) { + status.metadata = this.metadata; + } + return status; + } + } + exports.StatusBuilder = StatusBuilder; +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js +var require_load_balancer_pick_first = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LeafLoadBalancer = exports.PickFirstLoadBalancer = exports.PickFirstLoadBalancingConfig = undefined; + exports.shuffled = shuffled; + exports.setup = setup; + var load_balancer_1 = require_load_balancer(); + var connectivity_state_1 = require_connectivity_state(); + var picker_1 = require_picker(); + var subchannel_address_1 = require_subchannel_address(); + var logging = require_logging(); + var constants_1 = require_constants2(); + var subchannel_address_2 = require_subchannel_address(); + var net_1 = __require("net"); + var call_interface_1 = require_call_interface(); + var TRACER_NAME = "pick_first"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "pick_first"; + var CONNECTION_DELAY_INTERVAL_MS = 250; + + class PickFirstLoadBalancingConfig { + constructor(shuffleAddressList) { + this.shuffleAddressList = shuffleAddressList; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + return { + [TYPE_NAME]: { + shuffleAddressList: this.shuffleAddressList + } + }; + } + getShuffleAddressList() { + return this.shuffleAddressList; + } + static createFromJson(obj) { + if ("shuffleAddressList" in obj && !(typeof obj.shuffleAddressList === "boolean")) { + throw new Error("pick_first config field shuffleAddressList must be a boolean if provided"); + } + return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); + } + } + exports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; + + class PickFirstPicker { + constructor(subchannel) { + this.subchannel = subchannel; + } + pick(pickArgs) { + return { + pickResultType: picker_1.PickResultType.COMPLETE, + subchannel: this.subchannel, + status: null, + onCallStarted: null, + onCallEnded: null + }; + } + } + function shuffled(list) { + const result = list.slice(); + for (let i = result.length - 1;i > 1; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = result[i]; + result[i] = result[j]; + result[j] = temp; + } + return result; + } + function interleaveAddressFamilies(addressList) { + if (addressList.length === 0) { + return []; + } + const result = []; + const ipv6Addresses = []; + const ipv4Addresses = []; + const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); + for (const address of addressList) { + if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { + ipv6Addresses.push(address); + } else { + ipv4Addresses.push(address); + } + } + const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; + const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; + for (let i = 0;i < Math.max(firstList.length, secondList.length); i++) { + if (i < firstList.length) { + result.push(firstList[i]); + } + if (i < secondList.length) { + result.push(secondList[i]); + } + } + return result; + } + var REPORT_HEALTH_STATUS_OPTION_NAME = "grpc-node.internal.pick-first.report_health_status"; + + class PickFirstLoadBalancer { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.children = []; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.currentSubchannelIndex = 0; + this.currentPick = null; + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { + this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); + }; + this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); + this.stickyTransientFailureMode = false; + this.reportHealthStatus = false; + this.lastError = null; + this.latestAddressList = null; + this.latestOptions = {}; + this.latestResolutionNote = ""; + this.connectionDelayTimeout = setTimeout(() => {}, 0); + clearTimeout(this.connectionDelayTimeout); + } + allChildrenHaveReportedTF() { + return this.children.every((child) => child.hasReportedTransientFailure); + } + resetChildrenReportedTF() { + this.children.every((child) => child.hasReportedTransientFailure = false); + } + calculateAndReportNewState() { + var _a; + if (this.currentPick) { + if (this.reportHealthStatus && !this.currentPick.isHealthy()) { + const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null); + } + } else if (((_a = this.latestAddressList) === null || _a === undefined ? undefined : _a.length) === 0) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else if (this.children.length === 0) { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } else { + if (this.stickyTransientFailureMode) { + const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } + } + } + requestReresolution() { + this.channelControlHelper.requestReresolution(); + } + maybeEnterStickyTransientFailureMode() { + if (!this.allChildrenHaveReportedTF()) { + return; + } + this.requestReresolution(); + this.resetChildrenReportedTF(); + if (this.stickyTransientFailureMode) { + this.calculateAndReportNewState(); + return; + } + this.stickyTransientFailureMode = true; + for (const { subchannel } of this.children) { + subchannel.startConnecting(); + } + this.calculateAndReportNewState(); + } + removeCurrentPick() { + if (this.currentPick !== null) { + this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); + this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()); + this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); + this.currentPick.unref(); + this.currentPick = null; + } + } + onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { + var _a; + if ((_a = this.currentPick) === null || _a === undefined ? undefined : _a.realSubchannelEquals(subchannel)) { + if (newState !== connectivity_state_1.ConnectivityState.READY) { + this.removeCurrentPick(); + this.calculateAndReportNewState(); + } + return; + } + for (const [index, child] of this.children.entries()) { + if (subchannel.realSubchannelEquals(child.subchannel)) { + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(child.subchannel); + } + if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + if (errorMessage) { + this.lastError = errorMessage; + } + this.maybeEnterStickyTransientFailureMode(); + if (index === this.currentSubchannelIndex) { + this.startNextSubchannelConnecting(index + 1); + } + } + child.subchannel.startConnecting(); + return; + } + } + } + startNextSubchannelConnecting(startIndex) { + clearTimeout(this.connectionDelayTimeout); + for (const [index, child] of this.children.entries()) { + if (index >= startIndex) { + const subchannelState = child.subchannel.getConnectivityState(); + if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { + this.startConnecting(index); + return; + } + } + } + this.maybeEnterStickyTransientFailureMode(); + } + startConnecting(subchannelIndex) { + var _a, _b; + clearTimeout(this.connectionDelayTimeout); + this.currentSubchannelIndex = subchannelIndex; + if (this.children[subchannelIndex].subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + trace("Start connecting to subchannel with address " + this.children[subchannelIndex].subchannel.getAddress()); + process.nextTick(() => { + var _a2; + (_a2 = this.children[subchannelIndex]) === null || _a2 === undefined || _a2.subchannel.startConnecting(); + }); + } + this.connectionDelayTimeout = setTimeout(() => { + this.startNextSubchannelConnecting(subchannelIndex + 1); + }, CONNECTION_DELAY_INTERVAL_MS); + (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === undefined || _b.call(_a); + } + pickSubchannel(subchannel) { + trace("Pick subchannel with address " + subchannel.getAddress()); + this.stickyTransientFailureMode = false; + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + this.removeCurrentPick(); + this.resetSubchannelList(); + subchannel.addConnectivityStateListener(this.subchannelStateListener); + subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); + this.currentPick = subchannel; + clearTimeout(this.connectionDelayTimeout); + this.calculateAndReportNewState(); + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + resetSubchannelList() { + for (const child of this.children) { + child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + child.subchannel.unref(); + this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); + } + this.currentSubchannelIndex = 0; + this.children = []; + } + connectToAddressList(addressList, options) { + trace("connectToAddressList([" + addressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])"); + const newChildrenList = addressList.map((address) => ({ + subchannel: this.channelControlHelper.createSubchannel(address, options), + hasReportedTransientFailure: false + })); + for (const { subchannel } of newChildrenList) { + if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(subchannel); + return; + } + } + for (const { subchannel } of newChildrenList) { + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + } + this.resetSubchannelList(); + this.children = newChildrenList; + for (const { subchannel } of this.children) { + subchannel.addConnectivityStateListener(this.subchannelStateListener); + } + for (const child of this.children) { + if (child.subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + } + } + this.startNextSubchannelConnecting(0); + this.calculateAndReportNewState(); + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0 && this.currentPick === null) { + this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + let endpointList = maybeEndpointList.value; + this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; + if (lbConfig.getShuffleAddressList()) { + endpointList = shuffled(endpointList); + } + const rawAddressList = [].concat(...endpointList.map((endpoint) => endpoint.addresses)); + trace("updateAddressList([" + rawAddressList.map((address) => (0, subchannel_address_1.subchannelAddressToString)(address)) + "])"); + const addressList = interleaveAddressFamilies(rawAddressList); + this.latestAddressList = addressList; + this.latestOptions = options; + this.connectToAddressList(addressList, options); + this.latestResolutionNote = resolutionNote; + if (rawAddressList.length > 0) { + return true; + } else { + this.lastError = "No addresses resolved"; + return false; + } + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && this.latestAddressList) { + this.connectToAddressList(this.latestAddressList, this.latestOptions); + } + } + resetBackoff() {} + destroy() { + this.resetSubchannelList(); + this.removeCurrentPick(); + } + getTypeName() { + return TYPE_NAME; + } + } + exports.PickFirstLoadBalancer = PickFirstLoadBalancer; + var LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); + + class LeafLoadBalancer { + constructor(endpoint, channelControlHelper, options, resolutionNote) { + this.endpoint = endpoint; + this.options = options; + this.resolutionNote = resolutionNote; + this.latestState = connectivity_state_1.ConnectivityState.IDLE; + const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + this.latestState = connectivityState; + this.latestPicker = picker; + channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + }); + this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper); + this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); + } + startConnecting() { + this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote); + } + updateEndpoint(newEndpoint, newOptions) { + this.options = newOptions; + this.endpoint = newEndpoint; + if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { + this.startConnecting(); + } + } + getConnectivityState() { + return this.latestState; + } + getPicker() { + return this.latestPicker; + } + getEndpoint() { + return this.endpoint; + } + exitIdle() { + this.pickFirstBalancer.exitIdle(); + } + destroy() { + this.pickFirstBalancer.destroy(); + } + } + exports.LeafLoadBalancer = LeafLoadBalancer; + function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); + (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); + } +}); + +// node_modules/@grpc/grpc-js/build/src/certificate-provider.js +var require_certificate_provider = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileWatcherCertificateProvider = undefined; + var fs = __require("fs"); + var logging = require_logging(); + var constants_1 = require_constants2(); + var util_1 = __require("util"); + var TRACER_NAME = "certificate_provider"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var readFilePromise = (0, util_1.promisify)(fs.readFile); + + class FileWatcherCertificateProvider { + constructor(config) { + this.config = config; + this.refreshTimer = null; + this.fileResultPromise = null; + this.latestCaUpdate = undefined; + this.caListeners = new Set; + this.latestIdentityUpdate = undefined; + this.identityListeners = new Set; + this.lastUpdateTime = null; + if (config.certificateFile === undefined !== (config.privateKeyFile === undefined)) { + throw new Error("certificateFile and privateKeyFile must be set or unset together"); + } + if (config.certificateFile === undefined && config.caCertificateFile === undefined) { + throw new Error("At least one of certificateFile and caCertificateFile must be set"); + } + trace("File watcher constructed with config " + JSON.stringify(config)); + } + updateCertificates() { + if (this.fileResultPromise) { + return; + } + this.fileResultPromise = Promise.allSettled([ + this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), + this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), + this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() + ]); + this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { + if (!this.refreshTimer) { + return; + } + trace("File watcher read certificates certificate " + certificateResult.status + ", privateKey " + privateKeyResult.status + ", CA certificate " + caCertificateResult.status); + this.lastUpdateTime = new Date; + this.fileResultPromise = null; + if (certificateResult.status === "fulfilled" && privateKeyResult.status === "fulfilled") { + this.latestIdentityUpdate = { + certificate: certificateResult.value, + privateKey: privateKeyResult.value + }; + } else { + this.latestIdentityUpdate = null; + } + if (caCertificateResult.status === "fulfilled") { + this.latestCaUpdate = { + caCertificate: caCertificateResult.value + }; + } else { + this.latestCaUpdate = null; + } + for (const listener of this.identityListeners) { + listener(this.latestIdentityUpdate); + } + for (const listener of this.caListeners) { + listener(this.latestCaUpdate); + } + }); + trace("File watcher initiated certificate update"); + } + maybeStartWatchingFiles() { + if (!this.refreshTimer) { + const timeSinceLastUpdate = this.lastUpdateTime ? new Date().getTime() - this.lastUpdateTime.getTime() : Infinity; + if (timeSinceLastUpdate > this.config.refreshIntervalMs) { + this.updateCertificates(); + } + if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { + this.latestCaUpdate = undefined; + this.latestIdentityUpdate = undefined; + } + this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); + trace("File watcher started watching"); + } + } + maybeStopWatchingFiles() { + if (this.caListeners.size === 0 && this.identityListeners.size === 0) { + this.fileResultPromise = null; + if (this.refreshTimer) { + clearInterval(this.refreshTimer); + this.refreshTimer = null; + } + } + } + addCaCertificateListener(listener) { + this.caListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestCaUpdate !== undefined) { + process.nextTick(listener, this.latestCaUpdate); + } + } + removeCaCertificateListener(listener) { + this.caListeners.delete(listener); + this.maybeStopWatchingFiles(); + } + addIdentityCertificateListener(listener) { + this.identityListeners.add(listener); + this.maybeStartWatchingFiles(); + if (this.latestIdentityUpdate !== undefined) { + process.nextTick(listener, this.latestIdentityUpdate); + } + } + removeIdentityCertificateListener(listener) { + this.identityListeners.delete(listener); + this.maybeStopWatchingFiles(); + } + } + exports.FileWatcherCertificateProvider = FileWatcherCertificateProvider; +}); + +// node_modules/@grpc/grpc-js/build/src/experimental.js +var require_experimental = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports.createCertificateProviderChannelCredentials = exports.FileWatcherCertificateProvider = exports.createCertificateProviderServerCredentials = exports.createServerCredentialsWithInterceptors = exports.BaseSubchannelWrapper = exports.registerAdminService = exports.FilterStackFactory = exports.BaseFilter = exports.statusOrFromError = exports.statusOrFromValue = exports.PickResultType = exports.QueuePicker = exports.UnavailablePicker = exports.ChildLoadBalancerHandler = exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.subchannelAddressToString = exports.LeafLoadBalancer = exports.isLoadBalancerNameRegistered = exports.parseLoadBalancingConfig = exports.selectLbConfigFromList = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = exports.BackoffTimeout = exports.parseDuration = exports.durationToMs = exports.splitHostPort = exports.uriToString = exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports.createResolver = exports.registerResolver = exports.log = exports.trace = undefined; + var logging_1 = require_logging(); + Object.defineProperty(exports, "trace", { enumerable: true, get: function() { + return logging_1.trace; + } }); + Object.defineProperty(exports, "log", { enumerable: true, get: function() { + return logging_1.log; + } }); + var resolver_1 = require_resolver(); + Object.defineProperty(exports, "registerResolver", { enumerable: true, get: function() { + return resolver_1.registerResolver; + } }); + Object.defineProperty(exports, "createResolver", { enumerable: true, get: function() { + return resolver_1.createResolver; + } }); + Object.defineProperty(exports, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", { enumerable: true, get: function() { + return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY; + } }); + var uri_parser_1 = require_uri_parser(); + Object.defineProperty(exports, "uriToString", { enumerable: true, get: function() { + return uri_parser_1.uriToString; + } }); + Object.defineProperty(exports, "splitHostPort", { enumerable: true, get: function() { + return uri_parser_1.splitHostPort; + } }); + var duration_1 = require_duration(); + Object.defineProperty(exports, "durationToMs", { enumerable: true, get: function() { + return duration_1.durationToMs; + } }); + Object.defineProperty(exports, "parseDuration", { enumerable: true, get: function() { + return duration_1.parseDuration; + } }); + var backoff_timeout_1 = require_backoff_timeout(); + Object.defineProperty(exports, "BackoffTimeout", { enumerable: true, get: function() { + return backoff_timeout_1.BackoffTimeout; + } }); + var load_balancer_1 = require_load_balancer(); + Object.defineProperty(exports, "createChildChannelControlHelper", { enumerable: true, get: function() { + return load_balancer_1.createChildChannelControlHelper; + } }); + Object.defineProperty(exports, "registerLoadBalancerType", { enumerable: true, get: function() { + return load_balancer_1.registerLoadBalancerType; + } }); + Object.defineProperty(exports, "selectLbConfigFromList", { enumerable: true, get: function() { + return load_balancer_1.selectLbConfigFromList; + } }); + Object.defineProperty(exports, "parseLoadBalancingConfig", { enumerable: true, get: function() { + return load_balancer_1.parseLoadBalancingConfig; + } }); + Object.defineProperty(exports, "isLoadBalancerNameRegistered", { enumerable: true, get: function() { + return load_balancer_1.isLoadBalancerNameRegistered; + } }); + var load_balancer_pick_first_1 = require_load_balancer_pick_first(); + Object.defineProperty(exports, "LeafLoadBalancer", { enumerable: true, get: function() { + return load_balancer_pick_first_1.LeafLoadBalancer; + } }); + var subchannel_address_1 = require_subchannel_address(); + Object.defineProperty(exports, "subchannelAddressToString", { enumerable: true, get: function() { + return subchannel_address_1.subchannelAddressToString; + } }); + Object.defineProperty(exports, "endpointToString", { enumerable: true, get: function() { + return subchannel_address_1.endpointToString; + } }); + Object.defineProperty(exports, "endpointHasAddress", { enumerable: true, get: function() { + return subchannel_address_1.endpointHasAddress; + } }); + Object.defineProperty(exports, "EndpointMap", { enumerable: true, get: function() { + return subchannel_address_1.EndpointMap; + } }); + var load_balancer_child_handler_1 = require_load_balancer_child_handler(); + Object.defineProperty(exports, "ChildLoadBalancerHandler", { enumerable: true, get: function() { + return load_balancer_child_handler_1.ChildLoadBalancerHandler; + } }); + var picker_1 = require_picker(); + Object.defineProperty(exports, "UnavailablePicker", { enumerable: true, get: function() { + return picker_1.UnavailablePicker; + } }); + Object.defineProperty(exports, "QueuePicker", { enumerable: true, get: function() { + return picker_1.QueuePicker; + } }); + Object.defineProperty(exports, "PickResultType", { enumerable: true, get: function() { + return picker_1.PickResultType; + } }); + var call_interface_1 = require_call_interface(); + Object.defineProperty(exports, "statusOrFromValue", { enumerable: true, get: function() { + return call_interface_1.statusOrFromValue; + } }); + Object.defineProperty(exports, "statusOrFromError", { enumerable: true, get: function() { + return call_interface_1.statusOrFromError; + } }); + var filter_1 = require_filter(); + Object.defineProperty(exports, "BaseFilter", { enumerable: true, get: function() { + return filter_1.BaseFilter; + } }); + var filter_stack_1 = require_filter_stack(); + Object.defineProperty(exports, "FilterStackFactory", { enumerable: true, get: function() { + return filter_stack_1.FilterStackFactory; + } }); + var admin_1 = require_admin(); + Object.defineProperty(exports, "registerAdminService", { enumerable: true, get: function() { + return admin_1.registerAdminService; + } }); + var subchannel_interface_1 = require_subchannel_interface(); + Object.defineProperty(exports, "BaseSubchannelWrapper", { enumerable: true, get: function() { + return subchannel_interface_1.BaseSubchannelWrapper; + } }); + var server_credentials_1 = require_server_credentials(); + Object.defineProperty(exports, "createServerCredentialsWithInterceptors", { enumerable: true, get: function() { + return server_credentials_1.createServerCredentialsWithInterceptors; + } }); + Object.defineProperty(exports, "createCertificateProviderServerCredentials", { enumerable: true, get: function() { + return server_credentials_1.createCertificateProviderServerCredentials; + } }); + var certificate_provider_1 = require_certificate_provider(); + Object.defineProperty(exports, "FileWatcherCertificateProvider", { enumerable: true, get: function() { + return certificate_provider_1.FileWatcherCertificateProvider; + } }); + var channel_credentials_1 = require_channel_credentials(); + Object.defineProperty(exports, "createCertificateProviderChannelCredentials", { enumerable: true, get: function() { + return channel_credentials_1.createCertificateProviderChannelCredentials; + } }); + var internal_channel_1 = require_internal_channel(); + Object.defineProperty(exports, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", { enumerable: true, get: function() { + return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX; + } }); +}); + +// node_modules/@grpc/grpc-js/build/src/resolver-uds.js +var require_resolver_uds = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.setup = setup; + var resolver_1 = require_resolver(); + var call_interface_1 = require_call_interface(); + + class UdsResolver { + constructor(target, listener, channelOptions) { + this.listener = listener; + this.hasReturnedResult = false; + this.endpoints = []; + let path; + if (target.authority === "") { + path = "/" + target.path; + } else { + path = target.path; + } + this.endpoints = [{ addresses: [{ path }] }]; + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ""); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return "localhost"; + } + } + function setup() { + (0, resolver_1.registerResolver)("unix", UdsResolver); + } +}); + +// node_modules/@grpc/grpc-js/build/src/resolver-ip.js +var require_resolver_ip = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.setup = setup; + var net_1 = __require("net"); + var call_interface_1 = require_call_interface(); + var constants_1 = require_constants2(); + var metadata_1 = require_metadata(); + var resolver_1 = require_resolver(); + var subchannel_address_1 = require_subchannel_address(); + var uri_parser_1 = require_uri_parser(); + var logging = require_logging(); + var TRACER_NAME = "ip_resolver"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var IPV4_SCHEME = "ipv4"; + var IPV6_SCHEME = "ipv6"; + var DEFAULT_PORT = 443; + + class IpResolver { + constructor(target, listener, channelOptions) { + var _a; + this.listener = listener; + this.endpoints = []; + this.error = null; + this.hasReturnedResult = false; + trace("Resolver constructed for target " + (0, uri_parser_1.uriToString)(target)); + const addresses = []; + if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Unrecognized scheme ${target.scheme} in IP resolver`, + metadata: new metadata_1.Metadata + }; + return; + } + const pathList = target.path.split(","); + for (const path of pathList) { + const hostPort = (0, uri_parser_1.splitHostPort)(path); + if (hostPort === null) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata + }; + return; + } + if (target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host) || target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host)) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata + }; + return; + } + addresses.push({ + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== undefined ? _a : DEFAULT_PORT + }); + } + this.endpoints = addresses.map((address) => ({ addresses: [address] })); + trace("Parsed " + target.scheme + " address list " + addresses.map(subchannel_address_1.subchannelAddressToString)); + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(() => { + if (this.error) { + this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, ""); + } else { + this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ""); + } + }); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return target.path.split(",")[0]; + } + } + function setup() { + (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); + (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js +var require_load_balancer_round_robin = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RoundRobinLoadBalancer = undefined; + exports.setup = setup; + var load_balancer_1 = require_load_balancer(); + var connectivity_state_1 = require_connectivity_state(); + var picker_1 = require_picker(); + var logging = require_logging(); + var constants_1 = require_constants2(); + var subchannel_address_1 = require_subchannel_address(); + var load_balancer_pick_first_1 = require_load_balancer_pick_first(); + var TRACER_NAME = "round_robin"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "round_robin"; + + class RoundRobinLoadBalancingConfig { + getLoadBalancerName() { + return TYPE_NAME; + } + constructor() {} + toJsonObject() { + return { + [TYPE_NAME]: {} + }; + } + static createFromJson(obj) { + return new RoundRobinLoadBalancingConfig; + } + } + + class RoundRobinPicker { + constructor(children, nextIndex = 0) { + this.children = children; + this.nextIndex = nextIndex; + } + pick(pickArgs) { + const childPicker = this.children[this.nextIndex].picker; + this.nextIndex = (this.nextIndex + 1) % this.children.length; + return childPicker.pick(pickArgs); + } + peekNextEndpoint() { + return this.children[this.nextIndex].endpoint; + } + } + function rotateArray(list, startIndex) { + return [...list.slice(startIndex), ...list.slice(0, startIndex)]; + } + + class RoundRobinLoadBalancer { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.children = []; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.currentReadyPicker = null; + this.updatesPaused = false; + this.lastError = null; + this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + } + }); + } + countChildrenWithState(state) { + return this.children.filter((child) => child.getConnectivityState() === state).length; + } + calculateAndUpdateState() { + if (this.updatesPaused) { + return; + } + if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { + const readyChildren = this.children.filter((child) => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); + let index = 0; + if (this.currentReadyPicker !== null) { + const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); + index = readyChildren.findIndex((child) => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); + if (index < 0) { + index = 0; + } + } + this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map((child) => ({ + endpoint: child.getEndpoint(), + picker: child.getPicker() + })), index), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { + const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } + for (const child of this.children) { + if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.currentReadyPicker = picker; + } else { + this.currentReadyPicker = null; + } + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + resetSubchannelList() { + for (const child of this.children) { + child.destroy(); + } + this.children = []; + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.length === 0) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + const startIndex = Math.random() * maybeEndpointList.value.length | 0; + const endpointList = rotateArray(maybeEndpointList.value, startIndex); + this.resetSubchannelList(); + if (endpointList.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); + } + trace("Connect to endpoint list " + endpointList.map(subchannel_address_1.endpointToString)); + this.updatesPaused = true; + this.children = endpointList.map((endpoint) => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, options, resolutionNote)); + for (const child of this.children) { + child.startConnecting(); + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + return true; + } + exitIdle() {} + resetBackoff() {} + destroy() { + this.resetSubchannelList(); + } + getTypeName() { + return TYPE_NAME; + } + } + exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer; + function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); + } +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js +var require_load_balancer_outlier_detection = __commonJS((exports) => { + var _a; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OutlierDetectionLoadBalancer = exports.OutlierDetectionLoadBalancingConfig = undefined; + exports.setup = setup; + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants2(); + var duration_1 = require_duration(); + var experimental_1 = require_experimental(); + var load_balancer_1 = require_load_balancer(); + var load_balancer_child_handler_1 = require_load_balancer_child_handler(); + var picker_1 = require_picker(); + var subchannel_address_1 = require_subchannel_address(); + var subchannel_interface_1 = require_subchannel_interface(); + var logging = require_logging(); + var TRACER_NAME = "outlier_detection"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "outlier_detection"; + var OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== undefined ? _a : "true") === "true"; + var defaultSuccessRateEjectionConfig = { + stdev_factor: 1900, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 100 + }; + var defaultFailurePercentageEjectionConfig = { + threshold: 85, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 50 + }; + function validateFieldType(obj, fieldName, expectedType, objectName) { + if (fieldName in obj && obj[fieldName] !== undefined && typeof obj[fieldName] !== expectedType) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); + } + } + function validatePositiveDuration(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + if (fieldName in obj && obj[fieldName] !== undefined) { + if (!(0, duration_1.isDuration)(obj[fieldName])) { + throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); + } + if (!(obj[fieldName].seconds >= 0 && obj[fieldName].seconds <= 315576000000 && obj[fieldName].nanos >= 0 && obj[fieldName].nanos <= 999999999)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); + } + } + } + function validatePercentage(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + validateFieldType(obj, fieldName, "number", objectName); + if (fieldName in obj && obj[fieldName] !== undefined && !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); + } + } + + class OutlierDetectionLoadBalancingConfig { + constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { + this.childPolicy = childPolicy; + if (childPolicy.getLoadBalancerName() === "pick_first") { + throw new Error("outlier_detection LB policy cannot have a pick_first child policy"); + } + this.intervalMs = intervalMs !== null && intervalMs !== undefined ? intervalMs : 1e4; + this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== undefined ? baseEjectionTimeMs : 30000; + this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== undefined ? maxEjectionTimeMs : 300000; + this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== undefined ? maxEjectionPercent : 10; + this.successRateEjection = successRateEjection ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; + this.failurePercentageEjection = failurePercentageEjection ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + var _a2, _b; + return { + outlier_detection: { + interval: (0, duration_1.msToDuration)(this.intervalMs), + base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), + max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), + max_ejection_percent: this.maxEjectionPercent, + success_rate_ejection: (_a2 = this.successRateEjection) !== null && _a2 !== undefined ? _a2 : undefined, + failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== undefined ? _b : undefined, + child_policy: [this.childPolicy.toJsonObject()] + } + }; + } + getIntervalMs() { + return this.intervalMs; + } + getBaseEjectionTimeMs() { + return this.baseEjectionTimeMs; + } + getMaxEjectionTimeMs() { + return this.maxEjectionTimeMs; + } + getMaxEjectionPercent() { + return this.maxEjectionPercent; + } + getSuccessRateEjectionConfig() { + return this.successRateEjection; + } + getFailurePercentageEjectionConfig() { + return this.failurePercentageEjection; + } + getChildPolicy() { + return this.childPolicy; + } + static createFromJson(obj) { + var _a2; + validatePositiveDuration(obj, "interval"); + validatePositiveDuration(obj, "base_ejection_time"); + validatePositiveDuration(obj, "max_ejection_time"); + validatePercentage(obj, "max_ejection_percent"); + if ("success_rate_ejection" in obj && obj.success_rate_ejection !== undefined) { + if (typeof obj.success_rate_ejection !== "object") { + throw new Error("outlier detection config success_rate_ejection must be an object"); + } + validateFieldType(obj.success_rate_ejection, "stdev_factor", "number", "success_rate_ejection"); + validatePercentage(obj.success_rate_ejection, "enforcement_percentage", "success_rate_ejection"); + validateFieldType(obj.success_rate_ejection, "minimum_hosts", "number", "success_rate_ejection"); + validateFieldType(obj.success_rate_ejection, "request_volume", "number", "success_rate_ejection"); + } + if ("failure_percentage_ejection" in obj && obj.failure_percentage_ejection !== undefined) { + if (typeof obj.failure_percentage_ejection !== "object") { + throw new Error("outlier detection config failure_percentage_ejection must be an object"); + } + validatePercentage(obj.failure_percentage_ejection, "threshold", "failure_percentage_ejection"); + validatePercentage(obj.failure_percentage_ejection, "enforcement_percentage", "failure_percentage_ejection"); + validateFieldType(obj.failure_percentage_ejection, "minimum_hosts", "number", "failure_percentage_ejection"); + validateFieldType(obj.failure_percentage_ejection, "request_volume", "number", "failure_percentage_ejection"); + } + if (!("child_policy" in obj) || !Array.isArray(obj.child_policy)) { + throw new Error("outlier detection config child_policy must be an array"); + } + const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); + if (!childPolicy) { + throw new Error("outlier detection config child_policy: no valid recognized policy found"); + } + return new OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a2 = obj.max_ejection_percent) !== null && _a2 !== undefined ? _a2 : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); + } + } + exports.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; + + class OutlierDetectionSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, mapEntry) { + super(childSubchannel); + this.mapEntry = mapEntry; + this.refCount = 0; + } + ref() { + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + if (this.mapEntry) { + const index = this.mapEntry.subchannelWrappers.indexOf(this); + if (index >= 0) { + this.mapEntry.subchannelWrappers.splice(index, 1); + } + } + } + } + eject() { + this.setHealthy(false); + } + uneject() { + this.setHealthy(true); + } + getMapEntry() { + return this.mapEntry; + } + getWrappedSubchannel() { + return this.child; + } + } + function createEmptyBucket() { + return { + success: 0, + failure: 0 + }; + } + + class CallCounter { + constructor() { + this.activeBucket = createEmptyBucket(); + this.inactiveBucket = createEmptyBucket(); + } + addSuccess() { + this.activeBucket.success += 1; + } + addFailure() { + this.activeBucket.failure += 1; + } + switchBuckets() { + this.inactiveBucket = this.activeBucket; + this.activeBucket = createEmptyBucket(); + } + getLastSuccesses() { + return this.inactiveBucket.success; + } + getLastFailures() { + return this.inactiveBucket.failure; + } + } + + class OutlierDetectionPicker { + constructor(wrappedPicker, countCalls) { + this.wrappedPicker = wrappedPicker; + this.countCalls = countCalls; + } + pick(pickArgs) { + const wrappedPick = this.wrappedPicker.pick(pickArgs); + if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { + const subchannelWrapper = wrappedPick.subchannel; + const mapEntry = subchannelWrapper.getMapEntry(); + if (mapEntry) { + let onCallEnded = wrappedPick.onCallEnded; + if (this.countCalls) { + onCallEnded = (statusCode, details, metadata) => { + var _a2; + if (statusCode === constants_1.Status.OK) { + mapEntry.counter.addSuccess(); + } else { + mapEntry.counter.addFailure(); + } + (_a2 = wrappedPick.onCallEnded) === null || _a2 === undefined || _a2.call(wrappedPick, statusCode, details, metadata); + }; + } + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded }); + } else { + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); + } + } else { + return wrappedPick; + } + } + } + + class OutlierDetectionLoadBalancer { + constructor(channelControlHelper) { + this.entryMap = new subchannel_address_1.EndpointMap; + this.latestConfig = null; + this.timerStartTime = null; + this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); + const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); + if ((mapEntry === null || mapEntry === undefined ? undefined : mapEntry.currentEjectionTimestamp) !== null) { + subchannelWrapper.eject(); + } + mapEntry === null || mapEntry === undefined || mapEntry.subchannelWrappers.push(subchannelWrapper); + return subchannelWrapper; + }, + updateState: (connectivityState, picker, errorMessage) => { + if (connectivityState === connectivity_state_1.ConnectivityState.READY) { + channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage); + } else { + channelControlHelper.updateState(connectivityState, picker, errorMessage); + } + } + })); + this.ejectionTimer = setInterval(() => {}, 0); + clearInterval(this.ejectionTimer); + } + isCountingEnabled() { + return this.latestConfig !== null && (this.latestConfig.getSuccessRateEjectionConfig() !== null || this.latestConfig.getFailurePercentageEjectionConfig() !== null); + } + getCurrentEjectionPercent() { + let ejectionCount = 0; + for (const mapEntry of this.entryMap.values()) { + if (mapEntry.currentEjectionTimestamp !== null) { + ejectionCount += 1; + } + } + return ejectionCount * 100 / this.entryMap.size; + } + runSuccessRateCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); + if (!successRateConfig) { + return; + } + trace("Running success rate check"); + const targetRequestVolume = successRateConfig.request_volume; + let addresesWithTargetVolume = 0; + const successRates = []; + for (const [endpoint, mapEntry] of this.entryMap.entries()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace("Stats for " + (0, subchannel_address_1.endpointToString)(endpoint) + ": successes=" + successes + " failures=" + failures + " targetRequestVolume=" + targetRequestVolume); + if (successes + failures >= targetRequestVolume) { + addresesWithTargetVolume += 1; + successRates.push(successes / (successes + failures)); + } + } + trace("Found " + addresesWithTargetVolume + " success rate candidates; currentEjectionPercent=" + this.getCurrentEjectionPercent() + " successRates=[" + successRates + "]"); + if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { + return; + } + const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; + let successRateDeviationSum = 0; + for (const rate of successRates) { + const deviation = rate - successRateMean; + successRateDeviationSum += deviation * deviation; + } + const successRateVariance = successRateDeviationSum / successRates.length; + const successRateStdev = Math.sqrt(successRateVariance); + const ejectionThreshold = successRateMean - successRateStdev * (successRateConfig.stdev_factor / 1000); + trace("stdev=" + successRateStdev + " ejectionThreshold=" + ejectionThreshold); + for (const [address, mapEntry] of this.entryMap.entries()) { + if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) { + break; + } + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures < targetRequestVolume) { + continue; + } + const successRate = successes / (successes + failures); + trace("Checking candidate " + address + " successRate=" + successRate); + if (successRate < ejectionThreshold) { + const randomNumber = Math.random() * 100; + trace("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + successRateConfig.enforcement_percentage); + if (randomNumber < successRateConfig.enforcement_percentage) { + trace("Ejecting candidate " + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + runFailurePercentageCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); + if (!failurePercentageConfig) { + return; + } + trace("Running failure percentage check. threshold=" + failurePercentageConfig.threshold + " request volume threshold=" + failurePercentageConfig.request_volume); + let addressesWithTargetVolume = 0; + for (const mapEntry of this.entryMap.values()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures >= failurePercentageConfig.request_volume) { + addressesWithTargetVolume += 1; + } + } + if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { + return; + } + for (const [address, mapEntry] of this.entryMap.entries()) { + if (this.getCurrentEjectionPercent() >= this.latestConfig.getMaxEjectionPercent()) { + break; + } + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace("Candidate successes=" + successes + " failures=" + failures); + if (successes + failures < failurePercentageConfig.request_volume) { + continue; + } + const failurePercentage = failures * 100 / (failures + successes); + if (failurePercentage > failurePercentageConfig.threshold) { + const randomNumber = Math.random() * 100; + trace("Candidate " + address + " randomNumber=" + randomNumber + " enforcement_percentage=" + failurePercentageConfig.enforcement_percentage); + if (randomNumber < failurePercentageConfig.enforcement_percentage) { + trace("Ejecting candidate " + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + eject(mapEntry, ejectionTimestamp) { + mapEntry.currentEjectionTimestamp = new Date; + mapEntry.ejectionTimeMultiplier += 1; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.eject(); + } + } + uneject(mapEntry) { + mapEntry.currentEjectionTimestamp = null; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.uneject(); + } + } + switchAllBuckets() { + for (const mapEntry of this.entryMap.values()) { + mapEntry.counter.switchBuckets(); + } + } + startTimer(delayMs) { + var _a2, _b; + this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); + (_b = (_a2 = this.ejectionTimer).unref) === null || _b === undefined || _b.call(_a2); + } + runChecks() { + const ejectionTimestamp = new Date; + trace("Ejection timer running"); + this.switchAllBuckets(); + if (!this.latestConfig) { + return; + } + this.timerStartTime = ejectionTimestamp; + this.startTimer(this.latestConfig.getIntervalMs()); + this.runSuccessRateCheck(ejectionTimestamp); + this.runFailurePercentageCheck(ejectionTimestamp); + for (const [address, mapEntry] of this.entryMap.entries()) { + if (mapEntry.currentEjectionTimestamp === null) { + if (mapEntry.ejectionTimeMultiplier > 0) { + mapEntry.ejectionTimeMultiplier -= 1; + } + } else { + const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); + const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); + const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); + returnTime.setMilliseconds(returnTime.getMilliseconds() + Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); + if (returnTime < new Date) { + trace("Unejecting " + address); + this.uneject(mapEntry); + } + } + } + } + updateAddressList(endpointList, lbConfig, options, resolutionNote) { + if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { + return false; + } + trace("Received update with config: " + JSON.stringify(lbConfig.toJsonObject(), undefined, 2)); + if (endpointList.ok) { + for (const endpoint of endpointList.value) { + if (!this.entryMap.has(endpoint)) { + trace("Adding map entry for " + (0, subchannel_address_1.endpointToString)(endpoint)); + this.entryMap.set(endpoint, { + counter: new CallCounter, + currentEjectionTimestamp: null, + ejectionTimeMultiplier: 0, + subchannelWrappers: [] + }); + } + } + this.entryMap.deleteMissing(endpointList.value); + } + const childPolicy = lbConfig.getChildPolicy(); + this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); + if (lbConfig.getSuccessRateEjectionConfig() || lbConfig.getFailurePercentageEjectionConfig()) { + if (this.timerStartTime) { + trace("Previous timer existed. Replacing timer"); + clearTimeout(this.ejectionTimer); + const remainingDelay = lbConfig.getIntervalMs() - (new Date().getTime() - this.timerStartTime.getTime()); + this.startTimer(remainingDelay); + } else { + trace("Starting new timer"); + this.timerStartTime = new Date; + this.startTimer(lbConfig.getIntervalMs()); + this.switchAllBuckets(); + } + } else { + trace("Counting disabled. Cancelling timer."); + this.timerStartTime = null; + clearTimeout(this.ejectionTimer); + for (const mapEntry of this.entryMap.values()) { + this.uneject(mapEntry); + mapEntry.ejectionTimeMultiplier = 0; + } + } + this.latestConfig = lbConfig; + return true; + } + exitIdle() { + this.childBalancer.exitIdle(); + } + resetBackoff() { + this.childBalancer.resetBackoff(); + } + destroy() { + clearTimeout(this.ejectionTimer); + this.childBalancer.destroy(); + } + getTypeName() { + return TYPE_NAME; + } + } + exports.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; + function setup() { + if (OUTLIER_DETECTION_ENABLED) { + (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); + } + } +}); + +// node_modules/@grpc/grpc-js/build/src/priority-queue.js +var require_priority_queue = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PriorityQueue = undefined; + var top = 0; + var parent = (i) => Math.floor(i / 2); + var left = (i) => i * 2 + 1; + var right = (i) => i * 2 + 2; + + class PriorityQueue { + constructor(comparator = (a, b) => a > b) { + this.comparator = comparator; + this.heap = []; + } + size() { + return this.heap.length; + } + isEmpty() { + return this.size() == 0; + } + peek() { + return this.heap[top]; + } + push(...values) { + values.forEach((value) => { + this.heap.push(value); + this.siftUp(); + }); + return this.size(); + } + pop() { + const poppedValue = this.peek(); + const bottom = this.size() - 1; + if (bottom > top) { + this.swap(top, bottom); + } + this.heap.pop(); + this.siftDown(); + return poppedValue; + } + replace(value) { + const replacedValue = this.peek(); + this.heap[top] = value; + this.siftDown(); + return replacedValue; + } + greater(i, j) { + return this.comparator(this.heap[i], this.heap[j]); + } + swap(i, j) { + [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; + } + siftUp() { + let node = this.size() - 1; + while (node > top && this.greater(node, parent(node))) { + this.swap(node, parent(node)); + node = parent(node); + } + } + siftDown() { + let node = top; + while (left(node) < this.size() && this.greater(left(node), node) || right(node) < this.size() && this.greater(right(node), node)) { + let maxChild = right(node) < this.size() && this.greater(right(node), left(node)) ? right(node) : left(node); + this.swap(node, maxChild); + node = maxChild; + } + } + } + exports.PriorityQueue = PriorityQueue; +}); + +// node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js +var require_load_balancer_weighted_round_robin = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WeightedRoundRobinLoadBalancingConfig = undefined; + exports.setup = setup; + var connectivity_state_1 = require_connectivity_state(); + var constants_1 = require_constants2(); + var duration_1 = require_duration(); + var load_balancer_1 = require_load_balancer(); + var load_balancer_pick_first_1 = require_load_balancer_pick_first(); + var logging = require_logging(); + var orca_1 = require_orca(); + var picker_1 = require_picker(); + var priority_queue_1 = require_priority_queue(); + var subchannel_address_1 = require_subchannel_address(); + var TRACER_NAME = "weighted_round_robin"; + function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); + } + var TYPE_NAME = "weighted_round_robin"; + var DEFAULT_OOB_REPORTING_PERIOD_MS = 1e4; + var DEFAULT_BLACKOUT_PERIOD_MS = 1e4; + var DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 60000; + var DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1000; + var DEFAULT_ERROR_UTILIZATION_PENALTY = 1; + function validateFieldType(obj, fieldName, expectedType) { + if (fieldName in obj && obj[fieldName] !== undefined && typeof obj[fieldName] !== expectedType) { + throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); + } + } + function parseDurationField(obj, fieldName) { + if (fieldName in obj && obj[fieldName] !== undefined && obj[fieldName] !== null) { + let durationObject; + if ((0, duration_1.isDuration)(obj[fieldName])) { + durationObject = obj[fieldName]; + } else if ((0, duration_1.isDurationMessage)(obj[fieldName])) { + durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]); + } else if (typeof obj[fieldName] === "string") { + const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]); + if (!parsedDuration) { + throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); + } + durationObject = parsedDuration; + } else { + throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); + } + return (0, duration_1.durationToMs)(durationObject); + } + return null; + } + + class WeightedRoundRobinLoadBalancingConfig { + constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) { + this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== undefined ? enableOobLoadReport : false; + this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== undefined ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS; + this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== undefined ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS; + this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== undefined ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; + this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== undefined ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); + this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== undefined ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + return { + enable_oob_load_report: this.enableOobLoadReport, + oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)), + blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)), + weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)), + weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)), + error_utilization_penalty: this.errorUtilizationPenalty + }; + } + static createFromJson(obj) { + validateFieldType(obj, "enable_oob_load_report", "boolean"); + validateFieldType(obj, "error_utilization_penalty", "number"); + if (obj.error_utilization_penalty < 0) { + throw new Error("weighted round robin config error_utilization_penalty < 0"); + } + return new WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, "oob_load_reporting_period"), parseDurationField(obj, "blackout_period"), parseDurationField(obj, "weight_expiration_period"), parseDurationField(obj, "weight_update_period"), obj.error_utilization_penalty); + } + getEnableOobLoadReport() { + return this.enableOobLoadReport; + } + getOobLoadReportingPeriodMs() { + return this.oobLoadReportingPeriodMs; + } + getBlackoutPeriodMs() { + return this.blackoutPeriodMs; + } + getWeightExpirationPeriodMs() { + return this.weightExpirationPeriodMs; + } + getWeightUpdatePeriodMs() { + return this.weightUpdatePeriodMs; + } + getErrorUtilizationPenalty() { + return this.errorUtilizationPenalty; + } + } + exports.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig; + + class WeightedRoundRobinPicker { + constructor(children, metricsHandler) { + this.metricsHandler = metricsHandler; + this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline); + const positiveWeight = children.filter((picker) => picker.weight > 0); + let averageWeight; + if (positiveWeight.length < 2) { + averageWeight = 1; + } else { + let weightSum = 0; + for (const { weight } of positiveWeight) { + weightSum += weight; + } + averageWeight = weightSum / positiveWeight.length; + } + for (const child of children) { + const period = child.weight > 0 ? 1 / child.weight : averageWeight; + this.queue.push({ + endpointName: child.endpointName, + picker: child.picker, + period, + deadline: Math.random() * period + }); + } + } + pick(pickArgs) { + const entry = this.queue.pop(); + this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period })); + const childPick = entry.picker.pick(pickArgs); + if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) { + if (this.metricsHandler) { + return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)((loadReport) => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) }); + } else { + const subchannelWrapper = childPick.subchannel; + return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); + } + } else { + return childPick; + } + } + } + + class WeightedRoundRobinLoadBalancer { + constructor(channelControlHelper) { + this.channelControlHelper = channelControlHelper; + this.latestConfig = null; + this.children = new Map; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.updatesPaused = false; + this.lastError = null; + this.weightUpdateTimer = null; + } + countChildrenWithState(state) { + let count = 0; + for (const entry of this.children.values()) { + if (entry.child.getConnectivityState() === state) { + count += 1; + } + } + return count; + } + updateWeight(entry, loadReport) { + var _a, _b; + const qps = loadReport.rps_fractional; + let utilization = loadReport.application_utilization; + if (utilization > 0 && qps > 0) { + utilization += loadReport.eps / qps * ((_b = (_a = this.latestConfig) === null || _a === undefined ? undefined : _a.getErrorUtilizationPenalty()) !== null && _b !== undefined ? _b : 0); + } + const newWeight = utilization === 0 ? 0 : qps / utilization; + if (newWeight === 0) { + return; + } + const now = new Date; + if (entry.nonEmptySince === null) { + entry.nonEmptySince = now; + } + entry.lastUpdated = now; + entry.weight = newWeight; + } + getWeight(entry) { + if (!this.latestConfig) { + return 0; + } + const now = new Date().getTime(); + if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { + entry.nonEmptySince = null; + return 0; + } + const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); + if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { + return 0; + } + return entry.weight; + } + calculateAndUpdateState() { + if (this.updatesPaused || !this.latestConfig) { + return; + } + if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { + const weightedPickers = []; + for (const [endpoint, entry] of this.children) { + if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { + continue; + } + weightedPickers.push({ + endpointName: endpoint, + picker: entry.child.getPicker(), + weight: this.getWeight(entry) + }); + } + trace("Created picker with weights: " + weightedPickers.map((entry) => entry.endpointName + ":" + entry.weight).join(",")); + let metricsHandler; + if (!this.latestConfig.getEnableOobLoadReport()) { + metricsHandler = (loadReport, endpointName) => { + const childEntry = this.children.get(endpointName); + if (childEntry) { + this.updateWeight(childEntry, loadReport); + } + }; + } else { + metricsHandler = null; + } + this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); + } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { + const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: errorMessage + }), errorMessage); + } else { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); + } + for (const { child } of this.children.values()) { + if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + updateState(newState, picker, errorMessage) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker, errorMessage); + } + updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { + var _a, _b; + if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { + return false; + } + if (!maybeEndpointList.ok) { + if (this.children.size === 0) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); + } + return true; + } + if (maybeEndpointList.value.length === 0) { + const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); + return false; + } + trace("Connect to endpoint list " + maybeEndpointList.value.map(subchannel_address_1.endpointToString)); + const now = new Date; + const seenEndpointNames = new Set; + this.updatesPaused = true; + this.latestConfig = lbConfig; + for (const endpoint of maybeEndpointList.value) { + const name = (0, subchannel_address_1.endpointToString)(endpoint); + seenEndpointNames.add(name); + let entry = this.children.get(name); + if (!entry) { + entry = { + child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, { + updateState: (connectivityState, picker, errorMessage) => { + if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { + this.channelControlHelper.requestReresolution(); + } + if (connectivityState === connectivity_state_1.ConnectivityState.READY) { + entry.nonEmptySince = null; + } + if (errorMessage) { + this.lastError = errorMessage; + } + this.calculateAndUpdateState(); + }, + createSubchannel: (subchannelAddress, subchannelArgs) => { + const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + if (entry === null || entry === undefined ? undefined : entry.oobMetricsListener) { + return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs()); + } else { + return subchannel; + } + } + }), options, resolutionNote), + lastUpdated: now, + nonEmptySince: null, + weight: 0, + oobMetricsListener: null + }; + this.children.set(name, entry); + } + if (lbConfig.getEnableOobLoadReport()) { + entry.oobMetricsListener = (loadReport) => { + this.updateWeight(entry, loadReport); + }; + } else { + entry.oobMetricsListener = null; + } + } + for (const [endpointName, entry] of this.children) { + if (seenEndpointNames.has(endpointName)) { + entry.child.startConnecting(); + } else { + entry.child.destroy(); + this.children.delete(endpointName); + } + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + this.weightUpdateTimer = (_b = (_a = setInterval(() => { + if (this.currentState === connectivity_state_1.ConnectivityState.READY) { + this.calculateAndUpdateState(); + } + }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === undefined ? undefined : _b.call(_a); + return true; + } + exitIdle() {} + resetBackoff() {} + destroy() { + for (const entry of this.children.values()) { + entry.child.destroy(); + } + this.children.clear(); + if (this.weightUpdateTimer) { + clearInterval(this.weightUpdateTimer); + } + } + getTypeName() { + return TYPE_NAME; + } + } + function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig); + } +}); + +// node_modules/@grpc/grpc-js/build/src/index.js +var require_src19 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.experimental = exports.ServerMetricRecorder = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = exports.addAdminServicesToServer = exports.getChannelzHandlers = exports.getChannelzServiceDefinition = exports.InterceptorConfigurationError = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.compressionAlgorithms = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = undefined; + var call_credentials_1 = require_call_credentials(); + Object.defineProperty(exports, "CallCredentials", { enumerable: true, get: function() { + return call_credentials_1.CallCredentials; + } }); + var channel_1 = require_channel(); + Object.defineProperty(exports, "Channel", { enumerable: true, get: function() { + return channel_1.ChannelImplementation; + } }); + var compression_algorithms_1 = require_compression_algorithms(); + Object.defineProperty(exports, "compressionAlgorithms", { enumerable: true, get: function() { + return compression_algorithms_1.CompressionAlgorithms; + } }); + var connectivity_state_1 = require_connectivity_state(); + Object.defineProperty(exports, "connectivityState", { enumerable: true, get: function() { + return connectivity_state_1.ConnectivityState; + } }); + var channel_credentials_1 = require_channel_credentials(); + Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: function() { + return channel_credentials_1.ChannelCredentials; + } }); + var client_1 = require_client(); + Object.defineProperty(exports, "Client", { enumerable: true, get: function() { + return client_1.Client; + } }); + var constants_1 = require_constants2(); + Object.defineProperty(exports, "logVerbosity", { enumerable: true, get: function() { + return constants_1.LogVerbosity; + } }); + Object.defineProperty(exports, "status", { enumerable: true, get: function() { + return constants_1.Status; + } }); + Object.defineProperty(exports, "propagate", { enumerable: true, get: function() { + return constants_1.Propagate; + } }); + var logging = require_logging(); + var make_client_1 = require_make_client(); + Object.defineProperty(exports, "loadPackageDefinition", { enumerable: true, get: function() { + return make_client_1.loadPackageDefinition; + } }); + Object.defineProperty(exports, "makeClientConstructor", { enumerable: true, get: function() { + return make_client_1.makeClientConstructor; + } }); + Object.defineProperty(exports, "makeGenericClientConstructor", { enumerable: true, get: function() { + return make_client_1.makeClientConstructor; + } }); + var metadata_1 = require_metadata(); + Object.defineProperty(exports, "Metadata", { enumerable: true, get: function() { + return metadata_1.Metadata; + } }); + var server_1 = require_server(); + Object.defineProperty(exports, "Server", { enumerable: true, get: function() { + return server_1.Server; + } }); + var server_credentials_1 = require_server_credentials(); + Object.defineProperty(exports, "ServerCredentials", { enumerable: true, get: function() { + return server_credentials_1.ServerCredentials; + } }); + var status_builder_1 = require_status_builder(); + Object.defineProperty(exports, "StatusBuilder", { enumerable: true, get: function() { + return status_builder_1.StatusBuilder; + } }); + exports.credentials = { + combineChannelCredentials: (channelCredentials, ...callCredentials) => { + return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); + }, + combineCallCredentials: (first, ...additional) => { + return additional.reduce((acc, other) => acc.compose(other), first); + }, + createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, + createSsl: channel_credentials_1.ChannelCredentials.createSsl, + createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, + createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, + createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, + createEmpty: call_credentials_1.CallCredentials.createEmpty + }; + var closeClient = (client) => client.close(); + exports.closeClient = closeClient; + var waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); + exports.waitForClientReady = waitForClientReady; + var loadObject = (value, options) => { + throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead"); + }; + exports.loadObject = loadObject; + var load = (filename, format, options) => { + throw new Error("Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead"); + }; + exports.load = load; + var setLogger = (logger) => { + logging.setLogger(logger); + }; + exports.setLogger = setLogger; + var setLogVerbosity = (verbosity) => { + logging.setLoggerVerbosity(verbosity); + }; + exports.setLogVerbosity = setLogVerbosity; + var getClientChannel = (client) => { + return client_1.Client.prototype.getChannel.call(client); + }; + exports.getClientChannel = getClientChannel; + var client_interceptors_1 = require_client_interceptors(); + Object.defineProperty(exports, "ListenerBuilder", { enumerable: true, get: function() { + return client_interceptors_1.ListenerBuilder; + } }); + Object.defineProperty(exports, "RequesterBuilder", { enumerable: true, get: function() { + return client_interceptors_1.RequesterBuilder; + } }); + Object.defineProperty(exports, "InterceptingCall", { enumerable: true, get: function() { + return client_interceptors_1.InterceptingCall; + } }); + Object.defineProperty(exports, "InterceptorConfigurationError", { enumerable: true, get: function() { + return client_interceptors_1.InterceptorConfigurationError; + } }); + var channelz_1 = require_channelz(); + Object.defineProperty(exports, "getChannelzServiceDefinition", { enumerable: true, get: function() { + return channelz_1.getChannelzServiceDefinition; + } }); + Object.defineProperty(exports, "getChannelzHandlers", { enumerable: true, get: function() { + return channelz_1.getChannelzHandlers; + } }); + var admin_1 = require_admin(); + Object.defineProperty(exports, "addAdminServicesToServer", { enumerable: true, get: function() { + return admin_1.addAdminServicesToServer; + } }); + var server_interceptors_1 = require_server_interceptors(); + Object.defineProperty(exports, "ServerListenerBuilder", { enumerable: true, get: function() { + return server_interceptors_1.ServerListenerBuilder; + } }); + Object.defineProperty(exports, "ResponderBuilder", { enumerable: true, get: function() { + return server_interceptors_1.ResponderBuilder; + } }); + Object.defineProperty(exports, "ServerInterceptingCall", { enumerable: true, get: function() { + return server_interceptors_1.ServerInterceptingCall; + } }); + var orca_1 = require_orca(); + Object.defineProperty(exports, "ServerMetricRecorder", { enumerable: true, get: function() { + return orca_1.ServerMetricRecorder; + } }); + var experimental = require_experimental(); + exports.experimental = experimental; + var resolver_dns = require_resolver_dns(); + var resolver_uds = require_resolver_uds(); + var resolver_ip = require_resolver_ip(); + var load_balancer_pick_first = require_load_balancer_pick_first(); + var load_balancer_round_robin = require_load_balancer_round_robin(); + var load_balancer_outlier_detection = require_load_balancer_outlier_detection(); + var load_balancer_weighted_round_robin = require_load_balancer_weighted_round_robin(); + var channelz = require_channelz(); + (() => { + resolver_dns.setup(); + resolver_uds.setup(); + resolver_ip.setup(); + load_balancer_pick_first.setup(); + load_balancer_round_robin.setup(); + load_balancer_outlier_detection.setup(); + load_balancer_weighted_round_robin.setup(); + channelz.setup(); + })(); +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js +var require_create_service_client_constructor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createServiceClientConstructor = undefined; + var grpc = require_src19(); + function createServiceClientConstructor(path, name) { + const serviceDefinition = { + export: { + path, + requestStream: false, + responseStream: false, + requestSerialize: (arg) => { + return arg; + }, + requestDeserialize: (arg) => { + return arg; + }, + responseSerialize: (arg) => { + return arg; + }, + responseDeserialize: (arg) => { + return arg; + } + } + }; + return grpc.makeGenericClientConstructor(serviceDefinition, name); + } + exports.createServiceClientConstructor = createServiceClientConstructor; +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js +var require_grpc_exporter_transport = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createOtlpGrpcExporterTransport = exports.GrpcExporterTransport = exports.createEmptyMetadata = exports.createSslCredentials = exports.createInsecureCredentials = undefined; + var version_1 = require_version8(); + var DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`; + function createUserAgent(userAgent) { + if (userAgent) { + return `${userAgent} ${DEFAULT_USER_AGENT}`; + } + return DEFAULT_USER_AGENT; + } + var GRPC_COMPRESSION_NONE = 0; + var GRPC_COMPRESSION_GZIP = 2; + var GRPC_DEADLINE_EXCEEDED = 4; + var MAX_DEADLINE_EXCEEDED_COUNT = 5; + function toGrpcCompression(compression) { + return compression === "gzip" ? GRPC_COMPRESSION_GZIP : GRPC_COMPRESSION_NONE; + } + function createInsecureCredentials() { + const { + credentials + } = require_src19(); + return credentials.createInsecure(); + } + exports.createInsecureCredentials = createInsecureCredentials; + function createSslCredentials(rootCert, privateKey, certChain) { + const { + credentials + } = require_src19(); + return credentials.createSsl(rootCert, privateKey, certChain); + } + exports.createSslCredentials = createSslCredentials; + function createEmptyMetadata() { + const { + Metadata + } = require_src19(); + return new Metadata; + } + exports.createEmptyMetadata = createEmptyMetadata; + + class GrpcExporterTransport { + _client; + _metadata; + _parameters; + _deadlineExceededCount; + constructor(parameters) { + this._parameters = parameters; + this._deadlineExceededCount = 0; + } + shutdown() { + this._client?.close(); + } + send(data, timeoutMillis) { + const buffer = Buffer.from(data); + if (this._client == null) { + const { + createServiceClientConstructor + } = require_create_service_client_constructor(); + try { + this._metadata = this._parameters.metadata(); + } catch (error) { + return Promise.resolve({ + status: "failure", + error + }); + } + const clientConstructor = createServiceClientConstructor(this._parameters.grpcPath, this._parameters.grpcName); + try { + this._client = new clientConstructor(this._parameters.address, this._parameters.credentials(), { + "grpc.default_compression_algorithm": toGrpcCompression(this._parameters.compression), + "grpc.primary_user_agent": createUserAgent(this._parameters.userAgent) + }); + this._deadlineExceededCount = 0; + } catch (error) { + return Promise.resolve({ + status: "failure", + error + }); + } + } + return new Promise((resolve) => { + const deadline = Date.now() + timeoutMillis; + if (this._metadata == null) { + return resolve({ + error: new Error("metadata was null"), + status: "failure" + }); + } + this._client.export(buffer, this._metadata, { deadline }, (err, response) => { + if (err) { + resolve({ + status: "failure", + error: err + }); + if (err.code === GRPC_DEADLINE_EXCEEDED) { + this._deadlineExceededCount++; + if (this._deadlineExceededCount > MAX_DEADLINE_EXCEEDED_COUNT) { + this._client?.close(); + this._client = undefined; + } + } + } else { + resolve({ + data: response, + status: "success" + }); + this._deadlineExceededCount = 0; + } + }); + }); + } + } + exports.GrpcExporterTransport = GrpcExporterTransport; + function createOtlpGrpcExporterTransport(options) { + return new GrpcExporterTransport(options); + } + exports.createOtlpGrpcExporterTransport = createOtlpGrpcExporterTransport; +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js +var require_otlp_grpc_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getOtlpGrpcDefaultConfiguration = exports.mergeOtlpGrpcConfigurationWithDefaults = exports.validateAndNormalizeUrl = undefined; + var otlp_exporter_base_1 = require_src4(); + var grpc_exporter_transport_1 = require_grpc_exporter_transport(); + var url_1 = __require("url"); + var api_1 = require_src(); + function validateAndNormalizeUrl(url) { + url = url.trim(); + const hasProtocol = url.match(/^([\w]{1,8}):\/\//); + if (!hasProtocol) { + url = `https://${url}`; + } + const target = new url_1.URL(url); + if (target.protocol === "unix:") { + return url; + } + if (target.pathname && target.pathname !== "/") { + api_1.diag.warn("URL path should not be set when using grpc, the path part of the URL will be ignored."); + } + if (target.protocol !== "" && !target.protocol?.match(/^(http)s?:$/)) { + api_1.diag.warn("URL protocol should be http(s)://. Using http://."); + } + return target.host; + } + exports.validateAndNormalizeUrl = validateAndNormalizeUrl; + function overrideMetadataEntriesIfNotPresent(metadata, additionalMetadata) { + for (const [key, value] of Object.entries(additionalMetadata.getMap())) { + if (metadata.get(key).length < 1) { + metadata.set(key, value); + } + } + } + function mergeOtlpGrpcConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { + const rawUrl = userProvidedConfiguration.url ?? fallbackConfiguration.url ?? defaultConfiguration.url; + return { + ...(0, otlp_exporter_base_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), + metadata: () => { + const metadata = defaultConfiguration.metadata(); + overrideMetadataEntriesIfNotPresent(metadata, userProvidedConfiguration.metadata?.().clone() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()); + overrideMetadataEntriesIfNotPresent(metadata, fallbackConfiguration.metadata?.() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()); + return metadata; + }, + url: validateAndNormalizeUrl(rawUrl), + credentials: userProvidedConfiguration.credentials ?? fallbackConfiguration.credentials?.(rawUrl) ?? defaultConfiguration.credentials(rawUrl), + userAgent: userProvidedConfiguration.userAgent + }; + } + exports.mergeOtlpGrpcConfigurationWithDefaults = mergeOtlpGrpcConfigurationWithDefaults; + function getOtlpGrpcDefaultConfiguration() { + return { + ...(0, otlp_exporter_base_1.getSharedConfigurationDefaults)(), + metadata: () => (0, grpc_exporter_transport_1.createEmptyMetadata)(), + url: "http://localhost:4317", + credentials: (url) => { + if (url.startsWith("http://")) { + return () => (0, grpc_exporter_transport_1.createInsecureCredentials)(); + } else { + return () => (0, grpc_exporter_transport_1.createSslCredentials)(); + } + } + }; + } + exports.getOtlpGrpcDefaultConfiguration = getOtlpGrpcDefaultConfiguration; +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js +var require_otlp_grpc_env_configuration = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getOtlpGrpcConfigurationFromEnv = undefined; + var core_1 = require_src3(); + var grpc_exporter_transport_1 = require_grpc_exporter_transport(); + var node_http_1 = require_index_node_http(); + var fs = __require("fs"); + var path = __require("path"); + var api_1 = require_src(); + function fallbackIfNullishOrBlank(signalSpecific, nonSignalSpecific) { + if (signalSpecific != null && signalSpecific !== "") { + return signalSpecific; + } + if (nonSignalSpecific != null && nonSignalSpecific !== "") { + return nonSignalSpecific; + } + return; + } + function getMetadataFromEnv(signalIdentifier) { + const signalSpecificRawHeaders = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim(); + const nonSignalSpecificRawHeaders = process.env["OTEL_EXPORTER_OTLP_HEADERS"]?.trim(); + const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders); + const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders); + if (Object.keys(signalSpecificHeaders).length === 0 && Object.keys(nonSignalSpecificHeaders).length === 0) { + return; + } + const mergeHeaders = Object.assign({}, nonSignalSpecificHeaders, signalSpecificHeaders); + const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)(); + for (const [key, value] of Object.entries(mergeHeaders)) { + metadata.set(key, value); + } + return metadata; + } + function getMetadataProviderFromEnv(signalIdentifier) { + const metadata = getMetadataFromEnv(signalIdentifier); + if (metadata == null) { + return; + } + return () => metadata; + } + function getUrlFromEnv(signalIdentifier) { + const specificEndpoint = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim(); + const nonSpecificEndpoint = process.env["OTEL_EXPORTER_OTLP_ENDPOINT"]?.trim(); + return fallbackIfNullishOrBlank(specificEndpoint, nonSpecificEndpoint); + } + function getInsecureSettingFromEnv(signalIdentifier) { + const signalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_INSECURE`]?.toLowerCase().trim(); + const nonSignalSpecificInsecureValue = process.env["OTEL_EXPORTER_OTLP_INSECURE"]?.toLowerCase().trim(); + return fallbackIfNullishOrBlank(signalSpecificInsecureValue, nonSignalSpecificInsecureValue) === "true"; + } + function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) { + const signalSpecificPath = process.env[signalSpecificEnvVar]?.trim(); + const nonSignalSpecificPath = process.env[nonSignalSpecificEnvVar]?.trim(); + const filePath = fallbackIfNullishOrBlank(signalSpecificPath, nonSignalSpecificPath); + if (filePath != null) { + try { + return fs.readFileSync(path.resolve(process.cwd(), filePath)); + } catch { + api_1.diag.warn(warningMessage); + return; + } + } else { + return; + } + } + function getClientCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE", "Failed to read client certificate chain file"); + } + function getClientKeyFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, "OTEL_EXPORTER_OTLP_CLIENT_KEY", "Failed to read client certificate private key file"); + } + function getRootCertificateFromEnv(signalIdentifier) { + return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, "OTEL_EXPORTER_OTLP_CERTIFICATE", "Failed to read root certificate file"); + } + function getCredentialsFromEnvIgnoreInsecure(signalIdentifier) { + const clientKey = getClientKeyFromEnv(signalIdentifier); + const clientCertificate = getClientCertificateFromEnv(signalIdentifier); + const rootCertificate = getRootCertificateFromEnv(signalIdentifier); + const clientChainIntact = clientKey != null && clientCertificate != null; + if (rootCertificate != null && !clientChainIntact) { + api_1.diag.warn("Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate"); + return (0, grpc_exporter_transport_1.createSslCredentials)(getRootCertificateFromEnv(signalIdentifier)); + } + return (0, grpc_exporter_transport_1.createSslCredentials)(rootCertificate, clientKey, clientCertificate); + } + function getCredentialsFromEnv(signalIdentifier) { + if (getInsecureSettingFromEnv(signalIdentifier)) { + return (0, grpc_exporter_transport_1.createInsecureCredentials)(); + } + return getCredentialsFromEnvIgnoreInsecure(signalIdentifier); + } + function getOtlpGrpcConfigurationFromEnv(signalIdentifier) { + return { + ...(0, node_http_1.getSharedConfigurationFromEnvironment)(signalIdentifier), + metadata: getMetadataProviderFromEnv(signalIdentifier), + url: getUrlFromEnv(signalIdentifier), + credentials: (finalResolvedUrl) => { + if (finalResolvedUrl.startsWith("http://")) { + return () => { + return (0, grpc_exporter_transport_1.createInsecureCredentials)(); + }; + } else if (finalResolvedUrl.startsWith("https://")) { + return () => { + return getCredentialsFromEnvIgnoreInsecure(signalIdentifier); + }; + } + return () => { + return getCredentialsFromEnv(signalIdentifier); + }; + } + }; + } + exports.getOtlpGrpcConfigurationFromEnv = getOtlpGrpcConfigurationFromEnv; +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js +var require_convert_legacy_otlp_grpc_options = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.convertLegacyOtlpGrpcOptions = undefined; + var otlp_grpc_configuration_1 = require_otlp_grpc_configuration(); + var grpc_exporter_transport_1 = require_grpc_exporter_transport(); + var otlp_grpc_env_configuration_1 = require_otlp_grpc_env_configuration(); + function convertLegacyOtlpGrpcOptions(config, signalIdentifier) { + const userProvidedCredentials = config.credentials; + return (0, otlp_grpc_configuration_1.mergeOtlpGrpcConfigurationWithDefaults)({ + url: config.url, + metadata: () => { + return config.metadata ?? (0, grpc_exporter_transport_1.createEmptyMetadata)(); + }, + compression: config.compression, + timeoutMillis: config.timeoutMillis, + concurrencyLimit: config.concurrencyLimit, + credentials: userProvidedCredentials != null ? () => userProvidedCredentials : undefined, + userAgent: config.userAgent + }, (0, otlp_grpc_env_configuration_1.getOtlpGrpcConfigurationFromEnv)(signalIdentifier), (0, otlp_grpc_configuration_1.getOtlpGrpcDefaultConfiguration)()); + } + exports.convertLegacyOtlpGrpcOptions = convertLegacyOtlpGrpcOptions; +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js +var require_otlp_grpc_export_delegate = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createOtlpGrpcExportDelegate = undefined; + var otlp_exporter_base_1 = require_src4(); + var grpc_exporter_transport_1 = require_grpc_exporter_transport(); + function createOtlpGrpcExportDelegate(options, serializer, grpcName, grpcPath) { + return (0, otlp_exporter_base_1.createOtlpNetworkExportDelegate)(options, serializer, (0, grpc_exporter_transport_1.createOtlpGrpcExporterTransport)({ + address: options.url, + compression: options.compression, + credentials: options.credentials, + metadata: options.metadata, + userAgent: options.userAgent, + grpcName, + grpcPath + })); + } + exports.createOtlpGrpcExportDelegate = createOtlpGrpcExportDelegate; +}); + +// node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js +var require_src20 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createSslCredentials = exports.createInsecureCredentials = exports.createEmptyMetadata = exports.createOtlpGrpcExportDelegate = exports.convertLegacyOtlpGrpcOptions = undefined; + var convert_legacy_otlp_grpc_options_1 = require_convert_legacy_otlp_grpc_options(); + Object.defineProperty(exports, "convertLegacyOtlpGrpcOptions", { enumerable: true, get: function() { + return convert_legacy_otlp_grpc_options_1.convertLegacyOtlpGrpcOptions; + } }); + var otlp_grpc_export_delegate_1 = require_otlp_grpc_export_delegate(); + Object.defineProperty(exports, "createOtlpGrpcExportDelegate", { enumerable: true, get: function() { + return otlp_grpc_export_delegate_1.createOtlpGrpcExportDelegate; + } }); + var grpc_exporter_transport_1 = require_grpc_exporter_transport(); + Object.defineProperty(exports, "createEmptyMetadata", { enumerable: true, get: function() { + return grpc_exporter_transport_1.createEmptyMetadata; + } }); + Object.defineProperty(exports, "createInsecureCredentials", { enumerable: true, get: function() { + return grpc_exporter_transport_1.createInsecureCredentials; + } }); + Object.defineProperty(exports, "createSslCredentials", { enumerable: true, get: function() { + return grpc_exporter_transport_1.createSslCredentials; + } }); +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js +var require_OTLPLogExporter2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var otlp_grpc_exporter_base_1 = require_src20(); + var otlp_transformer_1 = require_src8(); + var otlp_exporter_base_1 = require_src4(); + + class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, "LOGS"), otlp_transformer_1.ProtobufLogsSerializer, "LogsExportService", "/opentelemetry.proto.collector.logs.v1.LogsService/Export")); + } + } + exports.OTLPLogExporter = OTLPLogExporter; +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js +var require_src21 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var OTLPLogExporter_1 = require_OTLPLogExporter2(); + Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function() { + return OTLPLogExporter_1.OTLPLogExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js +var require_OTLPLogExporter3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var otlp_exporter_base_1 = require_src4(); + var otlp_transformer_1 = require_src8(); + var node_http_1 = require_index_node_http(); + + class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "LOGS", "v1/logs", { + "Content-Type": "application/x-protobuf" + }), otlp_transformer_1.ProtobufLogsSerializer)); + } + } + exports.OTLPLogExporter = OTLPLogExporter; +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js +var require_node9 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var OTLPLogExporter_1 = require_OTLPLogExporter3(); + Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function() { + return OTLPLogExporter_1.OTLPLogExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js +var require_platform8 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var node_1 = require_node9(); + Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function() { + return node_1.OTLPLogExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js +var require_src22 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPLogExporter = undefined; + var platform_1 = require_platform8(); + Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function() { + return platform_1.OTLPLogExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js +var require_PrometheusSerializer = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PrometheusSerializer = undefined; + var api_1 = require_src(); + var sdk_metrics_1 = require_src7(); + var core_1 = require_src3(); + var semantic_conventions_1 = require_src2(); + var ATTR_OTEL_SCOPE_SCHEMA_URL = "otel.scope.schema_url"; + function escapeString(str) { + return str.replace(/\\/g, "\\\\").replace(/\n/g, "\\n"); + } + function escapeAttributeValue(str = "") { + if (typeof str !== "string") { + str = JSON.stringify(str); + } + return escapeString(str).replace(/"/g, "\\\""); + } + var invalidCharacterRegex = /[^a-z0-9_]/gi; + var multipleUnderscoreRegex = /_{2,}/g; + function sanitizePrometheusMetricName(name) { + return name.replace(invalidCharacterRegex, "_").replace(multipleUnderscoreRegex, "_"); + } + function enforcePrometheusNamingConvention(name, data) { + if (!name.endsWith("_total") && data.dataPointType === sdk_metrics_1.DataPointType.SUM && data.isMonotonic) { + name = name + "_total"; + } + return name; + } + function valueString(value) { + if (value === Infinity) { + return "+Inf"; + } else if (value === -Infinity) { + return "-Inf"; + } else { + return `${value}`; + } + } + function toPrometheusType(metricData) { + switch (metricData.dataPointType) { + case sdk_metrics_1.DataPointType.SUM: + if (metricData.isMonotonic) { + return "counter"; + } + return "gauge"; + case sdk_metrics_1.DataPointType.GAUGE: + return "gauge"; + case sdk_metrics_1.DataPointType.HISTOGRAM: + return "histogram"; + default: + return "untyped"; + } + } + function stringify(metricName, attributes, value, timestamp, additionalAttributes) { + let hasAttribute = false; + let attributesStr = ""; + for (const [key, val] of Object.entries(attributes)) { + const sanitizedAttributeName = sanitizePrometheusMetricName(key); + hasAttribute = true; + attributesStr += `${attributesStr.length > 0 ? "," : ""}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`; + } + if (additionalAttributes) { + for (const [key, val] of Object.entries(additionalAttributes)) { + const sanitizedAttributeName = sanitizePrometheusMetricName(key); + hasAttribute = true; + attributesStr += `${attributesStr.length > 0 ? "," : ""}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`; + } + } + if (hasAttribute) { + metricName += `{${attributesStr}}`; + } + return `${metricName} ${valueString(value)}${timestamp !== undefined ? " " + String(timestamp) : ""} +`; + } + var NO_REGISTERED_METRICS = "# no registered metrics"; + + class PrometheusSerializer { + _prefix; + _appendTimestamp; + _additionalAttributes; + _withResourceConstantLabels; + _withoutScopeInfo; + _withoutTargetInfo; + constructor(prefix, appendTimestamp = false, withResourceConstantLabels, withoutTargetInfo, withoutScopeInfo) { + if (prefix) { + this._prefix = prefix + "_"; + } + this._appendTimestamp = appendTimestamp; + this._withResourceConstantLabels = withResourceConstantLabels; + this._withoutScopeInfo = !!withoutScopeInfo; + this._withoutTargetInfo = !!withoutTargetInfo; + } + serialize(resourceMetrics) { + let str = ""; + this._additionalAttributes = this._filterResourceConstantLabels(resourceMetrics.resource.attributes, this._withResourceConstantLabels); + for (const scopeMetrics of resourceMetrics.scopeMetrics) { + str += this._serializeScopeMetrics(scopeMetrics); + } + if (str === "") { + str += NO_REGISTERED_METRICS; + } + return this._serializeResource(resourceMetrics.resource) + str; + } + _filterResourceConstantLabels(attributes, pattern) { + if (pattern) { + const filteredAttributes = {}; + for (const [key, value] of Object.entries(attributes)) { + if (key.match(pattern)) { + filteredAttributes[key] = value; + } + } + return filteredAttributes; + } + return; + } + _serializeScopeMetrics(scopeMetrics) { + let str = ""; + for (const metric of scopeMetrics.metrics) { + const metricStr = this._serializeMetricData(metric, scopeMetrics.scope); + if (metricStr) { + str += metricStr + ` +`; + } + } + return str; + } + _serializeMetricData(metricData, scope) { + let name = sanitizePrometheusMetricName(escapeString(metricData.descriptor.name)); + if (this._prefix) { + name = `${this._prefix}${name}`; + } + if (name === "") { + api_1.diag.error(`Normalization for metric "${metricData.descriptor.name}" resulted in empty name`); + return ""; + } else if (name === "_") { + api_1.diag.error(`Normalization for metric "${metricData.descriptor.name}" resulted in an invalid name: "_"`); + return ""; + } else if (name[0] >= "0" && name[0] <= "9") { + name = `_${name}`; + } + const dataPointType = metricData.dataPointType; + name = enforcePrometheusNamingConvention(name, metricData); + const help = `# HELP ${name} ${escapeString(metricData.descriptor.description || "description missing")}`; + const unit = metricData.descriptor.unit ? ` +# UNIT ${name} ${escapeString(metricData.descriptor.unit)}` : ""; + const type = `# TYPE ${name} ${toPrometheusType(metricData)}`; + let additionalAttributes; + if (this._withoutScopeInfo) { + additionalAttributes = this._additionalAttributes; + } else { + const scopeInfo = { [semantic_conventions_1.ATTR_OTEL_SCOPE_NAME]: scope.name }; + if (scope.schemaUrl) { + scopeInfo[ATTR_OTEL_SCOPE_SCHEMA_URL] = scope.schemaUrl; + } + if (scope.version) { + scopeInfo[semantic_conventions_1.ATTR_OTEL_SCOPE_VERSION] = scope.version; + } + additionalAttributes = Object.assign(scopeInfo, this._additionalAttributes); + } + let results = ""; + switch (dataPointType) { + case sdk_metrics_1.DataPointType.SUM: + case sdk_metrics_1.DataPointType.GAUGE: { + results = metricData.dataPoints.map((it) => this._serializeSingularDataPoint(name, metricData, it, additionalAttributes)).join(""); + break; + } + case sdk_metrics_1.DataPointType.HISTOGRAM: { + results = metricData.dataPoints.map((it) => this._serializeHistogramDataPoint(name, metricData, it, additionalAttributes)).join(""); + break; + } + default: { + api_1.diag.error(`Unrecognizable DataPointType: ${dataPointType} for metric "${name}"`); + } + } + return `${help}${unit} +${type} +${results}`.trim(); + } + _serializeSingularDataPoint(name, data, dataPoint, additionalAttributes) { + let results = ""; + const { value, attributes } = dataPoint; + const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime); + results += stringify(name, attributes, value, this._appendTimestamp ? timestamp : undefined, additionalAttributes); + return results; + } + _serializeHistogramDataPoint(name, data, dataPoint, additionalAttributes) { + let results = ""; + const attributes = dataPoint.attributes; + const histogram = dataPoint.value; + const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime); + for (const key of ["count", "sum"]) { + const value = histogram[key]; + if (value != null) + results += stringify(name + "_" + key, attributes, value, this._appendTimestamp ? timestamp : undefined, additionalAttributes); + } + let cumulativeSum = 0; + const countEntries = histogram.buckets.counts.entries(); + let infiniteBoundaryDefined = false; + for (const [idx, val] of countEntries) { + cumulativeSum += val; + const upperBound = histogram.buckets.boundaries[idx]; + if (upperBound === undefined && infiniteBoundaryDefined) { + break; + } + if (upperBound === Infinity) { + infiniteBoundaryDefined = true; + } + results += stringify(name + "_bucket", attributes, cumulativeSum, this._appendTimestamp ? timestamp : undefined, Object.assign({}, additionalAttributes, { + le: upperBound === undefined || upperBound === Infinity ? "+Inf" : String(upperBound) + })); + } + return results; + } + _serializeResource(resource) { + if (this._withoutTargetInfo === true) { + return ""; + } + const name = "target_info"; + const help = `# HELP ${name} Target metadata`; + const type = `# TYPE ${name} gauge`; + const results = stringify(name, resource.attributes, 1).trim(); + return `${help} +${type} +${results} +`; + } + } + exports.PrometheusSerializer = PrometheusSerializer; +}); + +// node_modules/@opentelemetry/exporter-prometheus/build/src/semconv.js +var require_semconv6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER = undefined; + exports.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER = "prometheus_http_text_metric_exporter"; +}); + +// node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js +var require_PrometheusExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PrometheusExporter = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var sdk_metrics_1 = require_src7(); + var http_1 = __require("http"); + var PrometheusSerializer_1 = require_PrometheusSerializer(); + var semconv_1 = require_semconv6(); + var url_1 = __require("url"); + + class PrometheusExporter extends sdk_metrics_1.MetricReader { + static DEFAULT_OPTIONS = { + host: undefined, + port: 9464, + endpoint: "/metrics", + prefix: "", + appendTimestamp: false, + withResourceConstantLabels: undefined, + withoutScopeInfo: false, + withoutTargetInfo: false + }; + _host; + _port; + _baseUrl; + _endpoint; + _server; + _prefix; + _appendTimestamp; + _serializer; + _startServerPromise; + constructor(config = {}, callback = () => {}) { + super({ + aggregationSelector: (_instrumentType) => { + return { + type: sdk_metrics_1.AggregationType.DEFAULT + }; + }, + aggregationTemporalitySelector: (_instrumentType) => sdk_metrics_1.AggregationTemporality.CUMULATIVE, + otelComponentType: semconv_1.OTEL_COMPONENT_TYPE_VALUE_PROMETHEUS_HTTP_TEXT_METRIC_EXPORTER, + metricProducers: config.metricProducers + }); + this._host = config.host || process.env.OTEL_EXPORTER_PROMETHEUS_HOST || PrometheusExporter.DEFAULT_OPTIONS.host; + this._port = config.port || Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT) || PrometheusExporter.DEFAULT_OPTIONS.port; + this._prefix = config.prefix || PrometheusExporter.DEFAULT_OPTIONS.prefix; + this._appendTimestamp = typeof config.appendTimestamp === "boolean" ? config.appendTimestamp : PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp; + const _withResourceConstantLabels = config.withResourceConstantLabels || PrometheusExporter.DEFAULT_OPTIONS.withResourceConstantLabels; + const _withoutScopeInfo = config.withoutScopeInfo || PrometheusExporter.DEFAULT_OPTIONS.withoutScopeInfo; + const _withoutTargetInfo = config.withoutTargetInfo || PrometheusExporter.DEFAULT_OPTIONS.withoutTargetInfo; + this._server = (0, http_1.createServer)(this._requestHandler).unref(); + this._serializer = new PrometheusSerializer_1.PrometheusSerializer(this._prefix, this._appendTimestamp, _withResourceConstantLabels, _withoutTargetInfo, _withoutScopeInfo); + this._baseUrl = `http://${this._host}:${this._port}/`; + this._endpoint = (config.endpoint || PrometheusExporter.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/, "/$1"); + if (config.preventServerStart !== true) { + this.startServer().then(callback, (err) => { + api_1.diag.error(err); + callback(err); + }); + } else if (callback) { + queueMicrotask(callback); + } + } + async onForceFlush() {} + onShutdown() { + return this.stopServer(); + } + stopServer() { + if (!this._server) { + api_1.diag.debug("Prometheus stopServer() was called but server was never started."); + return Promise.resolve(); + } else { + return new Promise((resolve) => { + this._server.close((err) => { + if (!err) { + api_1.diag.debug("Prometheus exporter was stopped"); + } else { + if (err.code !== "ERR_SERVER_NOT_RUNNING") { + (0, core_1.globalErrorHandler)(err); + } + } + resolve(); + }); + }); + } + } + startServer() { + this._startServerPromise ??= new Promise((resolve, reject) => { + this._server.once("error", reject); + this._server.listen({ + port: this._port, + host: this._host + }, () => { + api_1.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`); + resolve(); + }); + }); + return this._startServerPromise; + } + getMetricsRequestHandler(_request, response) { + this._exportMetrics(response); + } + _requestHandler = (request2, response) => { + let pathname; + try { + if (request2.url != null) { + pathname = new url_1.URL(request2.url, this._baseUrl).pathname; + } + } catch { + response.statusCode = 400; + response.end("Bad Request"); + return; + } + if (pathname === this._endpoint) { + this._exportMetrics(response); + } else { + this._notFound(response); + } + }; + _exportMetrics = (response) => { + response.statusCode = 200; + response.setHeader("content-type", "text/plain"); + this.collect().then((collectionResult) => { + const { resourceMetrics, errors } = collectionResult; + if (errors.length) { + api_1.diag.error("PrometheusExporter: metrics collection errors", ...errors); + } + response.end(this._serializer.serialize(resourceMetrics)); + }, (err) => { + response.end(`# failed to export metrics: ${err}`); + }); + }; + _notFound = (response) => { + response.statusCode = 404; + response.end(); + }; + } + exports.PrometheusExporter = PrometheusExporter; +}); + +// node_modules/@opentelemetry/exporter-prometheus/build/src/index.js +var require_src23 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PrometheusSerializer = exports.PrometheusExporter = undefined; + var PrometheusExporter_1 = require_PrometheusExporter(); + Object.defineProperty(exports, "PrometheusExporter", { enumerable: true, get: function() { + return PrometheusExporter_1.PrometheusExporter; + } }); + var PrometheusSerializer_1 = require_PrometheusSerializer(); + Object.defineProperty(exports, "PrometheusSerializer", { enumerable: true, get: function() { + return PrometheusSerializer_1.PrometheusSerializer; + } }); +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js +var require_OTLPTraceExporter2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var otlp_exporter_base_1 = require_src4(); + var otlp_transformer_1 = require_src8(); + var node_http_1 = require_index_node_http(); + + class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, "TRACES", "v1/traces", { + "Content-Type": "application/json" + }), otlp_transformer_1.JsonTraceSerializer)); + } + } + exports.OTLPTraceExporter = OTLPTraceExporter; +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js +var require_node10 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var OTLPTraceExporter_1 = require_OTLPTraceExporter2(); + Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function() { + return OTLPTraceExporter_1.OTLPTraceExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js +var require_platform9 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var node_1 = require_node10(); + Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function() { + return node_1.OTLPTraceExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js +var require_src24 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var platform_1 = require_platform9(); + Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function() { + return platform_1.OTLPTraceExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js +var require_OTLPTraceExporter3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var otlp_grpc_exporter_base_1 = require_src20(); + var otlp_transformer_1 = require_src8(); + var otlp_exporter_base_1 = require_src4(); + + class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { + constructor(config = {}) { + super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, "TRACES"), otlp_transformer_1.ProtobufTraceSerializer, "TraceExportService", "/opentelemetry.proto.collector.trace.v1.TraceService/Export")); + } + } + exports.OTLPTraceExporter = OTLPTraceExporter; +}); + +// node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js +var require_src25 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPTraceExporter = undefined; + var OTLPTraceExporter_1 = require_OTLPTraceExporter3(); + Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function() { + return OTLPTraceExporter_1.OTLPTraceExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/util.js +var require_util5 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.prepareSend = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var http = __require("http"); + var https = __require("https"); + function prepareSend(urlStr, headers) { + const url = new URL(urlStr); + const reqOpts = Object.assign({ + method: "POST", + headers: { + "Content-Type": "application/json", + ...headers + } + }); + return function send(zipkinSpans, done) { + if (zipkinSpans.length === 0) { + api_1.diag.debug("Zipkin send with empty spans"); + return done({ code: core_1.ExportResultCode.SUCCESS }); + } + const { request: request2 } = url.protocol === "http:" ? http : https; + const req = request2(url, reqOpts, (res) => { + let rawData = ""; + res.on("data", (chunk) => { + rawData += chunk; + }); + res.on("end", () => { + const statusCode = res.statusCode || 0; + api_1.diag.debug(`Zipkin response status code: ${statusCode}, body: ${rawData}`); + if (statusCode < 400) { + return done({ code: core_1.ExportResultCode.SUCCESS }); + } else { + return done({ + code: core_1.ExportResultCode.FAILED, + error: new Error(`Got unexpected status code from zipkin: ${statusCode}`) + }); + } + }); + }); + req.on("error", (error) => { + return done({ + code: core_1.ExportResultCode.FAILED, + error + }); + }); + const payload = JSON.stringify(zipkinSpans); + api_1.diag.debug(`Zipkin request payload: ${payload}`); + req.write(payload, "utf8"); + req.end(); + }; + } + exports.prepareSend = prepareSend; +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/node/index.js +var require_node11 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.prepareSend = undefined; + var util_1 = require_util5(); + Object.defineProperty(exports, "prepareSend", { enumerable: true, get: function() { + return util_1.prepareSend; + } }); +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/platform/index.js +var require_platform10 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.prepareSend = undefined; + var node_1 = require_node11(); + Object.defineProperty(exports, "prepareSend", { enumerable: true, get: function() { + return node_1.prepareSend; + } }); +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/types.js +var require_types6 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SpanKind = undefined; + var SpanKind; + (function(SpanKind2) { + SpanKind2["CLIENT"] = "CLIENT"; + SpanKind2["SERVER"] = "SERVER"; + SpanKind2["CONSUMER"] = "CONSUMER"; + SpanKind2["PRODUCER"] = "PRODUCER"; + })(SpanKind = exports.SpanKind || (exports.SpanKind = {})); +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/transform.js +var require_transform = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports._toZipkinAnnotations = exports._toZipkinTags = exports.toZipkinSpan = exports.defaultStatusErrorTagName = exports.defaultStatusCodeTagName = undefined; + var api = require_src(); + var core_1 = require_src3(); + var zipkinTypes = require_types6(); + var ZIPKIN_SPAN_KIND_MAPPING = { + [api.SpanKind.CLIENT]: zipkinTypes.SpanKind.CLIENT, + [api.SpanKind.SERVER]: zipkinTypes.SpanKind.SERVER, + [api.SpanKind.CONSUMER]: zipkinTypes.SpanKind.CONSUMER, + [api.SpanKind.PRODUCER]: zipkinTypes.SpanKind.PRODUCER, + [api.SpanKind.INTERNAL]: undefined + }; + exports.defaultStatusCodeTagName = "otel.status_code"; + exports.defaultStatusErrorTagName = "error"; + function toZipkinSpan(span, serviceName, statusCodeTagName, statusErrorTagName) { + const zipkinSpan = { + traceId: span.spanContext().traceId, + parentId: span.parentSpanContext?.spanId, + name: span.name, + id: span.spanContext().spanId, + kind: ZIPKIN_SPAN_KIND_MAPPING[span.kind], + timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime), + duration: Math.round((0, core_1.hrTimeToMicroseconds)(span.duration)), + localEndpoint: { serviceName }, + tags: _toZipkinTags(span, statusCodeTagName, statusErrorTagName), + annotations: span.events.length ? _toZipkinAnnotations(span.events) : undefined + }; + return zipkinSpan; + } + exports.toZipkinSpan = toZipkinSpan; + function _toZipkinTags({ attributes, resource, status, droppedAttributesCount, droppedEventsCount, droppedLinksCount }, statusCodeTagName, statusErrorTagName) { + const tags = {}; + for (const key of Object.keys(attributes)) { + tags[key] = String(attributes[key]); + } + if (status.code !== api.SpanStatusCode.UNSET) { + tags[statusCodeTagName] = String(api.SpanStatusCode[status.code]); + } + if (status.code === api.SpanStatusCode.ERROR && status.message) { + tags[statusErrorTagName] = status.message; + } + if (droppedAttributesCount) { + tags["otel.dropped_attributes_count"] = String(droppedAttributesCount); + } + if (droppedEventsCount) { + tags["otel.dropped_events_count"] = String(droppedEventsCount); + } + if (droppedLinksCount) { + tags["otel.dropped_links_count"] = String(droppedLinksCount); + } + Object.keys(resource.attributes).forEach((name) => tags[name] = String(resource.attributes[name])); + return tags; + } + exports._toZipkinTags = _toZipkinTags; + function _toZipkinAnnotations(events) { + return events.map((event) => ({ + timestamp: Math.round((0, core_1.hrTimeToMicroseconds)(event.time)), + value: event.name + })); + } + exports._toZipkinAnnotations = _toZipkinAnnotations; +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/utils.js +var require_utils12 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.prepareGetHeaders = undefined; + function prepareGetHeaders(getExportRequestHeaders) { + return function() { + return getExportRequestHeaders(); + }; + } + exports.prepareGetHeaders = prepareGetHeaders; +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/zipkin.js +var require_zipkin = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ZipkinExporter = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var index_1 = require_platform10(); + var transform_1 = require_transform(); + var semantic_conventions_1 = require_src2(); + var utils_1 = require_utils12(); + + class ZipkinExporter { + DEFAULT_SERVICE_NAME = "OpenTelemetry Service"; + _statusCodeTagName; + _statusDescriptionTagName; + _urlStr; + _send; + _getHeaders; + _serviceName; + _isShutdown; + _sendingPromises = []; + constructor(config = {}) { + this._urlStr = config.url || ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_ZIPKIN_ENDPOINT") ?? "http://localhost:9411/api/v2/spans"); + this._send = (0, index_1.prepareSend)(this._urlStr, config.headers); + this._serviceName = config.serviceName; + this._statusCodeTagName = config.statusCodeTagName || transform_1.defaultStatusCodeTagName; + this._statusDescriptionTagName = config.statusDescriptionTagName || transform_1.defaultStatusErrorTagName; + this._isShutdown = false; + if (typeof config.getExportRequestHeaders === "function") { + this._getHeaders = (0, utils_1.prepareGetHeaders)(config.getExportRequestHeaders); + } else { + this._beforeSend = function() {}; + } + } + export(spans, resultCallback) { + const serviceName = String(this._serviceName || spans[0].resource.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || this.DEFAULT_SERVICE_NAME); + api_1.diag.debug("Zipkin exporter export"); + if (this._isShutdown) { + setTimeout(() => resultCallback({ + code: core_1.ExportResultCode.FAILED, + error: new Error("Exporter has been shutdown") + })); + return; + } + const promise = new Promise((resolve) => { + this._sendSpans(spans, serviceName, (result) => { + resolve(); + resultCallback(result); + }); + }); + this._sendingPromises.push(promise); + const popPromise = () => { + const index = this._sendingPromises.indexOf(promise); + this._sendingPromises.splice(index, 1); + }; + promise.then(popPromise, popPromise); + } + shutdown() { + api_1.diag.debug("Zipkin exporter shutdown"); + this._isShutdown = true; + return this.forceFlush(); + } + forceFlush() { + return new Promise((resolve, reject) => { + Promise.all(this._sendingPromises).then(() => { + resolve(); + }, reject); + }); + } + _beforeSend() { + if (this._getHeaders) { + this._send = (0, index_1.prepareSend)(this._urlStr, this._getHeaders()); + } + } + _sendSpans(spans, serviceName, done) { + const zipkinSpans = spans.map((span) => (0, transform_1.toZipkinSpan)(span, String(span.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || span.resource.attributes[semantic_conventions_1.ATTR_SERVICE_NAME] || serviceName), this._statusCodeTagName, this._statusDescriptionTagName)); + this._beforeSend(); + return this._send(zipkinSpans, (result) => { + if (done) { + return done(result); + } + }); + } + } + exports.ZipkinExporter = ZipkinExporter; +}); + +// node_modules/@opentelemetry/exporter-zipkin/build/src/index.js +var require_src26 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ZipkinExporter = exports.prepareSend = undefined; + var platform_1 = require_platform10(); + Object.defineProperty(exports, "prepareSend", { enumerable: true, get: function() { + return platform_1.prepareSend; + } }); + var zipkin_1 = require_zipkin(); + Object.defineProperty(exports, "ZipkinExporter", { enumerable: true, get: function() { + return zipkin_1.ZipkinExporter; + } }); +}); + +// node_modules/@opentelemetry/propagator-b3/build/src/common.js +var require_common3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.B3_DEBUG_FLAG_KEY = undefined; + var api_1 = require_src(); + exports.B3_DEBUG_FLAG_KEY = (0, api_1.createContextKey)("OpenTelemetry Context Key B3 Debug Flag"); +}); + +// node_modules/@opentelemetry/propagator-b3/build/src/constants.js +var require_constants3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.X_B3_FLAGS = exports.X_B3_PARENT_SPAN_ID = exports.X_B3_SAMPLED = exports.X_B3_SPAN_ID = exports.X_B3_TRACE_ID = exports.B3_CONTEXT_HEADER = undefined; + exports.B3_CONTEXT_HEADER = "b3"; + exports.X_B3_TRACE_ID = "x-b3-traceid"; + exports.X_B3_SPAN_ID = "x-b3-spanid"; + exports.X_B3_SAMPLED = "x-b3-sampled"; + exports.X_B3_PARENT_SPAN_ID = "x-b3-parentspanid"; + exports.X_B3_FLAGS = "x-b3-flags"; +}); + +// node_modules/@opentelemetry/propagator-b3/build/src/B3MultiPropagator.js +var require_B3MultiPropagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.B3MultiPropagator = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var common_1 = require_common3(); + var constants_1 = require_constants3(); + var VALID_SAMPLED_VALUES = new Set([true, "true", "True", "1", 1]); + var VALID_UNSAMPLED_VALUES = new Set([false, "false", "False", "0", 0]); + function isValidSampledValue(sampled) { + return sampled === api_1.TraceFlags.SAMPLED || sampled === api_1.TraceFlags.NONE; + } + function parseHeader(header) { + return Array.isArray(header) ? header[0] : header; + } + function getHeaderValue(carrier, getter, key) { + const header = getter.get(carrier, key); + return parseHeader(header); + } + function getTraceId(carrier, getter) { + const traceId = getHeaderValue(carrier, getter, constants_1.X_B3_TRACE_ID); + if (typeof traceId === "string") { + return traceId.padStart(32, "0"); + } + return ""; + } + function getSpanId(carrier, getter) { + const spanId = getHeaderValue(carrier, getter, constants_1.X_B3_SPAN_ID); + if (typeof spanId === "string") { + return spanId; + } + return ""; + } + function getDebug(carrier, getter) { + const debug = getHeaderValue(carrier, getter, constants_1.X_B3_FLAGS); + return debug === "1" ? "1" : undefined; + } + function getTraceFlags(carrier, getter) { + const traceFlags = getHeaderValue(carrier, getter, constants_1.X_B3_SAMPLED); + const debug = getDebug(carrier, getter); + if (debug === "1" || VALID_SAMPLED_VALUES.has(traceFlags)) { + return api_1.TraceFlags.SAMPLED; + } + if (traceFlags === undefined || VALID_UNSAMPLED_VALUES.has(traceFlags)) { + return api_1.TraceFlags.NONE; + } + return; + } + + class B3MultiPropagator { + inject(context, carrier, setter) { + const spanContext = api_1.trace.getSpanContext(context); + if (!spanContext || !(0, api_1.isSpanContextValid)(spanContext) || (0, core_1.isTracingSuppressed)(context)) + return; + const debug = context.getValue(common_1.B3_DEBUG_FLAG_KEY); + setter.set(carrier, constants_1.X_B3_TRACE_ID, spanContext.traceId); + setter.set(carrier, constants_1.X_B3_SPAN_ID, spanContext.spanId); + if (debug === "1") { + setter.set(carrier, constants_1.X_B3_FLAGS, debug); + } else if (spanContext.traceFlags !== undefined) { + setter.set(carrier, constants_1.X_B3_SAMPLED, (api_1.TraceFlags.SAMPLED & spanContext.traceFlags) === api_1.TraceFlags.SAMPLED ? "1" : "0"); + } + } + extract(context, carrier, getter) { + const traceId = getTraceId(carrier, getter); + const spanId = getSpanId(carrier, getter); + const traceFlags = getTraceFlags(carrier, getter); + const debug = getDebug(carrier, getter); + if ((0, api_1.isValidTraceId)(traceId) && (0, api_1.isValidSpanId)(spanId) && isValidSampledValue(traceFlags)) { + context = context.setValue(common_1.B3_DEBUG_FLAG_KEY, debug); + return api_1.trace.setSpanContext(context, { + traceId, + spanId, + isRemote: true, + traceFlags + }); + } + return context; + } + fields() { + return [ + constants_1.X_B3_TRACE_ID, + constants_1.X_B3_SPAN_ID, + constants_1.X_B3_FLAGS, + constants_1.X_B3_SAMPLED, + constants_1.X_B3_PARENT_SPAN_ID + ]; + } + } + exports.B3MultiPropagator = B3MultiPropagator; +}); + +// node_modules/@opentelemetry/propagator-b3/build/src/B3SinglePropagator.js +var require_B3SinglePropagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.B3SinglePropagator = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var common_1 = require_common3(); + var constants_1 = require_constants3(); + var B3_CONTEXT_REGEX = /((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/; + var PADDING = "0".repeat(16); + var SAMPLED_VALUES = new Set(["d", "1"]); + var DEBUG_STATE = "d"; + function convertToTraceId128(traceId) { + return traceId.length === 32 ? traceId : `${PADDING}${traceId}`; + } + function convertToTraceFlags(samplingState) { + if (samplingState && SAMPLED_VALUES.has(samplingState)) { + return api_1.TraceFlags.SAMPLED; + } + return api_1.TraceFlags.NONE; + } + + class B3SinglePropagator { + inject(context, carrier, setter) { + const spanContext = api_1.trace.getSpanContext(context); + if (!spanContext || !(0, api_1.isSpanContextValid)(spanContext) || (0, core_1.isTracingSuppressed)(context)) + return; + const samplingState = context.getValue(common_1.B3_DEBUG_FLAG_KEY) || spanContext.traceFlags & 1; + const value = `${spanContext.traceId}-${spanContext.spanId}-${samplingState}`; + setter.set(carrier, constants_1.B3_CONTEXT_HEADER, value); + } + extract(context, carrier, getter) { + const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER); + const b3Context = Array.isArray(header) ? header[0] : header; + if (typeof b3Context !== "string") + return context; + const match = b3Context.match(B3_CONTEXT_REGEX); + if (!match) + return context; + const [, extractedTraceId, spanId, samplingState] = match; + const traceId = convertToTraceId128(extractedTraceId); + if (!(0, api_1.isValidTraceId)(traceId) || !(0, api_1.isValidSpanId)(spanId)) + return context; + const traceFlags = convertToTraceFlags(samplingState); + if (samplingState === DEBUG_STATE) { + context = context.setValue(common_1.B3_DEBUG_FLAG_KEY, samplingState); + } + return api_1.trace.setSpanContext(context, { + traceId, + spanId, + isRemote: true, + traceFlags + }); + } + fields() { + return [constants_1.B3_CONTEXT_HEADER]; + } + } + exports.B3SinglePropagator = B3SinglePropagator; +}); + +// node_modules/@opentelemetry/propagator-b3/build/src/types.js +var require_types7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.B3InjectEncoding = undefined; + var B3InjectEncoding; + (function(B3InjectEncoding2) { + B3InjectEncoding2[B3InjectEncoding2["SINGLE_HEADER"] = 0] = "SINGLE_HEADER"; + B3InjectEncoding2[B3InjectEncoding2["MULTI_HEADER"] = 1] = "MULTI_HEADER"; + })(B3InjectEncoding = exports.B3InjectEncoding || (exports.B3InjectEncoding = {})); +}); + +// node_modules/@opentelemetry/propagator-b3/build/src/B3Propagator.js +var require_B3Propagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.B3Propagator = undefined; + var core_1 = require_src3(); + var B3MultiPropagator_1 = require_B3MultiPropagator(); + var B3SinglePropagator_1 = require_B3SinglePropagator(); + var constants_1 = require_constants3(); + var types_1 = require_types7(); + + class B3Propagator { + _b3MultiPropagator = new B3MultiPropagator_1.B3MultiPropagator; + _b3SinglePropagator = new B3SinglePropagator_1.B3SinglePropagator; + _inject; + _fields; + constructor(config = {}) { + if (config.injectEncoding === types_1.B3InjectEncoding.MULTI_HEADER) { + this._inject = this._b3MultiPropagator.inject; + this._fields = this._b3MultiPropagator.fields(); + } else { + this._inject = this._b3SinglePropagator.inject; + this._fields = this._b3SinglePropagator.fields(); + } + } + inject(context, carrier, setter) { + if ((0, core_1.isTracingSuppressed)(context)) { + return; + } + this._inject(context, carrier, setter); + } + extract(context, carrier, getter) { + const header = getter.get(carrier, constants_1.B3_CONTEXT_HEADER); + const b3Context = Array.isArray(header) ? header[0] : header; + if (b3Context) { + return this._b3SinglePropagator.extract(context, carrier, getter); + } else { + return this._b3MultiPropagator.extract(context, carrier, getter); + } + } + fields() { + return this._fields; + } + } + exports.B3Propagator = B3Propagator; +}); + +// node_modules/@opentelemetry/propagator-b3/build/src/index.js +var require_src27 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.B3InjectEncoding = exports.X_B3_TRACE_ID = exports.X_B3_SPAN_ID = exports.X_B3_SAMPLED = exports.X_B3_PARENT_SPAN_ID = exports.X_B3_FLAGS = exports.B3_CONTEXT_HEADER = exports.B3Propagator = undefined; + var B3Propagator_1 = require_B3Propagator(); + Object.defineProperty(exports, "B3Propagator", { enumerable: true, get: function() { + return B3Propagator_1.B3Propagator; + } }); + var constants_1 = require_constants3(); + Object.defineProperty(exports, "B3_CONTEXT_HEADER", { enumerable: true, get: function() { + return constants_1.B3_CONTEXT_HEADER; + } }); + Object.defineProperty(exports, "X_B3_FLAGS", { enumerable: true, get: function() { + return constants_1.X_B3_FLAGS; + } }); + Object.defineProperty(exports, "X_B3_PARENT_SPAN_ID", { enumerable: true, get: function() { + return constants_1.X_B3_PARENT_SPAN_ID; + } }); + Object.defineProperty(exports, "X_B3_SAMPLED", { enumerable: true, get: function() { + return constants_1.X_B3_SAMPLED; + } }); + Object.defineProperty(exports, "X_B3_SPAN_ID", { enumerable: true, get: function() { + return constants_1.X_B3_SPAN_ID; + } }); + Object.defineProperty(exports, "X_B3_TRACE_ID", { enumerable: true, get: function() { + return constants_1.X_B3_TRACE_ID; + } }); + var types_1 = require_types7(); + Object.defineProperty(exports, "B3InjectEncoding", { enumerable: true, get: function() { + return types_1.B3InjectEncoding; + } }); +}); + +// node_modules/@opentelemetry/propagator-jaeger/build/src/JaegerPropagator.js +var require_JaegerPropagator = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JaegerPropagator = exports.UBER_BAGGAGE_HEADER_PREFIX = exports.UBER_TRACE_ID_HEADER = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + exports.UBER_TRACE_ID_HEADER = "uber-trace-id"; + exports.UBER_BAGGAGE_HEADER_PREFIX = "uberctx"; + + class JaegerPropagator { + _jaegerTraceHeader; + _jaegerBaggageHeaderPrefix; + constructor(config) { + if (typeof config === "string") { + this._jaegerTraceHeader = config; + this._jaegerBaggageHeaderPrefix = exports.UBER_BAGGAGE_HEADER_PREFIX; + } else { + this._jaegerTraceHeader = config?.customTraceHeader || exports.UBER_TRACE_ID_HEADER; + this._jaegerBaggageHeaderPrefix = config?.customBaggageHeaderPrefix || exports.UBER_BAGGAGE_HEADER_PREFIX; + } + } + inject(context, carrier, setter) { + const spanContext = api_1.trace.getSpanContext(context); + const baggage = api_1.propagation.getBaggage(context); + if (spanContext && (0, core_1.isTracingSuppressed)(context) === false) { + const traceFlags = `0${(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`; + setter.set(carrier, this._jaegerTraceHeader, `${spanContext.traceId}:${spanContext.spanId}:0:${traceFlags}`); + } + if (baggage) { + for (const [key, entry] of baggage.getAllEntries()) { + setter.set(carrier, `${this._jaegerBaggageHeaderPrefix}-${key}`, encodeURIComponent(entry.value)); + } + } + } + extract(context, carrier, getter) { + const uberTraceIdHeader = getter.get(carrier, this._jaegerTraceHeader); + const uberTraceId = Array.isArray(uberTraceIdHeader) ? uberTraceIdHeader[0] : uberTraceIdHeader; + const baggageValues = getter.keys(carrier).filter((key) => key.startsWith(`${this._jaegerBaggageHeaderPrefix}-`)).map((key) => { + const value = getter.get(carrier, key); + return { + key: key.substring(this._jaegerBaggageHeaderPrefix.length + 1), + value: Array.isArray(value) ? value[0] : value + }; + }); + let newContext = context; + if (typeof uberTraceId === "string") { + const spanContext = deserializeSpanContext(uberTraceId); + if (spanContext) { + newContext = api_1.trace.setSpanContext(newContext, spanContext); + } + } + if (baggageValues.length === 0) + return newContext; + let currentBaggage = api_1.propagation.getBaggage(context) ?? api_1.propagation.createBaggage(); + for (const baggageEntry of baggageValues) { + if (baggageEntry.value === undefined) + continue; + currentBaggage = currentBaggage.setEntry(baggageEntry.key, { + value: decodeURIComponent(baggageEntry.value) + }); + } + newContext = api_1.propagation.setBaggage(newContext, currentBaggage); + return newContext; + } + fields() { + return [this._jaegerTraceHeader]; + } + } + exports.JaegerPropagator = JaegerPropagator; + var VALID_HEX_RE = /^[0-9a-f]{1,2}$/i; + function deserializeSpanContext(serializedString) { + const headers = decodeURIComponent(serializedString).split(":"); + if (headers.length !== 4) { + return null; + } + const [_traceId, _spanId, , flags] = headers; + const traceId = _traceId.padStart(32, "0"); + const spanId = _spanId.padStart(16, "0"); + const traceFlags = VALID_HEX_RE.test(flags) ? parseInt(flags, 16) & 1 : 1; + return { traceId, spanId, isRemote: true, traceFlags }; + } +}); + +// node_modules/@opentelemetry/propagator-jaeger/build/src/index.js +var require_src28 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UBER_TRACE_ID_HEADER = exports.UBER_BAGGAGE_HEADER_PREFIX = exports.JaegerPropagator = undefined; + var JaegerPropagator_1 = require_JaegerPropagator(); + Object.defineProperty(exports, "JaegerPropagator", { enumerable: true, get: function() { + return JaegerPropagator_1.JaegerPropagator; + } }); + Object.defineProperty(exports, "UBER_BAGGAGE_HEADER_PREFIX", { enumerable: true, get: function() { + return JaegerPropagator_1.UBER_BAGGAGE_HEADER_PREFIX; + } }); + Object.defineProperty(exports, "UBER_TRACE_ID_HEADER", { enumerable: true, get: function() { + return JaegerPropagator_1.UBER_TRACE_ID_HEADER; + } }); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js +var require_OTLPMetricExporterOptions = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AggregationTemporalityPreference = undefined; + var AggregationTemporalityPreference; + (function(AggregationTemporalityPreference2) { + AggregationTemporalityPreference2[AggregationTemporalityPreference2["DELTA"] = 0] = "DELTA"; + AggregationTemporalityPreference2[AggregationTemporalityPreference2["CUMULATIVE"] = 1] = "CUMULATIVE"; + AggregationTemporalityPreference2[AggregationTemporalityPreference2["LOWMEMORY"] = 2] = "LOWMEMORY"; + })(AggregationTemporalityPreference = exports.AggregationTemporalityPreference || (exports.AggregationTemporalityPreference = {})); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js +var require_OTLPMetricExporterBase = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = undefined; + var core_1 = require_src3(); + var sdk_metrics_1 = require_src7(); + var OTLPMetricExporterOptions_1 = require_OTLPMetricExporterOptions(); + var otlp_exporter_base_1 = require_src4(); + var api_1 = require_src(); + var CumulativeTemporalitySelector = () => sdk_metrics_1.AggregationTemporality.CUMULATIVE; + exports.CumulativeTemporalitySelector = CumulativeTemporalitySelector; + var DeltaTemporalitySelector = (instrumentType) => { + switch (instrumentType) { + case sdk_metrics_1.InstrumentType.COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER: + case sdk_metrics_1.InstrumentType.GAUGE: + case sdk_metrics_1.InstrumentType.HISTOGRAM: + case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE: + return sdk_metrics_1.AggregationTemporality.DELTA; + case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: + return sdk_metrics_1.AggregationTemporality.CUMULATIVE; + } + }; + exports.DeltaTemporalitySelector = DeltaTemporalitySelector; + var LowMemoryTemporalitySelector = (instrumentType) => { + switch (instrumentType) { + case sdk_metrics_1.InstrumentType.COUNTER: + case sdk_metrics_1.InstrumentType.HISTOGRAM: + return sdk_metrics_1.AggregationTemporality.DELTA; + case sdk_metrics_1.InstrumentType.GAUGE: + case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER: + case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE: + return sdk_metrics_1.AggregationTemporality.CUMULATIVE; + } + }; + exports.LowMemoryTemporalitySelector = LowMemoryTemporalitySelector; + function chooseTemporalitySelectorFromEnvironment() { + const configuredTemporality = ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE") ?? "cumulative").toLowerCase(); + if (configuredTemporality === "cumulative") { + return exports.CumulativeTemporalitySelector; + } + if (configuredTemporality === "delta") { + return exports.DeltaTemporalitySelector; + } + if (configuredTemporality === "lowmemory") { + return exports.LowMemoryTemporalitySelector; + } + api_1.diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${configuredTemporality}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`); + return exports.CumulativeTemporalitySelector; + } + function chooseTemporalitySelector(temporalityPreference) { + if (temporalityPreference != null) { + if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.DELTA) { + return exports.DeltaTemporalitySelector; + } else if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.LOWMEMORY) { + return exports.LowMemoryTemporalitySelector; + } + return exports.CumulativeTemporalitySelector; + } + return chooseTemporalitySelectorFromEnvironment(); + } + var DEFAULT_AGGREGATION = Object.freeze({ + type: sdk_metrics_1.AggregationType.DEFAULT + }); + function chooseAggregationSelector(config) { + return config?.aggregationPreference ?? (() => DEFAULT_AGGREGATION); + } + + class OTLPMetricExporterBase extends otlp_exporter_base_1.OTLPExporterBase { + _aggregationTemporalitySelector; + _aggregationSelector; + constructor(delegate, config) { + super(delegate); + this._aggregationSelector = chooseAggregationSelector(config); + this._aggregationTemporalitySelector = chooseTemporalitySelector(config?.temporalityPreference); + } + selectAggregation(instrumentType) { + return this._aggregationSelector(instrumentType); + } + selectAggregationTemporality(instrumentType) { + return this._aggregationTemporalitySelector(instrumentType); + } + } + exports.OTLPMetricExporterBase = OTLPMetricExporterBase; +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js +var require_OTLPMetricExporter = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var OTLPMetricExporterBase_1 = require_OTLPMetricExporterBase(); + var otlp_transformer_1 = require_src8(); + var node_http_1 = require_index_node_http(); + + class OTLPMetricExporter extends OTLPMetricExporterBase_1.OTLPMetricExporterBase { + constructor(config) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, "METRICS", "v1/metrics", { + "Content-Type": "application/json" + }), otlp_transformer_1.JsonMetricsSerializer), config); + } + } + exports.OTLPMetricExporter = OTLPMetricExporter; +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js +var require_node12 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var OTLPMetricExporter_1 = require_OTLPMetricExporter(); + Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function() { + return OTLPMetricExporter_1.OTLPMetricExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js +var require_platform11 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var node_1 = require_node12(); + Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function() { + return node_1.OTLPMetricExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js +var require_src29 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = exports.AggregationTemporalityPreference = exports.OTLPMetricExporter = undefined; + var platform_1 = require_platform11(); + Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function() { + return platform_1.OTLPMetricExporter; + } }); + var OTLPMetricExporterOptions_1 = require_OTLPMetricExporterOptions(); + Object.defineProperty(exports, "AggregationTemporalityPreference", { enumerable: true, get: function() { + return OTLPMetricExporterOptions_1.AggregationTemporalityPreference; + } }); + var OTLPMetricExporterBase_1 = require_OTLPMetricExporterBase(); + Object.defineProperty(exports, "CumulativeTemporalitySelector", { enumerable: true, get: function() { + return OTLPMetricExporterBase_1.CumulativeTemporalitySelector; + } }); + Object.defineProperty(exports, "DeltaTemporalitySelector", { enumerable: true, get: function() { + return OTLPMetricExporterBase_1.DeltaTemporalitySelector; + } }); + Object.defineProperty(exports, "LowMemoryTemporalitySelector", { enumerable: true, get: function() { + return OTLPMetricExporterBase_1.LowMemoryTemporalitySelector; + } }); + Object.defineProperty(exports, "OTLPMetricExporterBase", { enumerable: true, get: function() { + return OTLPMetricExporterBase_1.OTLPMetricExporterBase; + } }); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js +var require_OTLPMetricExporter2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var exporter_metrics_otlp_http_1 = require_src29(); + var otlp_grpc_exporter_base_1 = require_src20(); + var otlp_transformer_1 = require_src8(); + + class OTLPMetricExporter extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase { + constructor(config) { + super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config ?? {}, "METRICS"), otlp_transformer_1.ProtobufMetricsSerializer, "MetricsExportService", "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export"), config); + } + } + exports.OTLPMetricExporter = OTLPMetricExporter; +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js +var require_src30 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var OTLPMetricExporter_1 = require_OTLPMetricExporter2(); + Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function() { + return OTLPMetricExporter_1.OTLPMetricExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js +var require_OTLPMetricExporter3 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var exporter_metrics_otlp_http_1 = require_src29(); + var otlp_transformer_1 = require_src8(); + var node_http_1 = require_index_node_http(); + + class OTLPMetricExporter extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase { + constructor(config) { + super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, "METRICS", "v1/metrics", { + "Content-Type": "application/x-protobuf" + }), otlp_transformer_1.ProtobufMetricsSerializer), config); + } + } + exports.OTLPMetricExporter = OTLPMetricExporter; +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js +var require_node13 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var OTLPMetricExporter_1 = require_OTLPMetricExporter3(); + Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function() { + return OTLPMetricExporter_1.OTLPMetricExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js +var require_platform12 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var node_1 = require_node13(); + Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function() { + return node_1.OTLPMetricExporter; + } }); +}); + +// node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js +var require_src31 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OTLPMetricExporter = undefined; + var platform_1 = require_platform12(); + Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function() { + return platform_1.OTLPMetricExporter; + } }); +}); + +// node_modules/@opentelemetry/sdk-node/build/src/utils.js +var require_utils13 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildSamplerFromConfig = exports.getInstanceID = exports.getMeterViewsFromConfiguration = exports.getAggregationType = exports.getInstrumentType = exports.getMeterReadersFromConfiguration = exports.getSpanLimitsFromConfiguration = exports.getSpanProcessorsFromConfiguration = exports.getSpanExporter = exports.getHttpAgentOptionsFromTls = exports.getHeadersFromConfiguration = exports.getLogRecordProcessorsFromConfiguration = exports.getLogRecordExporter = exports.getBatchLogRecordProcessorFromEnv = exports.getBatchLogRecordProcessorConfigFromEnv = exports.getLoggerProviderConfigFromEnv = exports.getPeriodicMetricReaderFromConfiguration = exports.getOtlpMetricExporterFromEnv = exports.getPeriodicExportingMetricReaderFromEnv = exports.getNonNegativeNumberFromEnv = exports.getKeyListFromObjectArray = exports.setupPropagator = exports.setupContextManager = exports.getPropagatorFromConfiguration = exports.getPropagatorFromEnv = exports.getSpanProcessorsFromEnv = exports.getOtlpProtocolFromEnv = exports.getResourceDetectorsFromConfiguration = exports.getResourceDetectorsFromEnv = exports.getResourceFromConfiguration = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var exporter_trace_otlp_proto_1 = require_src9(); + var exporter_trace_otlp_http_1 = require_src24(); + var exporter_trace_otlp_grpc_1 = require_src25(); + var exporter_zipkin_1 = require_src26(); + var resources_1 = require_src6(); + var sdk_trace_base_1 = require_src12(); + var propagator_b3_1 = require_src27(); + var propagator_jaeger_1 = require_src28(); + var context_async_hooks_1 = require_src11(); + var exporter_logs_otlp_http_1 = require_src16(); + var exporter_logs_otlp_grpc_1 = require_src21(); + var exporter_logs_otlp_proto_1 = require_src22(); + var otlp_exporter_base_1 = require_src4(); + var otlp_grpc_exporter_base_1 = require_src20(); + var sdk_metrics_1 = require_src7(); + var exporter_metrics_otlp_grpc_1 = require_src30(); + var exporter_metrics_otlp_http_1 = require_src29(); + var exporter_metrics_otlp_proto_1 = require_src31(); + var sdk_logs_1 = require_src10(); + var fs = __require("fs"); + var RESOURCE_DETECTOR_ENVIRONMENT = "env"; + var RESOURCE_DETECTOR_HOST = "host"; + var RESOURCE_DETECTOR_OS = "os"; + var RESOURCE_DETECTOR_PROCESS = "process"; + var RESOURCE_DETECTOR_SERVICE_INSTANCE_ID = "serviceinstance"; + function getResourceFromConfiguration(config) { + if (config.resource && config.resource.attributes) { + const attrs = {}; + for (let i = 0;i < config.resource.attributes.length; i++) { + const a = config.resource.attributes[i]; + if (a.value !== null) { + attrs[a.name] = a.value; + } + } + return (0, resources_1.resourceFromAttributes)(attrs, { + schemaUrl: config.resource.schema_url ?? undefined + }); + } + return; + } + exports.getResourceFromConfiguration = getResourceFromConfiguration; + function getResourceDetectorsFromEnv() { + const resourceDetectors = new Map([ + [RESOURCE_DETECTOR_HOST, resources_1.hostDetector], + [RESOURCE_DETECTOR_OS, resources_1.osDetector], + [RESOURCE_DETECTOR_SERVICE_INSTANCE_ID, resources_1.serviceInstanceIdDetector], + [RESOURCE_DETECTOR_PROCESS, resources_1.processDetector], + [RESOURCE_DETECTOR_ENVIRONMENT, resources_1.envDetector] + ]); + const resourceDetectorsFromEnv = (0, core_1.getStringListFromEnv)("OTEL_NODE_RESOURCE_DETECTORS") ?? ["all"]; + if (resourceDetectorsFromEnv.includes("all")) { + return [...resourceDetectors.values()].flat(); + } + if (resourceDetectorsFromEnv.includes("none")) { + return []; + } + return resourceDetectorsFromEnv.flatMap((detector) => { + const resourceDetector = resourceDetectors.get(detector); + if (!resourceDetector) { + api_1.diag.warn(`Invalid resource detector "${detector}" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS`); + } + return resourceDetector || []; + }); + } + exports.getResourceDetectorsFromEnv = getResourceDetectorsFromEnv; + function getResourceDetectorsFromConfiguration(config) { + const detectors = config.resource?.["detection/development"]?.detectors ?? []; + return detectors.flatMap((detector) => { + const result = []; + if (detector.host !== undefined) + result.push(resources_1.hostDetector); + if (detector.os !== undefined) + result.push(resources_1.osDetector); + if (detector.process !== undefined) + result.push(resources_1.processDetector); + if (detector.service !== undefined) + result.push(resources_1.serviceInstanceIdDetector); + if (detector.env !== undefined) + result.push(resources_1.envDetector); + return result; + }); + } + exports.getResourceDetectorsFromConfiguration = getResourceDetectorsFromConfiguration; + function getOtlpProtocolFromEnv() { + return (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf"; + } + exports.getOtlpProtocolFromEnv = getOtlpProtocolFromEnv; + function getOtlpExporterFromEnv() { + const protocol = getOtlpProtocolFromEnv(); + switch (protocol) { + case "grpc": + return new exporter_trace_otlp_grpc_1.OTLPTraceExporter; + case "http/json": + return new exporter_trace_otlp_http_1.OTLPTraceExporter; + case "http/protobuf": + return new exporter_trace_otlp_proto_1.OTLPTraceExporter; + default: + api_1.diag.warn(`Unsupported OTLP traces protocol: ${protocol}. Using http/protobuf.`); + return new exporter_trace_otlp_proto_1.OTLPTraceExporter; + } + } + function getSpanProcessorsFromEnv() { + const exportersMap = new Map([ + ["otlp", () => getOtlpExporterFromEnv()], + ["zipkin", () => new exporter_zipkin_1.ZipkinExporter], + ["console", () => new sdk_trace_base_1.ConsoleSpanExporter] + ]); + const exporters = []; + const processors = []; + let traceExportersList = Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_TRACES_EXPORTER"))).filter((s) => s !== "null"); + if (traceExportersList[0] === "none") { + api_1.diag.warn('OTEL_TRACES_EXPORTER contains "none". SDK will not be initialized.'); + return []; + } + if (traceExportersList.length === 0) { + api_1.diag.debug("OTEL_TRACES_EXPORTER is empty. Using default otlp exporter."); + traceExportersList = ["otlp"]; + } else if (traceExportersList.length > 1 && traceExportersList.includes("none")) { + api_1.diag.warn('OTEL_TRACES_EXPORTER contains "none" along with other exporters. Using default otlp exporter.'); + traceExportersList = ["otlp"]; + } + for (const name of traceExportersList) { + const exporter = exportersMap.get(name)?.(); + if (exporter) { + exporters.push(exporter); + } else { + api_1.diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${name}.`); + } + } + for (const exp of exporters) { + if (exp instanceof sdk_trace_base_1.ConsoleSpanExporter) { + processors.push(new sdk_trace_base_1.SimpleSpanProcessor(exp)); + } else { + processors.push(new sdk_trace_base_1.BatchSpanProcessor(exp)); + } + } + if (exporters.length === 0) { + api_1.diag.warn("Unable to set up trace exporter(s) due to invalid exporter and/or protocol values."); + } + return processors; + } + exports.getSpanProcessorsFromEnv = getSpanProcessorsFromEnv; + function getPropagatorFromEnv() { + const propagatorsEnvVarValue = (0, core_1.getStringListFromEnv)("OTEL_PROPAGATORS"); + if (propagatorsEnvVarValue == null) { + return; + } + if (propagatorsEnvVarValue.includes("none")) { + return null; + } + const propagatorsFactory = new Map([ + ["tracecontext", () => new core_1.W3CTraceContextPropagator], + ["baggage", () => new core_1.W3CBaggagePropagator], + ["b3", () => new propagator_b3_1.B3Propagator], + [ + "b3multi", + () => new propagator_b3_1.B3Propagator({ injectEncoding: propagator_b3_1.B3InjectEncoding.MULTI_HEADER }) + ], + ["jaeger", () => new propagator_jaeger_1.JaegerPropagator] + ]); + const uniquePropagatorNames = Array.from(new Set(propagatorsEnvVarValue)); + const validPropagators = []; + uniquePropagatorNames.forEach((name) => { + const propagator = propagatorsFactory.get(name)?.(); + if (!propagator) { + api_1.diag.warn(`Propagator "${name}" requested through environment variable is unavailable.`); + return; + } + validPropagators.push(propagator); + }); + if (validPropagators.length === 0) { + return null; + } else if (uniquePropagatorNames.length === 1) { + return validPropagators[0]; + } else { + return new core_1.CompositePropagator({ + propagators: validPropagators + }); + } + } + exports.getPropagatorFromEnv = getPropagatorFromEnv; + function getPropagatorFromConfiguration(config) { + const propagatorsValue = getKeyListFromObjectArray(config.propagator?.composite); + if (propagatorsValue == null) { + return; + } + if (propagatorsValue.includes("none")) { + return null; + } + const propagatorsFactory = new Map([ + ["tracecontext", () => new core_1.W3CTraceContextPropagator], + ["baggage", () => new core_1.W3CBaggagePropagator], + ["b3", () => new propagator_b3_1.B3Propagator], + [ + "b3multi", + () => new propagator_b3_1.B3Propagator({ injectEncoding: propagator_b3_1.B3InjectEncoding.MULTI_HEADER }) + ], + ["jaeger", () => new propagator_jaeger_1.JaegerPropagator] + ]); + const uniquePropagatorNames = Array.from(new Set(propagatorsValue)); + const validPropagators = []; + uniquePropagatorNames.forEach((name) => { + const propagator = propagatorsFactory.get(name)?.(); + if (!propagator) { + api_1.diag.warn(`Propagator "${name}" requested through configuration is unavailable.`); + return; + } + validPropagators.push(propagator); + }); + if (validPropagators.length === 0) { + return null; + } else if (uniquePropagatorNames.length === 1) { + return validPropagators[0]; + } else { + return new core_1.CompositePropagator({ + propagators: validPropagators + }); + } + } + exports.getPropagatorFromConfiguration = getPropagatorFromConfiguration; + function setupContextManager(contextManager) { + if (contextManager === null) { + return; + } + if (contextManager === undefined) { + const defaultContextManager = new context_async_hooks_1.AsyncLocalStorageContextManager; + defaultContextManager.enable(); + api_1.context.setGlobalContextManager(defaultContextManager); + return; + } + contextManager.enable(); + api_1.context.setGlobalContextManager(contextManager); + } + exports.setupContextManager = setupContextManager; + function setupPropagator(propagator) { + if (propagator === null) { + return; + } + if (propagator === undefined) { + api_1.propagation.setGlobalPropagator(new core_1.CompositePropagator({ + propagators: [ + new core_1.W3CTraceContextPropagator, + new core_1.W3CBaggagePropagator + ] + })); + return; + } + api_1.propagation.setGlobalPropagator(propagator); + } + exports.setupPropagator = setupPropagator; + function getKeyListFromObjectArray(obj) { + if (!obj || obj.length === 0) { + return; + } + const keys = []; + for (const item of obj) { + for (const key of Object.keys(item)) { + keys.push(key); + } + } + return keys; + } + exports.getKeyListFromObjectArray = getKeyListFromObjectArray; + function getNonNegativeNumberFromEnv(envVarName) { + const value = (0, core_1.getNumberFromEnv)(envVarName); + if (value != null && value <= 0) { + api_1.diag.warn(`${envVarName} (${value}) is invalid, expected number greater than 0, using default.`); + return; + } + return value; + } + exports.getNonNegativeNumberFromEnv = getNonNegativeNumberFromEnv; + function getPeriodicExportingMetricReaderFromEnv(exporter) { + const defaultTimeoutMillis = 30000; + const defaultIntervalMillis = 60000; + const rawExportIntervalMillis = getNonNegativeNumberFromEnv("OTEL_METRIC_EXPORT_INTERVAL"); + const rawExportTimeoutMillis = getNonNegativeNumberFromEnv("OTEL_METRIC_EXPORT_TIMEOUT"); + const exportIntervalMillis = rawExportIntervalMillis ?? defaultIntervalMillis; + let exportTimeoutMillis = rawExportTimeoutMillis ?? defaultTimeoutMillis; + if (exportTimeoutMillis > exportIntervalMillis) { + const timeoutSource = rawExportTimeoutMillis != null ? rawExportTimeoutMillis.toString() : `${defaultTimeoutMillis}, default`; + const intervalSource = rawExportIntervalMillis != null ? rawExportIntervalMillis.toString() : `${defaultIntervalMillis}, default`; + const bothSetByUser = rawExportTimeoutMillis != null && rawExportIntervalMillis != null; + const logMessage = `OTEL_METRIC_EXPORT_TIMEOUT (${timeoutSource}) is greater than OTEL_METRIC_EXPORT_INTERVAL (${intervalSource}). Clamping timeout to interval value.`; + if (bothSetByUser) { + api_1.diag.warn(logMessage); + } else { + api_1.diag.info(logMessage); + } + exportTimeoutMillis = exportIntervalMillis; + } + return new sdk_metrics_1.PeriodicExportingMetricReader({ + exportTimeoutMillis, + exportIntervalMillis, + exporter + }); + } + exports.getPeriodicExportingMetricReaderFromEnv = getPeriodicExportingMetricReaderFromEnv; + function getOtlpMetricExporterFromEnv() { + const protocol = ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim() || "http/protobuf"; + switch (protocol) { + case "grpc": + return new exporter_metrics_otlp_grpc_1.OTLPMetricExporter; + case "http/json": + return new exporter_metrics_otlp_http_1.OTLPMetricExporter; + case "http/protobuf": + return new exporter_metrics_otlp_proto_1.OTLPMetricExporter; + } + api_1.diag.warn(`Unsupported OTLP metrics protocol: "${protocol}". Using http/protobuf.`); + return new exporter_metrics_otlp_proto_1.OTLPMetricExporter; + } + exports.getOtlpMetricExporterFromEnv = getOtlpMetricExporterFromEnv; + function getMetricProducersFromConfiguration(producers) { + if (!producers || producers.length === 0) { + return; + } + const result = []; + for (const producer of producers) { + if (producer.opencensus) { + try { + const { + OpenCensusMetricProducer + } = (()=>{throw new Error("Cannot require module "+"@opentelemetry/shim-opencensus");})(); + result.push(new OpenCensusMetricProducer); + } catch { + api_1.diag.warn("OpenCensus metric producer configured but @opentelemetry/shim-opencensus is not installed."); + } + } else { + api_1.diag.warn("Unsupported metric producer configured."); + } + } + return result.length > 0 ? result : undefined; + } + function getPeriodicMetricReaderFromConfiguration(periodic) { + if (periodic.exporter) { + let exporter; + if (periodic.exporter.otlp_http !== undefined) { + const encoding = periodic.exporter.otlp_http?.encoding ?? "protobuf"; + if (encoding === "json") { + exporter = new exporter_metrics_otlp_http_1.OTLPMetricExporter({ + compression: periodic.exporter.otlp_http?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE + }); + } else if (encoding === "protobuf") { + exporter = new exporter_metrics_otlp_proto_1.OTLPMetricExporter({ + compression: periodic.exporter.otlp_http?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE + }); + } else { + api_1.diag.warn(`Unsupported OTLP metrics encoding: ${encoding}.`); + } + } + if (periodic.exporter.otlp_grpc !== undefined) { + exporter = new exporter_metrics_otlp_grpc_1.OTLPMetricExporter({ + compression: periodic.exporter.otlp_grpc?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE + }); + } + const metricProducers = getMetricProducersFromConfiguration(periodic.producers); + if (exporter) { + return new sdk_metrics_1.PeriodicExportingMetricReader({ + exportIntervalMillis: periodic.interval ?? 60000, + exportTimeoutMillis: periodic.timeout ?? 30000, + exporter, + metricProducers + }); + } + if (periodic.exporter.console !== undefined) { + return new sdk_metrics_1.PeriodicExportingMetricReader({ + exporter: new sdk_metrics_1.ConsoleMetricExporter, + metricProducers + }); + } + } + api_1.diag.warn("Unsupported Metric Exporter."); + return; + } + exports.getPeriodicMetricReaderFromConfiguration = getPeriodicMetricReaderFromConfiguration; + function getLoggerProviderConfigFromEnv() { + return { + logRecordLimits: { + attributeCountLimit: getNonNegativeNumberFromEnv("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT") ?? getNonNegativeNumberFromEnv("OTEL_ATTRIBUTE_COUNT_LIMIT"), + attributeValueLengthLimit: getNonNegativeNumberFromEnv("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT") ?? getNonNegativeNumberFromEnv("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") + } + }; + } + exports.getLoggerProviderConfigFromEnv = getLoggerProviderConfigFromEnv; + function getBatchLogRecordProcessorConfigFromEnv() { + return { + maxQueueSize: getNonNegativeNumberFromEnv("OTEL_BLRP_MAX_QUEUE_SIZE"), + scheduledDelayMillis: getNonNegativeNumberFromEnv("OTEL_BLRP_SCHEDULE_DELAY"), + exportTimeoutMillis: getNonNegativeNumberFromEnv("OTEL_BLRP_EXPORT_TIMEOUT"), + maxExportBatchSize: getNonNegativeNumberFromEnv("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE") + }; + } + exports.getBatchLogRecordProcessorConfigFromEnv = getBatchLogRecordProcessorConfigFromEnv; + function getBatchLogRecordProcessorFromEnv(exporter) { + return new sdk_logs_1.BatchLogRecordProcessor(exporter, getBatchLogRecordProcessorConfigFromEnv()); + } + exports.getBatchLogRecordProcessorFromEnv = getBatchLogRecordProcessorFromEnv; + function getLogRecordExporter(exporter) { + if (exporter.otlp_http !== undefined) { + const cfg = exporter.otlp_http; + const commonOpts = { + compression: cfg?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE, + url: cfg?.endpoint ?? undefined, + headers: getHeadersFromConfiguration(cfg?.headers), + timeoutMillis: validateExporterTimeout(cfg?.timeout), + httpAgentOptions: getHttpAgentOptionsFromTls(cfg?.tls) + }; + const encoding = cfg?.encoding ?? "protobuf"; + if (encoding === "json") { + return new exporter_logs_otlp_http_1.OTLPLogExporter(commonOpts); + } + if (encoding === "protobuf") { + return new exporter_logs_otlp_proto_1.OTLPLogExporter(commonOpts); + } + api_1.diag.warn(`Unsupported OTLP logs encoding: ${encoding}. Using http/protobuf.`); + return new exporter_logs_otlp_proto_1.OTLPLogExporter(commonOpts); + } else if (exporter.otlp_grpc !== undefined) { + const cfg = exporter.otlp_grpc; + return new exporter_logs_otlp_grpc_1.OTLPLogExporter({ + compression: cfg?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE, + url: cfg?.endpoint ?? undefined, + timeoutMillis: validateExporterTimeout(cfg?.timeout), + credentials: getGrpcCredentialsFromTls(cfg?.tls), + metadata: getGrpcMetadataFromHeaders(cfg?.headers) + }); + } else if (exporter.console !== undefined) { + return new sdk_logs_1.ConsoleLogRecordExporter; + } + api_1.diag.warn("Unsupported Exporter value. No Log Record Exporter registered"); + return; + } + exports.getLogRecordExporter = getLogRecordExporter; + function getLogRecordProcessorsFromConfiguration(config) { + const logRecordProcessors = []; + config.logger_provider?.processors?.forEach((processor) => { + if (processor.batch) { + const exporter = getLogRecordExporter(processor.batch.exporter); + if (exporter) { + logRecordProcessors.push(new sdk_logs_1.BatchLogRecordProcessor(exporter, { + maxQueueSize: processor.batch.max_queue_size ?? undefined, + maxExportBatchSize: processor.batch.max_export_batch_size ?? undefined, + scheduledDelayMillis: processor.batch.schedule_delay ?? undefined, + exportTimeoutMillis: processor.batch.export_timeout ?? undefined + })); + } + } + if (processor.simple) { + const exporter = getLogRecordExporter(processor.simple.exporter); + if (exporter) { + logRecordProcessors.push(new sdk_logs_1.SimpleLogRecordProcessor(exporter)); + } + } + }); + if (logRecordProcessors.length > 0) { + return logRecordProcessors; + } + return; + } + exports.getLogRecordProcessorsFromConfiguration = getLogRecordProcessorsFromConfiguration; + function getHeadersFromConfiguration(headers) { + if (!headers) { + return; + } + const result = {}; + headers.forEach((header) => { + if (header.value !== null) { + result[header.name] = header.value; + } + }); + return result; + } + exports.getHeadersFromConfiguration = getHeadersFromConfiguration; + function validateExporterTimeout(timeout) { + if (timeout === null) { + return; + } else if (timeout === 0) { + api_1.diag.warn("Exporter timeout of 0 (infinite) is not supported. Using default timeout."); + return; + } + return timeout; + } + function getHttpAgentOptionsFromTls(tls) { + if (tls && (tls.ca_file || tls.cert_file || tls.key_file)) { + return { + ca: readFileOrWarn(tls.ca_file, "TLS CA"), + cert: readFileOrWarn(tls.cert_file, "TLS cert"), + key: readFileOrWarn(tls.key_file, "TLS key") + }; + } + return; + } + exports.getHttpAgentOptionsFromTls = getHttpAgentOptionsFromTls; + function getGrpcCredentialsFromTls(tls) { + if (tls?.insecure) { + return (0, otlp_grpc_exporter_base_1.createInsecureCredentials)(); + } + const rootCert = readFileOrWarn(tls?.ca_file, "TLS CA"); + const privateKey = readFileOrWarn(tls?.key_file, "TLS key"); + const certChain = readFileOrWarn(tls?.cert_file, "TLS cert"); + if (rootCert || privateKey || certChain) { + try { + return (0, otlp_grpc_exporter_base_1.createSslCredentials)(rootCert, privateKey, certChain); + } catch (e) { + api_1.diag.warn(`Failed to create gRPC SSL credentials: ${e}`); + return; + } + } + return; + } + function getGrpcMetadataFromHeaders(headers) { + if (!headers || headers.length === 0) { + return; + } + const metadata = (0, otlp_grpc_exporter_base_1.createEmptyMetadata)(); + for (const header of headers) { + if (header.value !== null) { + metadata.set(header.name, header.value); + } + } + return metadata; + } + function readFileOrWarn(filePath, label) { + if (!filePath) + return; + try { + return fs.readFileSync(filePath); + } catch (e) { + api_1.diag.warn(`Failed to read ${label} file at ${filePath}: ${e}`); + return; + } + } + function getSpanExporter(exporter) { + if (exporter.otlp_http !== undefined) { + const encoding = exporter.otlp_http?.encoding ?? "protobuf"; + if (encoding === "json") { + return new exporter_trace_otlp_http_1.OTLPTraceExporter({ + compression: exporter.otlp_http?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE, + url: exporter.otlp_http?.endpoint ?? undefined, + headers: getHeadersFromConfiguration(exporter.otlp_http?.headers), + timeoutMillis: validateExporterTimeout(exporter.otlp_http?.timeout), + httpAgentOptions: getHttpAgentOptionsFromTls(exporter.otlp_http?.tls) + }); + } else { + return new exporter_trace_otlp_proto_1.OTLPTraceExporter({ + compression: exporter.otlp_http?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE, + url: exporter.otlp_http?.endpoint ?? undefined, + headers: getHeadersFromConfiguration(exporter.otlp_http?.headers), + timeoutMillis: validateExporterTimeout(exporter.otlp_http?.timeout), + httpAgentOptions: getHttpAgentOptionsFromTls(exporter.otlp_http?.tls) + }); + } + } else if (exporter.otlp_grpc !== undefined) { + return new exporter_trace_otlp_grpc_1.OTLPTraceExporter({ + compression: exporter.otlp_grpc?.compression === "gzip" ? otlp_exporter_base_1.CompressionAlgorithm.GZIP : otlp_exporter_base_1.CompressionAlgorithm.NONE, + url: exporter.otlp_grpc?.endpoint ?? undefined, + timeoutMillis: validateExporterTimeout(exporter.otlp_grpc?.timeout), + credentials: getGrpcCredentialsFromTls(exporter.otlp_grpc?.tls), + metadata: getGrpcMetadataFromHeaders(exporter.otlp_grpc?.headers) + }); + } else if (exporter.console !== undefined) { + return new sdk_trace_base_1.ConsoleSpanExporter; + } + api_1.diag.warn("Unsupported Exporter value. No Span Exporter registered"); + return; + } + exports.getSpanExporter = getSpanExporter; + function getSpanProcessorsFromConfiguration(config) { + const spanProcessors = []; + config.tracer_provider?.processors?.forEach((processor) => { + if (processor.batch) { + const exporter = getSpanExporter(processor.batch.exporter); + if (exporter) { + spanProcessors.push(new sdk_trace_base_1.BatchSpanProcessor(exporter, { + maxQueueSize: processor.batch.max_queue_size ?? undefined, + maxExportBatchSize: processor.batch.max_export_batch_size ?? undefined, + scheduledDelayMillis: processor.batch.schedule_delay ?? undefined, + exportTimeoutMillis: processor.batch.export_timeout ?? undefined + })); + } + } + if (processor.simple) { + const exporter = getSpanExporter(processor.simple.exporter); + if (exporter) { + spanProcessors.push(new sdk_trace_base_1.SimpleSpanProcessor(exporter)); + } + } + }); + if (spanProcessors.length > 0) { + return spanProcessors; + } + return; + } + exports.getSpanProcessorsFromConfiguration = getSpanProcessorsFromConfiguration; + function getSpanLimitsFromConfiguration(config) { + if (config.tracer_provider?.limits) { + const limitsConfig = config.tracer_provider.limits; + const spanLimits = {}; + spanLimits.attributeCountLimit = limitsConfig.attribute_count_limit ?? 128; + spanLimits.eventCountLimit = limitsConfig.event_count_limit ?? 128; + spanLimits.linkCountLimit = limitsConfig.link_count_limit ?? 128; + spanLimits.attributePerLinkCountLimit = limitsConfig.link_attribute_count_limit ?? 128; + spanLimits.attributePerEventCountLimit = limitsConfig.event_attribute_count_limit ?? 128; + if (limitsConfig.attribute_value_length_limit != null) { + spanLimits.attributeValueLengthLimit = limitsConfig.attribute_value_length_limit; + } + return spanLimits; + } + return; + } + exports.getSpanLimitsFromConfiguration = getSpanLimitsFromConfiguration; + function getMeterReadersFromConfiguration(config) { + const metricReaders = []; + config.meter_provider?.readers?.forEach((reader) => { + if (reader.periodic) { + const periodicReader = getPeriodicMetricReaderFromConfiguration(reader.periodic); + if (periodicReader) { + metricReaders.push(periodicReader); + } + } + }); + if (metricReaders.length > 0) { + return metricReaders; + } + return; + } + exports.getMeterReadersFromConfiguration = getMeterReadersFromConfiguration; + function getInstrumentType(instrument) { + switch (instrument) { + case "counter": + return sdk_metrics_1.InstrumentType.COUNTER; + case "gauge": + return sdk_metrics_1.InstrumentType.GAUGE; + case "histogram": + return sdk_metrics_1.InstrumentType.HISTOGRAM; + case "observable_counter": + return sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER; + case "observable_gauge": + return sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE; + case "observable_up_down_counter": + return sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; + case "up_down_counter": + return sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER; + default: + api_1.diag.warn(`Unsupported instrument type: ${instrument}`); + return; + } + } + exports.getInstrumentType = getInstrumentType; + function getAggregationType(aggregation) { + if (aggregation.default) { + return { + type: sdk_metrics_1.AggregationType.DEFAULT + }; + } + if (aggregation.drop) { + return { + type: sdk_metrics_1.AggregationType.DROP + }; + } + if (aggregation.explicit_bucket_histogram) { + return { + type: sdk_metrics_1.AggregationType.EXPLICIT_BUCKET_HISTOGRAM, + options: { + recordMinMax: aggregation.explicit_bucket_histogram.record_min_max ?? true, + boundaries: aggregation.explicit_bucket_histogram.boundaries ?? [ + 0, + 5, + 10, + 25, + 50, + 75, + 100, + 250, + 500, + 750, + 1000, + 2500, + 5000, + 7500, + 1e4 + ] + } + }; + } + if (aggregation.base2_exponential_bucket_histogram) { + return { + type: sdk_metrics_1.AggregationType.EXPONENTIAL_HISTOGRAM, + options: { + recordMinMax: aggregation.base2_exponential_bucket_histogram.record_min_max ?? undefined, + maxSize: aggregation.base2_exponential_bucket_histogram.max_size ?? undefined + } + }; + } + if (aggregation.last_value) { + return { + type: sdk_metrics_1.AggregationType.LAST_VALUE + }; + } + if (aggregation.sum) { + return { + type: sdk_metrics_1.AggregationType.SUM + }; + } + api_1.diag.warn("Unsupported aggregation type"); + return; + } + exports.getAggregationType = getAggregationType; + function getMeterViewsFromConfiguration(config) { + const metricViews = []; + config.meter_provider?.views?.forEach((view) => { + const viewOption = {}; + if (view.selector) { + if (view.selector.instrument_name) { + viewOption.instrumentName = view.selector.instrument_name; + } + if (view.selector.instrument_type) { + const instrumentType = getInstrumentType(view.selector.instrument_type); + if (instrumentType) { + viewOption.instrumentType = instrumentType; + } + } + if (view.selector.unit) { + viewOption.instrumentUnit = view.selector.unit; + } + if (view.selector.meter_name) { + viewOption.meterName = view.selector.meter_name; + } + if (view.selector.meter_version) { + viewOption.meterVersion = view.selector.meter_version; + } + if (view.selector.meter_schema_url) { + viewOption.meterSchemaUrl = view.selector.meter_schema_url; + } + } + if (view.stream) { + if (view.stream.name) { + viewOption.name = view.stream.name; + } + viewOption.aggregationCardinalityLimit = view.stream.aggregation_cardinality_limit ?? 2000; + if (view.stream.description) { + viewOption.description = view.stream.description; + } + if (view.stream.aggregation) { + const aggregationType = getAggregationType(view.stream.aggregation); + if (aggregationType) { + viewOption.aggregation = aggregationType; + } + } + if (view.stream.attribute_keys) { + const processors = []; + if (view.stream.attribute_keys.included && view.stream.attribute_keys.included.length > 0) { + processors.push((0, sdk_metrics_1.createAllowListAttributesProcessor)(view.stream.attribute_keys.included)); + } + if (view.stream.attribute_keys.excluded && view.stream.attribute_keys.excluded.length > 0) { + processors.push((0, sdk_metrics_1.createDenyListAttributesProcessor)(view.stream.attribute_keys.excluded)); + } + if (processors.length > 0) { + viewOption.attributesProcessors = processors; + } + } + } + if (Object.keys(viewOption).length > 0) { + metricViews.push(viewOption); + } + }); + if (metricViews.length > 0) { + return metricViews; + } + return; + } + exports.getMeterViewsFromConfiguration = getMeterViewsFromConfiguration; + function getInstanceID(config) { + if (config.resource?.attributes) { + for (let i = 0;i < config.resource.attributes.length; i++) { + const element = config.resource.attributes[i]; + if (element.name === "service.instance.id") { + return element.value?.toString(); + } + } + } + return; + } + exports.getInstanceID = getInstanceID; + var DEFAULT_RATIO = 1; + function buildSamplerFromConfig(samplerConfig) { + if (samplerConfig.always_on !== undefined) { + return new sdk_trace_base_1.AlwaysOnSampler; + } + if (samplerConfig.always_off !== undefined) { + return new sdk_trace_base_1.AlwaysOffSampler; + } + if (samplerConfig.trace_id_ratio_based !== undefined) { + return new sdk_trace_base_1.TraceIdRatioBasedSampler(samplerConfig.trace_id_ratio_based?.ratio ?? DEFAULT_RATIO); + } + if (samplerConfig.parent_based !== undefined) { + const pb = samplerConfig.parent_based ?? {}; + return new sdk_trace_base_1.ParentBasedSampler({ + root: pb.root ? buildSamplerFromConfig(pb.root) : new sdk_trace_base_1.AlwaysOnSampler, + remoteParentSampled: pb.remote_parent_sampled ? buildSamplerFromConfig(pb.remote_parent_sampled) : undefined, + remoteParentNotSampled: pb.remote_parent_not_sampled ? buildSamplerFromConfig(pb.remote_parent_not_sampled) : undefined, + localParentSampled: pb.local_parent_sampled ? buildSamplerFromConfig(pb.local_parent_sampled) : undefined, + localParentNotSampled: pb.local_parent_not_sampled ? buildSamplerFromConfig(pb.local_parent_not_sampled) : undefined + }); + } + api_1.diag.error("Unknown sampler config, defaulting to ParentBased(AlwaysOn)."); + return new sdk_trace_base_1.ParentBasedSampler({ root: new sdk_trace_base_1.AlwaysOnSampler }); + } + exports.buildSamplerFromConfig = buildSamplerFromConfig; +}); + +// node_modules/@opentelemetry/sdk-node/build/src/sdk.js +var require_sdk = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NodeSDK = undefined; + var api_1 = require_src(); + var api_logs_1 = require_src5(); + var instrumentation_1 = require_src15(); + var resources_1 = require_src6(); + var sdk_logs_1 = require_src10(); + var exporter_logs_otlp_http_1 = require_src16(); + var exporter_logs_otlp_grpc_1 = require_src21(); + var exporter_logs_otlp_proto_1 = require_src22(); + var exporter_prometheus_1 = require_src23(); + var sdk_metrics_1 = require_src7(); + var sdk_trace_base_1 = require_src12(); + var sdk_trace_node_1 = require_src13(); + var semantic_conventions_1 = require_src2(); + var core_1 = require_src3(); + var utils_1 = require_utils13(); + function getMetricReadersFromEnv() { + const metricReaders = []; + const enabledExporters = Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_METRICS_EXPORTER") ?? [])); + if (enabledExporters.length === 0) { + api_1.diag.debug("OTEL_METRICS_EXPORTER is empty. Using default otlp exporter."); + enabledExporters.push("otlp"); + } + if (enabledExporters.includes("none")) { + api_1.diag.info('OTEL_METRICS_EXPORTER contains "none". Metric provider will not be initialized.'); + return metricReaders; + } + enabledExporters.forEach((exporter) => { + if (exporter === "otlp") { + metricReaders.push((0, utils_1.getPeriodicExportingMetricReaderFromEnv)((0, utils_1.getOtlpMetricExporterFromEnv)())); + } else if (exporter === "console") { + metricReaders.push(new sdk_metrics_1.PeriodicExportingMetricReader({ + exporter: new sdk_metrics_1.ConsoleMetricExporter + })); + } else if (exporter === "prometheus") { + metricReaders.push(new exporter_prometheus_1.PrometheusExporter); + } else { + api_1.diag.warn(`Unsupported OTEL_METRICS_EXPORTER value: "${exporter}". Supported values are: otlp, console, prometheus, none.`); + } + }); + return metricReaders; + } + + class NodeSDK { + _tracerProviderConfig; + _loggerProviderConfig; + _meterProviderConfig; + _instrumentations; + _resource; + _resourceDetectors; + _autoDetectResources; + _tracerProvider; + _loggerProvider; + _meterProvider; + _serviceName; + _configuration; + _disabled; + constructor(configuration = {}) { + if ((0, core_1.getBooleanFromEnv)("OTEL_SDK_DISABLED")) { + this._disabled = true; + } + const logLevel = (0, core_1.getStringFromEnv)("OTEL_LOG_LEVEL"); + if (logLevel != null) { + api_1.diag.setLogger(new api_1.DiagConsoleLogger, { + logLevel: (0, core_1.diagLogLevelFromString)(logLevel) + }); + } + this._configuration = configuration; + this._resource = configuration.resource ?? (0, resources_1.defaultResource)(); + this._autoDetectResources = configuration.autoDetectResources ?? true; + if (!this._autoDetectResources) { + this._resourceDetectors = []; + } else if (configuration.resourceDetectors != null) { + this._resourceDetectors = configuration.resourceDetectors; + } else if ((0, core_1.getStringFromEnv)("OTEL_NODE_RESOURCE_DETECTORS")) { + this._resourceDetectors = (0, utils_1.getResourceDetectorsFromEnv)(); + } else { + this._resourceDetectors = [resources_1.envDetector, resources_1.processDetector, resources_1.hostDetector]; + } + this._serviceName = configuration.serviceName; + if (configuration.traceExporter || configuration.spanProcessor || configuration.spanProcessors) { + const tracerProviderConfig = {}; + if (configuration.sampler) { + tracerProviderConfig.sampler = configuration.sampler; + } + if (configuration.spanLimits) { + tracerProviderConfig.spanLimits = configuration.spanLimits; + } + if (configuration.idGenerator) { + tracerProviderConfig.idGenerator = configuration.idGenerator; + } + if (configuration.spanProcessor) { + api_1.diag.warn("The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead."); + } + const spanProcessor = configuration.spanProcessor ?? new sdk_trace_base_1.BatchSpanProcessor(configuration.traceExporter); + const spanProcessors = configuration.spanProcessors ?? [spanProcessor]; + this._tracerProviderConfig = { + tracerConfig: tracerProviderConfig, + spanProcessors + }; + } + if (configuration.logRecordProcessors) { + this._loggerProviderConfig = { + logRecordProcessors: configuration.logRecordProcessors + }; + } else if (configuration.logRecordProcessor) { + this._loggerProviderConfig = { + logRecordProcessors: [configuration.logRecordProcessor] + }; + api_1.diag.warn("The 'logRecordProcessor' option is deprecated. Please use 'logRecordProcessors' instead."); + } else { + this.configureLoggerProviderFromEnv(); + } + if (configuration.metricReaders) { + this._meterProviderConfig = { + readers: configuration.metricReaders, + views: configuration.views + }; + } else if (configuration.metricReader) { + this._meterProviderConfig = { + readers: [configuration.metricReader], + views: configuration.views + }; + api_1.diag.warn("The 'metricReader' option is deprecated. Please use 'metricReaders' instead."); + } else { + this._meterProviderConfig = { + readers: getMetricReadersFromEnv(), + views: configuration.views + }; + } + this._instrumentations = configuration.instrumentations?.flat() ?? []; + } + start() { + if (this._disabled) { + return; + } + (0, instrumentation_1.registerInstrumentations)({ + instrumentations: this._instrumentations + }); + (0, utils_1.setupContextManager)(this._configuration?.contextManager); + (0, utils_1.setupPropagator)(this._configuration?.textMapPropagator === null ? null : this._configuration?.textMapPropagator ?? (0, utils_1.getPropagatorFromEnv)()); + if (this._autoDetectResources) { + const internalConfig = { + detectors: this._resourceDetectors + }; + this._resource = this._resource.merge((0, resources_1.detectResources)(internalConfig)); + } + this._resource = this._serviceName === undefined ? this._resource : this._resource.merge((0, resources_1.resourceFromAttributes)({ + [semantic_conventions_1.ATTR_SERVICE_NAME]: this._serviceName + })); + const sdkMetricsEnabled = (0, core_1.getBooleanFromEnv)("OTEL_NODE_EXPERIMENTAL_SDK_METRICS"); + if (this._meterProviderConfig?.readers && this._meterProviderConfig.readers.length > 0) { + const meterProvider = new sdk_metrics_1.MeterProvider({ + resource: this._resource, + views: this._meterProviderConfig?.views ?? [], + readers: this._meterProviderConfig.readers, + sdkMetricsEnabled + }); + this._meterProvider = meterProvider; + api_1.metrics.setGlobalMeterProvider(meterProvider); + for (const instrumentation of this._instrumentations) { + instrumentation.setMeterProvider(api_1.metrics.getMeterProvider()); + } + } + const spanProcessors = this._tracerProviderConfig ? this._tracerProviderConfig.spanProcessors : (0, utils_1.getSpanProcessorsFromEnv)(); + if (spanProcessors.length > 0) { + this._tracerProvider = new sdk_trace_node_1.NodeTracerProvider({ + ...this._configuration, + resource: this._resource, + meterProvider: sdkMetricsEnabled ? this._meterProvider : undefined, + spanProcessors + }); + api_1.trace.setGlobalTracerProvider(this._tracerProvider); + } + if (this._loggerProviderConfig) { + const loggerProvider = new sdk_logs_1.LoggerProvider({ + ...(0, utils_1.getLoggerProviderConfigFromEnv)(), + resource: this._resource, + processors: this._loggerProviderConfig.logRecordProcessors, + meterProvider: sdkMetricsEnabled ? this._meterProvider : undefined + }); + this._loggerProvider = loggerProvider; + api_logs_1.logs.setGlobalLoggerProvider(loggerProvider); + } + } + shutdown() { + const promises = []; + if (this._tracerProvider) { + promises.push(this._tracerProvider.shutdown()); + } + if (this._loggerProvider) { + promises.push(this._loggerProvider.shutdown()); + } + if (this._meterProvider) { + promises.push(this._meterProvider.shutdown()); + } + return Promise.all(promises).then(() => {}); + } + configureLoggerProviderFromEnv() { + const enabledExporters = Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_LOGS_EXPORTER") ?? [])); + if (enabledExporters.length === 0) { + api_1.diag.debug("OTEL_LOGS_EXPORTER is empty. Using default otlp exporter."); + enabledExporters.push("otlp"); + } + if (enabledExporters.includes("none")) { + api_1.diag.info('OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.'); + return; + } + const exporters = []; + enabledExporters.forEach((exporter) => { + if (exporter === "otlp") { + const protocol = ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL"))?.trim() || "http/protobuf"; + switch (protocol) { + case "grpc": + exporters.push(new exporter_logs_otlp_grpc_1.OTLPLogExporter); + break; + case "http/json": + exporters.push(new exporter_logs_otlp_http_1.OTLPLogExporter); + break; + case "http/protobuf": + exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter); + break; + default: + api_1.diag.warn(`Unsupported OTLP logs protocol: "${protocol}". Using http/protobuf.`); + exporters.push(new exporter_logs_otlp_proto_1.OTLPLogExporter); + } + } else if (exporter === "console") { + exporters.push(new sdk_logs_1.ConsoleLogRecordExporter); + } else { + api_1.diag.warn(`Unsupported OTEL_LOGS_EXPORTER value: "${exporter}". Supported values are: otlp, console, none.`); + } + }); + if (exporters.length > 0) { + this._loggerProviderConfig = { + logRecordProcessors: exporters.map((exporter) => { + if (exporter instanceof sdk_logs_1.ConsoleLogRecordExporter) { + return new sdk_logs_1.SimpleLogRecordProcessor(exporter); + } else { + return (0, utils_1.getBatchLogRecordProcessorFromEnv)(exporter); + } + }) + }; + } + } + } + exports.NodeSDK = NodeSDK; +}); + +// node_modules/yaml/dist/nodes/identity.js +var require_identity = __commonJS((exports) => { + var ALIAS = Symbol.for("yaml.alias"); + var DOC = Symbol.for("yaml.document"); + var MAP = Symbol.for("yaml.map"); + var PAIR = Symbol.for("yaml.pair"); + var SCALAR = Symbol.for("yaml.scalar"); + var SEQ = Symbol.for("yaml.seq"); + var NODE_TYPE = Symbol.for("yaml.node.type"); + var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; + var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; + var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; + var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; + var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; + var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; + function isCollection(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case MAP: + case SEQ: + return true; + } + return false; + } + function isNode(node) { + if (node && typeof node === "object") + switch (node[NODE_TYPE]) { + case ALIAS: + case MAP: + case SCALAR: + case SEQ: + return true; + } + return false; + } + var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; + exports.ALIAS = ALIAS; + exports.DOC = DOC; + exports.MAP = MAP; + exports.NODE_TYPE = NODE_TYPE; + exports.PAIR = PAIR; + exports.SCALAR = SCALAR; + exports.SEQ = SEQ; + exports.hasAnchor = hasAnchor; + exports.isAlias = isAlias; + exports.isCollection = isCollection; + exports.isDocument = isDocument; + exports.isMap = isMap; + exports.isNode = isNode; + exports.isPair = isPair; + exports.isScalar = isScalar; + exports.isSeq = isSeq; +}); + +// node_modules/yaml/dist/visit.js +var require_visit = __commonJS((exports) => { + var identity = require_identity(); + var BREAK = Symbol("break visit"); + var SKIP = Symbol("skip children"); + var REMOVE = Symbol("remove node"); + function visit(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + visit_(null, node, visitor_, Object.freeze([])); + } + visit.BREAK = BREAK; + visit.SKIP = SKIP; + visit.REMOVE = REMOVE; + function visit_(key, node, visitor, path) { + const ctrl = callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visit_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0;i < node.items.length; ++i) { + const ci = visit_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = visit_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = visit_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; + } + async function visitAsync(node, visitor) { + const visitor_ = initVisitor(visitor); + if (identity.isDocument(node)) { + const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); + if (cd === REMOVE) + node.contents = null; + } else + await visitAsync_(null, node, visitor_, Object.freeze([])); + } + visitAsync.BREAK = BREAK; + visitAsync.SKIP = SKIP; + visitAsync.REMOVE = REMOVE; + async function visitAsync_(key, node, visitor, path) { + const ctrl = await callVisitor(key, node, visitor, path); + if (identity.isNode(ctrl) || identity.isPair(ctrl)) { + replaceNode(key, path, ctrl); + return visitAsync_(key, ctrl, visitor, path); + } + if (typeof ctrl !== "symbol") { + if (identity.isCollection(node)) { + path = Object.freeze(path.concat(node)); + for (let i = 0;i < node.items.length; ++i) { + const ci = await visitAsync_(i, node.items[i], visitor, path); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + node.items.splice(i, 1); + i -= 1; + } + } + } else if (identity.isPair(node)) { + path = Object.freeze(path.concat(node)); + const ck = await visitAsync_("key", node.key, visitor, path); + if (ck === BREAK) + return BREAK; + else if (ck === REMOVE) + node.key = null; + const cv = await visitAsync_("value", node.value, visitor, path); + if (cv === BREAK) + return BREAK; + else if (cv === REMOVE) + node.value = null; + } + } + return ctrl; + } + function initVisitor(visitor) { + if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { + return Object.assign({ + Alias: visitor.Node, + Map: visitor.Node, + Scalar: visitor.Node, + Seq: visitor.Node + }, visitor.Value && { + Map: visitor.Value, + Scalar: visitor.Value, + Seq: visitor.Value + }, visitor.Collection && { + Map: visitor.Collection, + Seq: visitor.Collection + }, visitor); + } + return visitor; + } + function callVisitor(key, node, visitor, path) { + if (typeof visitor === "function") + return visitor(key, node, path); + if (identity.isMap(node)) + return visitor.Map?.(key, node, path); + if (identity.isSeq(node)) + return visitor.Seq?.(key, node, path); + if (identity.isPair(node)) + return visitor.Pair?.(key, node, path); + if (identity.isScalar(node)) + return visitor.Scalar?.(key, node, path); + if (identity.isAlias(node)) + return visitor.Alias?.(key, node, path); + return; + } + function replaceNode(key, path, node) { + const parent = path[path.length - 1]; + if (identity.isCollection(parent)) { + parent.items[key] = node; + } else if (identity.isPair(parent)) { + if (key === "key") + parent.key = node; + else + parent.value = node; + } else if (identity.isDocument(parent)) { + parent.contents = node; + } else { + const pt = identity.isAlias(parent) ? "alias" : "scalar"; + throw new Error(`Cannot replace node with ${pt} parent`); + } + } + exports.visit = visit; + exports.visitAsync = visitAsync; +}); + +// node_modules/yaml/dist/doc/directives.js +var require_directives2 = __commonJS((exports) => { + var identity = require_identity(); + var visit = require_visit(); + var escapeChars = { + "!": "%21", + ",": "%2C", + "[": "%5B", + "]": "%5D", + "{": "%7B", + "}": "%7D" + }; + var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); + + class Directives { + constructor(yaml, tags) { + this.docStart = null; + this.docEnd = false; + this.yaml = Object.assign({}, Directives.defaultYaml, yaml); + this.tags = Object.assign({}, Directives.defaultTags, tags); + } + clone() { + const copy = new Directives(this.yaml, this.tags); + copy.docStart = this.docStart; + return copy; + } + atDocument() { + const res = new Directives(this.yaml, this.tags); + switch (this.yaml.version) { + case "1.1": + this.atNextDocument = true; + break; + case "1.2": + this.atNextDocument = false; + this.yaml = { + explicit: Directives.defaultYaml.explicit, + version: "1.2" + }; + this.tags = Object.assign({}, Directives.defaultTags); + break; + } + return res; + } + add(line, onError) { + if (this.atNextDocument) { + this.yaml = { explicit: Directives.defaultYaml.explicit, version: "1.1" }; + this.tags = Object.assign({}, Directives.defaultTags); + this.atNextDocument = false; + } + const parts = line.trim().split(/[ \t]+/); + const name = parts.shift(); + switch (name) { + case "%TAG": { + if (parts.length !== 2) { + onError(0, "%TAG directive should contain exactly two parts"); + if (parts.length < 2) + return false; + } + const [handle, prefix] = parts; + this.tags[handle] = prefix; + return true; + } + case "%YAML": { + this.yaml.explicit = true; + if (parts.length !== 1) { + onError(0, "%YAML directive should contain exactly one part"); + return false; + } + const [version] = parts; + if (version === "1.1" || version === "1.2") { + this.yaml.version = version; + return true; + } else { + const isValid = /^\d+\.\d+$/.test(version); + onError(6, `Unsupported YAML version ${version}`, isValid); + return false; + } + } + default: + onError(0, `Unknown directive ${name}`, true); + return false; + } + } + tagName(source, onError) { + if (source === "!") + return "!"; + if (source[0] !== "!") { + onError(`Not a valid tag: ${source}`); + return null; + } + if (source[1] === "<") { + const verbatim = source.slice(2, -1); + if (verbatim === "!" || verbatim === "!!") { + onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); + return null; + } + if (source[source.length - 1] !== ">") + onError("Verbatim tags must end with a >"); + return verbatim; + } + const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); + if (!suffix) + onError(`The ${source} tag has no suffix`); + const prefix = this.tags[handle]; + if (prefix) { + try { + return prefix + decodeURIComponent(suffix); + } catch (error) { + onError(String(error)); + return null; + } + } + if (handle === "!") + return source; + onError(`Could not resolve tag: ${source}`); + return null; + } + tagString(tag) { + for (const [handle, prefix] of Object.entries(this.tags)) { + if (tag.startsWith(prefix)) + return handle + escapeTagName(tag.substring(prefix.length)); + } + return tag[0] === "!" ? tag : `!<${tag}>`; + } + toString(doc) { + const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; + const tagEntries = Object.entries(this.tags); + let tagNames; + if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) { + const tags = {}; + visit.visit(doc.contents, (_key, node) => { + if (identity.isNode(node) && node.tag) + tags[node.tag] = true; + }); + tagNames = Object.keys(tags); + } else + tagNames = []; + for (const [handle, prefix] of tagEntries) { + if (handle === "!!" && prefix === "tag:yaml.org,2002:") + continue; + if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) + lines.push(`%TAG ${handle} ${prefix}`); + } + return lines.join(` +`); + } + } + Directives.defaultYaml = { explicit: false, version: "1.2" }; + Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; + exports.Directives = Directives; +}); + +// node_modules/yaml/dist/doc/anchors.js +var require_anchors = __commonJS((exports) => { + var identity = require_identity(); + var visit = require_visit(); + function anchorIsValid(anchor) { + if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { + const sa = JSON.stringify(anchor); + const msg = `Anchor must not contain whitespace or control characters: ${sa}`; + throw new Error(msg); + } + return true; + } + function anchorNames(root) { + const anchors = new Set; + visit.visit(root, { + Value(_key, node) { + if (node.anchor) + anchors.add(node.anchor); + } + }); + return anchors; + } + function findNewAnchor(prefix, exclude) { + for (let i = 1;; ++i) { + const name = `${prefix}${i}`; + if (!exclude.has(name)) + return name; + } + } + function createNodeAnchors(doc, prefix) { + const aliasObjects = []; + const sourceObjects = new Map; + let prevAnchors = null; + return { + onAnchor: (source) => { + aliasObjects.push(source); + prevAnchors ?? (prevAnchors = anchorNames(doc)); + const anchor = findNewAnchor(prefix, prevAnchors); + prevAnchors.add(anchor); + return anchor; + }, + setAnchors: () => { + for (const source of aliasObjects) { + const ref = sourceObjects.get(source); + if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) { + ref.node.anchor = ref.anchor; + } else { + const error = new Error("Failed to resolve repeated object (this should not happen)"); + error.source = source; + throw error; + } + } + }, + sourceObjects + }; + } + exports.anchorIsValid = anchorIsValid; + exports.anchorNames = anchorNames; + exports.createNodeAnchors = createNodeAnchors; + exports.findNewAnchor = findNewAnchor; +}); + +// node_modules/yaml/dist/doc/applyReviver.js +var require_applyReviver = __commonJS((exports) => { + function applyReviver(reviver, obj, key, val) { + if (val && typeof val === "object") { + if (Array.isArray(val)) { + for (let i = 0, len = val.length;i < len; ++i) { + const v0 = val[i]; + const v1 = applyReviver(reviver, val, String(i), v0); + if (v1 === undefined) + delete val[i]; + else if (v1 !== v0) + val[i] = v1; + } + } else if (val instanceof Map) { + for (const k of Array.from(val.keys())) { + const v0 = val.get(k); + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + val.delete(k); + else if (v1 !== v0) + val.set(k, v1); + } + } else if (val instanceof Set) { + for (const v0 of Array.from(val)) { + const v1 = applyReviver(reviver, val, v0, v0); + if (v1 === undefined) + val.delete(v0); + else if (v1 !== v0) { + val.delete(v0); + val.add(v1); + } + } + } else { + for (const [k, v0] of Object.entries(val)) { + const v1 = applyReviver(reviver, val, k, v0); + if (v1 === undefined) + delete val[k]; + else if (v1 !== v0) + val[k] = v1; + } + } + } + return reviver.call(obj, key, val); + } + exports.applyReviver = applyReviver; +}); + +// node_modules/yaml/dist/nodes/toJS.js +var require_toJS = __commonJS((exports) => { + var identity = require_identity(); + function toJS(value, arg, ctx) { + if (Array.isArray(value)) + return value.map((v, i) => toJS(v, String(i), ctx)); + if (value && typeof value.toJSON === "function") { + if (!ctx || !identity.hasAnchor(value)) + return value.toJSON(arg, ctx); + const data = { aliasCount: 0, count: 1, res: undefined }; + ctx.anchors.set(value, data); + ctx.onCreate = (res2) => { + data.res = res2; + delete ctx.onCreate; + }; + const res = value.toJSON(arg, ctx); + if (ctx.onCreate) + ctx.onCreate(res); + return res; + } + if (typeof value === "bigint" && !ctx?.keep) + return Number(value); + return value; + } + exports.toJS = toJS; +}); + +// node_modules/yaml/dist/nodes/Node.js +var require_Node = __commonJS((exports) => { + var applyReviver = require_applyReviver(); + var identity = require_identity(); + var toJS = require_toJS(); + + class NodeBase { + constructor(type) { + Object.defineProperty(this, identity.NODE_TYPE, { value: type }); + } + clone() { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + if (!identity.isDocument(doc)) + throw new TypeError("A document argument is required"); + const ctx = { + anchors: new Map, + doc, + keep: true, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this, "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; + } + } + exports.NodeBase = NodeBase; +}); + +// node_modules/yaml/dist/nodes/Alias.js +var require_Alias = __commonJS((exports) => { + var anchors = require_anchors(); + var visit = require_visit(); + var identity = require_identity(); + var Node = require_Node(); + var toJS = require_toJS(); + + class Alias extends Node.NodeBase { + constructor(source) { + super(identity.ALIAS); + this.source = source; + Object.defineProperty(this, "tag", { + set() { + throw new Error("Alias nodes cannot have tags"); + } + }); + } + resolve(doc, ctx) { + let nodes; + if (ctx?.aliasResolveCache) { + nodes = ctx.aliasResolveCache; + } else { + nodes = []; + visit.visit(doc, { + Node: (_key, node) => { + if (identity.isAlias(node) || identity.hasAnchor(node)) + nodes.push(node); + } + }); + if (ctx) + ctx.aliasResolveCache = nodes; + } + let found = undefined; + for (const node of nodes) { + if (node === this) + break; + if (node.anchor === this.source) + found = node; + } + return found; + } + toJSON(_arg, ctx) { + if (!ctx) + return { source: this.source }; + const { anchors: anchors2, doc, maxAliasCount } = ctx; + const source = this.resolve(doc, ctx); + if (!source) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new ReferenceError(msg); + } + let data = anchors2.get(source); + if (!data) { + toJS.toJS(source, null, ctx); + data = anchors2.get(source); + } + if (data?.res === undefined) { + const msg = "This should not happen: Alias anchor was not resolved?"; + throw new ReferenceError(msg); + } + if (maxAliasCount >= 0) { + data.count += 1; + if (data.aliasCount === 0) + data.aliasCount = getAliasCount(doc, source, anchors2); + if (data.count * data.aliasCount > maxAliasCount) { + const msg = "Excessive alias count indicates a resource exhaustion attack"; + throw new ReferenceError(msg); + } + } + return data.res; + } + toString(ctx, _onComment, _onChompKeep) { + const src = `*${this.source}`; + if (ctx) { + anchors.anchorIsValid(this.source); + if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { + const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; + throw new Error(msg); + } + if (ctx.implicitKey) + return `${src} `; + } + return src; + } + } + function getAliasCount(doc, node, anchors2) { + if (identity.isAlias(node)) { + const source = node.resolve(doc); + const anchor = anchors2 && source && anchors2.get(source); + return anchor ? anchor.count * anchor.aliasCount : 0; + } else if (identity.isCollection(node)) { + let count = 0; + for (const item of node.items) { + const c = getAliasCount(doc, item, anchors2); + if (c > count) + count = c; + } + return count; + } else if (identity.isPair(node)) { + const kc = getAliasCount(doc, node.key, anchors2); + const vc = getAliasCount(doc, node.value, anchors2); + return Math.max(kc, vc); + } + return 1; + } + exports.Alias = Alias; +}); + +// node_modules/yaml/dist/nodes/Scalar.js +var require_Scalar = __commonJS((exports) => { + var identity = require_identity(); + var Node = require_Node(); + var toJS = require_toJS(); + var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; + + class Scalar extends Node.NodeBase { + constructor(value) { + super(identity.SCALAR); + this.value = value; + } + toJSON(arg, ctx) { + return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); + } + toString() { + return String(this.value); + } + } + Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; + Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; + Scalar.PLAIN = "PLAIN"; + Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; + Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; + exports.Scalar = Scalar; + exports.isScalarValue = isScalarValue; +}); + +// node_modules/yaml/dist/doc/createNode.js +var require_createNode = __commonJS((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var Scalar = require_Scalar(); + var defaultTagPrefix = "tag:yaml.org,2002:"; + function findTagObject(value, tagName, tags) { + if (tagName) { + const match = tags.filter((t) => t.tag === tagName); + const tagObj = match.find((t) => !t.format) ?? match[0]; + if (!tagObj) + throw new Error(`Tag ${tagName} not found`); + return tagObj; + } + return tags.find((t) => t.identify?.(value) && !t.format); + } + function createNode(value, tagName, ctx) { + if (identity.isDocument(value)) + value = value.contents; + if (identity.isNode(value)) + return value; + if (identity.isPair(value)) { + const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); + map.items.push(value); + return map; + } + if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { + value = value.valueOf(); + } + const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; + let ref = undefined; + if (aliasDuplicateObjects && value && typeof value === "object") { + ref = sourceObjects.get(value); + if (ref) { + ref.anchor ?? (ref.anchor = onAnchor(value)); + return new Alias.Alias(ref.anchor); + } else { + ref = { anchor: null, node: null }; + sourceObjects.set(value, ref); + } + } + if (tagName?.startsWith("!!")) + tagName = defaultTagPrefix + tagName.slice(2); + let tagObj = findTagObject(value, tagName, schema.tags); + if (!tagObj) { + if (value && typeof value.toJSON === "function") { + value = value.toJSON(); + } + if (!value || typeof value !== "object") { + const node2 = new Scalar.Scalar(value); + if (ref) + ref.node = node2; + return node2; + } + tagObj = value instanceof Map ? schema[identity.MAP] : (Symbol.iterator in Object(value)) ? schema[identity.SEQ] : schema[identity.MAP]; + } + if (onTagObj) { + onTagObj(tagObj); + delete ctx.onTagObj; + } + const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value); + if (tagName) + node.tag = tagName; + else if (!tagObj.default) + node.tag = tagObj.tag; + if (ref) + ref.node = node; + return node; + } + exports.createNode = createNode; +}); + +// node_modules/yaml/dist/nodes/Collection.js +var require_Collection = __commonJS((exports) => { + var createNode = require_createNode(); + var identity = require_identity(); + var Node = require_Node(); + function collectionFromPath(schema, path, value) { + let v = value; + for (let i = path.length - 1;i >= 0; --i) { + const k = path[i]; + if (typeof k === "number" && Number.isInteger(k) && k >= 0) { + const a = []; + a[k] = v; + v = a; + } else { + v = new Map([[k, v]]); + } + } + return createNode.createNode(v, undefined, { + aliasDuplicateObjects: false, + keepUndefined: false, + onAnchor: () => { + throw new Error("This should not happen, please report a bug."); + }, + schema, + sourceObjects: new Map + }); + } + var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; + + class Collection extends Node.NodeBase { + constructor(type, schema) { + super(type); + Object.defineProperty(this, "schema", { + value: schema, + configurable: true, + enumerable: false, + writable: true + }); + } + clone(schema) { + const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); + if (schema) + copy.schema = schema; + copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); + if (this.range) + copy.range = this.range.slice(); + return copy; + } + addIn(path, value) { + if (isEmptyPath(path)) + this.add(value); + else { + const [key, ...rest] = path; + const node = this.get(key, true); + if (identity.isCollection(node)) + node.addIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + deleteIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.delete(key); + const node = this.get(key, true); + if (identity.isCollection(node)) + return node.deleteIn(rest); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + getIn(path, keepScalar) { + const [key, ...rest] = path; + const node = this.get(key, true); + if (rest.length === 0) + return !keepScalar && identity.isScalar(node) ? node.value : node; + else + return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined; + } + hasAllNullValues(allowScalar) { + return this.items.every((node) => { + if (!identity.isPair(node)) + return false; + const n = node.value; + return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; + }); + } + hasIn(path) { + const [key, ...rest] = path; + if (rest.length === 0) + return this.has(key); + const node = this.get(key, true); + return identity.isCollection(node) ? node.hasIn(rest) : false; + } + setIn(path, value) { + const [key, ...rest] = path; + if (rest.length === 0) { + this.set(key, value); + } else { + const node = this.get(key, true); + if (identity.isCollection(node)) + node.setIn(rest, value); + else if (node === undefined && this.schema) + this.set(key, collectionFromPath(this.schema, rest, value)); + else + throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); + } + } + } + exports.Collection = Collection; + exports.collectionFromPath = collectionFromPath; + exports.isEmptyPath = isEmptyPath; +}); + +// node_modules/yaml/dist/stringify/stringifyComment.js +var require_stringifyComment = __commonJS((exports) => { + var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); + function indentComment(comment, indent) { + if (/^\n+$/.test(comment)) + return comment.substring(1); + return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; + } + var lineComment = (str, indent, comment) => str.endsWith(` +`) ? indentComment(comment, indent) : comment.includes(` +`) ? ` +` + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; + exports.indentComment = indentComment; + exports.lineComment = lineComment; + exports.stringifyComment = stringifyComment; +}); + +// node_modules/yaml/dist/stringify/foldFlowLines.js +var require_foldFlowLines = __commonJS((exports) => { + var FOLD_FLOW = "flow"; + var FOLD_BLOCK = "block"; + var FOLD_QUOTED = "quoted"; + function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { + if (!lineWidth || lineWidth < 0) + return text; + if (lineWidth < minContentWidth) + minContentWidth = 0; + const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); + if (text.length <= endStep) + return text; + const folds = []; + const escapedFolds = {}; + let end = lineWidth - indent.length; + if (typeof indentAtStart === "number") { + if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) + folds.push(0); + else + end = lineWidth - indentAtStart; + } + let split = undefined; + let prev = undefined; + let overflow = false; + let i = -1; + let escStart = -1; + let escEnd = -1; + if (mode === FOLD_BLOCK) { + i = consumeMoreIndentedLines(text, i, indent.length); + if (i !== -1) + end = i + endStep; + } + for (let ch;ch = text[i += 1]; ) { + if (mode === FOLD_QUOTED && ch === "\\") { + escStart = i; + switch (text[i + 1]) { + case "x": + i += 3; + break; + case "u": + i += 5; + break; + case "U": + i += 9; + break; + default: + i += 1; + } + escEnd = i; + } + if (ch === ` +`) { + if (mode === FOLD_BLOCK) + i = consumeMoreIndentedLines(text, i, indent.length); + end = i + indent.length + endStep; + split = undefined; + } else { + if (ch === " " && prev && prev !== " " && prev !== ` +` && prev !== "\t") { + const next = text[i + 1]; + if (next && next !== " " && next !== ` +` && next !== "\t") + split = i; + } + if (i >= end) { + if (split) { + folds.push(split); + end = split + endStep; + split = undefined; + } else if (mode === FOLD_QUOTED) { + while (prev === " " || prev === "\t") { + prev = ch; + ch = text[i += 1]; + overflow = true; + } + const j = i > escEnd + 1 ? i - 2 : escStart - 1; + if (escapedFolds[j]) + return text; + folds.push(j); + escapedFolds[j] = true; + end = j + endStep; + split = undefined; + } else { + overflow = true; + } + } + } + prev = ch; + } + if (overflow && onOverflow) + onOverflow(); + if (folds.length === 0) + return text; + if (onFold) + onFold(); + let res = text.slice(0, folds[0]); + for (let i2 = 0;i2 < folds.length; ++i2) { + const fold = folds[i2]; + const end2 = folds[i2 + 1] || text.length; + if (fold === 0) + res = ` +${indent}${text.slice(0, end2)}`; + else { + if (mode === FOLD_QUOTED && escapedFolds[fold]) + res += `${text[fold]}\\`; + res += ` +${indent}${text.slice(fold + 1, end2)}`; + } + } + return res; + } + function consumeMoreIndentedLines(text, i, indent) { + let end = i; + let start = i + 1; + let ch = text[start]; + while (ch === " " || ch === "\t") { + if (i < start + indent) { + ch = text[++i]; + } else { + do { + ch = text[++i]; + } while (ch && ch !== ` +`); + end = i; + start = i + 1; + ch = text[start]; + } + } + return end; + } + exports.FOLD_BLOCK = FOLD_BLOCK; + exports.FOLD_FLOW = FOLD_FLOW; + exports.FOLD_QUOTED = FOLD_QUOTED; + exports.foldFlowLines = foldFlowLines; +}); + +// node_modules/yaml/dist/stringify/stringifyString.js +var require_stringifyString = __commonJS((exports) => { + var Scalar = require_Scalar(); + var foldFlowLines = require_foldFlowLines(); + var getFoldOptions = (ctx, isBlock) => ({ + indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, + lineWidth: ctx.options.lineWidth, + minContentWidth: ctx.options.minContentWidth + }); + var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); + function lineLengthOverLimit(str, lineWidth, indentLength) { + if (!lineWidth || lineWidth < 0) + return false; + const limit = lineWidth - indentLength; + const strLen = str.length; + if (strLen <= limit) + return false; + for (let i = 0, start = 0;i < strLen; ++i) { + if (str[i] === ` +`) { + if (i - start > limit) + return true; + start = i + 1; + if (strLen - start <= limit) + return false; + } + } + return true; + } + function doubleQuotedString(value, ctx) { + const json = JSON.stringify(value); + if (ctx.options.doubleQuotedAsJSON) + return json; + const { implicitKey } = ctx; + const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + let str = ""; + let start = 0; + for (let i = 0, ch = json[i];ch; ch = json[++i]) { + if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") { + str += json.slice(start, i) + "\\ "; + i += 1; + start = i; + ch = "\\"; + } + if (ch === "\\") + switch (json[i + 1]) { + case "u": + { + str += json.slice(start, i); + const code = json.substr(i + 2, 4); + switch (code) { + case "0000": + str += "\\0"; + break; + case "0007": + str += "\\a"; + break; + case "000b": + str += "\\v"; + break; + case "001b": + str += "\\e"; + break; + case "0085": + str += "\\N"; + break; + case "00a0": + str += "\\_"; + break; + case "2028": + str += "\\L"; + break; + case "2029": + str += "\\P"; + break; + default: + if (code.substr(0, 2) === "00") + str += "\\x" + code.substr(2); + else + str += json.substr(i, 6); + } + i += 5; + start = i + 1; + } + break; + case "n": + if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) { + i += 1; + } else { + str += json.slice(start, i) + ` + +`; + while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') { + str += ` +`; + i += 2; + } + str += indent; + if (json[i + 2] === " ") + str += "\\"; + i += 1; + start = i + 1; + } + break; + default: + i += 1; + } + } + str = start ? str + json.slice(start) : json; + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); + } + function singleQuotedString(value, ctx) { + if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes(` +`) || /[ \t]\n|\n[ \t]/.test(value)) + return doubleQuotedString(value, ctx); + const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); + const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& +${indent}`) + "'"; + return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + } + function quotedString(value, ctx) { + const { singleQuote } = ctx.options; + let qs; + if (singleQuote === false) + qs = doubleQuotedString; + else { + const hasDouble = value.includes('"'); + const hasSingle = value.includes("'"); + if (hasDouble && !hasSingle) + qs = singleQuotedString; + else if (hasSingle && !hasDouble) + qs = doubleQuotedString; + else + qs = singleQuote ? singleQuotedString : doubleQuotedString; + } + return qs(value, ctx); + } + var blockEndNewlines; + try { + blockEndNewlines = new RegExp(`(^|(? +`; + let chomp; + let endStart; + for (endStart = value.length;endStart > 0; --endStart) { + const ch = value[endStart - 1]; + if (ch !== ` +` && ch !== "\t" && ch !== " ") + break; + } + let end = value.substring(endStart); + const endNlPos = end.indexOf(` +`); + if (endNlPos === -1) { + chomp = "-"; + } else if (value === end || endNlPos !== end.length - 1) { + chomp = "+"; + if (onChompKeep) + onChompKeep(); + } else { + chomp = ""; + } + if (end) { + value = value.slice(0, -end.length); + if (end[end.length - 1] === ` +`) + end = end.slice(0, -1); + end = end.replace(blockEndNewlines, `$&${indent}`); + } + let startWithSpace = false; + let startEnd; + let startNlPos = -1; + for (startEnd = 0;startEnd < value.length; ++startEnd) { + const ch = value[startEnd]; + if (ch === " ") + startWithSpace = true; + else if (ch === ` +`) + startNlPos = startEnd; + else + break; + } + let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); + if (start) { + value = value.substring(start.length); + start = start.replace(/\n+/g, `$&${indent}`); + } + const indentSize = indent ? "2" : "1"; + let header = (startWithSpace ? indentSize : "") + chomp; + if (comment) { + header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); + if (onComment) + onComment(); + } + if (!literal) { + const foldedValue = value.replace(/\n+/g, ` +$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); + let literalFallback = false; + const foldOptions = getFoldOptions(ctx, true); + if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) { + foldOptions.onOverflow = () => { + literalFallback = true; + }; + } + const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); + if (!literalFallback) + return `>${header} +${indent}${body}`; + } + value = value.replace(/\n+/g, `$&${indent}`); + return `|${header} +${indent}${start}${value}${end}`; + } + function plainString(item, ctx, onComment, onChompKeep) { + const { type, value } = item; + const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; + if (implicitKey && value.includes(` +`) || inFlow && /[[\]{},]/.test(value)) { + return quotedString(value, ctx); + } + if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { + return implicitKey || inFlow || !value.includes(` +`) ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); + } + if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes(` +`)) { + return blockString(item, ctx, onComment, onChompKeep); + } + if (containsDocumentMarker(value)) { + if (indent === "") { + ctx.forceBlockIndent = true; + return blockString(item, ctx, onComment, onChompKeep); + } else if (implicitKey && indent === indentStep) { + return quotedString(value, ctx); + } + } + const str = value.replace(/\n+/g, `$& +${indent}`); + if (actualString) { + const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); + const { compat, tags } = ctx.doc.schema; + if (tags.some(test) || compat?.some(test)) + return quotedString(value, ctx); + } + return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); + } + function stringifyString(item, ctx, onComment, onChompKeep) { + const { implicitKey, inFlow } = ctx; + const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); + let { type } = item; + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) + type = Scalar.Scalar.QUOTE_DOUBLE; + } + const _stringify = (_type) => { + switch (_type) { + case Scalar.Scalar.BLOCK_FOLDED: + case Scalar.Scalar.BLOCK_LITERAL: + return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); + case Scalar.Scalar.QUOTE_DOUBLE: + return doubleQuotedString(ss.value, ctx); + case Scalar.Scalar.QUOTE_SINGLE: + return singleQuotedString(ss.value, ctx); + case Scalar.Scalar.PLAIN: + return plainString(ss, ctx, onComment, onChompKeep); + default: + return null; + } + }; + let res = _stringify(type); + if (res === null) { + const { defaultKeyType, defaultStringType } = ctx.options; + const t = implicitKey && defaultKeyType || defaultStringType; + res = _stringify(t); + if (res === null) + throw new Error(`Unsupported default string type ${t}`); + } + return res; + } + exports.stringifyString = stringifyString; +}); + +// node_modules/yaml/dist/stringify/stringify.js +var require_stringify = __commonJS((exports) => { + var anchors = require_anchors(); + var identity = require_identity(); + var stringifyComment = require_stringifyComment(); + var stringifyString = require_stringifyString(); + function createStringifyContext(doc, options) { + const opt = Object.assign({ + blockQuote: true, + commentString: stringifyComment.stringifyComment, + defaultKeyType: null, + defaultStringType: "PLAIN", + directives: null, + doubleQuotedAsJSON: false, + doubleQuotedMinMultiLineLength: 40, + falseStr: "false", + flowCollectionPadding: true, + indentSeq: true, + lineWidth: 80, + minContentWidth: 20, + nullStr: "null", + simpleKeys: false, + singleQuote: null, + trueStr: "true", + verifyAliasOrder: true + }, doc.schema.toStringOptions, options); + let inFlow; + switch (opt.collectionStyle) { + case "block": + inFlow = false; + break; + case "flow": + inFlow = true; + break; + default: + inFlow = null; + } + return { + anchors: new Set, + doc, + flowCollectionPadding: opt.flowCollectionPadding ? " " : "", + indent: "", + indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", + inFlow, + options: opt + }; + } + function getTagObject(tags, item) { + if (item.tag) { + const match = tags.filter((t) => t.tag === item.tag); + if (match.length > 0) + return match.find((t) => t.format === item.format) ?? match[0]; + } + let tagObj = undefined; + let obj; + if (identity.isScalar(item)) { + obj = item.value; + let match = tags.filter((t) => t.identify?.(obj)); + if (match.length > 1) { + const testMatch = match.filter((t) => t.test); + if (testMatch.length > 0) + match = testMatch; + } + tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); + } else { + obj = item; + tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); + } + if (!tagObj) { + const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); + throw new Error(`Tag not resolved for ${name} value`); + } + return tagObj; + } + function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) { + if (!doc.directives) + return ""; + const props = []; + const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; + if (anchor && anchors.anchorIsValid(anchor)) { + anchors$1.add(anchor); + props.push(`&${anchor}`); + } + const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); + if (tag) + props.push(doc.directives.tagString(tag)); + return props.join(" "); + } + function stringify(item, ctx, onComment, onChompKeep) { + if (identity.isPair(item)) + return item.toString(ctx, onComment, onChompKeep); + if (identity.isAlias(item)) { + if (ctx.doc.directives) + return item.toString(ctx); + if (ctx.resolvedAliases?.has(item)) { + throw new TypeError(`Cannot stringify circular structure without alias nodes`); + } else { + if (ctx.resolvedAliases) + ctx.resolvedAliases.add(item); + else + ctx.resolvedAliases = new Set([item]); + item = item.resolve(ctx.doc); + } + } + let tagObj = undefined; + const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); + tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); + const props = stringifyProps(node, tagObj, ctx); + if (props.length > 0) + ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; + const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); + if (!props) + return str; + return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} +${ctx.indent}${str}`; + } + exports.createStringifyContext = createStringifyContext; + exports.stringify = stringify; +}); + +// node_modules/yaml/dist/stringify/stringifyPair.js +var require_stringifyPair = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { + const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; + let keyComment = identity.isNode(key) && key.comment || null; + if (simpleKeys) { + if (keyComment) { + throw new Error("With simple keys, key nodes cannot have comments"); + } + if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") { + const msg = "With simple keys, collection cannot be used as a key value"; + throw new Error(msg); + } + } + let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object")); + ctx = Object.assign({}, ctx, { + allNullValues: false, + implicitKey: !explicitKey && (simpleKeys || !allNullValues), + indent: indent + indentStep + }); + let keyCommentDone = false; + let chompKeep = false; + let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); + if (!explicitKey && !ctx.inFlow && str.length > 1024) { + if (simpleKeys) + throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); + explicitKey = true; + } + if (ctx.inFlow) { + if (allNullValues || value == null) { + if (keyCommentDone && onComment) + onComment(); + return str === "" ? "?" : explicitKey ? `? ${str}` : str; + } + } else if (allNullValues && !simpleKeys || value == null && explicitKey) { + str = `? ${str}`; + if (keyComment && !keyCommentDone) { + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + if (keyCommentDone) + keyComment = null; + if (explicitKey) { + if (keyComment) + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + str = `? ${str} +${indent}:`; + } else { + str = `${str}:`; + if (keyComment) + str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); + } + let vsb, vcb, valueComment; + if (identity.isNode(value)) { + vsb = !!value.spaceBefore; + vcb = value.commentBefore; + valueComment = value.comment; + } else { + vsb = false; + vcb = null; + valueComment = null; + if (value && typeof value === "object") + value = doc.createNode(value); + } + ctx.implicitKey = false; + if (!explicitKey && !keyComment && identity.isScalar(value)) + ctx.indentAtStart = str.length + 1; + chompKeep = false; + if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) { + ctx.indent = ctx.indent.substring(2); + } + let valueCommentDone = false; + const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); + let ws = " "; + if (keyComment || vsb || vcb) { + ws = vsb ? ` +` : ""; + if (vcb) { + const cs = commentString(vcb); + ws += ` +${stringifyComment.indentComment(cs, ctx.indent)}`; + } + if (valueStr === "" && !ctx.inFlow) { + if (ws === ` +` && valueComment) + ws = ` + +`; + } else { + ws += ` +${ctx.indent}`; + } + } else if (!explicitKey && identity.isCollection(value)) { + const vs0 = valueStr[0]; + const nl0 = valueStr.indexOf(` +`); + const hasNewline = nl0 !== -1; + const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; + if (hasNewline || !flow) { + let hasPropsLine = false; + if (hasNewline && (vs0 === "&" || vs0 === "!")) { + let sp0 = valueStr.indexOf(" "); + if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { + sp0 = valueStr.indexOf(" ", sp0 + 1); + } + if (sp0 === -1 || nl0 < sp0) + hasPropsLine = true; + } + if (!hasPropsLine) + ws = ` +${ctx.indent}`; + } + } else if (valueStr === "" || valueStr[0] === ` +`) { + ws = ""; + } + str += ws + valueStr; + if (ctx.inFlow) { + if (valueCommentDone && onComment) + onComment(); + } else if (valueComment && !valueCommentDone) { + str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); + } else if (chompKeep && onChompKeep) { + onChompKeep(); + } + return str; + } + exports.stringifyPair = stringifyPair; +}); + +// node_modules/yaml/dist/log.js +var require_log = __commonJS((exports) => { + var node_process = __require("process"); + function debug(logLevel, ...messages) { + if (logLevel === "debug") + console.log(...messages); + } + function warn(logLevel, warning) { + if (logLevel === "debug" || logLevel === "warn") { + if (typeof node_process.emitWarning === "function") + node_process.emitWarning(warning); + else + console.warn(warning); + } + } + exports.debug = debug; + exports.warn = warn; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/merge.js +var require_merge2 = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var MERGE_KEY = "<<"; + var merge = { + identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, + default: "key", + tag: "tag:yaml.org,2002:merge", + test: /^<<$/, + resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { + addToJSMap: addMergeToJSMap + }), + stringify: () => MERGE_KEY + }; + var isMergeKey = (ctx, key) => (merge.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default); + function addMergeToJSMap(ctx, map, value) { + value = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value; + if (identity.isSeq(value)) + for (const it of value.items) + mergeValue(ctx, map, it); + else if (Array.isArray(value)) + for (const it of value) + mergeValue(ctx, map, it); + else + mergeValue(ctx, map, value); + } + function mergeValue(ctx, map, value) { + const source = ctx && identity.isAlias(value) ? value.resolve(ctx.doc) : value; + if (!identity.isMap(source)) + throw new Error("Merge sources must be maps or map aliases"); + const srcMap = source.toJSON(null, ctx, Map); + for (const [key, value2] of srcMap) { + if (map instanceof Map) { + if (!map.has(key)) + map.set(key, value2); + } else if (map instanceof Set) { + map.add(key); + } else if (!Object.prototype.hasOwnProperty.call(map, key)) { + Object.defineProperty(map, key, { + value: value2, + writable: true, + enumerable: true, + configurable: true + }); + } + } + return map; + } + exports.addMergeToJSMap = addMergeToJSMap; + exports.isMergeKey = isMergeKey; + exports.merge = merge; +}); + +// node_modules/yaml/dist/nodes/addPairToJSMap.js +var require_addPairToJSMap = __commonJS((exports) => { + var log = require_log(); + var merge = require_merge2(); + var stringify = require_stringify(); + var identity = require_identity(); + var toJS = require_toJS(); + function addPairToJSMap(ctx, map, { key, value }) { + if (identity.isNode(key) && key.addToJSMap) + key.addToJSMap(ctx, map, value); + else if (merge.isMergeKey(ctx, key)) + merge.addMergeToJSMap(ctx, map, value); + else { + const jsKey = toJS.toJS(key, "", ctx); + if (map instanceof Map) { + map.set(jsKey, toJS.toJS(value, jsKey, ctx)); + } else if (map instanceof Set) { + map.add(jsKey); + } else { + const stringKey = stringifyKey(key, jsKey, ctx); + const jsValue = toJS.toJS(value, stringKey, ctx); + if (stringKey in map) + Object.defineProperty(map, stringKey, { + value: jsValue, + writable: true, + enumerable: true, + configurable: true + }); + else + map[stringKey] = jsValue; + } + } + return map; + } + function stringifyKey(key, jsKey, ctx) { + if (jsKey === null) + return ""; + if (typeof jsKey !== "object") + return String(jsKey); + if (identity.isNode(key) && ctx?.doc) { + const strCtx = stringify.createStringifyContext(ctx.doc, {}); + strCtx.anchors = new Set; + for (const node of ctx.anchors.keys()) + strCtx.anchors.add(node.anchor); + strCtx.inFlow = true; + strCtx.inStringifyKey = true; + const strKey = key.toString(strCtx); + if (!ctx.mapKeyWarned) { + let jsonStr = JSON.stringify(strKey); + if (jsonStr.length > 40) + jsonStr = jsonStr.substring(0, 36) + '..."'; + log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); + ctx.mapKeyWarned = true; + } + return strKey; + } + return JSON.stringify(jsKey); + } + exports.addPairToJSMap = addPairToJSMap; +}); + +// node_modules/yaml/dist/nodes/Pair.js +var require_Pair = __commonJS((exports) => { + var createNode = require_createNode(); + var stringifyPair = require_stringifyPair(); + var addPairToJSMap = require_addPairToJSMap(); + var identity = require_identity(); + function createPair(key, value, ctx) { + const k = createNode.createNode(key, undefined, ctx); + const v = createNode.createNode(value, undefined, ctx); + return new Pair(k, v); + } + + class Pair { + constructor(key, value = null) { + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); + this.key = key; + this.value = value; + } + clone(schema) { + let { key, value } = this; + if (identity.isNode(key)) + key = key.clone(schema); + if (identity.isNode(value)) + value = value.clone(schema); + return new Pair(key, value); + } + toJSON(_, ctx) { + const pair = ctx?.mapAsMap ? new Map : {}; + return addPairToJSMap.addPairToJSMap(ctx, pair, this); + } + toString(ctx, onComment, onChompKeep) { + return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); + } + } + exports.Pair = Pair; + exports.createPair = createPair; +}); + +// node_modules/yaml/dist/stringify/stringifyCollection.js +var require_stringifyCollection = __commonJS((exports) => { + var identity = require_identity(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyCollection(collection, ctx, options) { + const flow = ctx.inFlow ?? collection.flow; + const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection; + return stringify2(collection, ctx, options); + } + function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { + const { indent, options: { commentString } } = ctx; + const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); + let chompKeep = false; + const lines = []; + for (let i = 0;i < items.length; ++i) { + const item = items[i]; + let comment2 = null; + if (identity.isNode(item)) { + if (!chompKeep && item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, chompKeep); + if (item.comment) + comment2 = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (!chompKeep && ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); + } + } + chompKeep = false; + let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); + if (comment2) + str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2)); + if (chompKeep && comment2) + chompKeep = false; + lines.push(blockItemPrefix + str2); + } + let str; + if (lines.length === 0) { + str = flowChars.start + flowChars.end; + } else { + str = lines[0]; + for (let i = 1;i < lines.length; ++i) { + const line = lines[i]; + str += line ? ` +${indent}${line}` : ` +`; + } + } + if (comment) { + str += ` +` + stringifyComment.indentComment(commentString(comment), indent); + if (onComment) + onComment(); + } else if (chompKeep && onChompKeep) + onChompKeep(); + return str; + } + function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { + const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; + itemIndent += indentStep; + const itemCtx = Object.assign({}, ctx, { + indent: itemIndent, + inFlow: true, + type: null + }); + let reqNewline = false; + let linesAtValue = 0; + const lines = []; + for (let i = 0;i < items.length; ++i) { + const item = items[i]; + let comment = null; + if (identity.isNode(item)) { + if (item.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, item.commentBefore, false); + if (item.comment) + comment = item.comment; + } else if (identity.isPair(item)) { + const ik = identity.isNode(item.key) ? item.key : null; + if (ik) { + if (ik.spaceBefore) + lines.push(""); + addCommentBefore(ctx, lines, ik.commentBefore, false); + if (ik.comment) + reqNewline = true; + } + const iv = identity.isNode(item.value) ? item.value : null; + if (iv) { + if (iv.comment) + comment = iv.comment; + if (iv.commentBefore) + reqNewline = true; + } else if (item.value == null && ik?.comment) { + comment = ik.comment; + } + } + if (comment) + reqNewline = true; + let str = stringify.stringify(item, itemCtx, () => comment = null); + if (i < items.length - 1) + str += ","; + if (comment) + str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); + if (!reqNewline && (lines.length > linesAtValue || str.includes(` +`))) + reqNewline = true; + lines.push(str); + linesAtValue = lines.length; + } + const { start, end } = flowChars; + if (lines.length === 0) { + return start + end; + } else { + if (!reqNewline) { + const len = lines.reduce((sum, line) => sum + line.length + 2, 2); + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; + } + if (reqNewline) { + let str = start; + for (const line of lines) + str += line ? ` +${indentStep}${indent}${line}` : ` +`; + return `${str} +${indent}${end}`; + } else { + return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; + } + } + } + function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { + if (comment && chompKeep) + comment = comment.replace(/^\n+/, ""); + if (comment) { + const ic = stringifyComment.indentComment(commentString(comment), indent); + lines.push(ic.trimStart()); + } + } + exports.stringifyCollection = stringifyCollection; +}); + +// node_modules/yaml/dist/nodes/YAMLMap.js +var require_YAMLMap = __commonJS((exports) => { + var stringifyCollection = require_stringifyCollection(); + var addPairToJSMap = require_addPairToJSMap(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + function findPair(items, key) { + const k = identity.isScalar(key) ? key.value : key; + for (const it of items) { + if (identity.isPair(it)) { + if (it.key === key || it.key === k) + return it; + if (identity.isScalar(it.key) && it.key.value === k) + return it; + } + } + return; + } + + class YAMLMap extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:map"; + } + constructor(schema) { + super(identity.MAP, schema); + this.items = []; + } + static from(schema, obj, ctx) { + const { keepUndefined, replacer } = ctx; + const map = new this(schema); + const add = (key, value) => { + if (typeof replacer === "function") + value = replacer.call(obj, key, value); + else if (Array.isArray(replacer) && !replacer.includes(key)) + return; + if (value !== undefined || keepUndefined) + map.items.push(Pair.createPair(key, value, ctx)); + }; + if (obj instanceof Map) { + for (const [key, value] of obj) + add(key, value); + } else if (obj && typeof obj === "object") { + for (const key of Object.keys(obj)) + add(key, obj[key]); + } + if (typeof schema.sortMapEntries === "function") { + map.items.sort(schema.sortMapEntries); + } + return map; + } + add(pair, overwrite) { + let _pair; + if (identity.isPair(pair)) + _pair = pair; + else if (!pair || typeof pair !== "object" || !("key" in pair)) { + _pair = new Pair.Pair(pair, pair?.value); + } else + _pair = new Pair.Pair(pair.key, pair.value); + const prev = findPair(this.items, _pair.key); + const sortEntries = this.schema?.sortMapEntries; + if (prev) { + if (!overwrite) + throw new Error(`Key ${_pair.key} already set`); + if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) + prev.value.value = _pair.value; + else + prev.value = _pair.value; + } else if (sortEntries) { + const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); + if (i === -1) + this.items.push(_pair); + else + this.items.splice(i, 0, _pair); + } else { + this.items.push(_pair); + } + } + delete(key) { + const it = findPair(this.items, key); + if (!it) + return false; + const del = this.items.splice(this.items.indexOf(it), 1); + return del.length > 0; + } + get(key, keepScalar) { + const it = findPair(this.items, key); + const node = it?.value; + return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined; + } + has(key) { + return !!findPair(this.items, key); + } + set(key, value) { + this.add(new Pair.Pair(key, value), true); + } + toJSON(_, ctx, Type) { + const map = Type ? new Type : ctx?.mapAsMap ? new Map : {}; + if (ctx?.onCreate) + ctx.onCreate(map); + for (const item of this.items) + addPairToJSMap.addPairToJSMap(ctx, map, item); + return map; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + for (const item of this.items) { + if (!identity.isPair(item)) + throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); + } + if (!ctx.allNullValues && this.hasAllNullValues(false)) + ctx = Object.assign({}, ctx, { allNullValues: true }); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "", + flowChars: { start: "{", end: "}" }, + itemIndent: ctx.indent || "", + onChompKeep, + onComment + }); + } + } + exports.YAMLMap = YAMLMap; + exports.findPair = findPair; +}); + +// node_modules/yaml/dist/schema/common/map.js +var require_map = __commonJS((exports) => { + var identity = require_identity(); + var YAMLMap = require_YAMLMap(); + var map = { + collection: "map", + default: true, + nodeClass: YAMLMap.YAMLMap, + tag: "tag:yaml.org,2002:map", + resolve(map2, onError) { + if (!identity.isMap(map2)) + onError("Expected a mapping for this tag"); + return map2; + }, + createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) + }; + exports.map = map; +}); + +// node_modules/yaml/dist/nodes/YAMLSeq.js +var require_YAMLSeq = __commonJS((exports) => { + var createNode = require_createNode(); + var stringifyCollection = require_stringifyCollection(); + var Collection = require_Collection(); + var identity = require_identity(); + var Scalar = require_Scalar(); + var toJS = require_toJS(); + + class YAMLSeq extends Collection.Collection { + static get tagName() { + return "tag:yaml.org,2002:seq"; + } + constructor(schema) { + super(identity.SEQ, schema); + this.items = []; + } + add(value) { + this.items.push(value); + } + delete(key) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return false; + const del = this.items.splice(idx, 1); + return del.length > 0; + } + get(key, keepScalar) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + return; + const it = this.items[idx]; + return !keepScalar && identity.isScalar(it) ? it.value : it; + } + has(key) { + const idx = asItemIndex(key); + return typeof idx === "number" && idx < this.items.length; + } + set(key, value) { + const idx = asItemIndex(key); + if (typeof idx !== "number") + throw new Error(`Expected a valid index, not ${key}.`); + const prev = this.items[idx]; + if (identity.isScalar(prev) && Scalar.isScalarValue(value)) + prev.value = value; + else + this.items[idx] = value; + } + toJSON(_, ctx) { + const seq = []; + if (ctx?.onCreate) + ctx.onCreate(seq); + let i = 0; + for (const item of this.items) + seq.push(toJS.toJS(item, String(i++), ctx)); + return seq; + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + return stringifyCollection.stringifyCollection(this, ctx, { + blockItemPrefix: "- ", + flowChars: { start: "[", end: "]" }, + itemIndent: (ctx.indent || "") + " ", + onChompKeep, + onComment + }); + } + static from(schema, obj, ctx) { + const { replacer } = ctx; + const seq = new this(schema); + if (obj && Symbol.iterator in Object(obj)) { + let i = 0; + for (let it of obj) { + if (typeof replacer === "function") { + const key = obj instanceof Set ? it : String(i++); + it = replacer.call(obj, key, it); + } + seq.items.push(createNode.createNode(it, undefined, ctx)); + } + } + return seq; + } + } + function asItemIndex(key) { + let idx = identity.isScalar(key) ? key.value : key; + if (idx && typeof idx === "string") + idx = Number(idx); + return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; + } + exports.YAMLSeq = YAMLSeq; +}); + +// node_modules/yaml/dist/schema/common/seq.js +var require_seq = __commonJS((exports) => { + var identity = require_identity(); + var YAMLSeq = require_YAMLSeq(); + var seq = { + collection: "seq", + default: true, + nodeClass: YAMLSeq.YAMLSeq, + tag: "tag:yaml.org,2002:seq", + resolve(seq2, onError) { + if (!identity.isSeq(seq2)) + onError("Expected a sequence for this tag"); + return seq2; + }, + createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) + }; + exports.seq = seq; +}); + +// node_modules/yaml/dist/schema/common/string.js +var require_string = __commonJS((exports) => { + var stringifyString = require_stringifyString(); + var string = { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify(item, ctx, onComment, onChompKeep) { + ctx = Object.assign({ actualString: true }, ctx); + return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); + } + }; + exports.string = string; +}); + +// node_modules/yaml/dist/schema/common/null.js +var require_null = __commonJS((exports) => { + var Scalar = require_Scalar(); + var nullTag = { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^(?:~|[Nn]ull|NULL)?$/, + resolve: () => new Scalar.Scalar(null), + stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr + }; + exports.nullTag = nullTag; +}); + +// node_modules/yaml/dist/schema/core/bool.js +var require_bool = __commonJS((exports) => { + var Scalar = require_Scalar(); + var boolTag = { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, + resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"), + stringify({ source, value }, ctx) { + if (source && boolTag.test.test(source)) { + const sv = source[0] === "t" || source[0] === "T"; + if (value === sv) + return source; + } + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + }; + exports.boolTag = boolTag; +}); + +// node_modules/yaml/dist/stringify/stringifyNumber.js +var require_stringifyNumber = __commonJS((exports) => { + function stringifyNumber({ format, minFractionDigits, tag, value }) { + if (typeof value === "bigint") + return String(value); + const num = typeof value === "number" ? value : Number(value); + if (!isFinite(num)) + return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; + let n = Object.is(value, -0) ? "-0" : JSON.stringify(value); + if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n)) { + let i = n.indexOf("."); + if (i < 0) { + i = n.length; + n += "."; + } + let d = minFractionDigits - (n.length - i - 1); + while (d-- > 0) + n += "0"; + } + return n; + } + exports.stringifyNumber = stringifyNumber; +}); + +// node_modules/yaml/dist/schema/core/float.js +var require_float2 = __commonJS((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + var floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + var floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } + }; + var float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str)); + const dot = str.indexOf("."); + if (dot !== -1 && str[str.length - 1] === "0") + node.minFractionDigits = str.length - dot - 1; + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.float = float; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +}); + +// node_modules/yaml/dist/schema/core/int.js +var require_int = __commonJS((exports) => { + var stringifyNumber = require_stringifyNumber(); + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value) && value >= 0) + return prefix + value.toString(radix); + return stringifyNumber.stringifyNumber(node); + } + var intOct = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^0o[0-7]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), + stringify: (node) => intStringify(node, 8, "0o") + }; + var int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9]+$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + var intHex = { + identify: (value) => intIdentify(value) && value >= 0, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^0x[0-9a-fA-F]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int; + exports.intHex = intHex; + exports.intOct = intOct; +}); + +// node_modules/yaml/dist/schema/core/schema.js +var require_schema2 = __commonJS((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string(); + var bool = require_bool(); + var float = require_float2(); + var int = require_int(); + var schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.boolTag, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float + ]; + exports.schema = schema; +}); + +// node_modules/yaml/dist/schema/json/schema.js +var require_schema3 = __commonJS((exports) => { + var Scalar = require_Scalar(); + var map = require_map(); + var seq = require_seq(); + function intIdentify(value) { + return typeof value === "bigint" || Number.isInteger(value); + } + var stringifyJSON = ({ value }) => JSON.stringify(value); + var jsonScalars = [ + { + identify: (value) => typeof value === "string", + default: true, + tag: "tag:yaml.org,2002:str", + resolve: (str) => str, + stringify: stringifyJSON + }, + { + identify: (value) => value == null, + createNode: () => new Scalar.Scalar(null), + default: true, + tag: "tag:yaml.org,2002:null", + test: /^null$/, + resolve: () => null, + stringify: stringifyJSON + }, + { + identify: (value) => typeof value === "boolean", + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^true$|^false$/, + resolve: (str) => str === "true", + stringify: stringifyJSON + }, + { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^-?(?:0|[1-9][0-9]*)$/, + resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), + stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) + }, + { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, + resolve: (str) => parseFloat(str), + stringify: stringifyJSON + } + ]; + var jsonError = { + default: true, + tag: "", + test: /^/, + resolve(str, onError) { + onError(`Unresolved plain scalar ${JSON.stringify(str)}`); + return str; + } + }; + var schema = [map.map, seq.seq].concat(jsonScalars, jsonError); + exports.schema = schema; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/binary.js +var require_binary = __commonJS((exports) => { + var node_buffer = __require("buffer"); + var Scalar = require_Scalar(); + var stringifyString = require_stringifyString(); + var binary = { + identify: (value) => value instanceof Uint8Array, + default: false, + tag: "tag:yaml.org,2002:binary", + resolve(src, onError) { + if (typeof node_buffer.Buffer === "function") { + return node_buffer.Buffer.from(src, "base64"); + } else if (typeof atob === "function") { + const str = atob(src.replace(/[\n\r]/g, "")); + const buffer = new Uint8Array(str.length); + for (let i = 0;i < str.length; ++i) + buffer[i] = str.charCodeAt(i); + return buffer; + } else { + onError("This environment does not support reading binary tags; either Buffer or atob is required"); + return src; + } + }, + stringify({ comment, type, value }, ctx, onComment, onChompKeep) { + if (!value) + return ""; + const buf = value; + let str; + if (typeof node_buffer.Buffer === "function") { + str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); + } else if (typeof btoa === "function") { + let s = ""; + for (let i = 0;i < buf.length; ++i) + s += String.fromCharCode(buf[i]); + str = btoa(s); + } else { + throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); + } + type ?? (type = Scalar.Scalar.BLOCK_LITERAL); + if (type !== Scalar.Scalar.QUOTE_DOUBLE) { + const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); + const n = Math.ceil(str.length / lineWidth); + const lines = new Array(n); + for (let i = 0, o = 0;i < n; ++i, o += lineWidth) { + lines[i] = str.substr(o, lineWidth); + } + str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? ` +` : " "); + } + return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); + } + }; + exports.binary = binary; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/pairs.js +var require_pairs = __commonJS((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLSeq = require_YAMLSeq(); + function resolvePairs(seq, onError) { + if (identity.isSeq(seq)) { + for (let i = 0;i < seq.items.length; ++i) { + let item = seq.items[i]; + if (identity.isPair(item)) + continue; + else if (identity.isMap(item)) { + if (item.items.length > 1) + onError("Each pair must have its own sequence indicator"); + const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); + if (item.commentBefore) + pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} +${pair.key.commentBefore}` : item.commentBefore; + if (item.comment) { + const cn = pair.value ?? pair.key; + cn.comment = cn.comment ? `${item.comment} +${cn.comment}` : item.comment; + } + item = pair; + } + seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); + } + } else + onError("Expected a sequence for this tag"); + return seq; + } + function createPairs(schema, iterable, ctx) { + const { replacer } = ctx; + const pairs2 = new YAMLSeq.YAMLSeq(schema); + pairs2.tag = "tag:yaml.org,2002:pairs"; + let i = 0; + if (iterable && Symbol.iterator in Object(iterable)) + for (let it of iterable) { + if (typeof replacer === "function") + it = replacer.call(iterable, String(i++), it); + let key, value; + if (Array.isArray(it)) { + if (it.length === 2) { + key = it[0]; + value = it[1]; + } else + throw new TypeError(`Expected [key, value] tuple: ${it}`); + } else if (it && it instanceof Object) { + const keys = Object.keys(it); + if (keys.length === 1) { + key = keys[0]; + value = it[key]; + } else { + throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); + } + } else { + key = it; + } + pairs2.items.push(Pair.createPair(key, value, ctx)); + } + return pairs2; + } + var pairs = { + collection: "seq", + default: false, + tag: "tag:yaml.org,2002:pairs", + resolve: resolvePairs, + createNode: createPairs + }; + exports.createPairs = createPairs; + exports.pairs = pairs; + exports.resolvePairs = resolvePairs; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/omap.js +var require_omap = __commonJS((exports) => { + var identity = require_identity(); + var toJS = require_toJS(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var pairs = require_pairs(); + + class YAMLOMap extends YAMLSeq.YAMLSeq { + constructor() { + super(); + this.add = YAMLMap.YAMLMap.prototype.add.bind(this); + this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); + this.get = YAMLMap.YAMLMap.prototype.get.bind(this); + this.has = YAMLMap.YAMLMap.prototype.has.bind(this); + this.set = YAMLMap.YAMLMap.prototype.set.bind(this); + this.tag = YAMLOMap.tag; + } + toJSON(_, ctx) { + if (!ctx) + return super.toJSON(_); + const map = new Map; + if (ctx?.onCreate) + ctx.onCreate(map); + for (const pair of this.items) { + let key, value; + if (identity.isPair(pair)) { + key = toJS.toJS(pair.key, "", ctx); + value = toJS.toJS(pair.value, key, ctx); + } else { + key = toJS.toJS(pair, "", ctx); + } + if (map.has(key)) + throw new Error("Ordered maps must not include duplicate keys"); + map.set(key, value); + } + return map; + } + static from(schema, iterable, ctx) { + const pairs$1 = pairs.createPairs(schema, iterable, ctx); + const omap2 = new this; + omap2.items = pairs$1.items; + return omap2; + } + } + YAMLOMap.tag = "tag:yaml.org,2002:omap"; + var omap = { + collection: "seq", + identify: (value) => value instanceof Map, + nodeClass: YAMLOMap, + default: false, + tag: "tag:yaml.org,2002:omap", + resolve(seq, onError) { + const pairs$1 = pairs.resolvePairs(seq, onError); + const seenKeys = []; + for (const { key } of pairs$1.items) { + if (identity.isScalar(key)) { + if (seenKeys.includes(key.value)) { + onError(`Ordered maps must not include duplicate keys: ${key.value}`); + } else { + seenKeys.push(key.value); + } + } + } + return Object.assign(new YAMLOMap, pairs$1); + }, + createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) + }; + exports.YAMLOMap = YAMLOMap; + exports.omap = omap; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/bool.js +var require_bool2 = __commonJS((exports) => { + var Scalar = require_Scalar(); + function boolStringify({ value, source }, ctx) { + const boolObj = value ? trueTag : falseTag; + if (source && boolObj.test.test(source)) + return source; + return value ? ctx.options.trueStr : ctx.options.falseStr; + } + var trueTag = { + identify: (value) => value === true, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, + resolve: () => new Scalar.Scalar(true), + stringify: boolStringify + }; + var falseTag = { + identify: (value) => value === false, + default: true, + tag: "tag:yaml.org,2002:bool", + test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, + resolve: () => new Scalar.Scalar(false), + stringify: boolStringify + }; + exports.falseTag = falseTag; + exports.trueTag = trueTag; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/float.js +var require_float3 = __commonJS((exports) => { + var Scalar = require_Scalar(); + var stringifyNumber = require_stringifyNumber(); + var floatNaN = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, + resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, + stringify: stringifyNumber.stringifyNumber + }; + var floatExp = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "EXP", + test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, + resolve: (str) => parseFloat(str.replace(/_/g, "")), + stringify(node) { + const num = Number(node.value); + return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); + } + }; + var float = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, + resolve(str) { + const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ""))); + const dot = str.indexOf("."); + if (dot !== -1) { + const f = str.substring(dot + 1).replace(/_/g, ""); + if (f[f.length - 1] === "0") + node.minFractionDigits = f.length; + } + return node; + }, + stringify: stringifyNumber.stringifyNumber + }; + exports.float = float; + exports.floatExp = floatExp; + exports.floatNaN = floatNaN; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/int.js +var require_int2 = __commonJS((exports) => { + var stringifyNumber = require_stringifyNumber(); + var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); + function intResolve(str, offset, radix, { intAsBigInt }) { + const sign = str[0]; + if (sign === "-" || sign === "+") + offset += 1; + str = str.substring(offset).replace(/_/g, ""); + if (intAsBigInt) { + switch (radix) { + case 2: + str = `0b${str}`; + break; + case 8: + str = `0o${str}`; + break; + case 16: + str = `0x${str}`; + break; + } + const n2 = BigInt(str); + return sign === "-" ? BigInt(-1) * n2 : n2; + } + const n = parseInt(str, radix); + return sign === "-" ? -1 * n : n; + } + function intStringify(node, radix, prefix) { + const { value } = node; + if (intIdentify(value)) { + const str = value.toString(radix); + return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; + } + return stringifyNumber.stringifyNumber(node); + } + var intBin = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "BIN", + test: /^[-+]?0b[0-1_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), + stringify: (node) => intStringify(node, 2, "0b") + }; + var intOct = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "OCT", + test: /^[-+]?0[0-7_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), + stringify: (node) => intStringify(node, 8, "0") + }; + var int = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + test: /^[-+]?[0-9][0-9_]*$/, + resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), + stringify: stringifyNumber.stringifyNumber + }; + var intHex = { + identify: intIdentify, + default: true, + tag: "tag:yaml.org,2002:int", + format: "HEX", + test: /^[-+]?0x[0-9a-fA-F_]+$/, + resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), + stringify: (node) => intStringify(node, 16, "0x") + }; + exports.int = int; + exports.intBin = intBin; + exports.intHex = intHex; + exports.intOct = intOct; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/set.js +var require_set = __commonJS((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + + class YAMLSet extends YAMLMap.YAMLMap { + constructor(schema) { + super(schema); + this.tag = YAMLSet.tag; + } + add(key) { + let pair; + if (identity.isPair(key)) + pair = key; + else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) + pair = new Pair.Pair(key.key, null); + else + pair = new Pair.Pair(key, null); + const prev = YAMLMap.findPair(this.items, pair.key); + if (!prev) + this.items.push(pair); + } + get(key, keepPair) { + const pair = YAMLMap.findPair(this.items, key); + return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair; + } + set(key, value) { + if (typeof value !== "boolean") + throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); + const prev = YAMLMap.findPair(this.items, key); + if (prev && !value) { + this.items.splice(this.items.indexOf(prev), 1); + } else if (!prev && value) { + this.items.push(new Pair.Pair(key)); + } + } + toJSON(_, ctx) { + return super.toJSON(_, ctx, Set); + } + toString(ctx, onComment, onChompKeep) { + if (!ctx) + return JSON.stringify(this); + if (this.hasAllNullValues(true)) + return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); + else + throw new Error("Set items must all have null values"); + } + static from(schema, iterable, ctx) { + const { replacer } = ctx; + const set2 = new this(schema); + if (iterable && Symbol.iterator in Object(iterable)) + for (let value of iterable) { + if (typeof replacer === "function") + value = replacer.call(iterable, value, value); + set2.items.push(Pair.createPair(value, null, ctx)); + } + return set2; + } + } + YAMLSet.tag = "tag:yaml.org,2002:set"; + var set = { + collection: "map", + identify: (value) => value instanceof Set, + nodeClass: YAMLSet, + default: false, + tag: "tag:yaml.org,2002:set", + createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), + resolve(map, onError) { + if (identity.isMap(map)) { + if (map.hasAllNullValues(true)) + return Object.assign(new YAMLSet, map); + else + onError("Set items must all have null values"); + } else + onError("Expected a mapping for this tag"); + return map; + } + }; + exports.YAMLSet = YAMLSet; + exports.set = set; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +var require_timestamp = __commonJS((exports) => { + var stringifyNumber = require_stringifyNumber(); + function parseSexagesimal(str, asBigInt) { + const sign = str[0]; + const parts = sign === "-" || sign === "+" ? str.substring(1) : str; + const num = (n) => asBigInt ? BigInt(n) : Number(n); + const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); + return sign === "-" ? num(-1) * res : res; + } + function stringifySexagesimal(node) { + let { value } = node; + let num = (n) => n; + if (typeof value === "bigint") + num = (n) => BigInt(n); + else if (isNaN(value) || !isFinite(value)) + return stringifyNumber.stringifyNumber(node); + let sign = ""; + if (value < 0) { + sign = "-"; + value *= num(-1); + } + const _60 = num(60); + const parts = [value % _60]; + if (value < 60) { + parts.unshift(0); + } else { + value = (value - parts[0]) / _60; + parts.unshift(value % _60); + if (value >= 60) { + value = (value - parts[0]) / _60; + parts.unshift(value); + } + } + return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); + } + var intTime = { + identify: (value) => typeof value === "bigint" || Number.isInteger(value), + default: true, + tag: "tag:yaml.org,2002:int", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, + resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), + stringify: stringifySexagesimal + }; + var floatTime = { + identify: (value) => typeof value === "number", + default: true, + tag: "tag:yaml.org,2002:float", + format: "TIME", + test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, + resolve: (str) => parseSexagesimal(str, false), + stringify: stringifySexagesimal + }; + var timestamp = { + identify: (value) => value instanceof Date, + default: true, + tag: "tag:yaml.org,2002:timestamp", + test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})" + "(?:" + "(?:t|T|[ \\t]+)" + "([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)" + "(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?" + ")?$"), + resolve(str) { + const match = str.match(timestamp.test); + if (!match) + throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); + const [, year, month, day, hour, minute, second] = match.map(Number); + const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; + let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); + const tz = match[8]; + if (tz && tz !== "Z") { + let d = parseSexagesimal(tz, false); + if (Math.abs(d) < 30) + d *= 60; + date -= 60000 * d; + } + return new Date(date); + }, + stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" + }; + exports.floatTime = floatTime; + exports.intTime = intTime; + exports.timestamp = timestamp; +}); + +// node_modules/yaml/dist/schema/yaml-1.1/schema.js +var require_schema4 = __commonJS((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string(); + var binary = require_binary(); + var bool = require_bool2(); + var float = require_float3(); + var int = require_int2(); + var merge = require_merge2(); + var omap = require_omap(); + var pairs = require_pairs(); + var set = require_set(); + var timestamp = require_timestamp(); + var schema = [ + map.map, + seq.seq, + string.string, + _null.nullTag, + bool.trueTag, + bool.falseTag, + int.intBin, + int.intOct, + int.int, + int.intHex, + float.floatNaN, + float.floatExp, + float.float, + binary.binary, + merge.merge, + omap.omap, + pairs.pairs, + set.set, + timestamp.intTime, + timestamp.floatTime, + timestamp.timestamp + ]; + exports.schema = schema; +}); + +// node_modules/yaml/dist/schema/tags.js +var require_tags = __commonJS((exports) => { + var map = require_map(); + var _null = require_null(); + var seq = require_seq(); + var string = require_string(); + var bool = require_bool(); + var float = require_float2(); + var int = require_int(); + var schema = require_schema2(); + var schema$1 = require_schema3(); + var binary = require_binary(); + var merge = require_merge2(); + var omap = require_omap(); + var pairs = require_pairs(); + var schema$2 = require_schema4(); + var set = require_set(); + var timestamp = require_timestamp(); + var schemas = new Map([ + ["core", schema.schema], + ["failsafe", [map.map, seq.seq, string.string]], + ["json", schema$1.schema], + ["yaml11", schema$2.schema], + ["yaml-1.1", schema$2.schema] + ]); + var tagsByName = { + binary: binary.binary, + bool: bool.boolTag, + float: float.float, + floatExp: float.floatExp, + floatNaN: float.floatNaN, + floatTime: timestamp.floatTime, + int: int.int, + intHex: int.intHex, + intOct: int.intOct, + intTime: timestamp.intTime, + map: map.map, + merge: merge.merge, + null: _null.nullTag, + omap: omap.omap, + pairs: pairs.pairs, + seq: seq.seq, + set: set.set, + timestamp: timestamp.timestamp + }; + var coreKnownTags = { + "tag:yaml.org,2002:binary": binary.binary, + "tag:yaml.org,2002:merge": merge.merge, + "tag:yaml.org,2002:omap": omap.omap, + "tag:yaml.org,2002:pairs": pairs.pairs, + "tag:yaml.org,2002:set": set.set, + "tag:yaml.org,2002:timestamp": timestamp.timestamp + }; + function getTags(customTags, schemaName, addMergeTag) { + const schemaTags = schemas.get(schemaName); + if (schemaTags && !customTags) { + return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice(); + } + let tags = schemaTags; + if (!tags) { + if (Array.isArray(customTags)) + tags = []; + else { + const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); + } + } + if (Array.isArray(customTags)) { + for (const tag of customTags) + tags = tags.concat(tag); + } else if (typeof customTags === "function") { + tags = customTags(tags.slice()); + } + if (addMergeTag) + tags = tags.concat(merge.merge); + return tags.reduce((tags2, tag) => { + const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; + if (!tagObj) { + const tagName = JSON.stringify(tag); + const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); + throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); + } + if (!tags2.includes(tagObj)) + tags2.push(tagObj); + return tags2; + }, []); + } + exports.coreKnownTags = coreKnownTags; + exports.getTags = getTags; +}); + +// node_modules/yaml/dist/schema/Schema.js +var require_Schema = __commonJS((exports) => { + var identity = require_identity(); + var map = require_map(); + var seq = require_seq(); + var string = require_string(); + var tags = require_tags(); + var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; + + class Schema { + constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { + this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null; + this.name = typeof schema === "string" && schema || "core"; + this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; + this.tags = tags.getTags(customTags, this.name, merge); + this.toStringOptions = toStringDefaults ?? null; + Object.defineProperty(this, identity.MAP, { value: map.map }); + Object.defineProperty(this, identity.SCALAR, { value: string.string }); + Object.defineProperty(this, identity.SEQ, { value: seq.seq }); + this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; + } + clone() { + const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this)); + copy.tags = this.tags.slice(); + return copy; + } + } + exports.Schema = Schema; +}); + +// node_modules/yaml/dist/stringify/stringifyDocument.js +var require_stringifyDocument = __commonJS((exports) => { + var identity = require_identity(); + var stringify = require_stringify(); + var stringifyComment = require_stringifyComment(); + function stringifyDocument(doc, options) { + const lines = []; + let hasDirectives = options.directives === true; + if (options.directives !== false && doc.directives) { + const dir = doc.directives.toString(doc); + if (dir) { + lines.push(dir); + hasDirectives = true; + } else if (doc.directives.docStart) + hasDirectives = true; + } + if (hasDirectives) + lines.push("---"); + const ctx = stringify.createStringifyContext(doc, options); + const { commentString } = ctx.options; + if (doc.commentBefore) { + if (lines.length !== 1) + lines.unshift(""); + const cs = commentString(doc.commentBefore); + lines.unshift(stringifyComment.indentComment(cs, "")); + } + let chompKeep = false; + let contentComment = null; + if (doc.contents) { + if (identity.isNode(doc.contents)) { + if (doc.contents.spaceBefore && hasDirectives) + lines.push(""); + if (doc.contents.commentBefore) { + const cs = commentString(doc.contents.commentBefore); + lines.push(stringifyComment.indentComment(cs, "")); + } + ctx.forceBlockIndent = !!doc.comment; + contentComment = doc.contents.comment; + } + const onChompKeep = contentComment ? undefined : () => chompKeep = true; + let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); + if (contentComment) + body += stringifyComment.lineComment(body, "", commentString(contentComment)); + if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { + lines[lines.length - 1] = `--- ${body}`; + } else + lines.push(body); + } else { + lines.push(stringify.stringify(doc.contents, ctx)); + } + if (doc.directives?.docEnd) { + if (doc.comment) { + const cs = commentString(doc.comment); + if (cs.includes(` +`)) { + lines.push("..."); + lines.push(stringifyComment.indentComment(cs, "")); + } else { + lines.push(`... ${cs}`); + } + } else { + lines.push("..."); + } + } else { + let dc = doc.comment; + if (dc && chompKeep) + dc = dc.replace(/^\n+/, ""); + if (dc) { + if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") + lines.push(""); + lines.push(stringifyComment.indentComment(commentString(dc), "")); + } + } + return lines.join(` +`) + ` +`; + } + exports.stringifyDocument = stringifyDocument; +}); + +// node_modules/yaml/dist/doc/Document.js +var require_Document = __commonJS((exports) => { + var Alias = require_Alias(); + var Collection = require_Collection(); + var identity = require_identity(); + var Pair = require_Pair(); + var toJS = require_toJS(); + var Schema = require_Schema(); + var stringifyDocument = require_stringifyDocument(); + var anchors = require_anchors(); + var applyReviver = require_applyReviver(); + var createNode = require_createNode(); + var directives = require_directives2(); + + class Document { + constructor(value, replacer, options) { + this.commentBefore = null; + this.comment = null; + this.errors = []; + this.warnings = []; + Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const opt = Object.assign({ + intAsBigInt: false, + keepSourceTokens: false, + logLevel: "warn", + prettyErrors: true, + strict: true, + stringKeys: false, + uniqueKeys: true, + version: "1.2" + }, options); + this.options = opt; + let { version } = opt; + if (options?._directives) { + this.directives = options._directives.atDocument(); + if (this.directives.yaml.explicit) + version = this.directives.yaml.version; + } else + this.directives = new directives.Directives({ version }); + this.setSchema(version, options); + this.contents = value === undefined ? null : this.createNode(value, _replacer, options); + } + clone() { + const copy = Object.create(Document.prototype, { + [identity.NODE_TYPE]: { value: identity.DOC } + }); + copy.commentBefore = this.commentBefore; + copy.comment = this.comment; + copy.errors = this.errors.slice(); + copy.warnings = this.warnings.slice(); + copy.options = Object.assign({}, this.options); + if (this.directives) + copy.directives = this.directives.clone(); + copy.schema = this.schema.clone(); + copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; + if (this.range) + copy.range = this.range.slice(); + return copy; + } + add(value) { + if (assertCollection(this.contents)) + this.contents.add(value); + } + addIn(path, value) { + if (assertCollection(this.contents)) + this.contents.addIn(path, value); + } + createAlias(node, name) { + if (!node.anchor) { + const prev = anchors.anchorNames(this); + node.anchor = !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; + } + return new Alias.Alias(node.anchor); + } + createNode(value, replacer, options) { + let _replacer = undefined; + if (typeof replacer === "function") { + value = replacer.call({ "": value }, "", value); + _replacer = replacer; + } else if (Array.isArray(replacer)) { + const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; + const asStr = replacer.filter(keyToStr).map(String); + if (asStr.length > 0) + replacer = replacer.concat(asStr); + _replacer = replacer; + } else if (options === undefined && replacer) { + options = replacer; + replacer = undefined; + } + const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; + const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, anchorPrefix || "a"); + const ctx = { + aliasDuplicateObjects: aliasDuplicateObjects ?? true, + keepUndefined: keepUndefined ?? false, + onAnchor, + onTagObj, + replacer: _replacer, + schema: this.schema, + sourceObjects + }; + const node = createNode.createNode(value, tag, ctx); + if (flow && identity.isCollection(node)) + node.flow = true; + setAnchors(); + return node; + } + createPair(key, value, options = {}) { + const k = this.createNode(key, null, options); + const v = this.createNode(value, null, options); + return new Pair.Pair(k, v); + } + delete(key) { + return assertCollection(this.contents) ? this.contents.delete(key) : false; + } + deleteIn(path) { + if (Collection.isEmptyPath(path)) { + if (this.contents == null) + return false; + this.contents = null; + return true; + } + return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; + } + get(key, keepScalar) { + return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined; + } + getIn(path, keepScalar) { + if (Collection.isEmptyPath(path)) + return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; + return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : undefined; + } + has(key) { + return identity.isCollection(this.contents) ? this.contents.has(key) : false; + } + hasIn(path) { + if (Collection.isEmptyPath(path)) + return this.contents !== undefined; + return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false; + } + set(key, value) { + if (this.contents == null) { + this.contents = Collection.collectionFromPath(this.schema, [key], value); + } else if (assertCollection(this.contents)) { + this.contents.set(key, value); + } + } + setIn(path, value) { + if (Collection.isEmptyPath(path)) { + this.contents = value; + } else if (this.contents == null) { + this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value); + } else if (assertCollection(this.contents)) { + this.contents.setIn(path, value); + } + } + setSchema(version, options = {}) { + if (typeof version === "number") + version = String(version); + let opt; + switch (version) { + case "1.1": + if (this.directives) + this.directives.yaml.version = "1.1"; + else + this.directives = new directives.Directives({ version: "1.1" }); + opt = { resolveKnownTags: false, schema: "yaml-1.1" }; + break; + case "1.2": + case "next": + if (this.directives) + this.directives.yaml.version = version; + else + this.directives = new directives.Directives({ version }); + opt = { resolveKnownTags: true, schema: "core" }; + break; + case null: + if (this.directives) + delete this.directives; + opt = null; + break; + default: { + const sv = JSON.stringify(version); + throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); + } + } + if (options.schema instanceof Object) + this.schema = options.schema; + else if (opt) + this.schema = new Schema.Schema(Object.assign(opt, options)); + else + throw new Error(`With a null YAML version, the { schema: Schema } option is required`); + } + toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { + const ctx = { + anchors: new Map, + doc: this, + keep: !json, + mapAsMap: mapAsMap === true, + mapKeyWarned: false, + maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 + }; + const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); + if (typeof onAnchor === "function") + for (const { count, res: res2 } of ctx.anchors.values()) + onAnchor(res2, count); + return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; + } + toJSON(jsonArg, onAnchor) { + return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); + } + toString(options = {}) { + if (this.errors.length > 0) + throw new Error("Document with errors cannot be stringified"); + if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { + const s = JSON.stringify(options.indent); + throw new Error(`"indent" option must be a positive integer, not ${s}`); + } + return stringifyDocument.stringifyDocument(this, options); + } + } + function assertCollection(contents) { + if (identity.isCollection(contents)) + return true; + throw new Error("Expected a YAML collection as document contents"); + } + exports.Document = Document; +}); + +// node_modules/yaml/dist/errors.js +var require_errors = __commonJS((exports) => { + class YAMLError extends Error { + constructor(name, pos, code, message) { + super(); + this.name = name; + this.code = code; + this.message = message; + this.pos = pos; + } + } + + class YAMLParseError extends YAMLError { + constructor(pos, code, message) { + super("YAMLParseError", pos, code, message); + } + } + + class YAMLWarning extends YAMLError { + constructor(pos, code, message) { + super("YAMLWarning", pos, code, message); + } + } + var prettifyError = (src, lc) => (error) => { + if (error.pos[0] === -1) + return; + error.linePos = error.pos.map((pos) => lc.linePos(pos)); + const { line, col } = error.linePos[0]; + error.message += ` at line ${line}, column ${col}`; + let ci = col - 1; + let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); + if (ci >= 60 && lineStr.length > 80) { + const trimStart = Math.min(ci - 39, lineStr.length - 79); + lineStr = "…" + lineStr.substring(trimStart); + ci -= trimStart - 1; + } + if (lineStr.length > 80) + lineStr = lineStr.substring(0, 79) + "…"; + if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { + let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); + if (prev.length > 80) + prev = prev.substring(0, 79) + `… +`; + lineStr = prev + lineStr; + } + if (/[^ ]/.test(lineStr)) { + let count = 1; + const end = error.linePos[1]; + if (end?.line === line && end.col > col) { + count = Math.max(1, Math.min(end.col - col, 80 - ci)); + } + const pointer = " ".repeat(ci) + "^".repeat(count); + error.message += `: + +${lineStr} +${pointer} +`; + } + }; + exports.YAMLError = YAMLError; + exports.YAMLParseError = YAMLParseError; + exports.YAMLWarning = YAMLWarning; + exports.prettifyError = prettifyError; +}); + +// node_modules/yaml/dist/compose/resolve-props.js +var require_resolve_props = __commonJS((exports) => { + function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { + let spaceBefore = false; + let atNewline = startOnNewline; + let hasSpace = startOnNewline; + let comment = ""; + let commentSep = ""; + let hasNewline = false; + let reqSpace = false; + let tab = null; + let anchor = null; + let tag = null; + let newlineAfterProp = null; + let comma = null; + let found = null; + let start = null; + for (const token of tokens) { + if (reqSpace) { + if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") + onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + reqSpace = false; + } + if (tab) { + if (atNewline && token.type !== "comment" && token.type !== "newline") { + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + } + tab = null; + } + switch (token.type) { + case "space": + if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes("\t")) { + tab = token; + } + hasSpace = true; + break; + case "comment": { + if (!hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = token.source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += commentSep + cb; + commentSep = ""; + atNewline = false; + break; + } + case "newline": + if (atNewline) { + if (comment) + comment += token.source; + else if (!found || indicator !== "seq-item-ind") + spaceBefore = true; + } else + commentSep += token.source; + atNewline = true; + hasNewline = true; + if (anchor || tag) + newlineAfterProp = token; + hasSpace = true; + break; + case "anchor": + if (anchor) + onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); + if (token.source.endsWith(":")) + onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); + anchor = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + case "tag": { + if (tag) + onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); + tag = token; + start ?? (start = token.offset); + atNewline = false; + hasSpace = false; + reqSpace = true; + break; + } + case indicator: + if (anchor || tag) + onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); + if (found) + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); + found = token; + atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; + hasSpace = false; + break; + case "comma": + if (flow) { + if (comma) + onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); + comma = token; + atNewline = false; + hasSpace = false; + break; + } + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); + atNewline = false; + hasSpace = false; + } + } + const last = tokens[tokens.length - 1]; + const end = last ? last.offset + last.source.length : offset; + if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { + onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); + } + if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) + onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); + return { + comma, + found, + spaceBefore, + comment, + hasNewline, + anchor, + tag, + newlineAfterProp, + end, + start: start ?? end + }; + } + exports.resolveProps = resolveProps; +}); + +// node_modules/yaml/dist/compose/util-contains-newline.js +var require_util_contains_newline = __commonJS((exports) => { + function containsNewline(key) { + if (!key) + return null; + switch (key.type) { + case "alias": + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + if (key.source.includes(` +`)) + return true; + if (key.end) { + for (const st of key.end) + if (st.type === "newline") + return true; + } + return false; + case "flow-collection": + for (const it of key.items) { + for (const st of it.start) + if (st.type === "newline") + return true; + if (it.sep) { + for (const st of it.sep) + if (st.type === "newline") + return true; + } + if (containsNewline(it.key) || containsNewline(it.value)) + return true; + } + return false; + default: + return true; + } + } + exports.containsNewline = containsNewline; +}); + +// node_modules/yaml/dist/compose/util-flow-indent-check.js +var require_util_flow_indent_check = __commonJS((exports) => { + var utilContainsNewline = require_util_contains_newline(); + function flowIndentCheck(indent, fc, onError) { + if (fc?.type === "flow-collection") { + const end = fc.end[0]; + if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) { + const msg = "Flow end indicator should be more indented than parent"; + onError(end, "BAD_INDENT", msg, true); + } + } + } + exports.flowIndentCheck = flowIndentCheck; +}); + +// node_modules/yaml/dist/compose/util-map-includes.js +var require_util_map_includes = __commonJS((exports) => { + var identity = require_identity(); + function mapIncludes(ctx, items, search) { + const { uniqueKeys } = ctx.options; + if (uniqueKeys === false) + return false; + const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value; + return items.some((pair) => isEqual(pair.key, search)); + } + exports.mapIncludes = mapIncludes; +}); + +// node_modules/yaml/dist/compose/resolve-block-map.js +var require_resolve_block_map = __commonJS((exports) => { + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + var utilMapIncludes = require_util_map_includes(); + var startColMsg = "All mapping items must start at the same column"; + function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap; + const map = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + let offset = bm.offset; + let commentEnd = null; + for (const collItem of bm.items) { + const { start, key, sep, value } = collItem; + const keyProps = resolveProps.resolveProps(start, { + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: bm.indent, + startOnNewline: true + }); + const implicitKey = !keyProps.found; + if (implicitKey) { + if (key) { + if (key.type === "block-seq") + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); + else if ("indent" in key && key.indent !== bm.indent) + onError(offset, "BAD_INDENT", startColMsg); + } + if (!keyProps.anchor && !keyProps.tag && !sep) { + commentEnd = keyProps.end; + if (keyProps.comment) { + if (map.comment) + map.comment += ` +` + keyProps.comment; + else + map.comment = keyProps.comment; + } + continue; + } + if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) { + onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); + } + } else if (keyProps.found?.indent !== bm.indent) { + onError(offset, "BAD_INDENT", startColMsg); + } + ctx.atKey = true; + const keyStart = keyProps.end; + const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError); + ctx.atKey = false; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + const valueProps = resolveProps.resolveProps(sep ?? [], { + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: bm.indent, + startOnNewline: !key || key.type === "block-scalar" + }); + offset = valueProps.end; + if (valueProps.found) { + if (implicitKey) { + if (value?.type === "block-map" && !valueProps.hasNewline) + onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); + if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) + onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); + } + const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError); + offset = valueNode.range[2]; + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } else { + if (implicitKey) + onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); + if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += ` +` + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair.Pair(keyNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + map.items.push(pair); + } + } + if (commentEnd && commentEnd < offset) + onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); + map.range = [bm.offset, offset, commentEnd ?? offset]; + return map; + } + exports.resolveBlockMap = resolveBlockMap; +}); + +// node_modules/yaml/dist/compose/resolve-block-seq.js +var require_resolve_block_seq = __commonJS((exports) => { + var YAMLSeq = require_YAMLSeq(); + var resolveProps = require_resolve_props(); + var utilFlowIndentCheck = require_util_flow_indent_check(); + function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { + const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq; + const seq = new NodeClass(ctx.schema); + if (ctx.atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = bs.offset; + let commentEnd = null; + for (const { start, value } of bs.items) { + const props = resolveProps.resolveProps(start, { + indicator: "seq-item-ind", + next: value, + offset, + onError, + parentIndent: bs.indent, + startOnNewline: true + }); + if (!props.found) { + if (props.anchor || props.tag || value) { + if (value?.type === "block-seq") + onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); + else + onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); + } else { + commentEnd = props.end; + if (props.comment) + seq.comment = props.comment; + continue; + } + } + const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); + if (ctx.schema.compat) + utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError); + offset = node.range[2]; + seq.items.push(node); + } + seq.range = [bs.offset, offset, commentEnd ?? offset]; + return seq; + } + exports.resolveBlockSeq = resolveBlockSeq; +}); + +// node_modules/yaml/dist/compose/resolve-end.js +var require_resolve_end = __commonJS((exports) => { + function resolveEnd(end, offset, reqSpace, onError) { + let comment = ""; + if (end) { + let hasSpace = false; + let sep = ""; + for (const token of end) { + const { source, type } = token; + switch (type) { + case "space": + hasSpace = true; + break; + case "comment": { + if (reqSpace && !hasSpace) + onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); + const cb = source.substring(1) || " "; + if (!comment) + comment = cb; + else + comment += sep + cb; + sep = ""; + break; + } + case "newline": + if (comment) + sep += source; + hasSpace = true; + break; + default: + onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); + } + offset += source.length; + } + } + return { comment, offset }; + } + exports.resolveEnd = resolveEnd; +}); + +// node_modules/yaml/dist/compose/resolve-flow-collection.js +var require_resolve_flow_collection = __commonJS((exports) => { + var identity = require_identity(); + var Pair = require_Pair(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + var utilContainsNewline = require_util_contains_newline(); + var utilMapIncludes = require_util_map_includes(); + var blockMsg = "Block collections are not allowed within flow collections"; + var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); + function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { + const isMap = fc.start.source === "{"; + const fcName = isMap ? "flow map" : "flow sequence"; + const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq); + const coll = new NodeClass(ctx.schema); + coll.flow = true; + const atRoot = ctx.atRoot; + if (atRoot) + ctx.atRoot = false; + if (ctx.atKey) + ctx.atKey = false; + let offset = fc.offset + fc.start.source.length; + for (let i = 0;i < fc.items.length; ++i) { + const collItem = fc.items[i]; + const { start, key, sep, value } = collItem; + const props = resolveProps.resolveProps(start, { + flow: fcName, + indicator: "explicit-key-ind", + next: key ?? sep?.[0], + offset, + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (!props.found) { + if (!props.anchor && !props.tag && !sep && !value) { + if (i === 0 && props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + else if (i < fc.items.length - 1) + onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); + if (props.comment) { + if (coll.comment) + coll.comment += ` +` + props.comment; + else + coll.comment = props.comment; + } + offset = props.end; + continue; + } + if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) + onError(key, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + } + if (i === 0) { + if (props.comma) + onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); + } else { + if (!props.comma) + onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); + if (props.comment) { + let prevItemComment = ""; + loop: + for (const st of start) { + switch (st.type) { + case "comma": + case "space": + break; + case "comment": + prevItemComment = st.source.substring(1); + break loop; + default: + break loop; + } + } + if (prevItemComment) { + let prev = coll.items[coll.items.length - 1]; + if (identity.isPair(prev)) + prev = prev.value ?? prev.key; + if (prev.comment) + prev.comment += ` +` + prevItemComment; + else + prev.comment = prevItemComment; + props.comment = props.comment.substring(prevItemComment.length + 1); + } + } + } + if (!isMap && !sep && !props.found) { + const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError); + coll.items.push(valueNode); + offset = valueNode.range[2]; + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else { + ctx.atKey = true; + const keyStart = props.end; + const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError); + if (isBlock(key)) + onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); + ctx.atKey = false; + const valueProps = resolveProps.resolveProps(sep ?? [], { + flow: fcName, + indicator: "map-value-ind", + next: value, + offset: keyNode.range[2], + onError, + parentIndent: fc.indent, + startOnNewline: false + }); + if (valueProps.found) { + if (!isMap && !props.found && ctx.options.strict) { + if (sep) + for (const st of sep) { + if (st === valueProps.found) + break; + if (st.type === "newline") { + onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); + break; + } + } + if (props.start < valueProps.found.offset - 1024) + onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); + } + } else if (value) { + if ("source" in value && value.source?.[0] === ":") + onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); + else + onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); + } + const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null; + if (valueNode) { + if (isBlock(value)) + onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); + } else if (valueProps.comment) { + if (keyNode.comment) + keyNode.comment += ` +` + valueProps.comment; + else + keyNode.comment = valueProps.comment; + } + const pair = new Pair.Pair(keyNode, valueNode); + if (ctx.options.keepSourceTokens) + pair.srcToken = collItem; + if (isMap) { + const map = coll; + if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) + onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); + map.items.push(pair); + } else { + const map = new YAMLMap.YAMLMap(ctx.schema); + map.flow = true; + map.items.push(pair); + const endRange = (valueNode ?? keyNode).range; + map.range = [keyNode.range[0], endRange[1], endRange[2]]; + coll.items.push(map); + } + offset = valueNode ? valueNode.range[2] : valueProps.end; + } + } + const expectedEnd = isMap ? "}" : "]"; + const [ce, ...ee] = fc.end; + let cePos = offset; + if (ce?.source === expectedEnd) + cePos = ce.offset + ce.source.length; + else { + const name = fcName[0].toUpperCase() + fcName.substring(1); + const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; + onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); + if (ce && ce.source.length !== 1) + ee.unshift(ce); + } + if (ee.length > 0) { + const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError); + if (end.comment) { + if (coll.comment) + coll.comment += ` +` + end.comment; + else + coll.comment = end.comment; + } + coll.range = [fc.offset, cePos, end.offset]; + } else { + coll.range = [fc.offset, cePos, cePos]; + } + return coll; + } + exports.resolveFlowCollection = resolveFlowCollection; +}); + +// node_modules/yaml/dist/compose/compose-collection.js +var require_compose_collection = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var resolveBlockMap = require_resolve_block_map(); + var resolveBlockSeq = require_resolve_block_seq(); + var resolveFlowCollection = require_resolve_flow_collection(); + function resolveCollection(CN, ctx, token, onError, tagName, tag) { + const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag); + const Coll = coll.constructor; + if (tagName === "!" || tagName === Coll.tagName) { + coll.tag = Coll.tagName; + return coll; + } + if (tagName) + coll.tag = tagName; + return coll; + } + function composeCollection(CN, ctx, token, props, onError) { + const tagToken = props.tag; + const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); + if (token.type === "block-seq") { + const { anchor, newlineAfterProp: nl } = props; + const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; + if (lastProp && (!nl || nl.offset < lastProp.offset)) { + const message = "Missing newline after block sequence props"; + onError(lastProp, "MISSING_CHAR", message); + } + } + const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; + if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") { + return resolveCollection(CN, ctx, token, onError, tagName); + } + let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); + if (!tag) { + const kt = ctx.schema.knownTags[tagName]; + if (kt?.collection === expType) { + ctx.schema.tags.push(Object.assign({}, kt, { default: false })); + tag = kt; + } else { + if (kt) { + onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); + } else { + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); + } + return resolveCollection(CN, ctx, token, onError, tagName); + } + } + const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); + const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; + const node = identity.isNode(res) ? res : new Scalar.Scalar(res); + node.range = coll.range; + node.tag = tagName; + if (tag?.format) + node.format = tag.format; + return node; + } + exports.composeCollection = composeCollection; +}); + +// node_modules/yaml/dist/compose/resolve-block-scalar.js +var require_resolve_block_scalar = __commonJS((exports) => { + var Scalar = require_Scalar(); + function resolveBlockScalar(ctx, scalar, onError) { + const start = scalar.offset; + const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); + if (!header) + return { value: "", type: null, comment: "", range: [start, start, start] }; + const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; + const lines = scalar.source ? splitLines(scalar.source) : []; + let chompStart = lines.length; + for (let i = lines.length - 1;i >= 0; --i) { + const content = lines[i][1]; + if (content === "" || content === "\r") + chompStart = i; + else + break; + } + if (chompStart === 0) { + const value2 = header.chomp === "+" && lines.length > 0 ? ` +`.repeat(Math.max(1, lines.length - 1)) : ""; + let end2 = start + header.length; + if (scalar.source) + end2 += scalar.source.length; + return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; + } + let trimIndent = scalar.indent + header.indent; + let offset = scalar.offset + header.length; + let contentStart = 0; + for (let i = 0;i < chompStart; ++i) { + const [indent, content] = lines[i]; + if (content === "" || content === "\r") { + if (header.indent === 0 && indent.length > trimIndent) + trimIndent = indent.length; + } else { + if (indent.length < trimIndent) { + const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; + onError(offset + indent.length, "MISSING_CHAR", message); + } + if (header.indent === 0) + trimIndent = indent.length; + contentStart = i; + if (trimIndent === 0 && !ctx.atRoot) { + const message = "Block scalar values in collections must be indented"; + onError(offset, "BAD_INDENT", message); + } + break; + } + offset += indent.length + content.length + 1; + } + for (let i = lines.length - 1;i >= chompStart; --i) { + if (lines[i][0].length > trimIndent) + chompStart = i + 1; + } + let value = ""; + let sep = ""; + let prevMoreIndented = false; + for (let i = 0;i < contentStart; ++i) + value += lines[i][0].slice(trimIndent) + ` +`; + for (let i = contentStart;i < chompStart; ++i) { + let [indent, content] = lines[i]; + offset += indent.length + content.length + 1; + const crlf = content[content.length - 1] === "\r"; + if (crlf) + content = content.slice(0, -1); + if (content && indent.length < trimIndent) { + const src = header.indent ? "explicit indentation indicator" : "first line"; + const message = `Block scalar lines must not be less indented than their ${src}`; + onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); + indent = ""; + } + if (type === Scalar.Scalar.BLOCK_LITERAL) { + value += sep + indent.slice(trimIndent) + content; + sep = ` +`; + } else if (indent.length > trimIndent || content[0] === "\t") { + if (sep === " ") + sep = ` +`; + else if (!prevMoreIndented && sep === ` +`) + sep = ` + +`; + value += sep + indent.slice(trimIndent) + content; + sep = ` +`; + prevMoreIndented = true; + } else if (content === "") { + if (sep === ` +`) + value += ` +`; + else + sep = ` +`; + } else { + value += sep + content; + sep = " "; + prevMoreIndented = false; + } + } + switch (header.chomp) { + case "-": + break; + case "+": + for (let i = chompStart;i < lines.length; ++i) + value += ` +` + lines[i][0].slice(trimIndent); + if (value[value.length - 1] !== ` +`) + value += ` +`; + break; + default: + value += ` +`; + } + const end = start + header.length + scalar.source.length; + return { value, type, comment: header.comment, range: [start, end, end] }; + } + function parseBlockScalarHeader({ offset, props }, strict, onError) { + if (props[0].type !== "block-scalar-header") { + onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); + return null; + } + const { source } = props[0]; + const mode = source[0]; + let indent = 0; + let chomp = ""; + let error = -1; + for (let i = 1;i < source.length; ++i) { + const ch = source[i]; + if (!chomp && (ch === "-" || ch === "+")) + chomp = ch; + else { + const n = Number(ch); + if (!indent && n) + indent = n; + else if (error === -1) + error = offset + i; + } + } + if (error !== -1) + onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); + let hasSpace = false; + let comment = ""; + let length = source.length; + for (let i = 1;i < props.length; ++i) { + const token = props[i]; + switch (token.type) { + case "space": + hasSpace = true; + case "newline": + length += token.source.length; + break; + case "comment": + if (strict && !hasSpace) { + const message = "Comments must be separated from other tokens by white space characters"; + onError(token, "MISSING_CHAR", message); + } + length += token.source.length; + comment = token.source.substring(1); + break; + case "error": + onError(token, "UNEXPECTED_TOKEN", token.message); + length += token.source.length; + break; + default: { + const message = `Unexpected token in block scalar header: ${token.type}`; + onError(token, "UNEXPECTED_TOKEN", message); + const ts = token.source; + if (ts && typeof ts === "string") + length += ts.length; + } + } + } + return { mode, indent, chomp, comment, length }; + } + function splitLines(source) { + const split = source.split(/\n( *)/); + const first = split[0]; + const m = first.match(/^( *)/); + const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; + const lines = [line0]; + for (let i = 1;i < split.length; i += 2) + lines.push([split[i], split[i + 1]]); + return lines; + } + exports.resolveBlockScalar = resolveBlockScalar; +}); + +// node_modules/yaml/dist/compose/resolve-flow-scalar.js +var require_resolve_flow_scalar = __commonJS((exports) => { + var Scalar = require_Scalar(); + var resolveEnd = require_resolve_end(); + function resolveFlowScalar(scalar, strict, onError) { + const { offset, type, source, end } = scalar; + let _type; + let value; + const _onError = (rel, code, msg) => onError(offset + rel, code, msg); + switch (type) { + case "scalar": + _type = Scalar.Scalar.PLAIN; + value = plainValue(source, _onError); + break; + case "single-quoted-scalar": + _type = Scalar.Scalar.QUOTE_SINGLE; + value = singleQuotedValue(source, _onError); + break; + case "double-quoted-scalar": + _type = Scalar.Scalar.QUOTE_DOUBLE; + value = doubleQuotedValue(source, _onError); + break; + default: + onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); + return { + value: "", + type: null, + comment: "", + range: [offset, offset + source.length, offset + source.length] + }; + } + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError); + return { + value, + type: _type, + comment: re.comment, + range: [offset, valueEnd, re.offset] + }; + } + function plainValue(source, onError) { + let badChar = ""; + switch (source[0]) { + case "\t": + badChar = "a tab character"; + break; + case ",": + badChar = "flow indicator character ,"; + break; + case "%": + badChar = "directive indicator character %"; + break; + case "|": + case ">": { + badChar = `block scalar indicator ${source[0]}`; + break; + } + case "@": + case "`": { + badChar = `reserved character ${source[0]}`; + break; + } + } + if (badChar) + onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); + return foldLines(source); + } + function singleQuotedValue(source, onError) { + if (source[source.length - 1] !== "'" || source.length === 1) + onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); + return foldLines(source.slice(1, -1)).replace(/''/g, "'"); + } + function foldLines(source) { + let first, line; + try { + first = new RegExp(`(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch; + } else { + res += ch; + } + } + if (source[source.length - 1] !== '"' || source.length === 1) + onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); + return res; + } + function foldNewline(source, offset) { + let fold = ""; + let ch = source[offset + 1]; + while (ch === " " || ch === "\t" || ch === ` +` || ch === "\r") { + if (ch === "\r" && source[offset + 2] !== ` +`) + break; + if (ch === ` +`) + fold += ` +`; + offset += 1; + ch = source[offset + 1]; + } + if (!fold) + fold = " "; + return { fold, offset }; + } + var escapeCodes = { + "0": "\x00", + a: "\x07", + b: "\b", + e: "\x1B", + f: "\f", + n: ` +`, + r: "\r", + t: "\t", + v: "\v", + N: "…", + _: " ", + L: "\u2028", + P: "\u2029", + " ": " ", + '"': '"', + "/": "/", + "\\": "\\", + "\t": "\t" + }; + function parseCharCode(source, offset, length, onError) { + const cc = source.substr(offset, length); + const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); + const code = ok ? parseInt(cc, 16) : NaN; + if (isNaN(code)) { + const raw = source.substr(offset - 2, length + 2); + onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); + return raw; + } + return String.fromCodePoint(code); + } + exports.resolveFlowScalar = resolveFlowScalar; +}); + +// node_modules/yaml/dist/compose/compose-scalar.js +var require_compose_scalar = __commonJS((exports) => { + var identity = require_identity(); + var Scalar = require_Scalar(); + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + function composeScalar(ctx, token, tagToken, onError) { + const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError); + const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; + let tag; + if (ctx.options.stringKeys && ctx.atKey) { + tag = ctx.schema[identity.SCALAR]; + } else if (tagName) + tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); + else if (token.type === "scalar") + tag = findScalarTagByTest(ctx, value, token, onError); + else + tag = ctx.schema[identity.SCALAR]; + let scalar; + try { + const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); + scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); + scalar = new Scalar.Scalar(value); + } + scalar.range = range; + scalar.source = value; + if (type) + scalar.type = type; + if (tagName) + scalar.tag = tagName; + if (tag.format) + scalar.format = tag.format; + if (comment) + scalar.comment = comment; + return scalar; + } + function findScalarTagByName(schema, value, tagName, tagToken, onError) { + if (tagName === "!") + return schema[identity.SCALAR]; + const matchWithTest = []; + for (const tag of schema.tags) { + if (!tag.collection && tag.tag === tagName) { + if (tag.default && tag.test) + matchWithTest.push(tag); + else + return tag; + } + } + for (const tag of matchWithTest) + if (tag.test?.test(value)) + return tag; + const kt = schema.knownTags[tagName]; + if (kt && !kt.collection) { + schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })); + return kt; + } + onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); + return schema[identity.SCALAR]; + } + function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) { + const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR]; + if (schema.compat) { + const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR]; + if (tag.tag !== compat.tag) { + const ts = directives.tagString(tag.tag); + const cs = directives.tagString(compat.tag); + const msg = `Value may be parsed as either ${ts} or ${cs}`; + onError(token, "TAG_RESOLVE_FAILED", msg, true); + } + } + return tag; + } + exports.composeScalar = composeScalar; +}); + +// node_modules/yaml/dist/compose/util-empty-scalar-position.js +var require_util_empty_scalar_position = __commonJS((exports) => { + function emptyScalarPosition(offset, before, pos) { + if (before) { + pos ?? (pos = before.length); + for (let i = pos - 1;i >= 0; --i) { + let st = before[i]; + switch (st.type) { + case "space": + case "comment": + case "newline": + offset -= st.source.length; + continue; + } + st = before[++i]; + while (st?.type === "space") { + offset += st.source.length; + st = before[++i]; + } + break; + } + } + return offset; + } + exports.emptyScalarPosition = emptyScalarPosition; +}); + +// node_modules/yaml/dist/compose/compose-node.js +var require_compose_node = __commonJS((exports) => { + var Alias = require_Alias(); + var identity = require_identity(); + var composeCollection = require_compose_collection(); + var composeScalar = require_compose_scalar(); + var resolveEnd = require_resolve_end(); + var utilEmptyScalarPosition = require_util_empty_scalar_position(); + var CN = { composeNode, composeEmptyNode }; + function composeNode(ctx, token, props, onError) { + const atKey = ctx.atKey; + const { spaceBefore, comment, anchor, tag } = props; + let node; + let isSrcToken = true; + switch (token.type) { + case "alias": + node = composeAlias(ctx, token, onError); + if (anchor || tag) + onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); + break; + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "block-scalar": + node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + case "block-map": + case "block-seq": + case "flow-collection": + node = composeCollection.composeCollection(CN, ctx, token, props, onError); + if (anchor) + node.anchor = anchor.source.substring(1); + break; + default: { + const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; + onError(token, "UNEXPECTED_TOKEN", message); + node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError); + isSrcToken = false; + } + } + if (anchor && node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { + const msg = "With stringKeys, all keys must be strings"; + onError(tag ?? token, "NON_STRING_KEY", msg); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + if (token.type === "scalar" && token.source === "") + node.comment = comment; + else + node.commentBefore = comment; + } + if (ctx.options.keepSourceTokens && isSrcToken) + node.srcToken = token; + return node; + } + function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { + const token = { + type: "scalar", + offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), + indent: -1, + source: "" + }; + const node = composeScalar.composeScalar(ctx, token, tag, onError); + if (anchor) { + node.anchor = anchor.source.substring(1); + if (node.anchor === "") + onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); + } + if (spaceBefore) + node.spaceBefore = true; + if (comment) { + node.comment = comment; + node.range[2] = end; + } + return node; + } + function composeAlias({ options }, { offset, source, end }, onError) { + const alias = new Alias.Alias(source.substring(1)); + if (alias.source === "") + onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); + if (alias.source.endsWith(":")) + onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); + const valueEnd = offset + source.length; + const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError); + alias.range = [offset, valueEnd, re.offset]; + if (re.comment) + alias.comment = re.comment; + return alias; + } + exports.composeEmptyNode = composeEmptyNode; + exports.composeNode = composeNode; +}); + +// node_modules/yaml/dist/compose/compose-doc.js +var require_compose_doc = __commonJS((exports) => { + var Document = require_Document(); + var composeNode = require_compose_node(); + var resolveEnd = require_resolve_end(); + var resolveProps = require_resolve_props(); + function composeDoc(options, directives, { offset, start, value, end }, onError) { + const opts = Object.assign({ _directives: directives }, options); + const doc = new Document.Document(undefined, opts); + const ctx = { + atKey: false, + atRoot: true, + directives: doc.directives, + options: doc.options, + schema: doc.schema + }; + const props = resolveProps.resolveProps(start, { + indicator: "doc-start", + next: value ?? end?.[0], + offset, + onError, + parentIndent: 0, + startOnNewline: true + }); + if (props.found) { + doc.directives.docStart = true; + if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) + onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); + } + doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError); + const contentEnd = doc.contents.range[2]; + const re = resolveEnd.resolveEnd(end, contentEnd, false, onError); + if (re.comment) + doc.comment = re.comment; + doc.range = [offset, contentEnd, re.offset]; + return doc; + } + exports.composeDoc = composeDoc; +}); + +// node_modules/yaml/dist/compose/composer.js +var require_composer = __commonJS((exports) => { + var node_process = __require("process"); + var directives = require_directives2(); + var Document = require_Document(); + var errors = require_errors(); + var identity = require_identity(); + var composeDoc = require_compose_doc(); + var resolveEnd = require_resolve_end(); + function getErrorPos(src) { + if (typeof src === "number") + return [src, src + 1]; + if (Array.isArray(src)) + return src.length === 2 ? src : [src[0], src[1]]; + const { offset, source } = src; + return [offset, offset + (typeof source === "string" ? source.length : 1)]; + } + function parsePrelude(prelude) { + let comment = ""; + let atComment = false; + let afterEmptyLine = false; + for (let i = 0;i < prelude.length; ++i) { + const source = prelude[i]; + switch (source[0]) { + case "#": + comment += (comment === "" ? "" : afterEmptyLine ? ` + +` : ` +`) + (source.substring(1) || " "); + atComment = true; + afterEmptyLine = false; + break; + case "%": + if (prelude[i + 1]?.[0] !== "#") + i += 1; + atComment = false; + break; + default: + if (!atComment) + afterEmptyLine = true; + atComment = false; + } + } + return { comment, afterEmptyLine }; + } + + class Composer { + constructor(options = {}) { + this.doc = null; + this.atDirectives = false; + this.prelude = []; + this.errors = []; + this.warnings = []; + this.onError = (source, code, message, warning) => { + const pos = getErrorPos(source); + if (warning) + this.warnings.push(new errors.YAMLWarning(pos, code, message)); + else + this.errors.push(new errors.YAMLParseError(pos, code, message)); + }; + this.directives = new directives.Directives({ version: options.version || "1.2" }); + this.options = options; + } + decorate(doc, afterDoc) { + const { comment, afterEmptyLine } = parsePrelude(this.prelude); + if (comment) { + const dc = doc.contents; + if (afterDoc) { + doc.comment = doc.comment ? `${doc.comment} +${comment}` : comment; + } else if (afterEmptyLine || doc.directives.docStart || !dc) { + doc.commentBefore = comment; + } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { + let it = dc.items[0]; + if (identity.isPair(it)) + it = it.key; + const cb = it.commentBefore; + it.commentBefore = cb ? `${comment} +${cb}` : comment; + } else { + const cb = dc.commentBefore; + dc.commentBefore = cb ? `${comment} +${cb}` : comment; + } + } + if (afterDoc) { + Array.prototype.push.apply(doc.errors, this.errors); + Array.prototype.push.apply(doc.warnings, this.warnings); + } else { + doc.errors = this.errors; + doc.warnings = this.warnings; + } + this.prelude = []; + this.errors = []; + this.warnings = []; + } + streamInfo() { + return { + comment: parsePrelude(this.prelude).comment, + directives: this.directives, + errors: this.errors, + warnings: this.warnings + }; + } + *compose(tokens, forceDoc = false, endOffset = -1) { + for (const token of tokens) + yield* this.next(token); + yield* this.end(forceDoc, endOffset); + } + *next(token) { + if (node_process.env.LOG_STREAM) + console.dir(token, { depth: null }); + switch (token.type) { + case "directive": + this.directives.add(token.source, (offset, message, warning) => { + const pos = getErrorPos(token); + pos[0] += offset; + this.onError(pos, "BAD_DIRECTIVE", message, warning); + }); + this.prelude.push(token.source); + this.atDirectives = true; + break; + case "document": { + const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError); + if (this.atDirectives && !doc.directives.docStart) + this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); + this.decorate(doc, false); + if (this.doc) + yield this.doc; + this.doc = doc; + this.atDirectives = false; + break; + } + case "byte-order-mark": + case "space": + break; + case "comment": + case "newline": + this.prelude.push(token.source); + break; + case "error": { + const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; + const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); + if (this.atDirectives || !this.doc) + this.errors.push(error); + else + this.doc.errors.push(error); + break; + } + case "doc-end": { + if (!this.doc) { + const msg = "Unexpected doc-end without preceding document"; + this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); + break; + } + this.doc.directives.docEnd = true; + const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); + this.decorate(this.doc, true); + if (end.comment) { + const dc = this.doc.comment; + this.doc.comment = dc ? `${dc} +${end.comment}` : end.comment; + } + this.doc.range[2] = end.offset; + break; + } + default: + this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); + } + } + *end(forceDoc = false, endOffset = -1) { + if (this.doc) { + this.decorate(this.doc, true); + yield this.doc; + this.doc = null; + } else if (forceDoc) { + const opts = Object.assign({ _directives: this.directives }, this.options); + const doc = new Document.Document(undefined, opts); + if (this.atDirectives) + this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); + doc.range = [0, endOffset, endOffset]; + this.decorate(doc, false); + yield doc; + } + } + } + exports.Composer = Composer; +}); + +// node_modules/yaml/dist/parse/cst-scalar.js +var require_cst_scalar = __commonJS((exports) => { + var resolveBlockScalar = require_resolve_block_scalar(); + var resolveFlowScalar = require_resolve_flow_scalar(); + var errors = require_errors(); + var stringifyString = require_stringifyString(); + function resolveAsScalar(token, strict = true, onError) { + if (token) { + const _onError = (pos, code, message) => { + const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; + if (onError) + onError(offset, code, message); + else + throw new errors.YAMLParseError([offset, offset + 1], code, message); + }; + switch (token.type) { + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); + case "block-scalar": + return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); + } + } + return null; + } + function createScalarToken(value, context) { + const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; + const source = stringifyString.stringifyString({ type, value }, { + implicitKey, + indent: indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + const end = context.end ?? [ + { type: "newline", offset: -1, indent, source: ` +` } + ]; + switch (source[0]) { + case "|": + case ">": { + const he = source.indexOf(` +`); + const head = source.substring(0, he); + const body = source.substring(he + 1) + ` +`; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, end)) + props.push({ type: "newline", offset: -1, indent, source: ` +` }); + return { type: "block-scalar", offset, indent, props, source: body }; + } + case '"': + return { type: "double-quoted-scalar", offset, indent, source, end }; + case "'": + return { type: "single-quoted-scalar", offset, indent, source, end }; + default: + return { type: "scalar", offset, indent, source, end }; + } + } + function setScalarValue(token, value, context = {}) { + let { afterKey = false, implicitKey = false, inFlow = false, type } = context; + let indent = "indent" in token ? token.indent : null; + if (afterKey && typeof indent === "number") + indent += 2; + if (!type) + switch (token.type) { + case "single-quoted-scalar": + type = "QUOTE_SINGLE"; + break; + case "double-quoted-scalar": + type = "QUOTE_DOUBLE"; + break; + case "block-scalar": { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; + break; + } + default: + type = "PLAIN"; + } + const source = stringifyString.stringifyString({ type, value }, { + implicitKey: implicitKey || indent === null, + indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", + inFlow, + options: { blockQuote: true, lineWidth: -1 } + }); + switch (source[0]) { + case "|": + case ">": + setBlockScalarValue(token, source); + break; + case '"': + setFlowScalarValue(token, source, "double-quoted-scalar"); + break; + case "'": + setFlowScalarValue(token, source, "single-quoted-scalar"); + break; + default: + setFlowScalarValue(token, source, "scalar"); + } + } + function setBlockScalarValue(token, source) { + const he = source.indexOf(` +`); + const head = source.substring(0, he); + const body = source.substring(he + 1) + ` +`; + if (token.type === "block-scalar") { + const header = token.props[0]; + if (header.type !== "block-scalar-header") + throw new Error("Invalid block scalar header"); + header.source = head; + token.source = body; + } else { + const { offset } = token; + const indent = "indent" in token ? token.indent : -1; + const props = [ + { type: "block-scalar-header", offset, indent, source: head } + ]; + if (!addEndtoBlockProps(props, "end" in token ? token.end : undefined)) + props.push({ type: "newline", offset: -1, indent, source: ` +` }); + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type: "block-scalar", indent, props, source: body }); + } + } + function addEndtoBlockProps(props, end) { + if (end) + for (const st of end) + switch (st.type) { + case "space": + case "comment": + props.push(st); + break; + case "newline": + props.push(st); + return true; + } + return false; + } + function setFlowScalarValue(token, source, type) { + switch (token.type) { + case "scalar": + case "double-quoted-scalar": + case "single-quoted-scalar": + token.type = type; + token.source = source; + break; + case "block-scalar": { + const end = token.props.slice(1); + let oa = source.length; + if (token.props[0].type === "block-scalar-header") + oa -= token.props[0].source.length; + for (const tok of end) + tok.offset += oa; + delete token.props; + Object.assign(token, { type, source, end }); + break; + } + case "block-map": + case "block-seq": { + const offset = token.offset + source.length; + const nl = { type: "newline", offset, indent: token.indent, source: ` +` }; + delete token.items; + Object.assign(token, { type, source, end: [nl] }); + break; + } + default: { + const indent = "indent" in token ? token.indent : -1; + const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; + for (const key of Object.keys(token)) + if (key !== "type" && key !== "offset") + delete token[key]; + Object.assign(token, { type, indent, source, end }); + } + } + } + exports.createScalarToken = createScalarToken; + exports.resolveAsScalar = resolveAsScalar; + exports.setScalarValue = setScalarValue; +}); + +// node_modules/yaml/dist/parse/cst-stringify.js +var require_cst_stringify = __commonJS((exports) => { + var stringify = (cst) => ("type" in cst) ? stringifyToken(cst) : stringifyItem(cst); + function stringifyToken(token) { + switch (token.type) { + case "block-scalar": { + let res = ""; + for (const tok of token.props) + res += stringifyToken(tok); + return res + token.source; + } + case "block-map": + case "block-seq": { + let res = ""; + for (const item of token.items) + res += stringifyItem(item); + return res; + } + case "flow-collection": { + let res = token.start.source; + for (const item of token.items) + res += stringifyItem(item); + for (const st of token.end) + res += st.source; + return res; + } + case "document": { + let res = stringifyItem(token); + if (token.end) + for (const st of token.end) + res += st.source; + return res; + } + default: { + let res = token.source; + if ("end" in token && token.end) + for (const st of token.end) + res += st.source; + return res; + } + } + } + function stringifyItem({ start, key, sep, value }) { + let res = ""; + for (const st of start) + res += st.source; + if (key) + res += stringifyToken(key); + if (sep) + for (const st of sep) + res += st.source; + if (value) + res += stringifyToken(value); + return res; + } + exports.stringify = stringify; +}); + +// node_modules/yaml/dist/parse/cst-visit.js +var require_cst_visit = __commonJS((exports) => { + var BREAK = Symbol("break visit"); + var SKIP = Symbol("skip children"); + var REMOVE = Symbol("remove item"); + function visit(cst, visitor) { + if ("type" in cst && cst.type === "document") + cst = { start: cst.start, value: cst.value }; + _visit(Object.freeze([]), cst, visitor); + } + visit.BREAK = BREAK; + visit.SKIP = SKIP; + visit.REMOVE = REMOVE; + visit.itemAtPath = (cst, path) => { + let item = cst; + for (const [field, index] of path) { + const tok = item?.[field]; + if (tok && "items" in tok) { + item = tok.items[index]; + } else + return; + } + return item; + }; + visit.parentCollection = (cst, path) => { + const parent = visit.itemAtPath(cst, path.slice(0, -1)); + const field = path[path.length - 1][0]; + const coll = parent?.[field]; + if (coll && "items" in coll) + return coll; + throw new Error("Parent collection not found"); + }; + function _visit(path, item, visitor) { + let ctrl = visitor(item, path); + if (typeof ctrl === "symbol") + return ctrl; + for (const field of ["key", "value"]) { + const token = item[field]; + if (token && "items" in token) { + for (let i = 0;i < token.items.length; ++i) { + const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); + if (typeof ci === "number") + i = ci - 1; + else if (ci === BREAK) + return BREAK; + else if (ci === REMOVE) { + token.items.splice(i, 1); + i -= 1; + } + } + if (typeof ctrl === "function" && field === "key") + ctrl = ctrl(item, path); + } + } + return typeof ctrl === "function" ? ctrl(item, path) : ctrl; + } + exports.visit = visit; +}); + +// node_modules/yaml/dist/parse/cst.js +var require_cst = __commonJS((exports) => { + var cstScalar = require_cst_scalar(); + var cstStringify = require_cst_stringify(); + var cstVisit = require_cst_visit(); + var BOM = "\uFEFF"; + var DOCUMENT = "\x02"; + var FLOW_END = "\x18"; + var SCALAR = "\x1F"; + var isCollection = (token) => !!token && ("items" in token); + var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); + function prettyToken(token) { + switch (token) { + case BOM: + return ""; + case DOCUMENT: + return ""; + case FLOW_END: + return ""; + case SCALAR: + return ""; + default: + return JSON.stringify(token); + } + } + function tokenType(source) { + switch (source) { + case BOM: + return "byte-order-mark"; + case DOCUMENT: + return "doc-mode"; + case FLOW_END: + return "flow-error-end"; + case SCALAR: + return "scalar"; + case "---": + return "doc-start"; + case "...": + return "doc-end"; + case "": + case ` +`: + case `\r +`: + return "newline"; + case "-": + return "seq-item-ind"; + case "?": + return "explicit-key-ind"; + case ":": + return "map-value-ind"; + case "{": + return "flow-map-start"; + case "}": + return "flow-map-end"; + case "[": + return "flow-seq-start"; + case "]": + return "flow-seq-end"; + case ",": + return "comma"; + } + switch (source[0]) { + case " ": + case "\t": + return "space"; + case "#": + return "comment"; + case "%": + return "directive-line"; + case "*": + return "alias"; + case "&": + return "anchor"; + case "!": + return "tag"; + case "'": + return "single-quoted-scalar"; + case '"': + return "double-quoted-scalar"; + case "|": + case ">": + return "block-scalar-header"; + } + return null; + } + exports.createScalarToken = cstScalar.createScalarToken; + exports.resolveAsScalar = cstScalar.resolveAsScalar; + exports.setScalarValue = cstScalar.setScalarValue; + exports.stringify = cstStringify.stringify; + exports.visit = cstVisit.visit; + exports.BOM = BOM; + exports.DOCUMENT = DOCUMENT; + exports.FLOW_END = FLOW_END; + exports.SCALAR = SCALAR; + exports.isCollection = isCollection; + exports.isScalar = isScalar; + exports.prettyToken = prettyToken; + exports.tokenType = tokenType; +}); + +// node_modules/yaml/dist/parse/lexer.js +var require_lexer2 = __commonJS((exports) => { + var cst = require_cst(); + function isEmpty(ch) { + switch (ch) { + case undefined: + case " ": + case ` +`: + case "\r": + case "\t": + return true; + default: + return false; + } + } + var hexDigits = new Set("0123456789ABCDEFabcdef"); + var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); + var flowIndicatorChars = new Set(",[]{}"); + var invalidAnchorChars = new Set(` ,[]{} +\r `); + var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); + + class Lexer { + constructor() { + this.atEnd = false; + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + this.buffer = ""; + this.flowKey = false; + this.flowLevel = 0; + this.indentNext = 0; + this.indentValue = 0; + this.lineEndPos = null; + this.next = null; + this.pos = 0; + } + *lex(source, incomplete = false) { + if (source) { + if (typeof source !== "string") + throw TypeError("source is not a string"); + this.buffer = this.buffer ? this.buffer + source : source; + this.lineEndPos = null; + } + this.atEnd = !incomplete; + let next = this.next ?? "stream"; + while (next && (incomplete || this.hasChars(1))) + next = yield* this.parseNext(next); + } + atLineEnd() { + let i = this.pos; + let ch = this.buffer[i]; + while (ch === " " || ch === "\t") + ch = this.buffer[++i]; + if (!ch || ch === "#" || ch === ` +`) + return true; + if (ch === "\r") + return this.buffer[i + 1] === ` +`; + return false; + } + charAt(n) { + return this.buffer[this.pos + n]; + } + continueScalar(offset) { + let ch = this.buffer[offset]; + if (this.indentNext > 0) { + let indent = 0; + while (ch === " ") + ch = this.buffer[++indent + offset]; + if (ch === "\r") { + const next = this.buffer[indent + offset + 1]; + if (next === ` +` || !next && !this.atEnd) + return offset + indent + 1; + } + return ch === ` +` || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; + } + if (ch === "-" || ch === ".") { + const dt = this.buffer.substr(offset, 3); + if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) + return -1; + } + return offset; + } + getLine() { + let end = this.lineEndPos; + if (typeof end !== "number" || end !== -1 && end < this.pos) { + end = this.buffer.indexOf(` +`, this.pos); + this.lineEndPos = end; + } + if (end === -1) + return this.atEnd ? this.buffer.substring(this.pos) : null; + if (this.buffer[end - 1] === "\r") + end -= 1; + return this.buffer.substring(this.pos, end); + } + hasChars(n) { + return this.pos + n <= this.buffer.length; + } + setNext(state) { + this.buffer = this.buffer.substring(this.pos); + this.pos = 0; + this.lineEndPos = null; + this.next = state; + return null; + } + peek(n) { + return this.buffer.substr(this.pos, n); + } + *parseNext(next) { + switch (next) { + case "stream": + return yield* this.parseStream(); + case "line-start": + return yield* this.parseLineStart(); + case "block-start": + return yield* this.parseBlockStart(); + case "doc": + return yield* this.parseDocument(); + case "flow": + return yield* this.parseFlowCollection(); + case "quoted-scalar": + return yield* this.parseQuotedScalar(); + case "block-scalar": + return yield* this.parseBlockScalar(); + case "plain-scalar": + return yield* this.parsePlainScalar(); + } + } + *parseStream() { + let line = this.getLine(); + if (line === null) + return this.setNext("stream"); + if (line[0] === cst.BOM) { + yield* this.pushCount(1); + line = line.substring(1); + } + if (line[0] === "%") { + let dirEnd = line.length; + let cs = line.indexOf("#"); + while (cs !== -1) { + const ch = line[cs - 1]; + if (ch === " " || ch === "\t") { + dirEnd = cs - 1; + break; + } else { + cs = line.indexOf("#", cs + 1); + } + } + while (true) { + const ch = line[dirEnd - 1]; + if (ch === " " || ch === "\t") + dirEnd -= 1; + else + break; + } + const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); + yield* this.pushCount(line.length - n); + this.pushNewline(); + return "stream"; + } + if (this.atLineEnd()) { + const sp = yield* this.pushSpaces(true); + yield* this.pushCount(line.length - sp); + yield* this.pushNewline(); + return "stream"; + } + yield cst.DOCUMENT; + return yield* this.parseLineStart(); + } + *parseLineStart() { + const ch = this.charAt(0); + if (!ch && !this.atEnd) + return this.setNext("line-start"); + if (ch === "-" || ch === ".") { + if (!this.atEnd && !this.hasChars(4)) + return this.setNext("line-start"); + const s = this.peek(3); + if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { + yield* this.pushCount(3); + this.indentValue = 0; + this.indentNext = 0; + return s === "---" ? "doc" : "stream"; + } + } + this.indentValue = yield* this.pushSpaces(false); + if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) + this.indentNext = this.indentValue; + return yield* this.parseBlockStart(); + } + *parseBlockStart() { + const [ch0, ch1] = this.peek(2); + if (!ch1 && !this.atEnd) + return this.setNext("block-start"); + if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { + const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); + this.indentNext = this.indentValue + 1; + this.indentValue += n; + return yield* this.parseBlockStart(); + } + return "doc"; + } + *parseDocument() { + yield* this.pushSpaces(true); + const line = this.getLine(); + if (line === null) + return this.setNext("doc"); + let n = yield* this.pushIndicators(); + switch (line[n]) { + case "#": + yield* this.pushCount(line.length - n); + case undefined: + yield* this.pushNewline(); + return yield* this.parseLineStart(); + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel = 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + return "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "doc"; + case '"': + case "'": + return yield* this.parseQuotedScalar(); + case "|": + case ">": + n += yield* this.parseBlockScalarHeader(); + n += yield* this.pushSpaces(true); + yield* this.pushCount(line.length - n); + yield* this.pushNewline(); + return yield* this.parseBlockScalar(); + default: + return yield* this.parsePlainScalar(); + } + } + *parseFlowCollection() { + let nl, sp; + let indent = -1; + do { + nl = yield* this.pushNewline(); + if (nl > 0) { + sp = yield* this.pushSpaces(false); + this.indentValue = indent = sp; + } else { + sp = 0; + } + sp += yield* this.pushSpaces(true); + } while (nl + sp > 0); + const line = this.getLine(); + if (line === null) + return this.setNext("flow"); + if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { + const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); + if (!atFlowEndMarker) { + this.flowLevel = 0; + yield cst.FLOW_END; + return yield* this.parseLineStart(); + } + } + let n = 0; + while (line[n] === ",") { + n += yield* this.pushCount(1); + n += yield* this.pushSpaces(true); + this.flowKey = false; + } + n += yield* this.pushIndicators(); + switch (line[n]) { + case undefined: + return "flow"; + case "#": + yield* this.pushCount(line.length - n); + return "flow"; + case "{": + case "[": + yield* this.pushCount(1); + this.flowKey = false; + this.flowLevel += 1; + return "flow"; + case "}": + case "]": + yield* this.pushCount(1); + this.flowKey = true; + this.flowLevel -= 1; + return this.flowLevel ? "flow" : "doc"; + case "*": + yield* this.pushUntil(isNotAnchorChar); + return "flow"; + case '"': + case "'": + this.flowKey = true; + return yield* this.parseQuotedScalar(); + case ":": { + const next = this.charAt(1); + if (this.flowKey || isEmpty(next) || next === ",") { + this.flowKey = false; + yield* this.pushCount(1); + yield* this.pushSpaces(true); + return "flow"; + } + } + default: + this.flowKey = false; + return yield* this.parsePlainScalar(); + } + } + *parseQuotedScalar() { + const quote = this.charAt(0); + let end = this.buffer.indexOf(quote, this.pos + 1); + if (quote === "'") { + while (end !== -1 && this.buffer[end + 1] === "'") + end = this.buffer.indexOf("'", end + 2); + } else { + while (end !== -1) { + let n = 0; + while (this.buffer[end - 1 - n] === "\\") + n += 1; + if (n % 2 === 0) + break; + end = this.buffer.indexOf('"', end + 1); + } + } + const qb = this.buffer.substring(0, end); + let nl = qb.indexOf(` +`, this.pos); + if (nl !== -1) { + while (nl !== -1) { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = qb.indexOf(` +`, cs); + } + if (nl !== -1) { + end = nl - (qb[nl - 1] === "\r" ? 2 : 1); + } + } + if (end === -1) { + if (!this.atEnd) + return this.setNext("quoted-scalar"); + end = this.buffer.length; + } + yield* this.pushToIndex(end + 1, false); + return this.flowLevel ? "flow" : "doc"; + } + *parseBlockScalarHeader() { + this.blockScalarIndent = -1; + this.blockScalarKeep = false; + let i = this.pos; + while (true) { + const ch = this.buffer[++i]; + if (ch === "+") + this.blockScalarKeep = true; + else if (ch > "0" && ch <= "9") + this.blockScalarIndent = Number(ch) - 1; + else if (ch !== "-") + break; + } + return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); + } + *parseBlockScalar() { + let nl = this.pos - 1; + let indent = 0; + let ch; + loop: + for (let i2 = this.pos;ch = this.buffer[i2]; ++i2) { + switch (ch) { + case " ": + indent += 1; + break; + case ` +`: + nl = i2; + indent = 0; + break; + case "\r": { + const next = this.buffer[i2 + 1]; + if (!next && !this.atEnd) + return this.setNext("block-scalar"); + if (next === ` +`) + break; + } + default: + break loop; + } + } + if (!ch && !this.atEnd) + return this.setNext("block-scalar"); + if (indent >= this.indentNext) { + if (this.blockScalarIndent === -1) + this.indentNext = indent; + else { + this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); + } + do { + const cs = this.continueScalar(nl + 1); + if (cs === -1) + break; + nl = this.buffer.indexOf(` +`, cs); + } while (nl !== -1); + if (nl === -1) { + if (!this.atEnd) + return this.setNext("block-scalar"); + nl = this.buffer.length; + } + } + let i = nl + 1; + ch = this.buffer[i]; + while (ch === " ") + ch = this.buffer[++i]; + if (ch === "\t") { + while (ch === "\t" || ch === " " || ch === "\r" || ch === ` +`) + ch = this.buffer[++i]; + nl = i - 1; + } else if (!this.blockScalarKeep) { + do { + let i2 = nl - 1; + let ch2 = this.buffer[i2]; + if (ch2 === "\r") + ch2 = this.buffer[--i2]; + const lastChar = i2; + while (ch2 === " ") + ch2 = this.buffer[--i2]; + if (ch2 === ` +` && i2 >= this.pos && i2 + 1 + indent > lastChar) + nl = i2; + else + break; + } while (true); + } + yield cst.SCALAR; + yield* this.pushToIndex(nl + 1, true); + return yield* this.parseLineStart(); + } + *parsePlainScalar() { + const inFlow = this.flowLevel > 0; + let end = this.pos - 1; + let i = this.pos - 1; + let ch; + while (ch = this.buffer[++i]) { + if (ch === ":") { + const next = this.buffer[i + 1]; + if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) + break; + end = i; + } else if (isEmpty(ch)) { + let next = this.buffer[i + 1]; + if (ch === "\r") { + if (next === ` +`) { + i += 1; + ch = ` +`; + next = this.buffer[i + 1]; + } else + end = i; + } + if (next === "#" || inFlow && flowIndicatorChars.has(next)) + break; + if (ch === ` +`) { + const cs = this.continueScalar(i + 1); + if (cs === -1) + break; + i = Math.max(i, cs - 2); + } + } else { + if (inFlow && flowIndicatorChars.has(ch)) + break; + end = i; + } + } + if (!ch && !this.atEnd) + return this.setNext("plain-scalar"); + yield cst.SCALAR; + yield* this.pushToIndex(end + 1, true); + return inFlow ? "flow" : "doc"; + } + *pushCount(n) { + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos += n; + return n; + } + return 0; + } + *pushToIndex(i, allowEmpty) { + const s = this.buffer.slice(this.pos, i); + if (s) { + yield s; + this.pos += s.length; + return s.length; + } else if (allowEmpty) + yield ""; + return 0; + } + *pushIndicators() { + switch (this.charAt(0)) { + case "!": + return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "&": + return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + case "-": + case "?": + case ":": { + const inFlow = this.flowLevel > 0; + const ch1 = this.charAt(1); + if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { + if (!inFlow) + this.indentNext = this.indentValue + 1; + else if (this.flowKey) + this.flowKey = false; + return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators()); + } + } + } + return 0; + } + *pushTag() { + if (this.charAt(1) === "<") { + let i = this.pos + 2; + let ch = this.buffer[i]; + while (!isEmpty(ch) && ch !== ">") + ch = this.buffer[++i]; + return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); + } else { + let i = this.pos + 1; + let ch = this.buffer[i]; + while (ch) { + if (tagChars.has(ch)) + ch = this.buffer[++i]; + else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { + ch = this.buffer[i += 3]; + } else + break; + } + return yield* this.pushToIndex(i, false); + } + } + *pushNewline() { + const ch = this.buffer[this.pos]; + if (ch === ` +`) + return yield* this.pushCount(1); + else if (ch === "\r" && this.charAt(1) === ` +`) + return yield* this.pushCount(2); + else + return 0; + } + *pushSpaces(allowTabs) { + let i = this.pos - 1; + let ch; + do { + ch = this.buffer[++i]; + } while (ch === " " || allowTabs && ch === "\t"); + const n = i - this.pos; + if (n > 0) { + yield this.buffer.substr(this.pos, n); + this.pos = i; + } + return n; + } + *pushUntil(test) { + let i = this.pos; + let ch = this.buffer[i]; + while (!test(ch)) + ch = this.buffer[++i]; + return yield* this.pushToIndex(i, false); + } + } + exports.Lexer = Lexer; +}); + +// node_modules/yaml/dist/parse/line-counter.js +var require_line_counter = __commonJS((exports) => { + class LineCounter { + constructor() { + this.lineStarts = []; + this.addNewLine = (offset) => this.lineStarts.push(offset); + this.linePos = (offset) => { + let low = 0; + let high = this.lineStarts.length; + while (low < high) { + const mid = low + high >> 1; + if (this.lineStarts[mid] < offset) + low = mid + 1; + else + high = mid; + } + if (this.lineStarts[low] === offset) + return { line: low + 1, col: 1 }; + if (low === 0) + return { line: 0, col: offset }; + const start = this.lineStarts[low - 1]; + return { line: low, col: offset - start + 1 }; + }; + } + } + exports.LineCounter = LineCounter; +}); + +// node_modules/yaml/dist/parse/parser.js +var require_parser2 = __commonJS((exports) => { + var node_process = __require("process"); + var cst = require_cst(); + var lexer = require_lexer2(); + function includesToken(list, type) { + for (let i = 0;i < list.length; ++i) + if (list[i].type === type) + return true; + return false; + } + function findNonEmptyIndex(list) { + for (let i = 0;i < list.length; ++i) { + switch (list[i].type) { + case "space": + case "comment": + case "newline": + break; + default: + return i; + } + } + return -1; + } + function isFlowToken(token) { + switch (token?.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + case "flow-collection": + return true; + default: + return false; + } + } + function getPrevProps(parent) { + switch (parent.type) { + case "document": + return parent.start; + case "block-map": { + const it = parent.items[parent.items.length - 1]; + return it.sep ?? it.start; + } + case "block-seq": + return parent.items[parent.items.length - 1].start; + default: + return []; + } + } + function getFirstKeyStartProps(prev) { + if (prev.length === 0) + return []; + let i = prev.length; + loop: + while (--i >= 0) { + switch (prev[i].type) { + case "doc-start": + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + case "newline": + break loop; + } + } + while (prev[++i]?.type === "space") {} + return prev.splice(i, prev.length); + } + function fixFlowSeqItems(fc) { + if (fc.start.type === "flow-seq-start") { + for (const it of fc.items) { + if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { + if (it.key) + it.value = it.key; + delete it.key; + if (isFlowToken(it.value)) { + if (it.value.end) + Array.prototype.push.apply(it.value.end, it.sep); + else + it.value.end = it.sep; + } else + Array.prototype.push.apply(it.start, it.sep); + delete it.sep; + } + } + } + } + + class Parser { + constructor(onNewLine) { + this.atNewLine = true; + this.atScalar = false; + this.indent = 0; + this.offset = 0; + this.onKeyLine = false; + this.stack = []; + this.source = ""; + this.type = ""; + this.lexer = new lexer.Lexer; + this.onNewLine = onNewLine; + } + *parse(source, incomplete = false) { + if (this.onNewLine && this.offset === 0) + this.onNewLine(0); + for (const lexeme of this.lexer.lex(source, incomplete)) + yield* this.next(lexeme); + if (!incomplete) + yield* this.end(); + } + *next(source) { + this.source = source; + if (node_process.env.LOG_TOKENS) + console.log("|", cst.prettyToken(source)); + if (this.atScalar) { + this.atScalar = false; + yield* this.step(); + this.offset += source.length; + return; + } + const type = cst.tokenType(source); + if (!type) { + const message = `Not a YAML token: ${source}`; + yield* this.pop({ type: "error", offset: this.offset, message, source }); + this.offset += source.length; + } else if (type === "scalar") { + this.atNewLine = false; + this.atScalar = true; + this.type = "scalar"; + } else { + this.type = type; + yield* this.step(); + switch (type) { + case "newline": + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) + this.onNewLine(this.offset + source.length); + break; + case "space": + if (this.atNewLine && source[0] === " ") + this.indent += source.length; + break; + case "explicit-key-ind": + case "map-value-ind": + case "seq-item-ind": + if (this.atNewLine) + this.indent += source.length; + break; + case "doc-mode": + case "flow-error-end": + return; + default: + this.atNewLine = false; + } + this.offset += source.length; + } + } + *end() { + while (this.stack.length > 0) + yield* this.pop(); + } + get sourceToken() { + const st = { + type: this.type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + return st; + } + *step() { + const top = this.peek(1); + if (this.type === "doc-end" && top?.type !== "doc-end") { + while (this.stack.length > 0) + yield* this.pop(); + this.stack.push({ + type: "doc-end", + offset: this.offset, + source: this.source + }); + return; + } + if (!top) + return yield* this.stream(); + switch (top.type) { + case "document": + return yield* this.document(top); + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return yield* this.scalar(top); + case "block-scalar": + return yield* this.blockScalar(top); + case "block-map": + return yield* this.blockMap(top); + case "block-seq": + return yield* this.blockSequence(top); + case "flow-collection": + return yield* this.flowCollection(top); + case "doc-end": + return yield* this.documentEnd(top); + } + yield* this.pop(); + } + peek(n) { + return this.stack[this.stack.length - n]; + } + *pop(error) { + const token = error ?? this.stack.pop(); + if (!token) { + const message = "Tried to pop an empty stack"; + yield { type: "error", offset: this.offset, source: "", message }; + } else if (this.stack.length === 0) { + yield token; + } else { + const top = this.peek(1); + if (token.type === "block-scalar") { + token.indent = "indent" in top ? top.indent : 0; + } else if (token.type === "flow-collection" && top.type === "document") { + token.indent = 0; + } + if (token.type === "flow-collection") + fixFlowSeqItems(token); + switch (top.type) { + case "document": + top.value = token; + break; + case "block-scalar": + top.props.push(token); + break; + case "block-map": { + const it = top.items[top.items.length - 1]; + if (it.value) { + top.items.push({ start: [], key: token, sep: [] }); + this.onKeyLine = true; + return; + } else if (it.sep) { + it.value = token; + } else { + Object.assign(it, { key: token, sep: [] }); + this.onKeyLine = !it.explicitKey; + return; + } + break; + } + case "block-seq": { + const it = top.items[top.items.length - 1]; + if (it.value) + top.items.push({ start: [], value: token }); + else + it.value = token; + break; + } + case "flow-collection": { + const it = top.items[top.items.length - 1]; + if (!it || it.value) + top.items.push({ start: [], key: token, sep: [] }); + else if (it.sep) + it.value = token; + else + Object.assign(it, { key: token, sep: [] }); + return; + } + default: + yield* this.pop(); + yield* this.pop(token); + } + if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { + const last = token.items[token.items.length - 1]; + if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { + if (top.type === "document") + top.end = last.start; + else + top.items.push({ start: last.start }); + token.items.splice(-1, 1); + } + } + } + } + *stream() { + switch (this.type) { + case "directive-line": + yield { type: "directive", offset: this.offset, source: this.source }; + return; + case "byte-order-mark": + case "space": + case "comment": + case "newline": + yield this.sourceToken; + return; + case "doc-mode": + case "doc-start": { + const doc = { + type: "document", + offset: this.offset, + start: [] + }; + if (this.type === "doc-start") + doc.start.push(this.sourceToken); + this.stack.push(doc); + return; + } + } + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML stream`, + source: this.source + }; + } + *document(doc) { + if (doc.value) + return yield* this.lineEnd(doc); + switch (this.type) { + case "doc-start": { + if (findNonEmptyIndex(doc.start) !== -1) { + yield* this.pop(); + yield* this.step(); + } else + doc.start.push(this.sourceToken); + return; + } + case "anchor": + case "tag": + case "space": + case "comment": + case "newline": + doc.start.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(doc); + if (bv) + this.stack.push(bv); + else { + yield { + type: "error", + offset: this.offset, + message: `Unexpected ${this.type} token in YAML document`, + source: this.source + }; + } + } + *scalar(scalar) { + if (this.type === "map-value-ind") { + const prev = getPrevProps(this.peek(2)); + const start = getFirstKeyStartProps(prev); + let sep; + if (scalar.end) { + sep = scalar.end; + sep.push(this.sourceToken); + delete scalar.end; + } else + sep = [this.sourceToken]; + const map = { + type: "block-map", + offset: scalar.offset, + indent: scalar.indent, + items: [{ start, key: scalar, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } else + yield* this.lineEnd(scalar); + } + *blockScalar(scalar) { + switch (this.type) { + case "space": + case "comment": + case "newline": + scalar.props.push(this.sourceToken); + return; + case "scalar": + scalar.source = this.source; + this.atNewLine = true; + this.indent = 0; + if (this.onNewLine) { + let nl = this.source.indexOf(` +`) + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf(` +`, nl) + 1; + } + } + yield* this.pop(); + break; + default: + yield* this.pop(); + yield* this.step(); + } + } + *blockMap(map) { + const it = map.items[map.items.length - 1]; + switch (this.type) { + case "newline": + this.onKeyLine = false; + if (it.value) { + const end = "end" in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + map.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "space": + case "comment": + if (it.value) { + map.items.push({ start: [this.sourceToken] }); + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + if (this.atIndentedComment(it.start, map.indent)) { + const prev = map.items[map.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + map.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + } + if (this.indent >= map.indent) { + const atMapIndent = !this.onKeyLine && this.indent === map.indent; + const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; + let start = []; + if (atNextItem && it.sep && !it.value) { + const nl = []; + for (let i = 0;i < it.sep.length; ++i) { + const st = it.sep[i]; + switch (st.type) { + case "newline": + nl.push(i); + break; + case "space": + break; + case "comment": + if (st.indent > map.indent) + nl.length = 0; + break; + default: + nl.length = 0; + } + } + if (nl.length >= 2) + start = it.sep.splice(nl[1]); + } + switch (this.type) { + case "anchor": + case "tag": + if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start }); + this.onKeyLine = true; + } else if (it.sep) { + it.sep.push(this.sourceToken); + } else { + it.start.push(this.sourceToken); + } + return; + case "explicit-key-ind": + if (!it.sep && !it.explicitKey) { + it.start.push(this.sourceToken); + it.explicitKey = true; + } else if (atNextItem || it.value) { + start.push(this.sourceToken); + map.items.push({ start, explicitKey: true }); + } else { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken], explicitKey: true }] + }); + } + this.onKeyLine = true; + return; + case "map-value-ind": + if (it.explicitKey) { + if (!it.sep) { + if (includesToken(it.start, "newline")) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else { + const start2 = getFirstKeyStartProps(it.start); + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key: null, sep: [this.sourceToken] }] + }); + } + } else if (it.value) { + map.items.push({ start: [], key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }); + } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { + const start2 = getFirstKeyStartProps(it.start); + const key = it.key; + const sep = it.sep; + sep.push(this.sourceToken); + delete it.key; + delete it.sep; + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: start2, key, sep }] + }); + } else if (start.length > 0) { + it.sep = it.sep.concat(start, this.sourceToken); + } else { + it.sep.push(this.sourceToken); + } + } else { + if (!it.sep) { + Object.assign(it, { key: null, sep: [this.sourceToken] }); + } else if (it.value || atNextItem) { + map.items.push({ start, key: null, sep: [this.sourceToken] }); + } else if (includesToken(it.sep, "map-value-ind")) { + this.stack.push({ + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start: [], key: null, sep: [this.sourceToken] }] + }); + } else { + it.sep.push(this.sourceToken); + } + } + this.onKeyLine = true; + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (atNextItem || it.value) { + map.items.push({ start, key: fs, sep: [] }); + this.onKeyLine = true; + } else if (it.sep) { + this.stack.push(fs); + } else { + Object.assign(it, { key: fs, sep: [] }); + this.onKeyLine = true; + } + return; + } + default: { + const bv = this.startBlockValue(map); + if (bv) { + if (bv.type === "block-seq") { + if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { + yield* this.pop({ + type: "error", + offset: this.offset, + message: "Unexpected block-seq-ind on same line with key", + source: this.source + }); + return; + } + } else if (atMapIndent) { + map.items.push({ start }); + } + this.stack.push(bv); + return; + } + } + } + } + yield* this.pop(); + yield* this.step(); + } + *blockSequence(seq) { + const it = seq.items[seq.items.length - 1]; + switch (this.type) { + case "newline": + if (it.value) { + const end = "end" in it.value ? it.value.end : undefined; + const last = Array.isArray(end) ? end[end.length - 1] : undefined; + if (last?.type === "comment") + end?.push(this.sourceToken); + else + seq.items.push({ start: [this.sourceToken] }); + } else + it.start.push(this.sourceToken); + return; + case "space": + case "comment": + if (it.value) + seq.items.push({ start: [this.sourceToken] }); + else { + if (this.atIndentedComment(it.start, seq.indent)) { + const prev = seq.items[seq.items.length - 2]; + const end = prev?.value?.end; + if (Array.isArray(end)) { + Array.prototype.push.apply(end, it.start); + end.push(this.sourceToken); + seq.items.pop(); + return; + } + } + it.start.push(this.sourceToken); + } + return; + case "anchor": + case "tag": + if (it.value || this.indent <= seq.indent) + break; + it.start.push(this.sourceToken); + return; + case "seq-item-ind": + if (this.indent !== seq.indent) + break; + if (it.value || includesToken(it.start, "seq-item-ind")) + seq.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + } + if (this.indent > seq.indent) { + const bv = this.startBlockValue(seq); + if (bv) { + this.stack.push(bv); + return; + } + } + yield* this.pop(); + yield* this.step(); + } + *flowCollection(fc) { + const it = fc.items[fc.items.length - 1]; + if (this.type === "flow-error-end") { + let top; + do { + yield* this.pop(); + top = this.peek(1); + } while (top?.type === "flow-collection"); + } else if (fc.end.length === 0) { + switch (this.type) { + case "comma": + case "explicit-key-ind": + if (!it || it.sep) + fc.items.push({ start: [this.sourceToken] }); + else + it.start.push(this.sourceToken); + return; + case "map-value-ind": + if (!it || it.value) + fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + Object.assign(it, { key: null, sep: [this.sourceToken] }); + return; + case "space": + case "comment": + case "newline": + case "anchor": + case "tag": + if (!it || it.value) + fc.items.push({ start: [this.sourceToken] }); + else if (it.sep) + it.sep.push(this.sourceToken); + else + it.start.push(this.sourceToken); + return; + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": { + const fs = this.flowScalar(this.type); + if (!it || it.value) + fc.items.push({ start: [], key: fs, sep: [] }); + else if (it.sep) + this.stack.push(fs); + else + Object.assign(it, { key: fs, sep: [] }); + return; + } + case "flow-map-end": + case "flow-seq-end": + fc.end.push(this.sourceToken); + return; + } + const bv = this.startBlockValue(fc); + if (bv) + this.stack.push(bv); + else { + yield* this.pop(); + yield* this.step(); + } + } else { + const parent = this.peek(2); + if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { + yield* this.pop(); + yield* this.step(); + } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + fixFlowSeqItems(fc); + const sep = fc.end.splice(1, fc.end.length); + sep.push(this.sourceToken); + const map = { + type: "block-map", + offset: fc.offset, + indent: fc.indent, + items: [{ start, key: fc, sep }] + }; + this.onKeyLine = true; + this.stack[this.stack.length - 1] = map; + } else { + yield* this.lineEnd(fc); + } + } + } + flowScalar(type) { + if (this.onNewLine) { + let nl = this.source.indexOf(` +`) + 1; + while (nl !== 0) { + this.onNewLine(this.offset + nl); + nl = this.source.indexOf(` +`, nl) + 1; + } + } + return { + type, + offset: this.offset, + indent: this.indent, + source: this.source + }; + } + startBlockValue(parent) { + switch (this.type) { + case "alias": + case "scalar": + case "single-quoted-scalar": + case "double-quoted-scalar": + return this.flowScalar(this.type); + case "block-scalar-header": + return { + type: "block-scalar", + offset: this.offset, + indent: this.indent, + props: [this.sourceToken], + source: "" + }; + case "flow-map-start": + case "flow-seq-start": + return { + type: "flow-collection", + offset: this.offset, + indent: this.indent, + start: this.sourceToken, + items: [], + end: [] + }; + case "seq-item-ind": + return { + type: "block-seq", + offset: this.offset, + indent: this.indent, + items: [{ start: [this.sourceToken] }] + }; + case "explicit-key-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + start.push(this.sourceToken); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, explicitKey: true }] + }; + } + case "map-value-ind": { + this.onKeyLine = true; + const prev = getPrevProps(parent); + const start = getFirstKeyStartProps(prev); + return { + type: "block-map", + offset: this.offset, + indent: this.indent, + items: [{ start, key: null, sep: [this.sourceToken] }] + }; + } + } + return null; + } + atIndentedComment(start, indent) { + if (this.type !== "comment") + return false; + if (this.indent <= indent) + return false; + return start.every((st) => st.type === "newline" || st.type === "space"); + } + *documentEnd(docEnd) { + if (this.type !== "doc-mode") { + if (docEnd.end) + docEnd.end.push(this.sourceToken); + else + docEnd.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + *lineEnd(token) { + switch (this.type) { + case "comma": + case "doc-start": + case "doc-end": + case "flow-seq-end": + case "flow-map-end": + case "map-value-ind": + yield* this.pop(); + yield* this.step(); + break; + case "newline": + this.onKeyLine = false; + case "space": + case "comment": + default: + if (token.end) + token.end.push(this.sourceToken); + else + token.end = [this.sourceToken]; + if (this.type === "newline") + yield* this.pop(); + } + } + } + exports.Parser = Parser; +}); + +// node_modules/yaml/dist/public-api.js +var require_public_api = __commonJS((exports) => { + var composer = require_composer(); + var Document = require_Document(); + var errors = require_errors(); + var log = require_log(); + var identity = require_identity(); + var lineCounter = require_line_counter(); + var parser = require_parser2(); + function parseOptions(options) { + const prettyErrors = options.prettyErrors !== false; + const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter || null; + return { lineCounter: lineCounter$1, prettyErrors }; + } + function parseAllDocuments(source, options = {}) { + const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter2?.addNewLine); + const composer$1 = new composer.Composer(options); + const docs = Array.from(composer$1.compose(parser$1.parse(source))); + if (prettyErrors && lineCounter2) + for (const doc of docs) { + doc.errors.forEach(errors.prettifyError(source, lineCounter2)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter2)); + } + if (docs.length > 0) + return docs; + return Object.assign([], { empty: true }, composer$1.streamInfo()); + } + function parseDocument(source, options = {}) { + const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); + const parser$1 = new parser.Parser(lineCounter2?.addNewLine); + const composer$1 = new composer.Composer(options); + let doc = null; + for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) { + if (!doc) + doc = _doc; + else if (doc.options.logLevel !== "silent") { + doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); + break; + } + } + if (prettyErrors && lineCounter2) { + doc.errors.forEach(errors.prettifyError(source, lineCounter2)); + doc.warnings.forEach(errors.prettifyError(source, lineCounter2)); + } + return doc; + } + function parse2(src, reviver, options) { + let _reviver = undefined; + if (typeof reviver === "function") { + _reviver = reviver; + } else if (options === undefined && reviver && typeof reviver === "object") { + options = reviver; + } + const doc = parseDocument(src, options); + if (!doc) + return null; + doc.warnings.forEach((warning) => log.warn(doc.options.logLevel, warning)); + if (doc.errors.length > 0) { + if (doc.options.logLevel !== "silent") + throw doc.errors[0]; + else + doc.errors = []; + } + return doc.toJS(Object.assign({ reviver: _reviver }, options)); + } + function stringify(value, replacer, options) { + let _replacer = null; + if (typeof replacer === "function" || Array.isArray(replacer)) { + _replacer = replacer; + } else if (options === undefined && replacer) { + options = replacer; + } + if (typeof options === "string") + options = options.length; + if (typeof options === "number") { + const indent = Math.round(options); + options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent }; + } + if (value === undefined) { + const { keepUndefined } = options ?? replacer ?? {}; + if (!keepUndefined) + return; + } + if (identity.isDocument(value) && !_replacer) + return value.toString(options); + return new Document.Document(value, _replacer, options).toString(options); + } + exports.parse = parse2; + exports.parseAllDocuments = parseAllDocuments; + exports.parseDocument = parseDocument; + exports.stringify = stringify; +}); + +// node_modules/yaml/dist/index.js +var require_dist = __commonJS((exports) => { + var composer = require_composer(); + var Document = require_Document(); + var Schema = require_Schema(); + var errors = require_errors(); + var Alias = require_Alias(); + var identity = require_identity(); + var Pair = require_Pair(); + var Scalar = require_Scalar(); + var YAMLMap = require_YAMLMap(); + var YAMLSeq = require_YAMLSeq(); + var cst = require_cst(); + var lexer = require_lexer2(); + var lineCounter = require_line_counter(); + var parser = require_parser2(); + var publicApi = require_public_api(); + var visit = require_visit(); + exports.Composer = composer.Composer; + exports.Document = Document.Document; + exports.Schema = Schema.Schema; + exports.YAMLError = errors.YAMLError; + exports.YAMLParseError = errors.YAMLParseError; + exports.YAMLWarning = errors.YAMLWarning; + exports.Alias = Alias.Alias; + exports.isAlias = identity.isAlias; + exports.isCollection = identity.isCollection; + exports.isDocument = identity.isDocument; + exports.isMap = identity.isMap; + exports.isNode = identity.isNode; + exports.isPair = identity.isPair; + exports.isScalar = identity.isScalar; + exports.isSeq = identity.isSeq; + exports.Pair = Pair.Pair; + exports.Scalar = Scalar.Scalar; + exports.YAMLMap = YAMLMap.YAMLMap; + exports.YAMLSeq = YAMLSeq.YAMLSeq; + exports.CST = cst; + exports.Lexer = lexer.Lexer; + exports.LineCounter = lineCounter.LineCounter; + exports.Parser = parser.Parser; + exports.parse = publicApi.parse; + exports.parseAllDocuments = publicApi.parseAllDocuments; + exports.parseDocument = publicApi.parseDocument; + exports.stringify = publicApi.stringify; + exports.visit = visit.visit; + exports.visitAsync = visit.visitAsync; +}); + +// node_modules/@opentelemetry/configuration/build/src/utils.js +var require_utils14 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getHttpTlsConfig = exports.initializeDefaultLoggerProviderConfiguration = exports.initializeDefaultMeterProviderConfiguration = exports.initializeDefaultTracerProviderConfiguration = exports.initializeDefaultConfiguration = exports.getGrpcTlsConfig = exports.substituteEnvVars = undefined; + var yaml = require_dist(); + var core_1 = require_src3(); + function substituteEnvVars(doc) { + yaml.visit(doc, { + Scalar: (key, node, _path) => { + if (key === "key") + return; + if (typeof node.value !== "string") + return; + let subbed = envVarSubst(node.value); + if (subbed !== node.value && node.type === yaml.Scalar.PLAIN) { + subbed = yamlScalarCoerce(subbed); + } + node.value = subbed; + } + }); + } + exports.substituteEnvVars = substituteEnvVars; + var ENV_SUBSTITUTION_RE = /^([a-zA-Z_][a-zA-Z0-9_]*)(?::-([^\n}]*))?$/; + function envVarSubst(s) { + const ESCAPE_RE = /(\$\$)/; + const chunks = s.split(ESCAPE_RE); + for (let i = 0;i < chunks.length; ++i) { + if (i % 2 === 1) { + chunks[i] = "$"; + continue; + } + const SUBSTITUTION_REF_RE = /\$\{(?:env:)?([^}]+)\}/g; + let chunk = ""; + let lastIndex = 0; + let match; + while ((match = SUBSTITUTION_REF_RE.exec(chunks[i])) !== null) { + chunk += chunks[i].slice(lastIndex, match.index); + const envMatch = ENV_SUBSTITUTION_RE.exec(match[1]); + if (!envMatch) { + throw new Error(`parse error: invalid env var substitution: ${match[0]}`); + } + const envName = envMatch[1]; + const defaultValue = envMatch[2] ?? ""; + chunk += (0, core_1.getStringFromEnv)(envName) || defaultValue; + lastIndex = SUBSTITUTION_REF_RE.lastIndex; + } + chunk += chunks[i].slice(lastIndex); + chunks[i] = chunk; + } + const result = chunks.join(""); + return result; + } + function yamlScalarCoerce(value) { + let coerced; + try { + coerced = yaml.parse(value, { version: "1.2" }); + } catch { + return value; + } + const type = typeof coerced; + if (coerced === null || type === "number" || type === "boolean") { + return coerced; + } else { + return value; + } + } + function getGrpcTlsConfig(certificateFile, clientKeyFile, clientCertificateFile, insecure) { + if (certificateFile || clientKeyFile || clientCertificateFile) { + const tls = {}; + if (certificateFile) { + tls.ca_file = certificateFile; + } + if (clientKeyFile) { + tls.key_file = clientKeyFile; + } + if (clientCertificateFile) { + tls.cert_file = clientCertificateFile; + } + if (insecure !== undefined) { + tls.insecure = insecure; + } + return tls; + } + return; + } + exports.getGrpcTlsConfig = getGrpcTlsConfig; + function initializeDefaultConfiguration() { + return { + disabled: false, + resource: {}, + attribute_limits: { + attribute_count_limit: 128 + } + }; + } + exports.initializeDefaultConfiguration = initializeDefaultConfiguration; + function initializeDefaultTracerProviderConfiguration() { + return { + processors: [], + limits: { + attribute_count_limit: 128, + event_count_limit: 128, + link_count_limit: 128, + event_attribute_count_limit: 128, + link_attribute_count_limit: 128 + }, + sampler: { + parent_based: { + root: { always_on: undefined }, + remote_parent_sampled: { always_on: undefined }, + remote_parent_not_sampled: { always_off: undefined }, + local_parent_sampled: { always_on: undefined }, + local_parent_not_sampled: { always_off: undefined } + } + } + }; + } + exports.initializeDefaultTracerProviderConfiguration = initializeDefaultTracerProviderConfiguration; + function initializeDefaultMeterProviderConfiguration() { + return { + readers: [], + views: [], + exemplar_filter: "trace_based" + }; + } + exports.initializeDefaultMeterProviderConfiguration = initializeDefaultMeterProviderConfiguration; + function initializeDefaultLoggerProviderConfiguration() { + return { + processors: [], + limits: { attribute_count_limit: 128 }, + "logger_configurator/development": {} + }; + } + exports.initializeDefaultLoggerProviderConfiguration = initializeDefaultLoggerProviderConfiguration; + function getHttpTlsConfig(certificateFile, clientKeyFile, clientCertificateFile) { + if (certificateFile || clientKeyFile || clientCertificateFile) { + const tls = {}; + if (certificateFile) { + tls.ca_file = certificateFile; + } + if (clientKeyFile) { + tls.key_file = clientKeyFile; + } + if (clientCertificateFile) { + tls.cert_file = clientCertificateFile; + } + return tls; + } + return; + } + exports.getHttpTlsConfig = getHttpTlsConfig; +}); + +// node_modules/@opentelemetry/configuration/build/src/EnvDefinition.js +var require_EnvDefinition = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ENV_DEFS = exports.SamplerType = undefined; + var SamplerType; + (function(SamplerType2) { + SamplerType2["AlwaysOn"] = "always_on"; + SamplerType2["AlwaysOff"] = "always_off"; + SamplerType2["TraceIdRatio"] = "traceidratio"; + SamplerType2["ParentBasedAlwaysOn"] = "parentbased_always_on"; + SamplerType2["ParentBasedAlwaysOff"] = "parentbased_always_off"; + SamplerType2["ParentBasedTraceIdRatio"] = "parentbased_traceidratio"; + })(SamplerType = exports.SamplerType || (exports.SamplerType = {})); + exports.ENV_DEFS = { + OTEL_SDK_DISABLED: { + key: "OTEL_SDK_DISABLED", + type: "boolean", + description: "Disable the SDK", + defaultValue: false + }, + OTEL_TRACES_SAMPLER: { + key: "OTEL_TRACES_SAMPLER", + type: "string", + description: "Traces sampler", + allowedValues: Object.values(SamplerType) + }, + OTEL_TRACES_SAMPLER_ARG: { + key: "OTEL_TRACES_SAMPLER_ARG", + type: "string", + description: "Traces sampler argument" + } + }; +}); + +// node_modules/@opentelemetry/configuration/build/src/EnvReader.js +var require_EnvReader = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readAllEnvVars = exports.readEnvVar = undefined; + var api_1 = require_src(); + var core_1 = require_src3(); + var EnvDefinition_1 = require_EnvDefinition(); + function readStringEnv(def) { + const value = (0, core_1.getStringFromEnv)(def.key); + if (value == null) { + return def.defaultValue; + } + if (def.allowedValues && !def.allowedValues.includes(value)) { + api_1.diag.warn(`Invalid value "${value}" for ${def.description} (env: ${def.key}). ` + `Expected one of: ${def.allowedValues.join(", ")}. ` + (def.defaultValue != null ? `Falling back to "${def.defaultValue}".` : "Value will be ignored.")); + return def.defaultValue; + } + return value; + } + function readBooleanEnv(def) { + const raw = (0, core_1.getStringFromEnv)(def.key)?.trim().toLowerCase(); + if (raw == null || raw === "") { + return def.defaultValue; + } + if (raw === "true") { + return true; + } + if (raw === "false") { + return false; + } + api_1.diag.warn(`Invalid value "${raw}" for ${def.description} (env: ${def.key}). ` + `Expected 'true' or 'false'. Falling back to "${def.defaultValue}".`); + return def.defaultValue; + } + function readEnvVar(def) { + switch (def.type) { + case "string": + return readStringEnv(def); + case "boolean": + return readBooleanEnv(def); + } + } + exports.readEnvVar = readEnvVar; + function readAllEnvVars() { + const result = {}; + for (const [name, def] of Object.entries(EnvDefinition_1.ENV_DEFS)) { + result[name] = readEnvVar(def); + } + return result; + } + exports.readAllEnvVars = readAllEnvVars; +}); + +// node_modules/@opentelemetry/configuration/build/src/EnvironmentConfigFactory.js +var require_EnvironmentConfigFactory = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.setLoggerProvider = exports.setMeterProvider = exports.setTracerProvider = exports.setSampler = exports.setPropagators = exports.setAttributeLimits = exports.setResources = exports.EnvironmentConfigFactory = undefined; + var core_1 = require_src3(); + var api_1 = require_src(); + var utils_1 = require_utils14(); + var EnvReader_1 = require_EnvReader(); + var EnvDefinition_1 = require_EnvDefinition(); + + class EnvironmentConfigFactory { + _config; + constructor() { + this._config = (0, utils_1.initializeDefaultConfiguration)(); + const envValues = (0, EnvReader_1.readAllEnvVars)(); + this._config.disabled = envValues.OTEL_SDK_DISABLED; + const logLevelString = (0, core_1.getStringFromEnv)("OTEL_LOG_LEVEL"); + if (logLevelString) { + this._config.log_level = severityNumberConfigFromLogLevelString(logLevelString); + } + setResources(this._config); + setAttributeLimits(this._config); + setPropagators(this._config); + setTracerProvider(this._config, envValues); + setMeterProvider(this._config); + setLoggerProvider(this._config); + } + getConfigModel() { + return this._config; + } + } + exports.EnvironmentConfigFactory = EnvironmentConfigFactory; + var SEV_NUM_CONFIG_FROM_LOG_LEVEL = { + NONE: "fatal", + ERROR: "error", + WARN: "warn", + INFO: "info", + DEBUG: "debug", + VERBOSE: "trace2", + ALL: "trace" + }; + function severityNumberConfigFromLogLevelString(str) { + if (!str) { + return; + } + const sevNumConfig = SEV_NUM_CONFIG_FROM_LOG_LEVEL[str.toUpperCase()]; + if (!sevNumConfig) { + api_1.diag.warn(`Unknown log level "${str}", expected one of ${Object.keys(SEV_NUM_CONFIG_FROM_LOG_LEVEL)}, using default info`); + return "info"; + } + return sevNumConfig; + } + function setResources(config) { + if (config.resource == null) { + config.resource = {}; + } + const resourceAttrList = (0, core_1.getStringFromEnv)("OTEL_RESOURCE_ATTRIBUTES"); + const list = resourceAttrList ? resourceAttrList.split(",").map((s) => s.trim()).filter((s) => s) : []; + const serviceName = (0, core_1.getStringFromEnv)("OTEL_SERVICE_NAME"); + if (serviceName) { + config.resource.attributes = [ + { + name: "service.name", + value: serviceName, + type: "string" + } + ]; + } + if (list.length > 0) { + config.resource.attributes_list = resourceAttrList; + if (config.resource.attributes == null) { + config.resource.attributes = []; + } + for (let i = 0;i < list.length; i++) { + const element = list[i].split("="); + if (element[0] !== "service.name" || element[0] === "service.name" && serviceName === undefined) { + config.resource.attributes.push({ + name: element[0], + value: element[1], + type: "string" + }); + } + } + } + const nodeDetectors = (0, core_1.getStringListFromEnv)("OTEL_NODE_RESOURCE_DETECTORS"); + if (nodeDetectors && nodeDetectors.length > 0 && !nodeDetectors.includes("none")) { + const all = nodeDetectors.includes("all"); + const detectors = []; + if (all || nodeDetectors.includes("container")) + detectors.push({ container: {} }); + if (all || nodeDetectors.includes("host")) + detectors.push({ host: {} }); + if (all || nodeDetectors.includes("os")) + detectors.push({ os: {} }); + if (all || nodeDetectors.includes("process")) + detectors.push({ process: {} }); + if (all || nodeDetectors.includes("serviceinstance")) + detectors.push({ service: {} }); + if (all || nodeDetectors.includes("env")) + detectors.push({ env: {} }); + if (detectors.length > 0) { + if (config.resource["detection/development"] == null) { + config.resource["detection/development"] = {}; + } + config.resource["detection/development"].detectors = detectors; + } + } + } + exports.setResources = setResources; + function setAttributeLimits(config) { + const attributeValueLengthLimit = (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT"); + if (attributeValueLengthLimit && attributeValueLengthLimit > 0) { + if (config.attribute_limits == null) { + config.attribute_limits = { attribute_count_limit: 128 }; + } + config.attribute_limits.attribute_value_length_limit = attributeValueLengthLimit; + } + const attributeCountLimit = (0, core_1.getNumberFromEnv)("OTEL_ATTRIBUTE_COUNT_LIMIT"); + if (attributeCountLimit) { + if (config.attribute_limits == null) { + config.attribute_limits = { attribute_count_limit: attributeCountLimit }; + } else { + config.attribute_limits.attribute_count_limit = attributeCountLimit; + } + } + } + exports.setAttributeLimits = setAttributeLimits; + function setPropagators(config) { + if (config.propagator == null) { + config.propagator = {}; + } + const compositeList = (0, core_1.getStringFromEnv)("OTEL_PROPAGATORS"); + if (compositeList) { + config.propagator.composite_list = compositeList; + const names = compositeList.split(",").map((s) => s.trim()).filter((s) => s); + if (names.length > 0) { + config.propagator.composite = []; + for (const name of names) { + config.propagator.composite.push({ [name]: {} }); + } + } + } + } + exports.setPropagators = setPropagators; + function setSampler(config, env) { + const sampler = env.OTEL_TRACES_SAMPLER; + const arg = env.OTEL_TRACES_SAMPLER_ARG; + if (!sampler || !config.tracer_provider) { + return; + } + const ratio = arg ? parseFloat(arg) : 1; + switch (sampler) { + case EnvDefinition_1.SamplerType.AlwaysOn: + config.tracer_provider.sampler = { always_on: {} }; + break; + case EnvDefinition_1.SamplerType.AlwaysOff: + config.tracer_provider.sampler = { always_off: {} }; + break; + case EnvDefinition_1.SamplerType.TraceIdRatio: + config.tracer_provider.sampler = { + trace_id_ratio_based: { ratio } + }; + break; + case EnvDefinition_1.SamplerType.ParentBasedAlwaysOn: + config.tracer_provider.sampler = { + parent_based: { root: { always_on: {} } } + }; + break; + case EnvDefinition_1.SamplerType.ParentBasedAlwaysOff: + config.tracer_provider.sampler = { + parent_based: { root: { always_off: {} } } + }; + break; + case EnvDefinition_1.SamplerType.ParentBasedTraceIdRatio: + config.tracer_provider.sampler = { + parent_based: { root: { trace_id_ratio_based: { ratio } } } + }; + break; + default: + break; + } + } + exports.setSampler = setSampler; + function setTracerProvider(config, env) { + const exportersType = Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_TRACES_EXPORTER"))); + if (exportersType.length === 0) { + return; + } + if (exportersType.includes("none")) { + api_1.diag.info('OTEL_TRACES_EXPORTER contains "none". Tracer provider will not be initialized.'); + return; + } + config.tracer_provider = (0, utils_1.initializeDefaultTracerProviderConfiguration)(); + setSampler(config, env); + const attributeValueLengthLimit = (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT"); + if (attributeValueLengthLimit) { + config.tracer_provider.limits.attribute_value_length_limit = attributeValueLengthLimit; + } + const attributeCountLimit = (0, core_1.getNumberFromEnv)("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT"); + if (attributeCountLimit) { + config.tracer_provider.limits.attribute_count_limit = attributeCountLimit; + } + const eventCountLimit = (0, core_1.getNumberFromEnv)("OTEL_SPAN_EVENT_COUNT_LIMIT"); + if (eventCountLimit) { + config.tracer_provider.limits.event_count_limit = eventCountLimit; + } + const linkCountLimit = (0, core_1.getNumberFromEnv)("OTEL_SPAN_LINK_COUNT_LIMIT"); + if (linkCountLimit) { + config.tracer_provider.limits.link_count_limit = linkCountLimit; + } + const eventAttributeCountLimit = (0, core_1.getNumberFromEnv)("OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT"); + if (eventAttributeCountLimit) { + config.tracer_provider.limits.event_attribute_count_limit = eventAttributeCountLimit; + } + const linkAttributeCountLimit = (0, core_1.getNumberFromEnv)("OTEL_LINK_ATTRIBUTE_COUNT_LIMIT"); + if (linkAttributeCountLimit) { + config.tracer_provider.limits.link_attribute_count_limit = linkAttributeCountLimit; + } + const batch = { + exporter: {}, + schedule_delay: (0, core_1.getNumberFromEnv)("OTEL_BSP_SCHEDULE_DELAY") ?? 5000, + export_timeout: (0, core_1.getNumberFromEnv)("OTEL_BSP_EXPORT_TIMEOUT") ?? 30000, + max_queue_size: (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_QUEUE_SIZE") ?? 2048, + max_export_batch_size: (0, core_1.getNumberFromEnv)("OTEL_BSP_MAX_EXPORT_BATCH_SIZE") ?? 512 + }; + for (let i = 0;i < exportersType.length; i++) { + const exporterType = exportersType[i]; + const batchInfo = { + ...batch, + exporter: {} + }; + if (exporterType === "console") { + const processor = { + simple: { exporter: { console: {} } } + }; + config.tracer_provider.processors.push(processor); + } else { + const protocol = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf"; + const certificateFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CERTIFICATE"); + const clientKeyFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CLIENT_KEY"); + const clientCertificateFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE"); + const compression = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_COMPRESSION") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_COMPRESSION"); + const timeout = (0, core_1.getNumberFromEnv)("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT") ?? (0, core_1.getNumberFromEnv)("OTEL_EXPORTER_OTLP_TIMEOUT") ?? 1e4; + const headersList = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_HEADERS") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_HEADERS"); + if (protocol === "grpc") { + const tls = (0, utils_1.getGrpcTlsConfig)(certificateFile, clientKeyFile, clientCertificateFile); + const otlpGrpc = { + endpoint: (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4317", + timeout, + ...tls !== undefined && { tls }, + ...compression !== undefined && { compression }, + ...headersList !== undefined && { headers_list: headersList } + }; + batchInfo.exporter = { otlp_grpc: otlpGrpc }; + } else { + const tls = (0, utils_1.getHttpTlsConfig)(certificateFile, clientKeyFile, clientCertificateFile); + const encoding = protocol === "http/json" ? "json" : protocol === "http/protobuf" ? "protobuf" : undefined; + const otlpHttp = { + endpoint: (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") ?? ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT") ? `${(0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT")}/v1/traces` : "http://localhost:4318/v1/traces"), + timeout, + ...tls !== undefined && { tls }, + ...compression !== undefined && { compression }, + ...headersList !== undefined && { headers_list: headersList }, + ...encoding !== undefined && { encoding } + }; + batchInfo.exporter = { otlp_http: otlpHttp }; + } + const processor = { batch: batchInfo }; + config.tracer_provider.processors.push(processor); + } + } + } + exports.setTracerProvider = setTracerProvider; + function setMeterProvider(config) { + const exportersType = Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_METRICS_EXPORTER"))); + if (exportersType.length === 0) { + return; + } + if (exportersType.includes("none")) { + api_1.diag.info('OTEL_METRICS_EXPORTER contains "none". Meter provider will not be initialized.'); + return; + } + config.meter_provider = (0, utils_1.initializeDefaultMeterProviderConfiguration)(); + const interval = (0, core_1.getNumberFromEnv)("OTEL_METRIC_EXPORT_INTERVAL") ?? 60000; + for (let i = 0;i < exportersType.length; i++) { + const exporterType = exportersType[i]; + if (exporterType === "prometheus") { + const pullReader = { + exporter: { + "prometheus/development": { + host: (0, core_1.getStringFromEnv)("OTEL_EXPORTER_PROMETHEUS_HOST") ?? "localhost", + port: (0, core_1.getNumberFromEnv)("OTEL_EXPORTER_PROMETHEUS_PORT") ?? 9464, + without_scope_info: false, + "without_target_info/development": false + } + } + }; + config.meter_provider.readers.push({ pull: pullReader }); + continue; + } + const readerPeriodicInfo = { + interval, + timeout: (0, core_1.getNumberFromEnv)("OTEL_METRIC_EXPORT_TIMEOUT") ?? 30000, + exporter: {} + }; + if (exporterType === "console") { + readerPeriodicInfo.exporter = { console: {} }; + } else { + const protocol = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf"; + const certificateFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CERTIFICATE"); + const clientKeyFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CLIENT_KEY"); + const clientCertificateFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE"); + const compression = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_COMPRESSION") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_COMPRESSION"); + const timeoutExporter = (0, core_1.getNumberFromEnv)("OTEL_EXPORTER_OTLP_METRICS_TIMEOUT") ?? (0, core_1.getNumberFromEnv)("OTEL_EXPORTER_OTLP_TIMEOUT") ?? 1e4; + const headersList = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_HEADERS") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_HEADERS"); + const rawTemporality = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE") ?? "cumulative"; + const validTemporalities = ["cumulative", "delta", "low_memory"]; + const temporalityPreference = validTemporalities.includes(rawTemporality) ? rawTemporality : "cumulative"; + const rawHistogramAgg = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION") ?? "explicit_bucket_histogram"; + const validHistogramAggs = [ + "explicit_bucket_histogram", + "base2_exponential_bucket_histogram" + ]; + const defaultHistogramAggregation = validHistogramAggs.includes(rawHistogramAgg) ? rawHistogramAgg : "explicit_bucket_histogram"; + if (protocol === "grpc") { + const tls = (0, utils_1.getGrpcTlsConfig)(certificateFile, clientKeyFile, clientCertificateFile); + const otlpGrpc = { + endpoint: (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4317", + timeout: timeoutExporter, + temporality_preference: temporalityPreference, + default_histogram_aggregation: defaultHistogramAggregation, + ...tls !== undefined && { tls }, + ...compression !== undefined && { compression }, + ...headersList !== undefined && { headers_list: headersList } + }; + readerPeriodicInfo.exporter = { otlp_grpc: otlpGrpc }; + } else { + const tls = (0, utils_1.getHttpTlsConfig)(certificateFile, clientKeyFile, clientCertificateFile); + const encoding = protocol === "http/json" ? "json" : protocol === "http/protobuf" ? "protobuf" : undefined; + const otlpHttp = { + endpoint: (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT") ?? ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT") ? `${(0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT")}/v1/metrics` : "http://localhost:4318/v1/metrics"), + timeout: timeoutExporter, + temporality_preference: temporalityPreference, + default_histogram_aggregation: defaultHistogramAggregation, + ...tls !== undefined && { tls }, + ...compression !== undefined && { compression }, + ...headersList !== undefined && { headers_list: headersList }, + ...encoding !== undefined && { encoding } + }; + readerPeriodicInfo.exporter = { otlp_http: otlpHttp }; + } + } + config.meter_provider.readers.push({ periodic: readerPeriodicInfo }); + } + const rawExemplarFilter = (0, core_1.getStringFromEnv)("OTEL_METRICS_EXEMPLAR_FILTER") ?? "trace_based"; + config.meter_provider.exemplar_filter = rawExemplarFilter === "default" ? "trace_based" : rawExemplarFilter; + } + exports.setMeterProvider = setMeterProvider; + function setLoggerProvider(config) { + const exportersType = Array.from(new Set((0, core_1.getStringListFromEnv)("OTEL_LOGS_EXPORTER"))); + if (exportersType.length === 0) { + return; + } + if (exportersType.includes("none")) { + api_1.diag.info('OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.'); + return; + } + config.logger_provider = (0, utils_1.initializeDefaultLoggerProviderConfiguration)(); + const attributeValueLengthLimit = (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT"); + const attributeCountLimit = (0, core_1.getNumberFromEnv)("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT"); + if (attributeValueLengthLimit || attributeCountLimit) { + if (attributeValueLengthLimit) { + config.logger_provider.limits.attribute_value_length_limit = attributeValueLengthLimit; + } + if (attributeCountLimit) { + config.logger_provider.limits.attribute_count_limit = attributeCountLimit; + } + } + const batch = { + exporter: {}, + schedule_delay: (0, core_1.getNumberFromEnv)("OTEL_BLRP_SCHEDULE_DELAY") ?? 1000, + export_timeout: (0, core_1.getNumberFromEnv)("OTEL_BLRP_EXPORT_TIMEOUT") ?? 30000, + max_queue_size: (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_QUEUE_SIZE") ?? 2048, + max_export_batch_size: (0, core_1.getNumberFromEnv)("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE") ?? 512 + }; + for (let i = 0;i < exportersType.length; i++) { + const exporterType = exportersType[i]; + const batchInfo = { + ...batch, + exporter: {} + }; + if (exporterType === "console") { + const processor = { + simple: { exporter: { console: {} } } + }; + config.logger_provider.processors.push(processor); + } else { + const protocol = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_PROTOCOL") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf"; + const certificateFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CERTIFICATE"); + const clientKeyFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CLIENT_KEY"); + const clientCertificateFile = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE"); + const compression = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_COMPRESSION") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_COMPRESSION"); + const timeout = (0, core_1.getNumberFromEnv)("OTEL_EXPORTER_OTLP_LOGS_TIMEOUT") ?? (0, core_1.getNumberFromEnv)("OTEL_EXPORTER_OTLP_TIMEOUT") ?? 1e4; + const headersList = (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_HEADERS") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_HEADERS"); + if (protocol === "grpc") { + const tls = (0, utils_1.getGrpcTlsConfig)(certificateFile, clientKeyFile, clientCertificateFile); + const otlpGrpc = { + endpoint: (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT") ?? (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT") ?? "http://localhost:4317", + timeout, + ...tls !== undefined && { tls }, + ...compression !== undefined && { compression }, + ...headersList !== undefined && { headers_list: headersList } + }; + batchInfo.exporter = { otlp_grpc: otlpGrpc }; + } else { + const tls = (0, utils_1.getHttpTlsConfig)(certificateFile, clientKeyFile, clientCertificateFile); + const encoding = protocol === "http/json" ? "json" : protocol === "http/protobuf" ? "protobuf" : undefined; + const otlpHttp = { + endpoint: (0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_LOGS_ENDPOINT") ?? ((0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT") ? `${(0, core_1.getStringFromEnv)("OTEL_EXPORTER_OTLP_ENDPOINT")}/v1/logs` : "http://localhost:4318/v1/logs"), + timeout, + ...tls !== undefined && { tls }, + ...compression !== undefined && { compression }, + ...headersList !== undefined && { headers_list: headersList }, + ...encoding !== undefined && { encoding } + }; + batchInfo.exporter = { otlp_http: otlpHttp }; + } + const processor = { batch: batchInfo }; + config.logger_provider.processors.push(processor); + } + } + } + exports.setLoggerProvider = setLoggerProvider; +}); + +// node_modules/@opentelemetry/configuration/build/src/generated/validator.js +var require_validator = __commonJS((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + module.exports = validate20; + module.exports.default = validate20; + var schema31 = { $schema: "https://json-schema.org/draft/2020-12/schema", title: "OpenTelemetryConfiguration", type: "object", additionalProperties: true, properties: { file_format: { type: "string", description: `The file format version. +Represented as a string including the semver major, minor version numbers (and optionally the meta tag). For example: "0.4", "1.0-rc.2", "1.0" (after stable release). +See https://github.com/open-telemetry/opentelemetry-configuration/blob/main/VERSIONING.md for more details. +The yaml format is documented at https://github.com/open-telemetry/opentelemetry-configuration/tree/main/schema +Property is required and must be non-null. +` }, disabled: { type: ["boolean", "null"], description: `Configure if the SDK is disabled or not. +If omitted or null, false is used. +` }, log_level: { $ref: "#/$defs/SeverityNumber", description: `Configure the log level of the internal logger used by the SDK. +Values include: +* debug: debug, severity number 5. +* debug2: debug2, severity number 6. +* debug3: debug3, severity number 7. +* debug4: debug4, severity number 8. +* error: error, severity number 17. +* error2: error2, severity number 18. +* error3: error3, severity number 19. +* error4: error4, severity number 20. +* fatal: fatal, severity number 21. +* fatal2: fatal2, severity number 22. +* fatal3: fatal3, severity number 23. +* fatal4: fatal4, severity number 24. +* info: info, severity number 9. +* info2: info2, severity number 10. +* info3: info3, severity number 11. +* info4: info4, severity number 12. +* trace: trace, severity number 1. +* trace2: trace2, severity number 2. +* trace3: trace3, severity number 3. +* trace4: trace4, severity number 4. +* warn: warn, severity number 13. +* warn2: warn2, severity number 14. +* warn3: warn3, severity number 15. +* warn4: warn4, severity number 16. +If omitted, INFO is used. +` }, attribute_limits: { $ref: "#/$defs/AttributeLimits", description: `Configure general attribute limits. See also tracer_provider.limits, logger_provider.limits. +If omitted, default values as described in AttributeLimits are used. +` }, logger_provider: { $ref: "#/$defs/LoggerProvider", description: `Configure logger provider. +If omitted, a noop logger provider is used. +` }, meter_provider: { $ref: "#/$defs/MeterProvider", description: `Configure meter provider. +If omitted, a noop meter provider is used. +` }, propagator: { $ref: "#/$defs/Propagator", description: `Configure text map context propagators. +If omitted, a noop propagator is used. +` }, tracer_provider: { $ref: "#/$defs/TracerProvider", description: `Configure tracer provider. +If omitted, a noop tracer provider is used. +` }, resource: { $ref: "#/$defs/Resource", description: `Configure resource for all signals. +If omitted, the default resource is used. +` }, "instrumentation/development": { $ref: "#/$defs/ExperimentalInstrumentation", description: `Configure instrumentation. +If omitted, instrumentation defaults are used. +` }, distribution: { $ref: "#/$defs/Distribution", description: `Defines configuration parameters specific to a particular OpenTelemetry distribution or vendor. +This section provides a standardized location for distribution-specific settings +that are not part of the OpenTelemetry configuration model. +It allows vendors to expose their own extensions and general configuration options. +If omitted, distribution defaults are used. +` } }, required: ["file_format"], $defs: { Aggregation: { type: "object", additionalProperties: false, minProperties: 1, maxProperties: 1, properties: { default: { $ref: "#/$defs/DefaultAggregation", description: `Configures the stream to use the instrument kind to select an aggregation and advisory parameters to influence aggregation configuration parameters. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#default-aggregation for details. +If omitted, ignore. +` }, drop: { $ref: "#/$defs/DropAggregation", description: `Configures the stream to ignore/drop all instrument measurements. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#drop-aggregation for details. +If omitted, ignore. +` }, explicit_bucket_histogram: { $ref: "#/$defs/ExplicitBucketHistogramAggregation", description: `Configures the stream to collect data for the histogram metric point using a set of explicit boundary values for histogram bucketing. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#explicit-bucket-histogram-aggregation for details +If omitted, ignore. +` }, base2_exponential_bucket_histogram: { $ref: "#/$defs/Base2ExponentialBucketHistogramAggregation", description: `Configures the stream to collect data for the exponential histogram metric point, which uses a base-2 exponential formula to determine bucket boundaries and an integer scale parameter to control resolution. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#base2-exponential-bucket-histogram-aggregation for details. +If omitted, ignore. +` }, last_value: { $ref: "#/$defs/LastValueAggregation", description: `Configures the stream to collect data using the last measurement. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#last-value-aggregation for details. +If omitted, ignore. +` }, sum: { $ref: "#/$defs/SumAggregation", description: `Configures the stream to collect the arithmetic sum of measurement values. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#sum-aggregation for details. +If omitted, ignore. +` } } }, AlwaysOffSampler: { type: ["object", "null"], additionalProperties: false }, AlwaysOnSampler: { type: ["object", "null"], additionalProperties: false }, AttributeLimits: { type: "object", additionalProperties: false, properties: { attribute_value_length_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute value size. +Value must be non-negative. +If omitted or null, there is no limit. +` }, attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute count. +Value must be non-negative. +If omitted or null, 128 is used. +` } } }, AttributeNameValue: { type: "object", additionalProperties: false, properties: { name: { type: "string", description: `The attribute name. +Property is required and must be non-null. +` }, value: { oneOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }, { type: "null" }, { type: "array", items: { type: "string" }, minItems: 1 }, { type: "array", items: { type: "boolean" }, minItems: 1 }, { type: "array", items: { type: "number" }, minItems: 1 }], description: `The attribute value. +The type of value must match .type. +Property is required and must be non-null. +` }, type: { $ref: "#/$defs/AttributeType", description: `The attribute type. +Values include: +* bool: Boolean attribute value. +* bool_array: Boolean array attribute value. +* double: Double attribute value. +* double_array: Double array attribute value. +* int: Integer attribute value. +* int_array: Integer array attribute value. +* string: String attribute value. +* string_array: String array attribute value. +If omitted, string is used. +` } }, required: ["name", "value"] }, AttributeType: { type: ["string", "null"], enum: ["string", "bool", "int", "double", "string_array", "bool_array", "int_array", "double_array"] }, B3MultiPropagator: { type: ["object", "null"], additionalProperties: false }, B3Propagator: { type: ["object", "null"], additionalProperties: false }, BaggagePropagator: { type: ["object", "null"], additionalProperties: false }, Base2ExponentialBucketHistogramAggregation: { type: ["object", "null"], additionalProperties: false, properties: { max_scale: { type: ["integer", "null"], minimum: -10, maximum: 20, description: `Configure the max scale factor. +If omitted or null, 20 is used. +` }, max_size: { type: ["integer", "null"], minimum: 2, description: `Configure the maximum number of buckets in each of the positive and negative ranges, not counting the special zero bucket. +If omitted or null, 160 is used. +` }, record_min_max: { type: ["boolean", "null"], description: `Configure whether or not to record min and max. +If omitted or null, true is used. +` } } }, BatchLogRecordProcessor: { type: "object", additionalProperties: false, properties: { schedule_delay: { type: ["integer", "null"], minimum: 0, description: `Configure delay interval (in milliseconds) between two consecutive exports. +Value must be non-negative. +If omitted or null, 1000 is used. +` }, export_timeout: { type: ["integer", "null"], minimum: 0, description: `Configure maximum allowed time (in milliseconds) to export data. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 30000 is used. +` }, max_queue_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum queue size. Value must be positive. +If omitted or null, 2048 is used. +` }, max_export_batch_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum batch size. Value must be positive. +If omitted or null, 512 is used. +` }, exporter: { $ref: "#/$defs/LogRecordExporter", description: `Configure exporter. +Property is required and must be non-null. +` } }, required: ["exporter"] }, BatchSpanProcessor: { type: "object", additionalProperties: false, properties: { schedule_delay: { type: ["integer", "null"], minimum: 0, description: `Configure delay interval (in milliseconds) between two consecutive exports. +Value must be non-negative. +If omitted or null, 5000 is used. +` }, export_timeout: { type: ["integer", "null"], minimum: 0, description: `Configure maximum allowed time (in milliseconds) to export data. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 30000 is used. +` }, max_queue_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum queue size. Value must be positive. +If omitted or null, 2048 is used. +` }, max_export_batch_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum batch size. Value must be positive. +If omitted or null, 512 is used. +` }, exporter: { $ref: "#/$defs/SpanExporter", description: `Configure exporter. +Property is required and must be non-null. +` } }, required: ["exporter"] }, CardinalityLimits: { type: "object", additionalProperties: false, properties: { default: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for all instrument types. +Instrument-specific cardinality limits take priority. +If omitted or null, 2000 is used. +` }, counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for counter instruments. +If omitted or null, the value from .default is used. +` }, gauge: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for gauge instruments. +If omitted or null, the value from .default is used. +` }, histogram: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for histogram instruments. +If omitted or null, the value from .default is used. +` }, observable_counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for observable_counter instruments. +If omitted or null, the value from .default is used. +` }, observable_gauge: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for observable_gauge instruments. +If omitted or null, the value from .default is used. +` }, observable_up_down_counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for observable_up_down_counter instruments. +If omitted or null, the value from .default is used. +` }, up_down_counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for up_down_counter instruments. +If omitted or null, the value from .default is used. +` } } }, ConsoleExporter: { type: ["object", "null"], additionalProperties: false }, ConsoleMetricExporter: { type: ["object", "null"], additionalProperties: false, properties: { temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }, DefaultAggregation: { type: ["object", "null"], additionalProperties: false }, Distribution: { type: "object", additionalProperties: { type: "object" }, minProperties: 1 }, DropAggregation: { type: ["object", "null"], additionalProperties: false }, ExemplarFilter: { type: ["string", "null"], enum: ["always_on", "always_off", "trace_based"] }, ExperimentalCodeInstrumentation: { type: "object", additionalProperties: false, properties: { semconv: { $ref: "#/$defs/ExperimentalSemconvConfig", description: `Configure code semantic convention version and migration behavior. + +This property takes precedence over the .instrumentation/development.general.stability_opt_in_list setting. + +See code semantic conventions: https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/ +If omitted, uses the general stability_opt_in_list setting, or instrumentations continue emitting their default semantic convention version if not set. +` } } }, ExperimentalComposableAlwaysOffSampler: { type: ["object", "null"], additionalProperties: false }, ExperimentalComposableAlwaysOnSampler: { type: ["object", "null"], additionalProperties: false }, ExperimentalComposableParentThresholdSampler: { type: ["object"], additionalProperties: false, properties: { root: { $ref: "#/$defs/ExperimentalComposableSampler", description: `Sampler to use when there is no parent. +Property is required and must be non-null. +` } }, required: ["root"] }, ExperimentalComposableProbabilitySampler: { type: ["object", "null"], additionalProperties: false, properties: { ratio: { type: ["number", "null"], minimum: 0, maximum: 1, description: `Configure ratio. +If omitted or null, 1.0 is used. +` } } }, ExperimentalComposableRuleBasedSampler: { type: ["object", "null"], additionalProperties: false, properties: { rules: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalComposableRuleBasedSamplerRule" }, description: `The rules for the sampler, matched in order. +Each rule can have multiple match conditions. All conditions must match for the rule to match. +If no conditions are specified, the rule matches all spans that reach it. +If no rules match, the span is not sampled. +If omitted, no span is sampled. +` } } }, ExperimentalComposableRuleBasedSamplerRule: { type: "object", description: `A rule for ExperimentalComposableRuleBasedSampler. A rule can have multiple match conditions - the sampler will be applied if all match. +If no conditions are specified, the rule matches all spans that reach it. +`, additionalProperties: false, properties: { attribute_values: { $ref: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues", description: `Values to match against a single attribute. Non-string attributes are matched using their string representation: +for example, a value of "404" would match the http.response.status_code 404. For array attributes, if any +item matches, it is considered a match. +If omitted, ignore. +` }, attribute_patterns: { $ref: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns", description: `Patterns to match against a single attribute. Non-string attributes are matched using their string representation: +for example, a pattern of "4*" would match any http.response.status_code in 400-499. For array attributes, if any +item matches, it is considered a match. +If omitted, ignore. +` }, span_kinds: { type: "array", minItems: 1, items: { $ref: "#/$defs/SpanKind" }, description: `The span kinds to match. If the span's kind matches any of these, it matches. +Values include: +* client: client, a client span. +* consumer: consumer, a consumer span. +* internal: internal, an internal span. +* producer: producer, a producer span. +* server: server, a server span. +If omitted, ignore. +` }, parent: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalSpanParent" }, description: `The parent span types to match. +Values include: +* local: local, a local parent. +* none: none, no parent, i.e., the trace root. +* remote: remote, a remote parent. +If omitted, ignore. +` }, sampler: { $ref: "#/$defs/ExperimentalComposableSampler", description: `The sampler to use for matching spans. +Property is required and must be non-null. +` } }, required: ["sampler"] }, ExperimentalComposableRuleBasedSamplerRuleAttributePatterns: { type: "object", additionalProperties: false, properties: { key: { type: "string", description: `The attribute key to match against. +Property is required and must be non-null. +` }, included: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure list of value patterns to include. +Values are evaluated to match as follows: + * If the value exactly matches. + * If the value matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +If omitted, all values are included. +` }, excluded: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure list of value patterns to exclude. Applies after .included (i.e. excluded has higher priority than included). +Values are evaluated to match as follows: + * If the value exactly matches. + * If the value matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +If omitted, .included attributes are included. +` } }, required: ["key"] }, ExperimentalComposableRuleBasedSamplerRuleAttributeValues: { type: "object", additionalProperties: false, properties: { key: { type: "string", description: `The attribute key to match against. +Property is required and must be non-null. +` }, values: { type: "array", minItems: 1, items: { type: "string" }, description: `The attribute values to match against. If the attribute's value matches any of these, it matches. +Property is required and must be non-null. +` } }, required: ["key", "values"] }, ExperimentalComposableSampler: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { always_off: { $ref: "#/$defs/ExperimentalComposableAlwaysOffSampler", description: `Configure sampler to be always_off. +If omitted, ignore. +` }, always_on: { $ref: "#/$defs/ExperimentalComposableAlwaysOnSampler", description: `Configure sampler to be always_on. +If omitted, ignore. +` }, parent_threshold: { $ref: "#/$defs/ExperimentalComposableParentThresholdSampler", description: `Configure sampler to be parent_threshold. +If omitted, ignore. +` }, probability: { $ref: "#/$defs/ExperimentalComposableProbabilitySampler", description: `Configure sampler to be probability. +If omitted, ignore. +` }, rule_based: { $ref: "#/$defs/ExperimentalComposableRuleBasedSampler", description: `Configure sampler to be rule_based. +If omitted, ignore. +` } } }, ExperimentalContainerResourceDetector: { type: ["object", "null"], additionalProperties: false }, ExperimentalDbInstrumentation: { type: "object", additionalProperties: false, properties: { semconv: { $ref: "#/$defs/ExperimentalSemconvConfig", description: `Configure database semantic convention version and migration behavior. + +This property takes precedence over the .instrumentation/development.general.stability_opt_in_list setting. + +See database migration: https://opentelemetry.io/docs/specs/semconv/database/ +If omitted, uses the general stability_opt_in_list setting, or instrumentations continue emitting their default semantic convention version if not set. +` } } }, ExperimentalGenAiInstrumentation: { type: "object", additionalProperties: false, properties: { semconv: { $ref: "#/$defs/ExperimentalSemconvConfig", description: `Configure GenAI semantic convention version and migration behavior. + +This property takes precedence over the .instrumentation/development.general.stability_opt_in_list setting. + +See GenAI semantic conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/ +If omitted, uses the general stability_opt_in_list setting, or instrumentations continue emitting their default semantic convention version if not set. +` } } }, ExperimentalGeneralInstrumentation: { type: "object", additionalProperties: false, properties: { http: { $ref: "#/$defs/ExperimentalHttpInstrumentation", description: `Configure instrumentations following the http semantic conventions. +See http semantic conventions: https://opentelemetry.io/docs/specs/semconv/http/ +If omitted, defaults as described in ExperimentalHttpInstrumentation are used. +` }, code: { $ref: "#/$defs/ExperimentalCodeInstrumentation", description: `Configure instrumentations following the code semantic conventions. +See code semantic conventions: https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/ +If omitted, defaults as described in ExperimentalCodeInstrumentation are used. +` }, db: { $ref: "#/$defs/ExperimentalDbInstrumentation", description: `Configure instrumentations following the database semantic conventions. +See database semantic conventions: https://opentelemetry.io/docs/specs/semconv/database/ +If omitted, defaults as described in ExperimentalDbInstrumentation are used. +` }, gen_ai: { $ref: "#/$defs/ExperimentalGenAiInstrumentation", description: `Configure instrumentations following the GenAI semantic conventions. +See GenAI semantic conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/ +If omitted, defaults as described in ExperimentalGenAiInstrumentation are used. +` }, messaging: { $ref: "#/$defs/ExperimentalMessagingInstrumentation", description: `Configure instrumentations following the messaging semantic conventions. +See messaging semantic conventions: https://opentelemetry.io/docs/specs/semconv/messaging/ +If omitted, defaults as described in ExperimentalMessagingInstrumentation are used. +` }, rpc: { $ref: "#/$defs/ExperimentalRpcInstrumentation", description: `Configure instrumentations following the RPC semantic conventions. +See RPC semantic conventions: https://opentelemetry.io/docs/specs/semconv/rpc/ +If omitted, defaults as described in ExperimentalRpcInstrumentation are used. +` }, sanitization: { $ref: "#/$defs/ExperimentalSanitization", description: `Configure general sanitization options. +If omitted, defaults as described in ExperimentalSanitization are used. +` }, stability_opt_in_list: { type: ["string", "null"], description: `Configure semantic convention stability opt-in as a comma-separated list. +This property follows the format and semantics of the OTEL_SEMCONV_STABILITY_OPT_IN environment variable. +Controls the emission of stable vs. experimental semantic conventions for instrumentation. +This setting is only intended for migrating from experimental to stable semantic conventions. + +Known values include: +- http: Emit stable HTTP and networking conventions only +- http/dup: Emit both old and stable HTTP and networking conventions (for phased migration) +- database: Emit stable database conventions only +- database/dup: Emit both old and stable database conventions (for phased migration) +- rpc: Emit stable RPC conventions only +- rpc/dup: Emit both experimental and stable RPC conventions (for phased migration) +- messaging: Emit stable messaging conventions only +- messaging/dup: Emit both old and stable messaging conventions (for phased migration) +- code: Emit stable code conventions only +- code/dup: Emit both old and stable code conventions (for phased migration) + +Multiple values can be specified as a comma-separated list (e.g., "http,database/dup"). +Additional signal types may be supported in future versions. + +Domain-specific semconv properties (e.g., .instrumentation/development.general.db.semconv) take precedence over this general setting. + +See: +- HTTP migration: https://opentelemetry.io/docs/specs/semconv/non-normative/http-migration/ +- Database migration: https://opentelemetry.io/docs/specs/semconv/database/ +- RPC: https://opentelemetry.io/docs/specs/semconv/rpc/ +- Messaging: https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/ +If omitted or null, no opt-in is configured and instrumentations continue emitting their default semantic convention version. +` } } }, ExperimentalHostResourceDetector: { type: ["object", "null"], additionalProperties: false }, ExperimentalHttpClientInstrumentation: { type: "object", additionalProperties: false, properties: { request_captured_headers: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure headers to capture for outbound http requests. +If omitted, no outbound request headers are captured. +` }, response_captured_headers: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure headers to capture for inbound http responses. +If omitted, no inbound response headers are captured. +` }, known_methods: { type: "array", minItems: 0, items: { type: "string" }, description: `Override the default list of known HTTP methods. +Known methods are case-sensitive. +This is a full override of the default known methods, not a list of known methods in addition to the defaults. +If omitted, HTTP methods GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH are known. +` } } }, ExperimentalHttpInstrumentation: { type: "object", additionalProperties: false, properties: { semconv: { $ref: "#/$defs/ExperimentalSemconvConfig", description: `Configure HTTP semantic convention version and migration behavior. + +This property takes precedence over the .instrumentation/development.general.stability_opt_in_list setting. + +See HTTP migration: https://opentelemetry.io/docs/specs/semconv/non-normative/http-migration/ +If omitted, uses the general stability_opt_in_list setting, or instrumentations continue emitting their default semantic convention version if not set. +` }, client: { $ref: "#/$defs/ExperimentalHttpClientInstrumentation", description: `Configure instrumentations following the http client semantic conventions. +If omitted, defaults as described in ExperimentalHttpClientInstrumentation are used. +` }, server: { $ref: "#/$defs/ExperimentalHttpServerInstrumentation", description: `Configure instrumentations following the http server semantic conventions. +If omitted, defaults as described in ExperimentalHttpServerInstrumentation are used. +` } } }, ExperimentalHttpServerInstrumentation: { type: "object", additionalProperties: false, properties: { request_captured_headers: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure headers to capture for inbound http requests. +If omitted, no request headers are captured. +` }, response_captured_headers: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure headers to capture for outbound http responses. +If omitted, no response headers are captures. +` }, known_methods: { type: "array", minItems: 0, items: { type: "string" }, description: `Override the default list of known HTTP methods. +Known methods are case-sensitive. +This is a full override of the default known methods, not a list of known methods in addition to the defaults. +If omitted, HTTP methods GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH are known. +` } } }, ExperimentalInstrumentation: { type: "object", additionalProperties: false, properties: { general: { $ref: "#/$defs/ExperimentalGeneralInstrumentation", description: `Configure general SemConv options that may apply to multiple languages and instrumentations. +Instrumenation may merge general config options with the language specific configuration at .instrumentation.. +If omitted, default values as described in ExperimentalGeneralInstrumentation are used. +` }, cpp: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure C++ language-specific instrumentation libraries. +If omitted, instrumentation defaults are used. +` }, dotnet: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure .NET language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, erlang: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Erlang language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, go: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Go language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, java: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Java language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, js: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure JavaScript language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, php: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure PHP language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, python: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Python language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, ruby: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Ruby language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, rust: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Rust language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, swift: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Swift language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` } } }, ExperimentalJaegerRemoteSampler: { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string"], description: `Configure the endpoint of the jaeger remote sampling service. +Property is required and must be non-null. +` }, interval: { type: ["integer", "null"], minimum: 0, description: `Configure the polling interval (in milliseconds) to fetch from the remote sampling service. +If omitted or null, 60000 is used. +` }, initial_sampler: { $ref: "#/$defs/Sampler", description: `Configure the initial sampler used before first configuration is fetched. +Property is required and must be non-null. +` } }, required: ["endpoint", "initial_sampler"] }, ExperimentalLanguageSpecificInstrumentation: { type: "object", additionalProperties: { type: "object" } }, ExperimentalLoggerConfig: { type: ["object"], additionalProperties: false, properties: { enabled: { type: ["boolean", "null"], description: `Configure if the logger is enabled or not. +If omitted or null, true is used. +` }, minimum_severity: { $ref: "#/$defs/SeverityNumber", description: `Configure severity filtering. +Log records with an non-zero (i.e. unspecified) severity number which is less than minimum_severity are not processed. +Values include: +* debug: debug, severity number 5. +* debug2: debug2, severity number 6. +* debug3: debug3, severity number 7. +* debug4: debug4, severity number 8. +* error: error, severity number 17. +* error2: error2, severity number 18. +* error3: error3, severity number 19. +* error4: error4, severity number 20. +* fatal: fatal, severity number 21. +* fatal2: fatal2, severity number 22. +* fatal3: fatal3, severity number 23. +* fatal4: fatal4, severity number 24. +* info: info, severity number 9. +* info2: info2, severity number 10. +* info3: info3, severity number 11. +* info4: info4, severity number 12. +* trace: trace, severity number 1. +* trace2: trace2, severity number 2. +* trace3: trace3, severity number 3. +* trace4: trace4, severity number 4. +* warn: warn, severity number 13. +* warn2: warn2, severity number 14. +* warn3: warn3, severity number 15. +* warn4: warn4, severity number 16. +If omitted, severity filtering is not applied. +` }, trace_based: { type: ["boolean", "null"], description: `Configure trace based filtering. +If true, log records associated with unsampled trace contexts traces are not processed. If false, or if a log record is not associated with a trace context, trace based filtering is not applied. +If omitted or null, trace based filtering is not applied. +` } } }, ExperimentalLoggerConfigurator: { type: ["object"], additionalProperties: false, properties: { default_config: { $ref: "#/$defs/ExperimentalLoggerConfig", description: `Configure the default logger config used there is no matching entry in .logger_configurator/development.loggers. +If omitted, unmatched .loggers use default values as described in ExperimentalLoggerConfig. +` }, loggers: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalLoggerMatcherAndConfig" }, description: `Configure loggers. +If omitted, all loggers use .default_config. +` } } }, ExperimentalLoggerMatcherAndConfig: { type: ["object"], additionalProperties: false, properties: { name: { type: ["string"], description: `Configure logger names to match, evaluated as follows: + + * If the logger name exactly matches. + * If the logger name matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +Property is required and must be non-null. +` }, config: { $ref: "#/$defs/ExperimentalLoggerConfig", description: `The logger config. +Property is required and must be non-null. +` } }, required: ["name", "config"] }, ExperimentalMessagingInstrumentation: { type: "object", additionalProperties: false, properties: { semconv: { $ref: "#/$defs/ExperimentalSemconvConfig", description: `Configure messaging semantic convention version and migration behavior. + +This property takes precedence over the .instrumentation/development.general.stability_opt_in_list setting. + +See messaging semantic conventions: https://opentelemetry.io/docs/specs/semconv/messaging/ +If omitted, uses the general stability_opt_in_list setting, or instrumentations continue emitting their default semantic convention version if not set. +` } } }, ExperimentalMeterConfig: { type: ["object"], additionalProperties: false, properties: { enabled: { type: ["boolean"], description: `Configure if the meter is enabled or not. +If omitted, true is used. +` } } }, ExperimentalMeterConfigurator: { type: ["object"], additionalProperties: false, properties: { default_config: { $ref: "#/$defs/ExperimentalMeterConfig", description: `Configure the default meter config used there is no matching entry in .meter_configurator/development.meters. +If omitted, unmatched .meters use default values as described in ExperimentalMeterConfig. +` }, meters: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalMeterMatcherAndConfig" }, description: `Configure meters. +If omitted, all meters used .default_config. +` } } }, ExperimentalMeterMatcherAndConfig: { type: ["object"], additionalProperties: false, properties: { name: { type: ["string"], description: `Configure meter names to match, evaluated as follows: + + * If the meter name exactly matches. + * If the meter name matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +Property is required and must be non-null. +` }, config: { $ref: "#/$defs/ExperimentalMeterConfig", description: `The meter config. +Property is required and must be non-null. +` } }, required: ["name", "config"] }, ExperimentalOtlpFileExporter: { type: ["object", "null"], additionalProperties: false, properties: { output_stream: { type: ["string", "null"], description: `Configure output stream. +Values include stdout, or scheme+destination. For example: file:///path/to/file.jsonl. +If omitted or null, stdout is used. +` } } }, ExperimentalOtlpFileMetricExporter: { type: ["object", "null"], additionalProperties: false, properties: { output_stream: { type: ["string", "null"], description: `Configure output stream. +Values include stdout, or scheme+destination. For example: file:///path/to/file.jsonl. +If omitted or null, stdout is used. +` }, temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }, ExperimentalProbabilitySampler: { type: ["object", "null"], additionalProperties: false, properties: { ratio: { type: ["number", "null"], minimum: 0, maximum: 1, description: `Configure ratio. +If omitted or null, 1.0 is used. +` } } }, ExperimentalProcessResourceDetector: { type: ["object", "null"], additionalProperties: false }, ExperimentalPrometheusMetricExporter: { type: ["object", "null"], additionalProperties: false, properties: { host: { type: ["string", "null"], description: `Configure host. +If omitted or null, localhost is used. +` }, port: { type: ["integer", "null"], description: `Configure port. +If omitted or null, 9464 is used. +` }, without_scope_info: { type: ["boolean", "null"], description: `Configure Prometheus Exporter to produce metrics without scope labels. +If omitted or null, false is used. +` }, "without_target_info/development": { type: ["boolean", "null"], description: `Configure Prometheus Exporter to produce metrics without a target info metric for the resource. +If omitted or null, false is used. +` }, with_resource_constant_labels: { $ref: "#/$defs/IncludeExclude", description: `Configure Prometheus Exporter to add resource attributes as metrics attributes, where the resource attribute keys match the patterns. +If omitted, no resource attributes are added. +` }, translation_strategy: { $ref: "#/$defs/ExperimentalPrometheusTranslationStrategy", description: `Configure how metric names are translated to Prometheus metric names. +Values include: +* no_translation/development: Special character escaping is disabled. Type and unit suffixes are disabled. Metric names are unaltered. +* no_utf8_escaping_with_suffixes/development: Special character escaping is disabled. Type and unit suffixes are enabled. +* underscore_escaping_with_suffixes: Special character escaping is enabled. Type and unit suffixes are enabled. +* underscore_escaping_without_suffixes/development: Special character escaping is enabled. Type and unit suffixes are disabled. This represents classic Prometheus metric name compatibility. +If omitted, underscore_escaping_with_suffixes is used. +` } } }, ExperimentalPrometheusTranslationStrategy: { type: ["string", "null"], enum: ["underscore_escaping_with_suffixes", "underscore_escaping_without_suffixes/development", "no_utf8_escaping_with_suffixes/development", "no_translation/development"] }, ExperimentalResourceDetection: { type: "object", additionalProperties: false, properties: { attributes: { $ref: "#/$defs/IncludeExclude", description: `Configure attributes provided by resource detectors. +If omitted, all attributes from resource detectors are added. +` }, detectors: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalResourceDetector" }, description: `Configure resource detectors. +Resource detector names are dependent on the SDK language ecosystem. Please consult documentation for each respective language. +If omitted, no resource detectors are enabled. +` } } }, ExperimentalResourceDetector: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { container: { $ref: "#/$defs/ExperimentalContainerResourceDetector", description: `Enable the container resource detector, which populates container.* attributes. +If omitted, ignore. +` }, host: { $ref: "#/$defs/ExperimentalHostResourceDetector", description: `Enable the host resource detector, which populates host.* and os.* attributes. +If omitted, ignore. +` }, process: { $ref: "#/$defs/ExperimentalProcessResourceDetector", description: `Enable the process resource detector, which populates process.* attributes. +If omitted, ignore. +` }, service: { $ref: "#/$defs/ExperimentalServiceResourceDetector", description: `Enable the service detector, which populates service.name based on the OTEL_SERVICE_NAME environment variable and service.instance.id. +If omitted, ignore. +` } } }, ExperimentalRpcInstrumentation: { type: "object", additionalProperties: false, properties: { semconv: { $ref: "#/$defs/ExperimentalSemconvConfig", description: `Configure RPC semantic convention version and migration behavior. + +This property takes precedence over the .instrumentation/development.general.stability_opt_in_list setting. + +See RPC semantic conventions: https://opentelemetry.io/docs/specs/semconv/rpc/ +If omitted, uses the general stability_opt_in_list setting, or instrumentations continue emitting their default semantic convention version if not set. +` } } }, ExperimentalSanitization: { type: "object", additionalProperties: false, properties: { url: { $ref: "#/$defs/ExperimentalUrlSanitization", description: `Configure URL sanitization options. +If omitted, defaults as described in ExperimentalUrlSanitization are used. +` } } }, ExperimentalSemconvConfig: { type: "object", additionalProperties: false, properties: { version: { type: ["integer", "null"], minimum: 0, description: `The target semantic convention version for this domain (e.g., 1). +If omitted or null, the latest stable version is used, or if no stable version is available and .experimental is true then the latest experimental version is used. +` }, experimental: { type: ["boolean", "null"], description: `Use latest experimental semantic conventions (before stable is available or to enable experimental features on top of stable conventions). +If omitted or null, false is used. +` }, dual_emit: { type: ["boolean", "null"], description: `When true, also emit the previous major version alongside the target version. +For version=1, the previous version refers to the pre-stable conventions that the instrumentation emitted before the first stable semantic convention version was defined. +For version=2 and above, the previous version is the prior stable major version (e.g., version=2, dual_emit=true emits both v2 and v1). +Enables dual-emit for phased migration between versions. +If omitted or null, false is used. +` } } }, ExperimentalServiceResourceDetector: { type: ["object", "null"], additionalProperties: false }, ExperimentalSpanParent: { type: ["string", "null"], enum: ["none", "remote", "local"] }, ExperimentalTracerConfig: { type: ["object"], additionalProperties: false, properties: { enabled: { type: ["boolean"], description: `Configure if the tracer is enabled or not. +If omitted, true is used. +` } } }, ExperimentalTracerConfigurator: { type: ["object"], additionalProperties: false, properties: { default_config: { $ref: "#/$defs/ExperimentalTracerConfig", description: `Configure the default tracer config used there is no matching entry in .tracer_configurator/development.tracers. +If omitted, unmatched .tracers use default values as described in ExperimentalTracerConfig. +` }, tracers: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalTracerMatcherAndConfig" }, description: `Configure tracers. +If omitted, all tracers use .default_config. +` } } }, ExperimentalTracerMatcherAndConfig: { type: ["object"], additionalProperties: false, properties: { name: { type: ["string"], description: `Configure tracer names to match, evaluated as follows: + + * If the tracer name exactly matches. + * If the tracer name matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +Property is required and must be non-null. +` }, config: { $ref: "#/$defs/ExperimentalTracerConfig", description: `The tracer config. +Property is required and must be non-null. +` } }, required: ["name", "config"] }, ExperimentalUrlSanitization: { type: "object", additionalProperties: false, properties: { sensitive_query_parameters: { type: "array", minItems: 0, items: { type: "string" }, description: `List of query parameter names whose values should be redacted from URLs. +Query parameter names are case-sensitive. +This is a full override of the default sensitive query parameter keys, it is not a list of keys in addition to the defaults. +Set to an empty array to disable query parameter redaction. +If omitted, the default sensitive query parameter list as defined by the url semantic conventions (https://github.com/open-telemetry/semantic-conventions/blob/main/docs/registry/attributes/url.md) is used. +` } } }, ExplicitBucketHistogramAggregation: { type: ["object", "null"], additionalProperties: false, properties: { boundaries: { type: "array", minItems: 0, items: { type: "number" }, description: `Configure bucket boundaries. +If omitted, [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000] is used. +` }, record_min_max: { type: ["boolean", "null"], description: `Configure record min and max. +If omitted or null, true is used. +` } } }, ExporterDefaultHistogramAggregation: { type: ["string", "null"], enum: ["explicit_bucket_histogram", "base2_exponential_bucket_histogram"] }, ExporterTemporalityPreference: { type: ["string", "null"], enum: ["cumulative", "delta", "low_memory"] }, GrpcTls: { type: ["object", "null"], additionalProperties: false, properties: { ca_file: { type: ["string", "null"], description: `Configure certificate used to verify a server's TLS credentials. +Absolute path to certificate file in PEM format. +If omitted or null, system default certificate verification is used for secure connections. +` }, key_file: { type: ["string", "null"], description: `Configure mTLS private client key. +Absolute path to client key file in PEM format. If set, .client_certificate must also be set. +If omitted or null, mTLS is not used. +` }, cert_file: { type: ["string", "null"], description: `Configure mTLS client certificate. +Absolute path to client certificate file in PEM format. If set, .client_key must also be set. +If omitted or null, mTLS is not used. +` }, insecure: { type: ["boolean", "null"], description: `Configure client transport security for the exporter's connection. +Only applicable when .endpoint is provided without http or https scheme. Implementations may choose to ignore .insecure. +If omitted or null, false is used. +` } } }, HttpTls: { type: ["object", "null"], additionalProperties: false, properties: { ca_file: { type: ["string", "null"], description: `Configure certificate used to verify a server's TLS credentials. +Absolute path to certificate file in PEM format. +If omitted or null, system default certificate verification is used for secure connections. +` }, key_file: { type: ["string", "null"], description: `Configure mTLS private client key. +Absolute path to client key file in PEM format. If set, .client_certificate must also be set. +If omitted or null, mTLS is not used. +` }, cert_file: { type: ["string", "null"], description: `Configure mTLS client certificate. +Absolute path to client certificate file in PEM format. If set, .client_key must also be set. +If omitted or null, mTLS is not used. +` } } }, IncludeExclude: { type: "object", additionalProperties: false, properties: { included: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure list of value patterns to include. +Values are evaluated to match as follows: + * If the value exactly matches. + * If the value matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +If omitted, all values are included. +` }, excluded: { type: "array", minItems: 1, items: { type: "string" }, description: `Configure list of value patterns to exclude. Applies after .included (i.e. excluded has higher priority than included). +Values are evaluated to match as follows: + * If the value exactly matches. + * If the value matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +If omitted, .included attributes are included. +` } } }, InstrumentType: { type: ["string", "null"], enum: ["counter", "gauge", "histogram", "observable_counter", "observable_gauge", "observable_up_down_counter", "up_down_counter"] }, LastValueAggregation: { type: ["object", "null"], additionalProperties: false }, LoggerProvider: { type: "object", additionalProperties: false, properties: { processors: { type: "array", minItems: 1, items: { $ref: "#/$defs/LogRecordProcessor" }, description: `Configure log record processors. +Property is required and must be non-null. +` }, limits: { $ref: "#/$defs/LogRecordLimits", description: `Configure log record limits. See also attribute_limits. +If omitted, default values as described in LogRecordLimits are used. +` }, "logger_configurator/development": { $ref: "#/$defs/ExperimentalLoggerConfigurator", description: `Configure loggers. +If omitted, all loggers use default values as described in ExperimentalLoggerConfig. +` } }, required: ["processors"] }, LogRecordExporter: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { otlp_http: { $ref: "#/$defs/OtlpHttpExporter", description: `Configure exporter to be OTLP with HTTP transport. +If omitted, ignore. +` }, otlp_grpc: { $ref: "#/$defs/OtlpGrpcExporter", description: `Configure exporter to be OTLP with gRPC transport. +If omitted, ignore. +` }, "otlp_file/development": { $ref: "#/$defs/ExperimentalOtlpFileExporter", description: `Configure exporter to be OTLP with file transport. +If omitted, ignore. +` }, console: { $ref: "#/$defs/ConsoleExporter", description: `Configure exporter to be console. +If omitted, ignore. +` } } }, LogRecordLimits: { type: "object", additionalProperties: false, properties: { attribute_value_length_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute value size. Overrides .attribute_limits.attribute_value_length_limit. +Value must be non-negative. +If omitted or null, there is no limit. +` }, attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute count. Overrides .attribute_limits.attribute_count_limit. +Value must be non-negative. +If omitted or null, 128 is used. +` } } }, LogRecordProcessor: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { batch: { $ref: "#/$defs/BatchLogRecordProcessor", description: `Configure a batch log record processor. +If omitted, ignore. +` }, simple: { $ref: "#/$defs/SimpleLogRecordProcessor", description: `Configure a simple log record processor. +If omitted, ignore. +` } } }, MeterProvider: { type: "object", additionalProperties: false, properties: { readers: { type: "array", minItems: 1, items: { $ref: "#/$defs/MetricReader" }, description: `Configure metric readers. +Property is required and must be non-null. +` }, views: { type: "array", minItems: 1, items: { $ref: "#/$defs/View" }, description: `Configure views. +Each view has a selector which determines the instrument(s) it applies to, and a configuration for the resulting stream(s). +If omitted, no views are registered. +` }, exemplar_filter: { $ref: "#/$defs/ExemplarFilter", description: `Configure the exemplar filter. +Values include: +* always_off: ExemplarFilter which makes no measurements eligible for being an Exemplar. +* always_on: ExemplarFilter which makes all measurements eligible for being an Exemplar. +* trace_based: ExemplarFilter which makes measurements recorded in the context of a sampled parent span eligible for being an Exemplar. +If omitted, trace_based is used. +` }, "meter_configurator/development": { $ref: "#/$defs/ExperimentalMeterConfigurator", description: `Configure meters. +If omitted, all meters use default values as described in ExperimentalMeterConfig. +` } }, required: ["readers"] }, MetricProducer: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { opencensus: { $ref: "#/$defs/OpenCensusMetricProducer", description: `Configure metric producer to be opencensus. +If omitted, ignore. +` } } }, MetricReader: { type: "object", additionalProperties: false, minProperties: 1, maxProperties: 1, properties: { periodic: { $ref: "#/$defs/PeriodicMetricReader", description: `Configure a periodic metric reader. +If omitted, ignore. +` }, pull: { $ref: "#/$defs/PullMetricReader", description: `Configure a pull based metric reader. +If omitted, ignore. +` } } }, NameStringValuePair: { type: "object", additionalProperties: false, properties: { name: { type: "string", description: `The name of the pair. +Property is required and must be non-null. +` }, value: { type: ["string", "null"], description: `The value of the pair. +Property must be present, but if null the behavior is dependent on usage context. +` } }, required: ["name", "value"] }, OpenCensusMetricProducer: { type: ["object", "null"], additionalProperties: false }, OtlpGrpcExporter: { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint. +If omitted or null, http://localhost:4317 is used. +` }, tls: { $ref: "#/$defs/GrpcTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` } } }, OtlpGrpcMetricExporter: { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint. +If omitted or null, http://localhost:4317 is used. +` }, tls: { $ref: "#/$defs/GrpcTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` }, temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }, OtlpHttpEncoding: { type: ["string", "null"], enum: ["protobuf", "json"] }, OtlpHttpExporter: { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint, including the signal specific path. +If omitted or null, the http://localhost:4318/v1/{signal} (where signal is 'traces', 'logs', or 'metrics') is used. +` }, tls: { $ref: "#/$defs/HttpTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` }, encoding: { $ref: "#/$defs/OtlpHttpEncoding", description: `Configure the encoding used for messages. +Implementations may not support json. +Values include: +* json: Protobuf JSON encoding. +* protobuf: Protobuf binary encoding. +If omitted, protobuf is used. +` } } }, OtlpHttpMetricExporter: { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint. +If omitted or null, http://localhost:4318/v1/metrics is used. +` }, tls: { $ref: "#/$defs/HttpTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` }, encoding: { $ref: "#/$defs/OtlpHttpEncoding", description: `Configure the encoding used for messages. +Implementations may not support json. +Values include: +* json: Protobuf JSON encoding. +* protobuf: Protobuf binary encoding. +If omitted, protobuf is used. +` }, temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }, ParentBasedSampler: { type: ["object", "null"], additionalProperties: false, properties: { root: { $ref: "#/$defs/Sampler", description: `Configure root sampler. +If omitted, always_on is used. +` }, remote_parent_sampled: { $ref: "#/$defs/Sampler", description: `Configure remote_parent_sampled sampler. +If omitted, always_on is used. +` }, remote_parent_not_sampled: { $ref: "#/$defs/Sampler", description: `Configure remote_parent_not_sampled sampler. +If omitted, always_off is used. +` }, local_parent_sampled: { $ref: "#/$defs/Sampler", description: `Configure local_parent_sampled sampler. +If omitted, always_on is used. +` }, local_parent_not_sampled: { $ref: "#/$defs/Sampler", description: `Configure local_parent_not_sampled sampler. +If omitted, always_off is used. +` } } }, PeriodicMetricReader: { type: "object", additionalProperties: false, properties: { interval: { type: ["integer", "null"], minimum: 0, description: `Configure delay interval (in milliseconds) between start of two consecutive exports. +Value must be non-negative. +If omitted or null, 60000 is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure maximum allowed time (in milliseconds) to export data. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 30000 is used. +` }, exporter: { $ref: "#/$defs/PushMetricExporter", description: `Configure exporter. +Property is required and must be non-null. +` }, producers: { type: "array", minItems: 1, items: { $ref: "#/$defs/MetricProducer" }, description: `Configure metric producers. +If omitted, no metric producers are added. +` }, cardinality_limits: { $ref: "#/$defs/CardinalityLimits", description: `Configure cardinality limits. +If omitted, default values as described in CardinalityLimits are used. +` } }, required: ["exporter"] }, Propagator: { type: "object", additionalProperties: false, properties: { composite: { type: "array", minItems: 1, items: { $ref: "#/$defs/TextMapPropagator" }, description: `Configure the propagators in the composite text map propagator. Entries from .composite_list are appended to the list here with duplicates filtered out. +Built-in propagator keys include: tracecontext, baggage, b3, b3multi. Known third party keys include: xray. +If omitted, and .composite_list is omitted or null, a noop propagator is used. +` }, composite_list: { type: ["string", "null"], description: `Configure the propagators in the composite text map propagator. Entries are appended to .composite with duplicates filtered out. +The value is a comma separated list of propagator identifiers matching the format of OTEL_PROPAGATORS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration for details. +Built-in propagator identifiers include: tracecontext, baggage, b3, b3multi. Known third party identifiers include: xray. +If omitted or null, and .composite is omitted or null, a noop propagator is used. +` } } }, PullMetricExporter: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { "prometheus/development": { $ref: "#/$defs/ExperimentalPrometheusMetricExporter", description: `Configure exporter to be prometheus. +If omitted, ignore. +` } } }, PullMetricReader: { type: "object", additionalProperties: false, properties: { exporter: { $ref: "#/$defs/PullMetricExporter", description: `Configure exporter. +Property is required and must be non-null. +` }, producers: { type: "array", minItems: 1, items: { $ref: "#/$defs/MetricProducer" }, description: `Configure metric producers. +If omitted, no metric producers are added. +` }, cardinality_limits: { $ref: "#/$defs/CardinalityLimits", description: `Configure cardinality limits. +If omitted, default values as described in CardinalityLimits are used. +` } }, required: ["exporter"] }, PushMetricExporter: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { otlp_http: { $ref: "#/$defs/OtlpHttpMetricExporter", description: `Configure exporter to be OTLP with HTTP transport. +If omitted, ignore. +` }, otlp_grpc: { $ref: "#/$defs/OtlpGrpcMetricExporter", description: `Configure exporter to be OTLP with gRPC transport. +If omitted, ignore. +` }, "otlp_file/development": { $ref: "#/$defs/ExperimentalOtlpFileMetricExporter", description: `Configure exporter to be OTLP with file transport. +If omitted, ignore. +` }, console: { $ref: "#/$defs/ConsoleMetricExporter", description: `Configure exporter to be console. +If omitted, ignore. +` } } }, Resource: { type: "object", additionalProperties: false, properties: { attributes: { type: "array", minItems: 1, items: { $ref: "#/$defs/AttributeNameValue" }, description: `Configure resource attributes. Entries have higher priority than entries from .resource.attributes_list. +If omitted, no resource attributes are added. +` }, "detection/development": { $ref: "#/$defs/ExperimentalResourceDetection", description: `Configure resource detection. +If omitted, resource detection is disabled. +` }, schema_url: { type: ["string", "null"], description: `Configure resource schema URL. +If omitted or null, no schema URL is used. +` }, attributes_list: { type: ["string", "null"], description: `Configure resource attributes. Entries have lower priority than entries from .resource.attributes. +The value is a list of comma separated key-value pairs matching the format of OTEL_RESOURCE_ATTRIBUTES. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration for details. +If omitted or null, no resource attributes are added. +` } } }, Sampler: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { always_off: { $ref: "#/$defs/AlwaysOffSampler", description: `Configure sampler to be always_off. +If omitted, ignore. +` }, always_on: { $ref: "#/$defs/AlwaysOnSampler", description: `Configure sampler to be always_on. +If omitted, ignore. +` }, "composite/development": { $ref: "#/$defs/ExperimentalComposableSampler", description: `Configure sampler to be composite. +If omitted, ignore. +` }, "jaeger_remote/development": { $ref: "#/$defs/ExperimentalJaegerRemoteSampler", description: `Configure sampler to be jaeger_remote. +If omitted, ignore. +` }, parent_based: { $ref: "#/$defs/ParentBasedSampler", description: `Configure sampler to be parent_based. +If omitted, ignore. +` }, "probability/development": { $ref: "#/$defs/ExperimentalProbabilitySampler", description: `Configure sampler to be probability. +If omitted, ignore. +` }, trace_id_ratio_based: { $ref: "#/$defs/TraceIdRatioBasedSampler", description: `Configure sampler to be trace_id_ratio_based. +If omitted, ignore. +` } } }, SeverityNumber: { type: ["string", "null"], enum: ["trace", "trace2", "trace3", "trace4", "debug", "debug2", "debug3", "debug4", "info", "info2", "info3", "info4", "warn", "warn2", "warn3", "warn4", "error", "error2", "error3", "error4", "fatal", "fatal2", "fatal3", "fatal4"] }, SimpleLogRecordProcessor: { type: "object", additionalProperties: false, properties: { exporter: { $ref: "#/$defs/LogRecordExporter", description: `Configure exporter. +Property is required and must be non-null. +` } }, required: ["exporter"] }, SimpleSpanProcessor: { type: "object", additionalProperties: false, properties: { exporter: { $ref: "#/$defs/SpanExporter", description: `Configure exporter. +Property is required and must be non-null. +` } }, required: ["exporter"] }, SpanExporter: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { otlp_http: { $ref: "#/$defs/OtlpHttpExporter", description: `Configure exporter to be OTLP with HTTP transport. +If omitted, ignore. +` }, otlp_grpc: { $ref: "#/$defs/OtlpGrpcExporter", description: `Configure exporter to be OTLP with gRPC transport. +If omitted, ignore. +` }, "otlp_file/development": { $ref: "#/$defs/ExperimentalOtlpFileExporter", description: `Configure exporter to be OTLP with file transport. +If omitted, ignore. +` }, console: { $ref: "#/$defs/ConsoleExporter", description: `Configure exporter to be console. +If omitted, ignore. +` } } }, SpanKind: { type: ["string", "null"], enum: ["internal", "server", "client", "producer", "consumer"] }, SpanLimits: { type: "object", additionalProperties: false, properties: { attribute_value_length_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute value size. Overrides .attribute_limits.attribute_value_length_limit. +Value must be non-negative. +If omitted or null, there is no limit. +` }, attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute count. Overrides .attribute_limits.attribute_count_limit. +Value must be non-negative. +If omitted or null, 128 is used. +` }, event_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max span event count. +Value must be non-negative. +If omitted or null, 128 is used. +` }, link_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max span link count. +Value must be non-negative. +If omitted or null, 128 is used. +` }, event_attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attributes per span event. +Value must be non-negative. +If omitted or null, 128 is used. +` }, link_attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attributes per span link. +Value must be non-negative. +If omitted or null, 128 is used. +` } } }, SpanProcessor: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { batch: { $ref: "#/$defs/BatchSpanProcessor", description: `Configure a batch span processor. +If omitted, ignore. +` }, simple: { $ref: "#/$defs/SimpleSpanProcessor", description: `Configure a simple span processor. +If omitted, ignore. +` } } }, SumAggregation: { type: ["object", "null"], additionalProperties: false }, TextMapPropagator: { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { tracecontext: { $ref: "#/$defs/TraceContextPropagator", description: `Include the w3c trace context propagator. +If omitted, ignore. +` }, baggage: { $ref: "#/$defs/BaggagePropagator", description: `Include the w3c baggage propagator. +If omitted, ignore. +` }, b3: { $ref: "#/$defs/B3Propagator", description: `Include the zipkin b3 propagator. +If omitted, ignore. +` }, b3multi: { $ref: "#/$defs/B3MultiPropagator", description: `Include the zipkin b3 multi propagator. +If omitted, ignore. +` } } }, TraceContextPropagator: { type: ["object", "null"], additionalProperties: false }, TraceIdRatioBasedSampler: { type: ["object", "null"], additionalProperties: false, properties: { ratio: { type: ["number", "null"], minimum: 0, maximum: 1, description: `Configure trace_id_ratio. +If omitted or null, 1.0 is used. +` } } }, TracerProvider: { type: "object", additionalProperties: false, properties: { processors: { type: "array", minItems: 1, items: { $ref: "#/$defs/SpanProcessor" }, description: `Configure span processors. +Property is required and must be non-null. +` }, limits: { $ref: "#/$defs/SpanLimits", description: `Configure span limits. See also attribute_limits. +If omitted, default values as described in SpanLimits are used. +` }, sampler: { $ref: "#/$defs/Sampler", description: `Configure the sampler. +If omitted, parent based sampler with a root of always_on is used. +` }, "tracer_configurator/development": { $ref: "#/$defs/ExperimentalTracerConfigurator", description: `Configure tracers. +If omitted, all tracers use default values as described in ExperimentalTracerConfig. +` } }, required: ["processors"] }, View: { type: "object", additionalProperties: false, properties: { selector: { $ref: "#/$defs/ViewSelector", description: `Configure view selector. +Selection criteria is additive as described in https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#instrument-selection-criteria. +Property is required and must be non-null. +` }, stream: { $ref: "#/$defs/ViewStream", description: `Configure view stream. +Property is required and must be non-null. +` } }, required: ["selector", "stream"] }, ViewSelector: { type: "object", additionalProperties: false, properties: { instrument_name: { type: ["string", "null"], description: `Configure instrument name selection criteria. +If omitted or null, all instrument names match. +` }, instrument_type: { $ref: "#/$defs/InstrumentType", description: `Configure instrument type selection criteria. +Values include: +* counter: Synchronous counter instruments. +* gauge: Synchronous gauge instruments. +* histogram: Synchronous histogram instruments. +* observable_counter: Asynchronous counter instruments. +* observable_gauge: Asynchronous gauge instruments. +* observable_up_down_counter: Asynchronous up down counter instruments. +* up_down_counter: Synchronous up down counter instruments. +If omitted, all instrument types match. +` }, unit: { type: ["string", "null"], description: `Configure the instrument unit selection criteria. +If omitted or null, all instrument units match. +` }, meter_name: { type: ["string", "null"], description: `Configure meter name selection criteria. +If omitted or null, all meter names match. +` }, meter_version: { type: ["string", "null"], description: `Configure meter version selection criteria. +If omitted or null, all meter versions match. +` }, meter_schema_url: { type: ["string", "null"], description: `Configure meter schema url selection criteria. +If omitted or null, all meter schema URLs match. +` } } }, ViewStream: { type: "object", additionalProperties: false, properties: { name: { type: ["string", "null"], description: `Configure metric name of the resulting stream(s). +If omitted or null, the instrument's original name is used. +` }, description: { type: ["string", "null"], description: `Configure metric description of the resulting stream(s). +If omitted or null, the instrument's origin description is used. +` }, aggregation: { $ref: "#/$defs/Aggregation", description: `Configure aggregation of the resulting stream(s). +If omitted, default is used. +` }, aggregation_cardinality_limit: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure the aggregation cardinality limit. +If omitted or null, the metric reader's default cardinality limit is used. +` }, attribute_keys: { $ref: "#/$defs/IncludeExclude", description: `Configure attribute keys retained in the resulting stream(s). +If omitted, all attribute keys are retained. +` } } } } }; + var schema32 = { type: ["string", "null"], enum: ["trace", "trace2", "trace3", "trace4", "debug", "debug2", "debug3", "debug4", "info", "info2", "info3", "info4", "warn", "warn2", "warn3", "warn4", "error", "error2", "error3", "error4", "fatal", "fatal2", "fatal3", "fatal4"] }; + var schema33 = { type: "object", additionalProperties: false, properties: { attribute_value_length_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute value size. +Value must be non-negative. +If omitted or null, there is no limit. +` }, attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute count. +Value must be non-negative. +If omitted or null, 128 is used. +` } } }; + var schema48 = { type: "object", additionalProperties: false, properties: { attribute_value_length_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute value size. Overrides .attribute_limits.attribute_value_length_limit. +Value must be non-negative. +If omitted or null, there is no limit. +` }, attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute count. Overrides .attribute_limits.attribute_count_limit. +Value must be non-negative. +If omitted or null, 128 is used. +` } } }; + var schema35 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { batch: { $ref: "#/$defs/BatchLogRecordProcessor", description: `Configure a batch log record processor. +If omitted, ignore. +` }, simple: { $ref: "#/$defs/SimpleLogRecordProcessor", description: `Configure a simple log record processor. +If omitted, ignore. +` } } }; + var schema36 = { type: "object", additionalProperties: false, properties: { schedule_delay: { type: ["integer", "null"], minimum: 0, description: `Configure delay interval (in milliseconds) between two consecutive exports. +Value must be non-negative. +If omitted or null, 1000 is used. +` }, export_timeout: { type: ["integer", "null"], minimum: 0, description: `Configure maximum allowed time (in milliseconds) to export data. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 30000 is used. +` }, max_queue_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum queue size. Value must be positive. +If omitted or null, 2048 is used. +` }, max_export_batch_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum batch size. Value must be positive. +If omitted or null, 512 is used. +` }, exporter: { $ref: "#/$defs/LogRecordExporter", description: `Configure exporter. +Property is required and must be non-null. +` } }, required: ["exporter"] }; + var schema37 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { otlp_http: { $ref: "#/$defs/OtlpHttpExporter", description: `Configure exporter to be OTLP with HTTP transport. +If omitted, ignore. +` }, otlp_grpc: { $ref: "#/$defs/OtlpGrpcExporter", description: `Configure exporter to be OTLP with gRPC transport. +If omitted, ignore. +` }, "otlp_file/development": { $ref: "#/$defs/ExperimentalOtlpFileExporter", description: `Configure exporter to be OTLP with file transport. +If omitted, ignore. +` }, console: { $ref: "#/$defs/ConsoleExporter", description: `Configure exporter to be console. +If omitted, ignore. +` } } }; + var schema45 = { type: ["object", "null"], additionalProperties: false, properties: { output_stream: { type: ["string", "null"], description: `Configure output stream. +Values include stdout, or scheme+destination. For example: file:///path/to/file.jsonl. +If omitted or null, stdout is used. +` } } }; + var schema46 = { type: ["object", "null"], additionalProperties: false }; + var schema38 = { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint, including the signal specific path. +If omitted or null, the http://localhost:4318/v1/{signal} (where signal is 'traces', 'logs', or 'metrics') is used. +` }, tls: { $ref: "#/$defs/HttpTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` }, encoding: { $ref: "#/$defs/OtlpHttpEncoding", description: `Configure the encoding used for messages. +Implementations may not support json. +Values include: +* json: Protobuf JSON encoding. +* protobuf: Protobuf binary encoding. +If omitted, protobuf is used. +` } } }; + var schema39 = { type: ["object", "null"], additionalProperties: false, properties: { ca_file: { type: ["string", "null"], description: `Configure certificate used to verify a server's TLS credentials. +Absolute path to certificate file in PEM format. +If omitted or null, system default certificate verification is used for secure connections. +` }, key_file: { type: ["string", "null"], description: `Configure mTLS private client key. +Absolute path to client key file in PEM format. If set, .client_certificate must also be set. +If omitted or null, mTLS is not used. +` }, cert_file: { type: ["string", "null"], description: `Configure mTLS client certificate. +Absolute path to client certificate file in PEM format. If set, .client_key must also be set. +If omitted or null, mTLS is not used. +` } } }; + var schema40 = { type: "object", additionalProperties: false, properties: { name: { type: "string", description: `The name of the pair. +Property is required and must be non-null. +` }, value: { type: ["string", "null"], description: `The value of the pair. +Property must be present, but if null the behavior is dependent on usage context. +` } }, required: ["name", "value"] }; + var schema41 = { type: ["string", "null"], enum: ["protobuf", "json"] }; + function validate25(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate25.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate25.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema38.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "endpoint" || key0 === "tls" || key0 === "headers" || key0 === "headers_list" || key0 === "compression" || key0 === "timeout" || key0 === "encoding")) { + validate25.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.endpoint !== undefined) { + let data0 = data.endpoint; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate25.errors = [{ instancePath: instancePath + "/endpoint", schemaPath: "#/properties/endpoint/type", keyword: "type", params: { type: schema38.properties.endpoint.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.tls !== undefined) { + let data1 = data.tls; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate25.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/HttpTls/type", keyword: "type", params: { type: schema39.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + const _errs7 = errors; + for (const key1 in data1) { + if (!(key1 === "ca_file" || key1 === "key_file" || key1 === "cert_file")) { + validate25.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/HttpTls/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs7 === errors) { + if (data1.ca_file !== undefined) { + let data2 = data1.ca_file; + const _errs8 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate25.errors = [{ instancePath: instancePath + "/tls/ca_file", schemaPath: "#/$defs/HttpTls/properties/ca_file/type", keyword: "type", params: { type: schema39.properties.ca_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.key_file !== undefined) { + let data3 = data1.key_file; + const _errs10 = errors; + if (typeof data3 !== "string" && data3 !== null) { + validate25.errors = [{ instancePath: instancePath + "/tls/key_file", schemaPath: "#/$defs/HttpTls/properties/key_file/type", keyword: "type", params: { type: schema39.properties.key_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.cert_file !== undefined) { + let data4 = data1.cert_file; + const _errs12 = errors; + if (typeof data4 !== "string" && data4 !== null) { + validate25.errors = [{ instancePath: instancePath + "/tls/cert_file", schemaPath: "#/$defs/HttpTls/properties/cert_file/type", keyword: "type", params: { type: schema39.properties.cert_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs12 === errors; + } else { + var valid2 = true; + } + } + } + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers !== undefined) { + let data5 = data.headers; + const _errs14 = errors; + if (errors === _errs14) { + if (Array.isArray(data5)) { + if (data5.length < 1) { + validate25.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data5.length; + for (let i0 = 0;i0 < len0; i0++) { + let data6 = data5[i0]; + const _errs16 = errors; + const _errs17 = errors; + if (errors === _errs17) { + if (data6 && typeof data6 == "object" && !Array.isArray(data6)) { + let missing0; + if (data6.name === undefined && (missing0 = "name") || data6.value === undefined && (missing0 = "value")) { + validate25.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs19 = errors; + for (const key2 in data6) { + if (!(key2 === "name" || key2 === "value")) { + validate25.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs19 === errors) { + if (data6.name !== undefined) { + const _errs20 = errors; + if (typeof data6.name !== "string") { + validate25.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/name", schemaPath: "#/$defs/NameStringValuePair/properties/name/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid5 = _errs20 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data6.value !== undefined) { + let data8 = data6.value; + const _errs22 = errors; + if (typeof data8 !== "string" && data8 !== null) { + validate25.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/value", schemaPath: "#/$defs/NameStringValuePair/properties/value/type", keyword: "type", params: { type: schema40.properties.value.type }, message: "must be string,null" }]; + return false; + } + var valid5 = _errs22 === errors; + } else { + var valid5 = true; + } + } + } + } + } else { + validate25.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid3 = _errs16 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate25.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs14 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers_list !== undefined) { + let data9 = data.headers_list; + const _errs24 = errors; + if (typeof data9 !== "string" && data9 !== null) { + validate25.errors = [{ instancePath: instancePath + "/headers_list", schemaPath: "#/properties/headers_list/type", keyword: "type", params: { type: schema38.properties.headers_list.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs24 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.compression !== undefined) { + let data10 = data.compression; + const _errs26 = errors; + if (typeof data10 !== "string" && data10 !== null) { + validate25.errors = [{ instancePath: instancePath + "/compression", schemaPath: "#/properties/compression/type", keyword: "type", params: { type: schema38.properties.compression.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs26 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.timeout !== undefined) { + let data11 = data.timeout; + const _errs28 = errors; + if (!(typeof data11 == "number" && (!(data11 % 1) && !isNaN(data11))) && data11 !== null) { + validate25.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/type", keyword: "type", params: { type: schema38.properties.timeout.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs28) { + if (typeof data11 == "number") { + if (data11 < 0 || isNaN(data11)) { + validate25.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs28 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.encoding !== undefined) { + let data12 = data.encoding; + const _errs30 = errors; + if (typeof data12 !== "string" && data12 !== null) { + validate25.errors = [{ instancePath: instancePath + "/encoding", schemaPath: "#/$defs/OtlpHttpEncoding/type", keyword: "type", params: { type: schema41.type }, message: "must be string,null" }]; + return false; + } + if (!(data12 === "protobuf" || data12 === "json")) { + validate25.errors = [{ instancePath: instancePath + "/encoding", schemaPath: "#/$defs/OtlpHttpEncoding/enum", keyword: "enum", params: { allowedValues: schema41.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs30 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } + validate25.errors = vErrors; + return errors === 0; + } + validate25.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema42 = { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint. +If omitted or null, http://localhost:4317 is used. +` }, tls: { $ref: "#/$defs/GrpcTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` } } }; + var schema43 = { type: ["object", "null"], additionalProperties: false, properties: { ca_file: { type: ["string", "null"], description: `Configure certificate used to verify a server's TLS credentials. +Absolute path to certificate file in PEM format. +If omitted or null, system default certificate verification is used for secure connections. +` }, key_file: { type: ["string", "null"], description: `Configure mTLS private client key. +Absolute path to client key file in PEM format. If set, .client_certificate must also be set. +If omitted or null, mTLS is not used. +` }, cert_file: { type: ["string", "null"], description: `Configure mTLS client certificate. +Absolute path to client certificate file in PEM format. If set, .client_key must also be set. +If omitted or null, mTLS is not used. +` }, insecure: { type: ["boolean", "null"], description: `Configure client transport security for the exporter's connection. +Only applicable when .endpoint is provided without http or https scheme. Implementations may choose to ignore .insecure. +If omitted or null, false is used. +` } } }; + function validate27(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate27.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate27.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema42.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "endpoint" || key0 === "tls" || key0 === "headers" || key0 === "headers_list" || key0 === "compression" || key0 === "timeout")) { + validate27.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.endpoint !== undefined) { + let data0 = data.endpoint; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate27.errors = [{ instancePath: instancePath + "/endpoint", schemaPath: "#/properties/endpoint/type", keyword: "type", params: { type: schema42.properties.endpoint.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.tls !== undefined) { + let data1 = data.tls; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate27.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/GrpcTls/type", keyword: "type", params: { type: schema43.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + const _errs7 = errors; + for (const key1 in data1) { + if (!(key1 === "ca_file" || key1 === "key_file" || key1 === "cert_file" || key1 === "insecure")) { + validate27.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/GrpcTls/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs7 === errors) { + if (data1.ca_file !== undefined) { + let data2 = data1.ca_file; + const _errs8 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate27.errors = [{ instancePath: instancePath + "/tls/ca_file", schemaPath: "#/$defs/GrpcTls/properties/ca_file/type", keyword: "type", params: { type: schema43.properties.ca_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.key_file !== undefined) { + let data3 = data1.key_file; + const _errs10 = errors; + if (typeof data3 !== "string" && data3 !== null) { + validate27.errors = [{ instancePath: instancePath + "/tls/key_file", schemaPath: "#/$defs/GrpcTls/properties/key_file/type", keyword: "type", params: { type: schema43.properties.key_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.cert_file !== undefined) { + let data4 = data1.cert_file; + const _errs12 = errors; + if (typeof data4 !== "string" && data4 !== null) { + validate27.errors = [{ instancePath: instancePath + "/tls/cert_file", schemaPath: "#/$defs/GrpcTls/properties/cert_file/type", keyword: "type", params: { type: schema43.properties.cert_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs12 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.insecure !== undefined) { + let data5 = data1.insecure; + const _errs14 = errors; + if (typeof data5 !== "boolean" && data5 !== null) { + validate27.errors = [{ instancePath: instancePath + "/tls/insecure", schemaPath: "#/$defs/GrpcTls/properties/insecure/type", keyword: "type", params: { type: schema43.properties.insecure.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs14 === errors; + } else { + var valid2 = true; + } + } + } + } + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers !== undefined) { + let data6 = data.headers; + const _errs16 = errors; + if (errors === _errs16) { + if (Array.isArray(data6)) { + if (data6.length < 1) { + validate27.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data6.length; + for (let i0 = 0;i0 < len0; i0++) { + let data7 = data6[i0]; + const _errs18 = errors; + const _errs19 = errors; + if (errors === _errs19) { + if (data7 && typeof data7 == "object" && !Array.isArray(data7)) { + let missing0; + if (data7.name === undefined && (missing0 = "name") || data7.value === undefined && (missing0 = "value")) { + validate27.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs21 = errors; + for (const key2 in data7) { + if (!(key2 === "name" || key2 === "value")) { + validate27.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs21 === errors) { + if (data7.name !== undefined) { + const _errs22 = errors; + if (typeof data7.name !== "string") { + validate27.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/name", schemaPath: "#/$defs/NameStringValuePair/properties/name/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid5 = _errs22 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data7.value !== undefined) { + let data9 = data7.value; + const _errs24 = errors; + if (typeof data9 !== "string" && data9 !== null) { + validate27.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/value", schemaPath: "#/$defs/NameStringValuePair/properties/value/type", keyword: "type", params: { type: schema40.properties.value.type }, message: "must be string,null" }]; + return false; + } + var valid5 = _errs24 === errors; + } else { + var valid5 = true; + } + } + } + } + } else { + validate27.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid3 = _errs18 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate27.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs16 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers_list !== undefined) { + let data10 = data.headers_list; + const _errs26 = errors; + if (typeof data10 !== "string" && data10 !== null) { + validate27.errors = [{ instancePath: instancePath + "/headers_list", schemaPath: "#/properties/headers_list/type", keyword: "type", params: { type: schema42.properties.headers_list.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs26 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.compression !== undefined) { + let data11 = data.compression; + const _errs28 = errors; + if (typeof data11 !== "string" && data11 !== null) { + validate27.errors = [{ instancePath: instancePath + "/compression", schemaPath: "#/properties/compression/type", keyword: "type", params: { type: schema42.properties.compression.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs28 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.timeout !== undefined) { + let data12 = data.timeout; + const _errs30 = errors; + if (!(typeof data12 == "number" && (!(data12 % 1) && !isNaN(data12))) && data12 !== null) { + validate27.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/type", keyword: "type", params: { type: schema42.properties.timeout.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs30) { + if (typeof data12 == "number") { + if (data12 < 0 || isNaN(data12)) { + validate27.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs30 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + validate27.errors = vErrors; + return errors === 0; + } + validate27.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate24(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate24.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate24.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate24.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "otlp_http" || key0 === "otlp_grpc" || key0 === "otlp_file/development" || key0 === "console")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate24.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema37.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.otlp_http !== undefined) { + const _errs4 = errors; + if (!validate25(data.otlp_http, { instancePath: instancePath + "/otlp_http", parentData: data, parentDataProperty: "otlp_http", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate25.errors : vErrors.concat(validate25.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.otlp_grpc !== undefined) { + const _errs5 = errors; + if (!validate27(data.otlp_grpc, { instancePath: instancePath + "/otlp_grpc", parentData: data, parentDataProperty: "otlp_grpc", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate27.errors : vErrors.concat(validate27.errors); + errors = vErrors.length; + } + var valid1 = _errs5 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data["otlp_file/development"] !== undefined) { + let data3 = data["otlp_file/development"]; + const _errs6 = errors; + const _errs7 = errors; + if (!(data3 && typeof data3 == "object" && !Array.isArray(data3)) && data3 !== null) { + validate24.errors = [{ instancePath: instancePath + "/otlp_file~1development", schemaPath: "#/$defs/ExperimentalOtlpFileExporter/type", keyword: "type", params: { type: schema45.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs7) { + if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { + const _errs9 = errors; + for (const key1 in data3) { + if (!(key1 === "output_stream")) { + validate24.errors = [{ instancePath: instancePath + "/otlp_file~1development", schemaPath: "#/$defs/ExperimentalOtlpFileExporter/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs9 === errors) { + if (data3.output_stream !== undefined) { + let data4 = data3.output_stream; + if (typeof data4 !== "string" && data4 !== null) { + validate24.errors = [{ instancePath: instancePath + "/otlp_file~1development/output_stream", schemaPath: "#/$defs/ExperimentalOtlpFileExporter/properties/output_stream/type", keyword: "type", params: { type: schema45.properties.output_stream.type }, message: "must be string,null" }]; + return false; + } + } + } + } + } + var valid1 = _errs6 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.console !== undefined) { + let data5 = data.console; + const _errs12 = errors; + const _errs13 = errors; + if (!(data5 && typeof data5 == "object" && !Array.isArray(data5)) && data5 !== null) { + validate24.errors = [{ instancePath: instancePath + "/console", schemaPath: "#/$defs/ConsoleExporter/type", keyword: "type", params: { type: schema46.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs13) { + if (data5 && typeof data5 == "object" && !Array.isArray(data5)) { + for (const key2 in data5) { + validate24.errors = [{ instancePath: instancePath + "/console", schemaPath: "#/$defs/ConsoleExporter/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs12 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } else { + validate24.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate24.errors = vErrors; + return errors === 0; + } + validate24.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate23(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate23.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.exporter === undefined && (missing0 = "exporter")) { + validate23.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "schedule_delay" || key0 === "export_timeout" || key0 === "max_queue_size" || key0 === "max_export_batch_size" || key0 === "exporter")) { + validate23.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.schedule_delay !== undefined) { + let data0 = data.schedule_delay; + const _errs2 = errors; + if (!(typeof data0 == "number" && (!(data0 % 1) && !isNaN(data0))) && data0 !== null) { + validate23.errors = [{ instancePath: instancePath + "/schedule_delay", schemaPath: "#/properties/schedule_delay/type", keyword: "type", params: { type: schema36.properties.schedule_delay.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs2) { + if (typeof data0 == "number") { + if (data0 < 0 || isNaN(data0)) { + validate23.errors = [{ instancePath: instancePath + "/schedule_delay", schemaPath: "#/properties/schedule_delay/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.export_timeout !== undefined) { + let data1 = data.export_timeout; + const _errs4 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate23.errors = [{ instancePath: instancePath + "/export_timeout", schemaPath: "#/properties/export_timeout/type", keyword: "type", params: { type: schema36.properties.export_timeout.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs4) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate23.errors = [{ instancePath: instancePath + "/export_timeout", schemaPath: "#/properties/export_timeout/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.max_queue_size !== undefined) { + let data2 = data.max_queue_size; + const _errs6 = errors; + if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2))) && data2 !== null) { + validate23.errors = [{ instancePath: instancePath + "/max_queue_size", schemaPath: "#/properties/max_queue_size/type", keyword: "type", params: { type: schema36.properties.max_queue_size.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data2 == "number") { + if (data2 <= 0 || isNaN(data2)) { + validate23.errors = [{ instancePath: instancePath + "/max_queue_size", schemaPath: "#/properties/max_queue_size/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.max_export_batch_size !== undefined) { + let data3 = data.max_export_batch_size; + const _errs8 = errors; + if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3))) && data3 !== null) { + validate23.errors = [{ instancePath: instancePath + "/max_export_batch_size", schemaPath: "#/properties/max_export_batch_size/type", keyword: "type", params: { type: schema36.properties.max_export_batch_size.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs8) { + if (typeof data3 == "number") { + if (data3 <= 0 || isNaN(data3)) { + validate23.errors = [{ instancePath: instancePath + "/max_export_batch_size", schemaPath: "#/properties/max_export_batch_size/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.exporter !== undefined) { + const _errs10 = errors; + if (!validate24(data.exporter, { instancePath: instancePath + "/exporter", parentData: data, parentDataProperty: "exporter", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate24.errors : vErrors.concat(validate24.errors); + errors = vErrors.length; + } + var valid0 = _errs10 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } else { + validate23.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate23.errors = vErrors; + return errors === 0; + } + validate23.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate31(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate31.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.exporter === undefined && (missing0 = "exporter")) { + validate31.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "exporter")) { + validate31.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.exporter !== undefined) { + if (!validate24(data.exporter, { instancePath: instancePath + "/exporter", parentData: data, parentDataProperty: "exporter", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate24.errors : vErrors.concat(validate24.errors); + errors = vErrors.length; + } + } + } + } + } else { + validate31.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate31.errors = vErrors; + return errors === 0; + } + validate31.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate22(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate22.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate22.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate22.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "batch" || key0 === "simple")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate22.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema35.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.batch !== undefined) { + const _errs4 = errors; + if (!validate23(data.batch, { instancePath: instancePath + "/batch", parentData: data, parentDataProperty: "batch", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate23.errors : vErrors.concat(validate23.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.simple !== undefined) { + const _errs5 = errors; + if (!validate31(data.simple, { instancePath: instancePath + "/simple", parentData: data, parentDataProperty: "simple", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate31.errors : vErrors.concat(validate31.errors); + errors = vErrors.length; + } + var valid1 = _errs5 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } else { + validate22.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate22.errors = vErrors; + return errors === 0; + } + validate22.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema49 = { type: ["object"], additionalProperties: false, properties: { default_config: { $ref: "#/$defs/ExperimentalLoggerConfig", description: `Configure the default logger config used there is no matching entry in .logger_configurator/development.loggers. +If omitted, unmatched .loggers use default values as described in ExperimentalLoggerConfig. +` }, loggers: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalLoggerMatcherAndConfig" }, description: `Configure loggers. +If omitted, all loggers use .default_config. +` } } }; + var schema50 = { type: ["object"], additionalProperties: false, properties: { enabled: { type: ["boolean", "null"], description: `Configure if the logger is enabled or not. +If omitted or null, true is used. +` }, minimum_severity: { $ref: "#/$defs/SeverityNumber", description: `Configure severity filtering. +Log records with an non-zero (i.e. unspecified) severity number which is less than minimum_severity are not processed. +Values include: +* debug: debug, severity number 5. +* debug2: debug2, severity number 6. +* debug3: debug3, severity number 7. +* debug4: debug4, severity number 8. +* error: error, severity number 17. +* error2: error2, severity number 18. +* error3: error3, severity number 19. +* error4: error4, severity number 20. +* fatal: fatal, severity number 21. +* fatal2: fatal2, severity number 22. +* fatal3: fatal3, severity number 23. +* fatal4: fatal4, severity number 24. +* info: info, severity number 9. +* info2: info2, severity number 10. +* info3: info3, severity number 11. +* info4: info4, severity number 12. +* trace: trace, severity number 1. +* trace2: trace2, severity number 2. +* trace3: trace3, severity number 3. +* trace4: trace4, severity number 4. +* warn: warn, severity number 13. +* warn2: warn2, severity number 14. +* warn3: warn3, severity number 15. +* warn4: warn4, severity number 16. +If omitted, severity filtering is not applied. +` }, trace_based: { type: ["boolean", "null"], description: `Configure trace based filtering. +If true, log records associated with unsampled trace contexts traces are not processed. If false, or if a log record is not associated with a trace context, trace based filtering is not applied. +If omitted or null, trace based filtering is not applied. +` } } }; + function validate36(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate36.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "enabled" || key0 === "minimum_severity" || key0 === "trace_based")) { + validate36.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.enabled !== undefined) { + let data0 = data.enabled; + const _errs2 = errors; + if (typeof data0 !== "boolean" && data0 !== null) { + validate36.errors = [{ instancePath: instancePath + "/enabled", schemaPath: "#/properties/enabled/type", keyword: "type", params: { type: schema50.properties.enabled.type }, message: "must be boolean,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.minimum_severity !== undefined) { + let data1 = data.minimum_severity; + const _errs4 = errors; + if (typeof data1 !== "string" && data1 !== null) { + validate36.errors = [{ instancePath: instancePath + "/minimum_severity", schemaPath: "#/$defs/SeverityNumber/type", keyword: "type", params: { type: schema32.type }, message: "must be string,null" }]; + return false; + } + if (!(data1 === "trace" || data1 === "trace2" || data1 === "trace3" || data1 === "trace4" || data1 === "debug" || data1 === "debug2" || data1 === "debug3" || data1 === "debug4" || data1 === "info" || data1 === "info2" || data1 === "info3" || data1 === "info4" || data1 === "warn" || data1 === "warn2" || data1 === "warn3" || data1 === "warn4" || data1 === "error" || data1 === "error2" || data1 === "error3" || data1 === "error4" || data1 === "fatal" || data1 === "fatal2" || data1 === "fatal3" || data1 === "fatal4")) { + validate36.errors = [{ instancePath: instancePath + "/minimum_severity", schemaPath: "#/$defs/SeverityNumber/enum", keyword: "enum", params: { allowedValues: schema32.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.trace_based !== undefined) { + let data2 = data.trace_based; + const _errs7 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate36.errors = [{ instancePath: instancePath + "/trace_based", schemaPath: "#/properties/trace_based/type", keyword: "type", params: { type: schema50.properties.trace_based.type }, message: "must be boolean,null" }]; + return false; + } + var valid0 = _errs7 === errors; + } else { + var valid0 = true; + } + } + } + } + } else { + validate36.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema50.type }, message: "must be object" }]; + return false; + } + } + validate36.errors = vErrors; + return errors === 0; + } + validate36.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema52 = { type: ["object"], additionalProperties: false, properties: { name: { type: ["string"], description: `Configure logger names to match, evaluated as follows: + + * If the logger name exactly matches. + * If the logger name matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +Property is required and must be non-null. +` }, config: { $ref: "#/$defs/ExperimentalLoggerConfig", description: `The logger config. +Property is required and must be non-null. +` } }, required: ["name", "config"] }; + function validate38(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate38.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.name === undefined && (missing0 = "name") || data.config === undefined && (missing0 = "config")) { + validate38.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "name" || key0 === "config")) { + validate38.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.name !== undefined) { + const _errs2 = errors; + if (typeof data.name !== "string") { + validate38.errors = [{ instancePath: instancePath + "/name", schemaPath: "#/properties/name/type", keyword: "type", params: { type: schema52.properties.name.type }, message: "must be string" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.config !== undefined) { + const _errs4 = errors; + if (!validate36(data.config, { instancePath: instancePath + "/config", parentData: data, parentDataProperty: "config", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate36.errors : vErrors.concat(validate36.errors); + errors = vErrors.length; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + } + } + } + } else { + validate38.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema52.type }, message: "must be object" }]; + return false; + } + } + validate38.errors = vErrors; + return errors === 0; + } + validate38.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate35(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate35.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "default_config" || key0 === "loggers")) { + validate35.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.default_config !== undefined) { + const _errs2 = errors; + if (!validate36(data.default_config, { instancePath: instancePath + "/default_config", parentData: data, parentDataProperty: "default_config", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate36.errors : vErrors.concat(validate36.errors); + errors = vErrors.length; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.loggers !== undefined) { + let data1 = data.loggers; + const _errs3 = errors; + if (errors === _errs3) { + if (Array.isArray(data1)) { + if (data1.length < 1) { + validate35.errors = [{ instancePath: instancePath + "/loggers", schemaPath: "#/properties/loggers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data1.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs5 = errors; + if (!validate38(data1[i0], { instancePath: instancePath + "/loggers/" + i0, parentData: data1, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate38.errors : vErrors.concat(validate38.errors); + errors = vErrors.length; + } + var valid1 = _errs5 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate35.errors = [{ instancePath: instancePath + "/loggers", schemaPath: "#/properties/loggers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + } + } + } else { + validate35.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema49.type }, message: "must be object" }]; + return false; + } + } + validate35.errors = vErrors; + return errors === 0; + } + validate35.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate21(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate21.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.processors === undefined && (missing0 = "processors")) { + validate21.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "processors" || key0 === "limits" || key0 === "logger_configurator/development")) { + validate21.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.processors !== undefined) { + let data0 = data.processors; + const _errs2 = errors; + if (errors === _errs2) { + if (Array.isArray(data0)) { + if (data0.length < 1) { + validate21.errors = [{ instancePath: instancePath + "/processors", schemaPath: "#/properties/processors/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data0.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs4 = errors; + if (!validate22(data0[i0], { instancePath: instancePath + "/processors/" + i0, parentData: data0, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate22.errors : vErrors.concat(validate22.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate21.errors = [{ instancePath: instancePath + "/processors", schemaPath: "#/properties/processors/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.limits !== undefined) { + let data2 = data.limits; + const _errs5 = errors; + const _errs6 = errors; + if (errors === _errs6) { + if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { + const _errs8 = errors; + for (const key1 in data2) { + if (!(key1 === "attribute_value_length_limit" || key1 === "attribute_count_limit")) { + validate21.errors = [{ instancePath: instancePath + "/limits", schemaPath: "#/$defs/LogRecordLimits/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs8 === errors) { + if (data2.attribute_value_length_limit !== undefined) { + let data3 = data2.attribute_value_length_limit; + const _errs9 = errors; + if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3))) && data3 !== null) { + validate21.errors = [{ instancePath: instancePath + "/limits/attribute_value_length_limit", schemaPath: "#/$defs/LogRecordLimits/properties/attribute_value_length_limit/type", keyword: "type", params: { type: schema48.properties.attribute_value_length_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs9) { + if (typeof data3 == "number") { + if (data3 < 0 || isNaN(data3)) { + validate21.errors = [{ instancePath: instancePath + "/limits/attribute_value_length_limit", schemaPath: "#/$defs/LogRecordLimits/properties/attribute_value_length_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs9 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data2.attribute_count_limit !== undefined) { + let data4 = data2.attribute_count_limit; + const _errs11 = errors; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4))) && data4 !== null) { + validate21.errors = [{ instancePath: instancePath + "/limits/attribute_count_limit", schemaPath: "#/$defs/LogRecordLimits/properties/attribute_count_limit/type", keyword: "type", params: { type: schema48.properties.attribute_count_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs11) { + if (typeof data4 == "number") { + if (data4 < 0 || isNaN(data4)) { + validate21.errors = [{ instancePath: instancePath + "/limits/attribute_count_limit", schemaPath: "#/$defs/LogRecordLimits/properties/attribute_count_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs11 === errors; + } else { + var valid3 = true; + } + } + } + } else { + validate21.errors = [{ instancePath: instancePath + "/limits", schemaPath: "#/$defs/LogRecordLimits/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data["logger_configurator/development"] !== undefined) { + const _errs13 = errors; + if (!validate35(data["logger_configurator/development"], { instancePath: instancePath + "/logger_configurator~1development", parentData: data, parentDataProperty: "logger_configurator/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate35.errors : vErrors.concat(validate35.errors); + errors = vErrors.length; + } + var valid0 = _errs13 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } else { + validate21.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate21.errors = vErrors; + return errors === 0; + } + validate21.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema95 = { type: ["string", "null"], enum: ["always_on", "always_off", "trace_based"] }; + var schema55 = { type: "object", additionalProperties: false, properties: { interval: { type: ["integer", "null"], minimum: 0, description: `Configure delay interval (in milliseconds) between start of two consecutive exports. +Value must be non-negative. +If omitted or null, 60000 is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure maximum allowed time (in milliseconds) to export data. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 30000 is used. +` }, exporter: { $ref: "#/$defs/PushMetricExporter", description: `Configure exporter. +Property is required and must be non-null. +` }, producers: { type: "array", minItems: 1, items: { $ref: "#/$defs/MetricProducer" }, description: `Configure metric producers. +If omitted, no metric producers are added. +` }, cardinality_limits: { $ref: "#/$defs/CardinalityLimits", description: `Configure cardinality limits. +If omitted, default values as described in CardinalityLimits are used. +` } }, required: ["exporter"] }; + var schema76 = { type: "object", additionalProperties: false, properties: { default: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for all instrument types. +Instrument-specific cardinality limits take priority. +If omitted or null, 2000 is used. +` }, counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for counter instruments. +If omitted or null, the value from .default is used. +` }, gauge: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for gauge instruments. +If omitted or null, the value from .default is used. +` }, histogram: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for histogram instruments. +If omitted or null, the value from .default is used. +` }, observable_counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for observable_counter instruments. +If omitted or null, the value from .default is used. +` }, observable_gauge: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for observable_gauge instruments. +If omitted or null, the value from .default is used. +` }, observable_up_down_counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for observable_up_down_counter instruments. +If omitted or null, the value from .default is used. +` }, up_down_counter: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure default cardinality limit for up_down_counter instruments. +If omitted or null, the value from .default is used. +` } } }; + var schema56 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { otlp_http: { $ref: "#/$defs/OtlpHttpMetricExporter", description: `Configure exporter to be OTLP with HTTP transport. +If omitted, ignore. +` }, otlp_grpc: { $ref: "#/$defs/OtlpGrpcMetricExporter", description: `Configure exporter to be OTLP with gRPC transport. +If omitted, ignore. +` }, "otlp_file/development": { $ref: "#/$defs/ExperimentalOtlpFileMetricExporter", description: `Configure exporter to be OTLP with file transport. +If omitted, ignore. +` }, console: { $ref: "#/$defs/ConsoleMetricExporter", description: `Configure exporter to be console. +If omitted, ignore. +` } } }; + var schema57 = { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint. +If omitted or null, http://localhost:4318/v1/metrics is used. +` }, tls: { $ref: "#/$defs/HttpTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` }, encoding: { $ref: "#/$defs/OtlpHttpEncoding", description: `Configure the encoding used for messages. +Implementations may not support json. +Values include: +* json: Protobuf JSON encoding. +* protobuf: Protobuf binary encoding. +If omitted, protobuf is used. +` }, temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }; + var schema61 = { type: ["string", "null"], enum: ["cumulative", "delta", "low_memory"] }; + var schema62 = { type: ["string", "null"], enum: ["explicit_bucket_histogram", "base2_exponential_bucket_histogram"] }; + var func1 = Object.prototype.hasOwnProperty; + function validate47(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate47.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate47.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema57.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!func1.call(schema57.properties, key0)) { + validate47.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.endpoint !== undefined) { + let data0 = data.endpoint; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate47.errors = [{ instancePath: instancePath + "/endpoint", schemaPath: "#/properties/endpoint/type", keyword: "type", params: { type: schema57.properties.endpoint.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.tls !== undefined) { + let data1 = data.tls; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate47.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/HttpTls/type", keyword: "type", params: { type: schema39.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + const _errs7 = errors; + for (const key1 in data1) { + if (!(key1 === "ca_file" || key1 === "key_file" || key1 === "cert_file")) { + validate47.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/HttpTls/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs7 === errors) { + if (data1.ca_file !== undefined) { + let data2 = data1.ca_file; + const _errs8 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate47.errors = [{ instancePath: instancePath + "/tls/ca_file", schemaPath: "#/$defs/HttpTls/properties/ca_file/type", keyword: "type", params: { type: schema39.properties.ca_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.key_file !== undefined) { + let data3 = data1.key_file; + const _errs10 = errors; + if (typeof data3 !== "string" && data3 !== null) { + validate47.errors = [{ instancePath: instancePath + "/tls/key_file", schemaPath: "#/$defs/HttpTls/properties/key_file/type", keyword: "type", params: { type: schema39.properties.key_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.cert_file !== undefined) { + let data4 = data1.cert_file; + const _errs12 = errors; + if (typeof data4 !== "string" && data4 !== null) { + validate47.errors = [{ instancePath: instancePath + "/tls/cert_file", schemaPath: "#/$defs/HttpTls/properties/cert_file/type", keyword: "type", params: { type: schema39.properties.cert_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs12 === errors; + } else { + var valid2 = true; + } + } + } + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers !== undefined) { + let data5 = data.headers; + const _errs14 = errors; + if (errors === _errs14) { + if (Array.isArray(data5)) { + if (data5.length < 1) { + validate47.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data5.length; + for (let i0 = 0;i0 < len0; i0++) { + let data6 = data5[i0]; + const _errs16 = errors; + const _errs17 = errors; + if (errors === _errs17) { + if (data6 && typeof data6 == "object" && !Array.isArray(data6)) { + let missing0; + if (data6.name === undefined && (missing0 = "name") || data6.value === undefined && (missing0 = "value")) { + validate47.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs19 = errors; + for (const key2 in data6) { + if (!(key2 === "name" || key2 === "value")) { + validate47.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs19 === errors) { + if (data6.name !== undefined) { + const _errs20 = errors; + if (typeof data6.name !== "string") { + validate47.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/name", schemaPath: "#/$defs/NameStringValuePair/properties/name/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid5 = _errs20 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data6.value !== undefined) { + let data8 = data6.value; + const _errs22 = errors; + if (typeof data8 !== "string" && data8 !== null) { + validate47.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/value", schemaPath: "#/$defs/NameStringValuePair/properties/value/type", keyword: "type", params: { type: schema40.properties.value.type }, message: "must be string,null" }]; + return false; + } + var valid5 = _errs22 === errors; + } else { + var valid5 = true; + } + } + } + } + } else { + validate47.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid3 = _errs16 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate47.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs14 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers_list !== undefined) { + let data9 = data.headers_list; + const _errs24 = errors; + if (typeof data9 !== "string" && data9 !== null) { + validate47.errors = [{ instancePath: instancePath + "/headers_list", schemaPath: "#/properties/headers_list/type", keyword: "type", params: { type: schema57.properties.headers_list.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs24 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.compression !== undefined) { + let data10 = data.compression; + const _errs26 = errors; + if (typeof data10 !== "string" && data10 !== null) { + validate47.errors = [{ instancePath: instancePath + "/compression", schemaPath: "#/properties/compression/type", keyword: "type", params: { type: schema57.properties.compression.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs26 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.timeout !== undefined) { + let data11 = data.timeout; + const _errs28 = errors; + if (!(typeof data11 == "number" && (!(data11 % 1) && !isNaN(data11))) && data11 !== null) { + validate47.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/type", keyword: "type", params: { type: schema57.properties.timeout.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs28) { + if (typeof data11 == "number") { + if (data11 < 0 || isNaN(data11)) { + validate47.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs28 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.encoding !== undefined) { + let data12 = data.encoding; + const _errs30 = errors; + if (typeof data12 !== "string" && data12 !== null) { + validate47.errors = [{ instancePath: instancePath + "/encoding", schemaPath: "#/$defs/OtlpHttpEncoding/type", keyword: "type", params: { type: schema41.type }, message: "must be string,null" }]; + return false; + } + if (!(data12 === "protobuf" || data12 === "json")) { + validate47.errors = [{ instancePath: instancePath + "/encoding", schemaPath: "#/$defs/OtlpHttpEncoding/enum", keyword: "enum", params: { allowedValues: schema41.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs30 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.temporality_preference !== undefined) { + let data13 = data.temporality_preference; + const _errs33 = errors; + if (typeof data13 !== "string" && data13 !== null) { + validate47.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/type", keyword: "type", params: { type: schema61.type }, message: "must be string,null" }]; + return false; + } + if (!(data13 === "cumulative" || data13 === "delta" || data13 === "low_memory")) { + validate47.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/enum", keyword: "enum", params: { allowedValues: schema61.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs33 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.default_histogram_aggregation !== undefined) { + let data14 = data.default_histogram_aggregation; + const _errs36 = errors; + if (typeof data14 !== "string" && data14 !== null) { + validate47.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/type", keyword: "type", params: { type: schema62.type }, message: "must be string,null" }]; + return false; + } + if (!(data14 === "explicit_bucket_histogram" || data14 === "base2_exponential_bucket_histogram")) { + validate47.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/enum", keyword: "enum", params: { allowedValues: schema62.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs36 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } + } + } + validate47.errors = vErrors; + return errors === 0; + } + validate47.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema63 = { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string", "null"], description: `Configure endpoint. +If omitted or null, http://localhost:4317 is used. +` }, tls: { $ref: "#/$defs/GrpcTls", description: `Configure TLS settings for the exporter. +If omitted, system default TLS settings are used. +` }, headers: { type: "array", minItems: 1, items: { $ref: "#/$defs/NameStringValuePair" }, description: `Configure headers. Entries have higher priority than entries from .headers_list. +If an entry's .value is null, the entry is ignored. +If omitted, no headers are added. +` }, headers_list: { type: ["string", "null"], description: `Configure headers. Entries have lower priority than entries from .headers. +The value is a list of comma separated key-value pairs matching the format of OTEL_EXPORTER_OTLP_HEADERS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options for details. +If omitted or null, no headers are added. +` }, compression: { type: ["string", "null"], description: `Configure compression. +Known values include: gzip, none. Implementations may support other compression algorithms. +If omitted or null, none is used. +` }, timeout: { type: ["integer", "null"], minimum: 0, description: `Configure max time (in milliseconds) to wait for each export. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 10000 is used. +` }, temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }; + function validate49(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate49.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate49.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema63.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "endpoint" || key0 === "tls" || key0 === "headers" || key0 === "headers_list" || key0 === "compression" || key0 === "timeout" || key0 === "temporality_preference" || key0 === "default_histogram_aggregation")) { + validate49.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.endpoint !== undefined) { + let data0 = data.endpoint; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate49.errors = [{ instancePath: instancePath + "/endpoint", schemaPath: "#/properties/endpoint/type", keyword: "type", params: { type: schema63.properties.endpoint.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.tls !== undefined) { + let data1 = data.tls; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate49.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/GrpcTls/type", keyword: "type", params: { type: schema43.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + const _errs7 = errors; + for (const key1 in data1) { + if (!(key1 === "ca_file" || key1 === "key_file" || key1 === "cert_file" || key1 === "insecure")) { + validate49.errors = [{ instancePath: instancePath + "/tls", schemaPath: "#/$defs/GrpcTls/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs7 === errors) { + if (data1.ca_file !== undefined) { + let data2 = data1.ca_file; + const _errs8 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate49.errors = [{ instancePath: instancePath + "/tls/ca_file", schemaPath: "#/$defs/GrpcTls/properties/ca_file/type", keyword: "type", params: { type: schema43.properties.ca_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.key_file !== undefined) { + let data3 = data1.key_file; + const _errs10 = errors; + if (typeof data3 !== "string" && data3 !== null) { + validate49.errors = [{ instancePath: instancePath + "/tls/key_file", schemaPath: "#/$defs/GrpcTls/properties/key_file/type", keyword: "type", params: { type: schema43.properties.key_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.cert_file !== undefined) { + let data4 = data1.cert_file; + const _errs12 = errors; + if (typeof data4 !== "string" && data4 !== null) { + validate49.errors = [{ instancePath: instancePath + "/tls/cert_file", schemaPath: "#/$defs/GrpcTls/properties/cert_file/type", keyword: "type", params: { type: schema43.properties.cert_file.type }, message: "must be string,null" }]; + return false; + } + var valid2 = _errs12 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data1.insecure !== undefined) { + let data5 = data1.insecure; + const _errs14 = errors; + if (typeof data5 !== "boolean" && data5 !== null) { + validate49.errors = [{ instancePath: instancePath + "/tls/insecure", schemaPath: "#/$defs/GrpcTls/properties/insecure/type", keyword: "type", params: { type: schema43.properties.insecure.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs14 === errors; + } else { + var valid2 = true; + } + } + } + } + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers !== undefined) { + let data6 = data.headers; + const _errs16 = errors; + if (errors === _errs16) { + if (Array.isArray(data6)) { + if (data6.length < 1) { + validate49.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data6.length; + for (let i0 = 0;i0 < len0; i0++) { + let data7 = data6[i0]; + const _errs18 = errors; + const _errs19 = errors; + if (errors === _errs19) { + if (data7 && typeof data7 == "object" && !Array.isArray(data7)) { + let missing0; + if (data7.name === undefined && (missing0 = "name") || data7.value === undefined && (missing0 = "value")) { + validate49.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs21 = errors; + for (const key2 in data7) { + if (!(key2 === "name" || key2 === "value")) { + validate49.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs21 === errors) { + if (data7.name !== undefined) { + const _errs22 = errors; + if (typeof data7.name !== "string") { + validate49.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/name", schemaPath: "#/$defs/NameStringValuePair/properties/name/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid5 = _errs22 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data7.value !== undefined) { + let data9 = data7.value; + const _errs24 = errors; + if (typeof data9 !== "string" && data9 !== null) { + validate49.errors = [{ instancePath: instancePath + "/headers/" + i0 + "/value", schemaPath: "#/$defs/NameStringValuePair/properties/value/type", keyword: "type", params: { type: schema40.properties.value.type }, message: "must be string,null" }]; + return false; + } + var valid5 = _errs24 === errors; + } else { + var valid5 = true; + } + } + } + } + } else { + validate49.errors = [{ instancePath: instancePath + "/headers/" + i0, schemaPath: "#/$defs/NameStringValuePair/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid3 = _errs18 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate49.errors = [{ instancePath: instancePath + "/headers", schemaPath: "#/properties/headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs16 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.headers_list !== undefined) { + let data10 = data.headers_list; + const _errs26 = errors; + if (typeof data10 !== "string" && data10 !== null) { + validate49.errors = [{ instancePath: instancePath + "/headers_list", schemaPath: "#/properties/headers_list/type", keyword: "type", params: { type: schema63.properties.headers_list.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs26 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.compression !== undefined) { + let data11 = data.compression; + const _errs28 = errors; + if (typeof data11 !== "string" && data11 !== null) { + validate49.errors = [{ instancePath: instancePath + "/compression", schemaPath: "#/properties/compression/type", keyword: "type", params: { type: schema63.properties.compression.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs28 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.timeout !== undefined) { + let data12 = data.timeout; + const _errs30 = errors; + if (!(typeof data12 == "number" && (!(data12 % 1) && !isNaN(data12))) && data12 !== null) { + validate49.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/type", keyword: "type", params: { type: schema63.properties.timeout.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs30) { + if (typeof data12 == "number") { + if (data12 < 0 || isNaN(data12)) { + validate49.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs30 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.temporality_preference !== undefined) { + let data13 = data.temporality_preference; + const _errs32 = errors; + if (typeof data13 !== "string" && data13 !== null) { + validate49.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/type", keyword: "type", params: { type: schema61.type }, message: "must be string,null" }]; + return false; + } + if (!(data13 === "cumulative" || data13 === "delta" || data13 === "low_memory")) { + validate49.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/enum", keyword: "enum", params: { allowedValues: schema61.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs32 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.default_histogram_aggregation !== undefined) { + let data14 = data.default_histogram_aggregation; + const _errs35 = errors; + if (typeof data14 !== "string" && data14 !== null) { + validate49.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/type", keyword: "type", params: { type: schema62.type }, message: "must be string,null" }]; + return false; + } + if (!(data14 === "explicit_bucket_histogram" || data14 === "base2_exponential_bucket_histogram")) { + validate49.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/enum", keyword: "enum", params: { allowedValues: schema62.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs35 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } + } + validate49.errors = vErrors; + return errors === 0; + } + validate49.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema68 = { type: ["object", "null"], additionalProperties: false, properties: { output_stream: { type: ["string", "null"], description: `Configure output stream. +Values include stdout, or scheme+destination. For example: file:///path/to/file.jsonl. +If omitted or null, stdout is used. +` }, temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }; + function validate51(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate51.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate51.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema68.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "output_stream" || key0 === "temporality_preference" || key0 === "default_histogram_aggregation")) { + validate51.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.output_stream !== undefined) { + let data0 = data.output_stream; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate51.errors = [{ instancePath: instancePath + "/output_stream", schemaPath: "#/properties/output_stream/type", keyword: "type", params: { type: schema68.properties.output_stream.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.temporality_preference !== undefined) { + let data1 = data.temporality_preference; + const _errs4 = errors; + if (typeof data1 !== "string" && data1 !== null) { + validate51.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/type", keyword: "type", params: { type: schema61.type }, message: "must be string,null" }]; + return false; + } + if (!(data1 === "cumulative" || data1 === "delta" || data1 === "low_memory")) { + validate51.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/enum", keyword: "enum", params: { allowedValues: schema61.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.default_histogram_aggregation !== undefined) { + let data2 = data.default_histogram_aggregation; + const _errs7 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate51.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/type", keyword: "type", params: { type: schema62.type }, message: "must be string,null" }]; + return false; + } + if (!(data2 === "explicit_bucket_histogram" || data2 === "base2_exponential_bucket_histogram")) { + validate51.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/enum", keyword: "enum", params: { allowedValues: schema62.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs7 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + validate51.errors = vErrors; + return errors === 0; + } + validate51.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema71 = { type: ["object", "null"], additionalProperties: false, properties: { temporality_preference: { $ref: "#/$defs/ExporterTemporalityPreference", description: `Configure temporality preference. +Values include: +* cumulative: Use cumulative aggregation temporality for all instrument types. +* delta: Use delta aggregation for all instrument types except up down counter and asynchronous up down counter. +* low_memory: Use delta aggregation temporality for counter and histogram instrument types. Use cumulative aggregation temporality for all other instrument types. +If omitted, cumulative is used. +` }, default_histogram_aggregation: { $ref: "#/$defs/ExporterDefaultHistogramAggregation", description: `Configure default histogram aggregation. +Values include: +* base2_exponential_bucket_histogram: Use base2 exponential histogram as the default aggregation for histogram instruments. +* explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for histogram instruments. +If omitted, explicit_bucket_histogram is used. +` } } }; + function validate53(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate53.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate53.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema71.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "temporality_preference" || key0 === "default_histogram_aggregation")) { + validate53.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.temporality_preference !== undefined) { + let data0 = data.temporality_preference; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate53.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/type", keyword: "type", params: { type: schema61.type }, message: "must be string,null" }]; + return false; + } + if (!(data0 === "cumulative" || data0 === "delta" || data0 === "low_memory")) { + validate53.errors = [{ instancePath: instancePath + "/temporality_preference", schemaPath: "#/$defs/ExporterTemporalityPreference/enum", keyword: "enum", params: { allowedValues: schema61.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.default_histogram_aggregation !== undefined) { + let data1 = data.default_histogram_aggregation; + const _errs5 = errors; + if (typeof data1 !== "string" && data1 !== null) { + validate53.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/type", keyword: "type", params: { type: schema62.type }, message: "must be string,null" }]; + return false; + } + if (!(data1 === "explicit_bucket_histogram" || data1 === "base2_exponential_bucket_histogram")) { + validate53.errors = [{ instancePath: instancePath + "/default_histogram_aggregation", schemaPath: "#/$defs/ExporterDefaultHistogramAggregation/enum", keyword: "enum", params: { allowedValues: schema62.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + } + } + } + } + validate53.errors = vErrors; + return errors === 0; + } + validate53.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate46(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate46.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate46.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate46.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "otlp_http" || key0 === "otlp_grpc" || key0 === "otlp_file/development" || key0 === "console")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate46.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema56.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.otlp_http !== undefined) { + const _errs4 = errors; + if (!validate47(data.otlp_http, { instancePath: instancePath + "/otlp_http", parentData: data, parentDataProperty: "otlp_http", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate47.errors : vErrors.concat(validate47.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.otlp_grpc !== undefined) { + const _errs5 = errors; + if (!validate49(data.otlp_grpc, { instancePath: instancePath + "/otlp_grpc", parentData: data, parentDataProperty: "otlp_grpc", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate49.errors : vErrors.concat(validate49.errors); + errors = vErrors.length; + } + var valid1 = _errs5 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data["otlp_file/development"] !== undefined) { + const _errs6 = errors; + if (!validate51(data["otlp_file/development"], { instancePath: instancePath + "/otlp_file~1development", parentData: data, parentDataProperty: "otlp_file/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate51.errors : vErrors.concat(validate51.errors); + errors = vErrors.length; + } + var valid1 = _errs6 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.console !== undefined) { + const _errs7 = errors; + if (!validate53(data.console, { instancePath: instancePath + "/console", parentData: data, parentDataProperty: "console", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate53.errors : vErrors.concat(validate53.errors); + errors = vErrors.length; + } + var valid1 = _errs7 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } else { + validate46.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate46.errors = vErrors; + return errors === 0; + } + validate46.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema74 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { opencensus: { $ref: "#/$defs/OpenCensusMetricProducer", description: `Configure metric producer to be opencensus. +If omitted, ignore. +` } } }; + var schema75 = { type: ["object", "null"], additionalProperties: false }; + function validate56(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate56.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate56.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate56.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "opencensus")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate56.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema74.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.opencensus !== undefined) { + let data1 = data.opencensus; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate56.errors = [{ instancePath: instancePath + "/opencensus", schemaPath: "#/$defs/OpenCensusMetricProducer/type", keyword: "type", params: { type: schema75.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + for (const key1 in data1) { + validate56.errors = [{ instancePath: instancePath + "/opencensus", schemaPath: "#/$defs/OpenCensusMetricProducer/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + } + } + } + } + } else { + validate56.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate56.errors = vErrors; + return errors === 0; + } + validate56.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate45(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate45.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.exporter === undefined && (missing0 = "exporter")) { + validate45.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "interval" || key0 === "timeout" || key0 === "exporter" || key0 === "producers" || key0 === "cardinality_limits")) { + validate45.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.interval !== undefined) { + let data0 = data.interval; + const _errs2 = errors; + if (!(typeof data0 == "number" && (!(data0 % 1) && !isNaN(data0))) && data0 !== null) { + validate45.errors = [{ instancePath: instancePath + "/interval", schemaPath: "#/properties/interval/type", keyword: "type", params: { type: schema55.properties.interval.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs2) { + if (typeof data0 == "number") { + if (data0 < 0 || isNaN(data0)) { + validate45.errors = [{ instancePath: instancePath + "/interval", schemaPath: "#/properties/interval/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.timeout !== undefined) { + let data1 = data.timeout; + const _errs4 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate45.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/type", keyword: "type", params: { type: schema55.properties.timeout.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs4) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate45.errors = [{ instancePath: instancePath + "/timeout", schemaPath: "#/properties/timeout/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.exporter !== undefined) { + const _errs6 = errors; + if (!validate46(data.exporter, { instancePath: instancePath + "/exporter", parentData: data, parentDataProperty: "exporter", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate46.errors : vErrors.concat(validate46.errors); + errors = vErrors.length; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.producers !== undefined) { + let data3 = data.producers; + const _errs7 = errors; + if (errors === _errs7) { + if (Array.isArray(data3)) { + if (data3.length < 1) { + validate45.errors = [{ instancePath: instancePath + "/producers", schemaPath: "#/properties/producers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data3.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs9 = errors; + if (!validate56(data3[i0], { instancePath: instancePath + "/producers/" + i0, parentData: data3, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate56.errors : vErrors.concat(validate56.errors); + errors = vErrors.length; + } + var valid1 = _errs9 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate45.errors = [{ instancePath: instancePath + "/producers", schemaPath: "#/properties/producers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs7 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.cardinality_limits !== undefined) { + let data5 = data.cardinality_limits; + const _errs10 = errors; + const _errs11 = errors; + if (errors === _errs11) { + if (data5 && typeof data5 == "object" && !Array.isArray(data5)) { + const _errs13 = errors; + for (const key1 in data5) { + if (!(key1 === "default" || key1 === "counter" || key1 === "gauge" || key1 === "histogram" || key1 === "observable_counter" || key1 === "observable_gauge" || key1 === "observable_up_down_counter" || key1 === "up_down_counter")) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits", schemaPath: "#/$defs/CardinalityLimits/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs13 === errors) { + if (data5.default !== undefined) { + let data6 = data5.default; + const _errs14 = errors; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6))) && data6 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/default", schemaPath: "#/$defs/CardinalityLimits/properties/default/type", keyword: "type", params: { type: schema76.properties.default.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs14) { + if (typeof data6 == "number") { + if (data6 <= 0 || isNaN(data6)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/default", schemaPath: "#/$defs/CardinalityLimits/properties/default/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs14 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data5.counter !== undefined) { + let data7 = data5.counter; + const _errs16 = errors; + if (!(typeof data7 == "number" && (!(data7 % 1) && !isNaN(data7))) && data7 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/counter", schemaPath: "#/$defs/CardinalityLimits/properties/counter/type", keyword: "type", params: { type: schema76.properties.counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs16) { + if (typeof data7 == "number") { + if (data7 <= 0 || isNaN(data7)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/counter", schemaPath: "#/$defs/CardinalityLimits/properties/counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs16 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data5.gauge !== undefined) { + let data8 = data5.gauge; + const _errs18 = errors; + if (!(typeof data8 == "number" && (!(data8 % 1) && !isNaN(data8))) && data8 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/gauge", schemaPath: "#/$defs/CardinalityLimits/properties/gauge/type", keyword: "type", params: { type: schema76.properties.gauge.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs18) { + if (typeof data8 == "number") { + if (data8 <= 0 || isNaN(data8)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/gauge", schemaPath: "#/$defs/CardinalityLimits/properties/gauge/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs18 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data5.histogram !== undefined) { + let data9 = data5.histogram; + const _errs20 = errors; + if (!(typeof data9 == "number" && (!(data9 % 1) && !isNaN(data9))) && data9 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/histogram", schemaPath: "#/$defs/CardinalityLimits/properties/histogram/type", keyword: "type", params: { type: schema76.properties.histogram.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs20) { + if (typeof data9 == "number") { + if (data9 <= 0 || isNaN(data9)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/histogram", schemaPath: "#/$defs/CardinalityLimits/properties/histogram/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs20 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data5.observable_counter !== undefined) { + let data10 = data5.observable_counter; + const _errs22 = errors; + if (!(typeof data10 == "number" && (!(data10 % 1) && !isNaN(data10))) && data10 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_counter/type", keyword: "type", params: { type: schema76.properties.observable_counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs22) { + if (typeof data10 == "number") { + if (data10 <= 0 || isNaN(data10)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs22 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data5.observable_gauge !== undefined) { + let data11 = data5.observable_gauge; + const _errs24 = errors; + if (!(typeof data11 == "number" && (!(data11 % 1) && !isNaN(data11))) && data11 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_gauge", schemaPath: "#/$defs/CardinalityLimits/properties/observable_gauge/type", keyword: "type", params: { type: schema76.properties.observable_gauge.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs24) { + if (typeof data11 == "number") { + if (data11 <= 0 || isNaN(data11)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_gauge", schemaPath: "#/$defs/CardinalityLimits/properties/observable_gauge/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs24 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data5.observable_up_down_counter !== undefined) { + let data12 = data5.observable_up_down_counter; + const _errs26 = errors; + if (!(typeof data12 == "number" && (!(data12 % 1) && !isNaN(data12))) && data12 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_up_down_counter/type", keyword: "type", params: { type: schema76.properties.observable_up_down_counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs26) { + if (typeof data12 == "number") { + if (data12 <= 0 || isNaN(data12)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_up_down_counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs26 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data5.up_down_counter !== undefined) { + let data13 = data5.up_down_counter; + const _errs28 = errors; + if (!(typeof data13 == "number" && (!(data13 % 1) && !isNaN(data13))) && data13 !== null) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/up_down_counter/type", keyword: "type", params: { type: schema76.properties.up_down_counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs28) { + if (typeof data13 == "number") { + if (data13 <= 0 || isNaN(data13)) { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits/up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/up_down_counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs28 === errors; + } else { + var valid3 = true; + } + } + } + } + } + } + } + } + } + } else { + validate45.errors = [{ instancePath: instancePath + "/cardinality_limits", schemaPath: "#/$defs/CardinalityLimits/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs10 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } else { + validate45.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate45.errors = vErrors; + return errors === 0; + } + validate45.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema78 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { "prometheus/development": { $ref: "#/$defs/ExperimentalPrometheusMetricExporter", description: `Configure exporter to be prometheus. +If omitted, ignore. +` } } }; + var schema79 = { type: ["object", "null"], additionalProperties: false, properties: { host: { type: ["string", "null"], description: `Configure host. +If omitted or null, localhost is used. +` }, port: { type: ["integer", "null"], description: `Configure port. +If omitted or null, 9464 is used. +` }, without_scope_info: { type: ["boolean", "null"], description: `Configure Prometheus Exporter to produce metrics without scope labels. +If omitted or null, false is used. +` }, "without_target_info/development": { type: ["boolean", "null"], description: `Configure Prometheus Exporter to produce metrics without a target info metric for the resource. +If omitted or null, false is used. +` }, with_resource_constant_labels: { $ref: "#/$defs/IncludeExclude", description: `Configure Prometheus Exporter to add resource attributes as metrics attributes, where the resource attribute keys match the patterns. +If omitted, no resource attributes are added. +` }, translation_strategy: { $ref: "#/$defs/ExperimentalPrometheusTranslationStrategy", description: `Configure how metric names are translated to Prometheus metric names. +Values include: +* no_translation/development: Special character escaping is disabled. Type and unit suffixes are disabled. Metric names are unaltered. +* no_utf8_escaping_with_suffixes/development: Special character escaping is disabled. Type and unit suffixes are enabled. +* underscore_escaping_with_suffixes: Special character escaping is enabled. Type and unit suffixes are enabled. +* underscore_escaping_without_suffixes/development: Special character escaping is enabled. Type and unit suffixes are disabled. This represents classic Prometheus metric name compatibility. +If omitted, underscore_escaping_with_suffixes is used. +` } } }; + var schema81 = { type: ["string", "null"], enum: ["underscore_escaping_with_suffixes", "underscore_escaping_without_suffixes/development", "no_utf8_escaping_with_suffixes/development", "no_translation/development"] }; + function validate61(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate61.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate61.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema79.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "host" || key0 === "port" || key0 === "without_scope_info" || key0 === "without_target_info/development" || key0 === "with_resource_constant_labels" || key0 === "translation_strategy")) { + validate61.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.host !== undefined) { + let data0 = data.host; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate61.errors = [{ instancePath: instancePath + "/host", schemaPath: "#/properties/host/type", keyword: "type", params: { type: schema79.properties.host.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.port !== undefined) { + let data1 = data.port; + const _errs4 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate61.errors = [{ instancePath: instancePath + "/port", schemaPath: "#/properties/port/type", keyword: "type", params: { type: schema79.properties.port.type }, message: "must be integer,null" }]; + return false; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.without_scope_info !== undefined) { + let data2 = data.without_scope_info; + const _errs6 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate61.errors = [{ instancePath: instancePath + "/without_scope_info", schemaPath: "#/properties/without_scope_info/type", keyword: "type", params: { type: schema79.properties.without_scope_info.type }, message: "must be boolean,null" }]; + return false; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data["without_target_info/development"] !== undefined) { + let data3 = data["without_target_info/development"]; + const _errs8 = errors; + if (typeof data3 !== "boolean" && data3 !== null) { + validate61.errors = [{ instancePath: instancePath + "/without_target_info~1development", schemaPath: "#/properties/without_target_info~1development/type", keyword: "type", params: { type: schema79.properties["without_target_info/development"].type }, message: "must be boolean,null" }]; + return false; + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.with_resource_constant_labels !== undefined) { + let data4 = data.with_resource_constant_labels; + const _errs10 = errors; + const _errs11 = errors; + if (errors === _errs11) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + const _errs13 = errors; + for (const key1 in data4) { + if (!(key1 === "included" || key1 === "excluded")) { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels", schemaPath: "#/$defs/IncludeExclude/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs13 === errors) { + if (data4.included !== undefined) { + let data5 = data4.included; + const _errs14 = errors; + if (errors === _errs14) { + if (Array.isArray(data5)) { + if (data5.length < 1) { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels/included", schemaPath: "#/$defs/IncludeExclude/properties/included/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data5.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs16 = errors; + if (typeof data5[i0] !== "string") { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels/included/" + i0, schemaPath: "#/$defs/IncludeExclude/properties/included/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid3 = _errs16 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels/included", schemaPath: "#/$defs/IncludeExclude/properties/included/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid2 = _errs14 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data4.excluded !== undefined) { + let data7 = data4.excluded; + const _errs18 = errors; + if (errors === _errs18) { + if (Array.isArray(data7)) { + if (data7.length < 1) { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels/excluded", schemaPath: "#/$defs/IncludeExclude/properties/excluded/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid4 = true; + const len1 = data7.length; + for (let i1 = 0;i1 < len1; i1++) { + const _errs20 = errors; + if (typeof data7[i1] !== "string") { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels/excluded/" + i1, schemaPath: "#/$defs/IncludeExclude/properties/excluded/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid4 = _errs20 === errors; + if (!valid4) { + break; + } + } + } + } else { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels/excluded", schemaPath: "#/$defs/IncludeExclude/properties/excluded/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid2 = _errs18 === errors; + } else { + var valid2 = true; + } + } + } + } else { + validate61.errors = [{ instancePath: instancePath + "/with_resource_constant_labels", schemaPath: "#/$defs/IncludeExclude/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs10 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.translation_strategy !== undefined) { + let data9 = data.translation_strategy; + const _errs22 = errors; + if (typeof data9 !== "string" && data9 !== null) { + validate61.errors = [{ instancePath: instancePath + "/translation_strategy", schemaPath: "#/$defs/ExperimentalPrometheusTranslationStrategy/type", keyword: "type", params: { type: schema81.type }, message: "must be string,null" }]; + return false; + } + if (!(data9 === "underscore_escaping_with_suffixes" || data9 === "underscore_escaping_without_suffixes/development" || data9 === "no_utf8_escaping_with_suffixes/development" || data9 === "no_translation/development")) { + validate61.errors = [{ instancePath: instancePath + "/translation_strategy", schemaPath: "#/$defs/ExperimentalPrometheusTranslationStrategy/enum", keyword: "enum", params: { allowedValues: schema81.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs22 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + validate61.errors = vErrors; + return errors === 0; + } + validate61.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate60(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate60.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate60.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate60.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "prometheus/development")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate60.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema78.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data["prometheus/development"] !== undefined) { + if (!validate61(data["prometheus/development"], { instancePath: instancePath + "/prometheus~1development", parentData: data, parentDataProperty: "prometheus/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate61.errors : vErrors.concat(validate61.errors); + errors = vErrors.length; + } + } + } + } + } + } else { + validate60.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate60.errors = vErrors; + return errors === 0; + } + validate60.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate59(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate59.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.exporter === undefined && (missing0 = "exporter")) { + validate59.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "exporter" || key0 === "producers" || key0 === "cardinality_limits")) { + validate59.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.exporter !== undefined) { + const _errs2 = errors; + if (!validate60(data.exporter, { instancePath: instancePath + "/exporter", parentData: data, parentDataProperty: "exporter", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate60.errors : vErrors.concat(validate60.errors); + errors = vErrors.length; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.producers !== undefined) { + let data1 = data.producers; + const _errs3 = errors; + if (errors === _errs3) { + if (Array.isArray(data1)) { + if (data1.length < 1) { + validate59.errors = [{ instancePath: instancePath + "/producers", schemaPath: "#/properties/producers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data1.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs5 = errors; + if (!validate56(data1[i0], { instancePath: instancePath + "/producers/" + i0, parentData: data1, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate56.errors : vErrors.concat(validate56.errors); + errors = vErrors.length; + } + var valid1 = _errs5 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate59.errors = [{ instancePath: instancePath + "/producers", schemaPath: "#/properties/producers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.cardinality_limits !== undefined) { + let data3 = data.cardinality_limits; + const _errs6 = errors; + const _errs7 = errors; + if (errors === _errs7) { + if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { + const _errs9 = errors; + for (const key1 in data3) { + if (!(key1 === "default" || key1 === "counter" || key1 === "gauge" || key1 === "histogram" || key1 === "observable_counter" || key1 === "observable_gauge" || key1 === "observable_up_down_counter" || key1 === "up_down_counter")) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits", schemaPath: "#/$defs/CardinalityLimits/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs9 === errors) { + if (data3.default !== undefined) { + let data4 = data3.default; + const _errs10 = errors; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4))) && data4 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/default", schemaPath: "#/$defs/CardinalityLimits/properties/default/type", keyword: "type", params: { type: schema76.properties.default.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs10) { + if (typeof data4 == "number") { + if (data4 <= 0 || isNaN(data4)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/default", schemaPath: "#/$defs/CardinalityLimits/properties/default/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs10 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.counter !== undefined) { + let data5 = data3.counter; + const _errs12 = errors; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5))) && data5 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/counter", schemaPath: "#/$defs/CardinalityLimits/properties/counter/type", keyword: "type", params: { type: schema76.properties.counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs12) { + if (typeof data5 == "number") { + if (data5 <= 0 || isNaN(data5)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/counter", schemaPath: "#/$defs/CardinalityLimits/properties/counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs12 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.gauge !== undefined) { + let data6 = data3.gauge; + const _errs14 = errors; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6))) && data6 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/gauge", schemaPath: "#/$defs/CardinalityLimits/properties/gauge/type", keyword: "type", params: { type: schema76.properties.gauge.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs14) { + if (typeof data6 == "number") { + if (data6 <= 0 || isNaN(data6)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/gauge", schemaPath: "#/$defs/CardinalityLimits/properties/gauge/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs14 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.histogram !== undefined) { + let data7 = data3.histogram; + const _errs16 = errors; + if (!(typeof data7 == "number" && (!(data7 % 1) && !isNaN(data7))) && data7 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/histogram", schemaPath: "#/$defs/CardinalityLimits/properties/histogram/type", keyword: "type", params: { type: schema76.properties.histogram.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs16) { + if (typeof data7 == "number") { + if (data7 <= 0 || isNaN(data7)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/histogram", schemaPath: "#/$defs/CardinalityLimits/properties/histogram/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs16 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.observable_counter !== undefined) { + let data8 = data3.observable_counter; + const _errs18 = errors; + if (!(typeof data8 == "number" && (!(data8 % 1) && !isNaN(data8))) && data8 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_counter/type", keyword: "type", params: { type: schema76.properties.observable_counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs18) { + if (typeof data8 == "number") { + if (data8 <= 0 || isNaN(data8)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs18 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.observable_gauge !== undefined) { + let data9 = data3.observable_gauge; + const _errs20 = errors; + if (!(typeof data9 == "number" && (!(data9 % 1) && !isNaN(data9))) && data9 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_gauge", schemaPath: "#/$defs/CardinalityLimits/properties/observable_gauge/type", keyword: "type", params: { type: schema76.properties.observable_gauge.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs20) { + if (typeof data9 == "number") { + if (data9 <= 0 || isNaN(data9)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_gauge", schemaPath: "#/$defs/CardinalityLimits/properties/observable_gauge/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs20 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.observable_up_down_counter !== undefined) { + let data10 = data3.observable_up_down_counter; + const _errs22 = errors; + if (!(typeof data10 == "number" && (!(data10 % 1) && !isNaN(data10))) && data10 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_up_down_counter/type", keyword: "type", params: { type: schema76.properties.observable_up_down_counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs22) { + if (typeof data10 == "number") { + if (data10 <= 0 || isNaN(data10)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/observable_up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/observable_up_down_counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs22 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.up_down_counter !== undefined) { + let data11 = data3.up_down_counter; + const _errs24 = errors; + if (!(typeof data11 == "number" && (!(data11 % 1) && !isNaN(data11))) && data11 !== null) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/up_down_counter/type", keyword: "type", params: { type: schema76.properties.up_down_counter.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs24) { + if (typeof data11 == "number") { + if (data11 <= 0 || isNaN(data11)) { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits/up_down_counter", schemaPath: "#/$defs/CardinalityLimits/properties/up_down_counter/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid3 = _errs24 === errors; + } else { + var valid3 = true; + } + } + } + } + } + } + } + } + } + } else { + validate59.errors = [{ instancePath: instancePath + "/cardinality_limits", schemaPath: "#/$defs/CardinalityLimits/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } else { + validate59.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate59.errors = vErrors; + return errors === 0; + } + validate59.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate44(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate44.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate44.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate44.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "periodic" || key0 === "pull")) { + validate44.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.periodic !== undefined) { + const _errs2 = errors; + if (!validate45(data.periodic, { instancePath: instancePath + "/periodic", parentData: data, parentDataProperty: "periodic", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate45.errors : vErrors.concat(validate45.errors); + errors = vErrors.length; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.pull !== undefined) { + const _errs3 = errors; + if (!validate59(data.pull, { instancePath: instancePath + "/pull", parentData: data, parentDataProperty: "pull", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate59.errors : vErrors.concat(validate59.errors); + errors = vErrors.length; + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } else { + validate44.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate44.errors = vErrors; + return errors === 0; + } + validate44.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema84 = { type: "object", additionalProperties: false, properties: { instrument_name: { type: ["string", "null"], description: `Configure instrument name selection criteria. +If omitted or null, all instrument names match. +` }, instrument_type: { $ref: "#/$defs/InstrumentType", description: `Configure instrument type selection criteria. +Values include: +* counter: Synchronous counter instruments. +* gauge: Synchronous gauge instruments. +* histogram: Synchronous histogram instruments. +* observable_counter: Asynchronous counter instruments. +* observable_gauge: Asynchronous gauge instruments. +* observable_up_down_counter: Asynchronous up down counter instruments. +* up_down_counter: Synchronous up down counter instruments. +If omitted, all instrument types match. +` }, unit: { type: ["string", "null"], description: `Configure the instrument unit selection criteria. +If omitted or null, all instrument units match. +` }, meter_name: { type: ["string", "null"], description: `Configure meter name selection criteria. +If omitted or null, all meter names match. +` }, meter_version: { type: ["string", "null"], description: `Configure meter version selection criteria. +If omitted or null, all meter versions match. +` }, meter_schema_url: { type: ["string", "null"], description: `Configure meter schema url selection criteria. +If omitted or null, all meter schema URLs match. +` } } }; + var schema85 = { type: ["string", "null"], enum: ["counter", "gauge", "histogram", "observable_counter", "observable_gauge", "observable_up_down_counter", "up_down_counter"] }; + function validate68(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate68.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "instrument_name" || key0 === "instrument_type" || key0 === "unit" || key0 === "meter_name" || key0 === "meter_version" || key0 === "meter_schema_url")) { + validate68.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.instrument_name !== undefined) { + let data0 = data.instrument_name; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate68.errors = [{ instancePath: instancePath + "/instrument_name", schemaPath: "#/properties/instrument_name/type", keyword: "type", params: { type: schema84.properties.instrument_name.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.instrument_type !== undefined) { + let data1 = data.instrument_type; + const _errs4 = errors; + if (typeof data1 !== "string" && data1 !== null) { + validate68.errors = [{ instancePath: instancePath + "/instrument_type", schemaPath: "#/$defs/InstrumentType/type", keyword: "type", params: { type: schema85.type }, message: "must be string,null" }]; + return false; + } + if (!(data1 === "counter" || data1 === "gauge" || data1 === "histogram" || data1 === "observable_counter" || data1 === "observable_gauge" || data1 === "observable_up_down_counter" || data1 === "up_down_counter")) { + validate68.errors = [{ instancePath: instancePath + "/instrument_type", schemaPath: "#/$defs/InstrumentType/enum", keyword: "enum", params: { allowedValues: schema85.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.unit !== undefined) { + let data2 = data.unit; + const _errs7 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate68.errors = [{ instancePath: instancePath + "/unit", schemaPath: "#/properties/unit/type", keyword: "type", params: { type: schema84.properties.unit.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs7 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.meter_name !== undefined) { + let data3 = data.meter_name; + const _errs9 = errors; + if (typeof data3 !== "string" && data3 !== null) { + validate68.errors = [{ instancePath: instancePath + "/meter_name", schemaPath: "#/properties/meter_name/type", keyword: "type", params: { type: schema84.properties.meter_name.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs9 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.meter_version !== undefined) { + let data4 = data.meter_version; + const _errs11 = errors; + if (typeof data4 !== "string" && data4 !== null) { + validate68.errors = [{ instancePath: instancePath + "/meter_version", schemaPath: "#/properties/meter_version/type", keyword: "type", params: { type: schema84.properties.meter_version.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs11 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.meter_schema_url !== undefined) { + let data5 = data.meter_schema_url; + const _errs13 = errors; + if (typeof data5 !== "string" && data5 !== null) { + validate68.errors = [{ instancePath: instancePath + "/meter_schema_url", schemaPath: "#/properties/meter_schema_url/type", keyword: "type", params: { type: schema84.properties.meter_schema_url.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs13 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } else { + validate68.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate68.errors = vErrors; + return errors === 0; + } + validate68.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema86 = { type: "object", additionalProperties: false, properties: { name: { type: ["string", "null"], description: `Configure metric name of the resulting stream(s). +If omitted or null, the instrument's original name is used. +` }, description: { type: ["string", "null"], description: `Configure metric description of the resulting stream(s). +If omitted or null, the instrument's origin description is used. +` }, aggregation: { $ref: "#/$defs/Aggregation", description: `Configure aggregation of the resulting stream(s). +If omitted, default is used. +` }, aggregation_cardinality_limit: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure the aggregation cardinality limit. +If omitted or null, the metric reader's default cardinality limit is used. +` }, attribute_keys: { $ref: "#/$defs/IncludeExclude", description: `Configure attribute keys retained in the resulting stream(s). +If omitted, all attribute keys are retained. +` } } }; + var schema88 = { type: ["object", "null"], additionalProperties: false }; + var schema89 = { type: ["object", "null"], additionalProperties: false }; + var schema90 = { type: ["object", "null"], additionalProperties: false, properties: { boundaries: { type: "array", minItems: 0, items: { type: "number" }, description: `Configure bucket boundaries. +If omitted, [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000] is used. +` }, record_min_max: { type: ["boolean", "null"], description: `Configure record min and max. +If omitted or null, true is used. +` } } }; + var schema91 = { type: ["object", "null"], additionalProperties: false, properties: { max_scale: { type: ["integer", "null"], minimum: -10, maximum: 20, description: `Configure the max scale factor. +If omitted or null, 20 is used. +` }, max_size: { type: ["integer", "null"], minimum: 2, description: `Configure the maximum number of buckets in each of the positive and negative ranges, not counting the special zero bucket. +If omitted or null, 160 is used. +` }, record_min_max: { type: ["boolean", "null"], description: `Configure whether or not to record min and max. +If omitted or null, true is used. +` } } }; + var schema92 = { type: ["object", "null"], additionalProperties: false }; + var schema93 = { type: ["object", "null"], additionalProperties: false }; + function validate71(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate71.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate71.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate71.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "default" || key0 === "drop" || key0 === "explicit_bucket_histogram" || key0 === "base2_exponential_bucket_histogram" || key0 === "last_value" || key0 === "sum")) { + validate71.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.default !== undefined) { + let data0 = data.default; + const _errs2 = errors; + const _errs3 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate71.errors = [{ instancePath: instancePath + "/default", schemaPath: "#/$defs/DefaultAggregation/type", keyword: "type", params: { type: schema88.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + for (const key1 in data0) { + validate71.errors = [{ instancePath: instancePath + "/default", schemaPath: "#/$defs/DefaultAggregation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.drop !== undefined) { + let data1 = data.drop; + const _errs6 = errors; + const _errs7 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate71.errors = [{ instancePath: instancePath + "/drop", schemaPath: "#/$defs/DropAggregation/type", keyword: "type", params: { type: schema89.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs7) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + for (const key2 in data1) { + validate71.errors = [{ instancePath: instancePath + "/drop", schemaPath: "#/$defs/DropAggregation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.explicit_bucket_histogram !== undefined) { + let data2 = data.explicit_bucket_histogram; + const _errs10 = errors; + const _errs11 = errors; + if (!(data2 && typeof data2 == "object" && !Array.isArray(data2)) && data2 !== null) { + validate71.errors = [{ instancePath: instancePath + "/explicit_bucket_histogram", schemaPath: "#/$defs/ExplicitBucketHistogramAggregation/type", keyword: "type", params: { type: schema90.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs11) { + if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { + const _errs13 = errors; + for (const key3 in data2) { + if (!(key3 === "boundaries" || key3 === "record_min_max")) { + validate71.errors = [{ instancePath: instancePath + "/explicit_bucket_histogram", schemaPath: "#/$defs/ExplicitBucketHistogramAggregation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs13 === errors) { + if (data2.boundaries !== undefined) { + let data3 = data2.boundaries; + const _errs14 = errors; + if (errors === _errs14) { + if (Array.isArray(data3)) { + if (data3.length < 0) { + validate71.errors = [{ instancePath: instancePath + "/explicit_bucket_histogram/boundaries", schemaPath: "#/$defs/ExplicitBucketHistogramAggregation/properties/boundaries/minItems", keyword: "minItems", params: { limit: 0 }, message: "must NOT have fewer than 0 items" }]; + return false; + } else { + var valid5 = true; + const len0 = data3.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs16 = errors; + if (!(typeof data3[i0] == "number")) { + validate71.errors = [{ instancePath: instancePath + "/explicit_bucket_histogram/boundaries/" + i0, schemaPath: "#/$defs/ExplicitBucketHistogramAggregation/properties/boundaries/items/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; + return false; + } + var valid5 = _errs16 === errors; + if (!valid5) { + break; + } + } + } + } else { + validate71.errors = [{ instancePath: instancePath + "/explicit_bucket_histogram/boundaries", schemaPath: "#/$defs/ExplicitBucketHistogramAggregation/properties/boundaries/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid4 = _errs14 === errors; + } else { + var valid4 = true; + } + if (valid4) { + if (data2.record_min_max !== undefined) { + let data5 = data2.record_min_max; + const _errs18 = errors; + if (typeof data5 !== "boolean" && data5 !== null) { + validate71.errors = [{ instancePath: instancePath + "/explicit_bucket_histogram/record_min_max", schemaPath: "#/$defs/ExplicitBucketHistogramAggregation/properties/record_min_max/type", keyword: "type", params: { type: schema90.properties.record_min_max.type }, message: "must be boolean,null" }]; + return false; + } + var valid4 = _errs18 === errors; + } else { + var valid4 = true; + } + } + } + } + } + var valid0 = _errs10 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.base2_exponential_bucket_histogram !== undefined) { + let data6 = data.base2_exponential_bucket_histogram; + const _errs20 = errors; + const _errs21 = errors; + if (!(data6 && typeof data6 == "object" && !Array.isArray(data6)) && data6 !== null) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/type", keyword: "type", params: { type: schema91.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs21) { + if (data6 && typeof data6 == "object" && !Array.isArray(data6)) { + const _errs23 = errors; + for (const key4 in data6) { + if (!(key4 === "max_scale" || key4 === "max_size" || key4 === "record_min_max")) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key4 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs23 === errors) { + if (data6.max_scale !== undefined) { + let data7 = data6.max_scale; + const _errs24 = errors; + if (!(typeof data7 == "number" && (!(data7 % 1) && !isNaN(data7))) && data7 !== null) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram/max_scale", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/properties/max_scale/type", keyword: "type", params: { type: schema91.properties.max_scale.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs24) { + if (typeof data7 == "number") { + if (data7 > 20 || isNaN(data7)) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram/max_scale", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/properties/max_scale/maximum", keyword: "maximum", params: { comparison: "<=", limit: 20 }, message: "must be <= 20" }]; + return false; + } else { + if (data7 < -10 || isNaN(data7)) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram/max_scale", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/properties/max_scale/minimum", keyword: "minimum", params: { comparison: ">=", limit: -10 }, message: "must be >= -10" }]; + return false; + } + } + } + } + var valid7 = _errs24 === errors; + } else { + var valid7 = true; + } + if (valid7) { + if (data6.max_size !== undefined) { + let data8 = data6.max_size; + const _errs26 = errors; + if (!(typeof data8 == "number" && (!(data8 % 1) && !isNaN(data8))) && data8 !== null) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram/max_size", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/properties/max_size/type", keyword: "type", params: { type: schema91.properties.max_size.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs26) { + if (typeof data8 == "number") { + if (data8 < 2 || isNaN(data8)) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram/max_size", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/properties/max_size/minimum", keyword: "minimum", params: { comparison: ">=", limit: 2 }, message: "must be >= 2" }]; + return false; + } + } + } + var valid7 = _errs26 === errors; + } else { + var valid7 = true; + } + if (valid7) { + if (data6.record_min_max !== undefined) { + let data9 = data6.record_min_max; + const _errs28 = errors; + if (typeof data9 !== "boolean" && data9 !== null) { + validate71.errors = [{ instancePath: instancePath + "/base2_exponential_bucket_histogram/record_min_max", schemaPath: "#/$defs/Base2ExponentialBucketHistogramAggregation/properties/record_min_max/type", keyword: "type", params: { type: schema91.properties.record_min_max.type }, message: "must be boolean,null" }]; + return false; + } + var valid7 = _errs28 === errors; + } else { + var valid7 = true; + } + } + } + } + } + } + var valid0 = _errs20 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.last_value !== undefined) { + let data10 = data.last_value; + const _errs30 = errors; + const _errs31 = errors; + if (!(data10 && typeof data10 == "object" && !Array.isArray(data10)) && data10 !== null) { + validate71.errors = [{ instancePath: instancePath + "/last_value", schemaPath: "#/$defs/LastValueAggregation/type", keyword: "type", params: { type: schema92.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs31) { + if (data10 && typeof data10 == "object" && !Array.isArray(data10)) { + for (const key5 in data10) { + validate71.errors = [{ instancePath: instancePath + "/last_value", schemaPath: "#/$defs/LastValueAggregation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key5 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid0 = _errs30 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.sum !== undefined) { + let data11 = data.sum; + const _errs34 = errors; + const _errs35 = errors; + if (!(data11 && typeof data11 == "object" && !Array.isArray(data11)) && data11 !== null) { + validate71.errors = [{ instancePath: instancePath + "/sum", schemaPath: "#/$defs/SumAggregation/type", keyword: "type", params: { type: schema93.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs35) { + if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { + for (const key6 in data11) { + validate71.errors = [{ instancePath: instancePath + "/sum", schemaPath: "#/$defs/SumAggregation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key6 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid0 = _errs34 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } else { + validate71.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate71.errors = vErrors; + return errors === 0; + } + validate71.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate70(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate70.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "name" || key0 === "description" || key0 === "aggregation" || key0 === "aggregation_cardinality_limit" || key0 === "attribute_keys")) { + validate70.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.name !== undefined) { + let data0 = data.name; + const _errs2 = errors; + if (typeof data0 !== "string" && data0 !== null) { + validate70.errors = [{ instancePath: instancePath + "/name", schemaPath: "#/properties/name/type", keyword: "type", params: { type: schema86.properties.name.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.description !== undefined) { + let data1 = data.description; + const _errs4 = errors; + if (typeof data1 !== "string" && data1 !== null) { + validate70.errors = [{ instancePath: instancePath + "/description", schemaPath: "#/properties/description/type", keyword: "type", params: { type: schema86.properties.description.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.aggregation !== undefined) { + const _errs6 = errors; + if (!validate71(data.aggregation, { instancePath: instancePath + "/aggregation", parentData: data, parentDataProperty: "aggregation", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); + errors = vErrors.length; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.aggregation_cardinality_limit !== undefined) { + let data3 = data.aggregation_cardinality_limit; + const _errs7 = errors; + if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3))) && data3 !== null) { + validate70.errors = [{ instancePath: instancePath + "/aggregation_cardinality_limit", schemaPath: "#/properties/aggregation_cardinality_limit/type", keyword: "type", params: { type: schema86.properties.aggregation_cardinality_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs7) { + if (typeof data3 == "number") { + if (data3 <= 0 || isNaN(data3)) { + validate70.errors = [{ instancePath: instancePath + "/aggregation_cardinality_limit", schemaPath: "#/properties/aggregation_cardinality_limit/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid0 = _errs7 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.attribute_keys !== undefined) { + let data4 = data.attribute_keys; + const _errs9 = errors; + const _errs10 = errors; + if (errors === _errs10) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + const _errs12 = errors; + for (const key1 in data4) { + if (!(key1 === "included" || key1 === "excluded")) { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys", schemaPath: "#/$defs/IncludeExclude/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs12 === errors) { + if (data4.included !== undefined) { + let data5 = data4.included; + const _errs13 = errors; + if (errors === _errs13) { + if (Array.isArray(data5)) { + if (data5.length < 1) { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys/included", schemaPath: "#/$defs/IncludeExclude/properties/included/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data5.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs15 = errors; + if (typeof data5[i0] !== "string") { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys/included/" + i0, schemaPath: "#/$defs/IncludeExclude/properties/included/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid3 = _errs15 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys/included", schemaPath: "#/$defs/IncludeExclude/properties/included/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid2 = _errs13 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data4.excluded !== undefined) { + let data7 = data4.excluded; + const _errs17 = errors; + if (errors === _errs17) { + if (Array.isArray(data7)) { + if (data7.length < 1) { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys/excluded", schemaPath: "#/$defs/IncludeExclude/properties/excluded/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid4 = true; + const len1 = data7.length; + for (let i1 = 0;i1 < len1; i1++) { + const _errs19 = errors; + if (typeof data7[i1] !== "string") { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys/excluded/" + i1, schemaPath: "#/$defs/IncludeExclude/properties/excluded/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid4 = _errs19 === errors; + if (!valid4) { + break; + } + } + } + } else { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys/excluded", schemaPath: "#/$defs/IncludeExclude/properties/excluded/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid2 = _errs17 === errors; + } else { + var valid2 = true; + } + } + } + } else { + validate70.errors = [{ instancePath: instancePath + "/attribute_keys", schemaPath: "#/$defs/IncludeExclude/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs9 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } else { + validate70.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate70.errors = vErrors; + return errors === 0; + } + validate70.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate67(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate67.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.selector === undefined && (missing0 = "selector") || data.stream === undefined && (missing0 = "stream")) { + validate67.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "selector" || key0 === "stream")) { + validate67.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.selector !== undefined) { + const _errs2 = errors; + if (!validate68(data.selector, { instancePath: instancePath + "/selector", parentData: data, parentDataProperty: "selector", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate68.errors : vErrors.concat(validate68.errors); + errors = vErrors.length; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.stream !== undefined) { + const _errs3 = errors; + if (!validate70(data.stream, { instancePath: instancePath + "/stream", parentData: data, parentDataProperty: "stream", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate70.errors : vErrors.concat(validate70.errors); + errors = vErrors.length; + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + } + } + } + } else { + validate67.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate67.errors = vErrors; + return errors === 0; + } + validate67.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema96 = { type: ["object"], additionalProperties: false, properties: { default_config: { $ref: "#/$defs/ExperimentalMeterConfig", description: `Configure the default meter config used there is no matching entry in .meter_configurator/development.meters. +If omitted, unmatched .meters use default values as described in ExperimentalMeterConfig. +` }, meters: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalMeterMatcherAndConfig" }, description: `Configure meters. +If omitted, all meters used .default_config. +` } } }; + var schema97 = { type: ["object"], additionalProperties: false, properties: { enabled: { type: ["boolean"], description: `Configure if the meter is enabled or not. +If omitted, true is used. +` } } }; + var schema98 = { type: ["object"], additionalProperties: false, properties: { name: { type: ["string"], description: `Configure meter names to match, evaluated as follows: + + * If the meter name exactly matches. + * If the meter name matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +Property is required and must be non-null. +` }, config: { $ref: "#/$defs/ExperimentalMeterConfig", description: `The meter config. +Property is required and must be non-null. +` } }, required: ["name", "config"] }; + function validate76(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate76.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.name === undefined && (missing0 = "name") || data.config === undefined && (missing0 = "config")) { + validate76.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "name" || key0 === "config")) { + validate76.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.name !== undefined) { + const _errs2 = errors; + if (typeof data.name !== "string") { + validate76.errors = [{ instancePath: instancePath + "/name", schemaPath: "#/properties/name/type", keyword: "type", params: { type: schema98.properties.name.type }, message: "must be string" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.config !== undefined) { + let data1 = data.config; + const _errs4 = errors; + const _errs5 = errors; + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + const _errs7 = errors; + for (const key1 in data1) { + if (!(key1 === "enabled")) { + validate76.errors = [{ instancePath: instancePath + "/config", schemaPath: "#/$defs/ExperimentalMeterConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs7 === errors) { + if (data1.enabled !== undefined) { + if (typeof data1.enabled !== "boolean") { + validate76.errors = [{ instancePath: instancePath + "/config/enabled", schemaPath: "#/$defs/ExperimentalMeterConfig/properties/enabled/type", keyword: "type", params: { type: schema97.properties.enabled.type }, message: "must be boolean" }]; + return false; + } + } + } + } else { + validate76.errors = [{ instancePath: instancePath + "/config", schemaPath: "#/$defs/ExperimentalMeterConfig/type", keyword: "type", params: { type: schema97.type }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + } + } + } + } else { + validate76.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema98.type }, message: "must be object" }]; + return false; + } + } + validate76.errors = vErrors; + return errors === 0; + } + validate76.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate75(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate75.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "default_config" || key0 === "meters")) { + validate75.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.default_config !== undefined) { + let data0 = data.default_config; + const _errs2 = errors; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "enabled")) { + validate75.errors = [{ instancePath: instancePath + "/default_config", schemaPath: "#/$defs/ExperimentalMeterConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.enabled !== undefined) { + if (typeof data0.enabled !== "boolean") { + validate75.errors = [{ instancePath: instancePath + "/default_config/enabled", schemaPath: "#/$defs/ExperimentalMeterConfig/properties/enabled/type", keyword: "type", params: { type: schema97.properties.enabled.type }, message: "must be boolean" }]; + return false; + } + } + } + } else { + validate75.errors = [{ instancePath: instancePath + "/default_config", schemaPath: "#/$defs/ExperimentalMeterConfig/type", keyword: "type", params: { type: schema97.type }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.meters !== undefined) { + let data2 = data.meters; + const _errs8 = errors; + if (errors === _errs8) { + if (Array.isArray(data2)) { + if (data2.length < 1) { + validate75.errors = [{ instancePath: instancePath + "/meters", schemaPath: "#/properties/meters/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data2.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs10 = errors; + if (!validate76(data2[i0], { instancePath: instancePath + "/meters/" + i0, parentData: data2, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate76.errors : vErrors.concat(validate76.errors); + errors = vErrors.length; + } + var valid3 = _errs10 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate75.errors = [{ instancePath: instancePath + "/meters", schemaPath: "#/properties/meters/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + } + } + } else { + validate75.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema96.type }, message: "must be object" }]; + return false; + } + } + validate75.errors = vErrors; + return errors === 0; + } + validate75.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate43(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate43.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.readers === undefined && (missing0 = "readers")) { + validate43.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "readers" || key0 === "views" || key0 === "exemplar_filter" || key0 === "meter_configurator/development")) { + validate43.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.readers !== undefined) { + let data0 = data.readers; + const _errs2 = errors; + if (errors === _errs2) { + if (Array.isArray(data0)) { + if (data0.length < 1) { + validate43.errors = [{ instancePath: instancePath + "/readers", schemaPath: "#/properties/readers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data0.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs4 = errors; + if (!validate44(data0[i0], { instancePath: instancePath + "/readers/" + i0, parentData: data0, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate44.errors : vErrors.concat(validate44.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate43.errors = [{ instancePath: instancePath + "/readers", schemaPath: "#/properties/readers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.views !== undefined) { + let data2 = data.views; + const _errs5 = errors; + if (errors === _errs5) { + if (Array.isArray(data2)) { + if (data2.length < 1) { + validate43.errors = [{ instancePath: instancePath + "/views", schemaPath: "#/properties/views/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid2 = true; + const len1 = data2.length; + for (let i1 = 0;i1 < len1; i1++) { + const _errs7 = errors; + if (!validate67(data2[i1], { instancePath: instancePath + "/views/" + i1, parentData: data2, parentDataProperty: i1, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate67.errors : vErrors.concat(validate67.errors); + errors = vErrors.length; + } + var valid2 = _errs7 === errors; + if (!valid2) { + break; + } + } + } + } else { + validate43.errors = [{ instancePath: instancePath + "/views", schemaPath: "#/properties/views/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.exemplar_filter !== undefined) { + let data4 = data.exemplar_filter; + const _errs8 = errors; + if (typeof data4 !== "string" && data4 !== null) { + validate43.errors = [{ instancePath: instancePath + "/exemplar_filter", schemaPath: "#/$defs/ExemplarFilter/type", keyword: "type", params: { type: schema95.type }, message: "must be string,null" }]; + return false; + } + if (!(data4 === "always_on" || data4 === "always_off" || data4 === "trace_based")) { + validate43.errors = [{ instancePath: instancePath + "/exemplar_filter", schemaPath: "#/$defs/ExemplarFilter/enum", keyword: "enum", params: { allowedValues: schema95.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data["meter_configurator/development"] !== undefined) { + const _errs11 = errors; + if (!validate75(data["meter_configurator/development"], { instancePath: instancePath + "/meter_configurator~1development", parentData: data, parentDataProperty: "meter_configurator/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate75.errors : vErrors.concat(validate75.errors); + errors = vErrors.length; + } + var valid0 = _errs11 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } else { + validate43.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate43.errors = vErrors; + return errors === 0; + } + validate43.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema100 = { type: "object", additionalProperties: false, properties: { composite: { type: "array", minItems: 1, items: { $ref: "#/$defs/TextMapPropagator" }, description: `Configure the propagators in the composite text map propagator. Entries from .composite_list are appended to the list here with duplicates filtered out. +Built-in propagator keys include: tracecontext, baggage, b3, b3multi. Known third party keys include: xray. +If omitted, and .composite_list is omitted or null, a noop propagator is used. +` }, composite_list: { type: ["string", "null"], description: `Configure the propagators in the composite text map propagator. Entries are appended to .composite with duplicates filtered out. +The value is a comma separated list of propagator identifiers matching the format of OTEL_PROPAGATORS. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration for details. +Built-in propagator identifiers include: tracecontext, baggage, b3, b3multi. Known third party identifiers include: xray. +If omitted or null, and .composite is omitted or null, a noop propagator is used. +` } } }; + var schema101 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { tracecontext: { $ref: "#/$defs/TraceContextPropagator", description: `Include the w3c trace context propagator. +If omitted, ignore. +` }, baggage: { $ref: "#/$defs/BaggagePropagator", description: `Include the w3c baggage propagator. +If omitted, ignore. +` }, b3: { $ref: "#/$defs/B3Propagator", description: `Include the zipkin b3 propagator. +If omitted, ignore. +` }, b3multi: { $ref: "#/$defs/B3MultiPropagator", description: `Include the zipkin b3 multi propagator. +If omitted, ignore. +` } } }; + var schema102 = { type: ["object", "null"], additionalProperties: false }; + var schema103 = { type: ["object", "null"], additionalProperties: false }; + var schema104 = { type: ["object", "null"], additionalProperties: false }; + var schema105 = { type: ["object", "null"], additionalProperties: false }; + function validate81(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate81.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate81.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate81.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "tracecontext" || key0 === "baggage" || key0 === "b3" || key0 === "b3multi")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate81.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema101.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.tracecontext !== undefined) { + let data1 = data.tracecontext; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate81.errors = [{ instancePath: instancePath + "/tracecontext", schemaPath: "#/$defs/TraceContextPropagator/type", keyword: "type", params: { type: schema102.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + for (const key1 in data1) { + validate81.errors = [{ instancePath: instancePath + "/tracecontext", schemaPath: "#/$defs/TraceContextPropagator/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.baggage !== undefined) { + let data2 = data.baggage; + const _errs8 = errors; + const _errs9 = errors; + if (!(data2 && typeof data2 == "object" && !Array.isArray(data2)) && data2 !== null) { + validate81.errors = [{ instancePath: instancePath + "/baggage", schemaPath: "#/$defs/BaggagePropagator/type", keyword: "type", params: { type: schema103.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs9) { + if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { + for (const key2 in data2) { + validate81.errors = [{ instancePath: instancePath + "/baggage", schemaPath: "#/$defs/BaggagePropagator/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs8 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.b3 !== undefined) { + let data3 = data.b3; + const _errs12 = errors; + const _errs13 = errors; + if (!(data3 && typeof data3 == "object" && !Array.isArray(data3)) && data3 !== null) { + validate81.errors = [{ instancePath: instancePath + "/b3", schemaPath: "#/$defs/B3Propagator/type", keyword: "type", params: { type: schema104.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs13) { + if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { + for (const key3 in data3) { + validate81.errors = [{ instancePath: instancePath + "/b3", schemaPath: "#/$defs/B3Propagator/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs12 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.b3multi !== undefined) { + let data4 = data.b3multi; + const _errs16 = errors; + const _errs17 = errors; + if (!(data4 && typeof data4 == "object" && !Array.isArray(data4)) && data4 !== null) { + validate81.errors = [{ instancePath: instancePath + "/b3multi", schemaPath: "#/$defs/B3MultiPropagator/type", keyword: "type", params: { type: schema105.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs17) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + for (const key4 in data4) { + validate81.errors = [{ instancePath: instancePath + "/b3multi", schemaPath: "#/$defs/B3MultiPropagator/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key4 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs16 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } else { + validate81.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate81.errors = vErrors; + return errors === 0; + } + validate81.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate80(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate80.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "composite" || key0 === "composite_list")) { + validate80.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.composite !== undefined) { + let data0 = data.composite; + const _errs2 = errors; + if (errors === _errs2) { + if (Array.isArray(data0)) { + if (data0.length < 1) { + validate80.errors = [{ instancePath: instancePath + "/composite", schemaPath: "#/properties/composite/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data0.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs4 = errors; + if (!validate81(data0[i0], { instancePath: instancePath + "/composite/" + i0, parentData: data0, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate81.errors : vErrors.concat(validate81.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate80.errors = [{ instancePath: instancePath + "/composite", schemaPath: "#/properties/composite/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.composite_list !== undefined) { + let data2 = data.composite_list; + const _errs5 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate80.errors = [{ instancePath: instancePath + "/composite_list", schemaPath: "#/properties/composite_list/type", keyword: "type", params: { type: schema100.properties.composite_list.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + } + } + } else { + validate80.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate80.errors = vErrors; + return errors === 0; + } + validate80.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema113 = { type: "object", additionalProperties: false, properties: { attribute_value_length_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute value size. Overrides .attribute_limits.attribute_value_length_limit. +Value must be non-negative. +If omitted or null, there is no limit. +` }, attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attribute count. Overrides .attribute_limits.attribute_count_limit. +Value must be non-negative. +If omitted or null, 128 is used. +` }, event_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max span event count. +Value must be non-negative. +If omitted or null, 128 is used. +` }, link_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max span link count. +Value must be non-negative. +If omitted or null, 128 is used. +` }, event_attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attributes per span event. +Value must be non-negative. +If omitted or null, 128 is used. +` }, link_attribute_count_limit: { type: ["integer", "null"], minimum: 0, description: `Configure max attributes per span link. +Value must be non-negative. +If omitted or null, 128 is used. +` } } }; + var schema107 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { batch: { $ref: "#/$defs/BatchSpanProcessor", description: `Configure a batch span processor. +If omitted, ignore. +` }, simple: { $ref: "#/$defs/SimpleSpanProcessor", description: `Configure a simple span processor. +If omitted, ignore. +` } } }; + var schema108 = { type: "object", additionalProperties: false, properties: { schedule_delay: { type: ["integer", "null"], minimum: 0, description: `Configure delay interval (in milliseconds) between two consecutive exports. +Value must be non-negative. +If omitted or null, 5000 is used. +` }, export_timeout: { type: ["integer", "null"], minimum: 0, description: `Configure maximum allowed time (in milliseconds) to export data. +Value must be non-negative. A value of 0 indicates no limit (infinity). +If omitted or null, 30000 is used. +` }, max_queue_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum queue size. Value must be positive. +If omitted or null, 2048 is used. +` }, max_export_batch_size: { type: ["integer", "null"], exclusiveMinimum: 0, description: `Configure maximum batch size. Value must be positive. +If omitted or null, 512 is used. +` }, exporter: { $ref: "#/$defs/SpanExporter", description: `Configure exporter. +Property is required and must be non-null. +` } }, required: ["exporter"] }; + var schema109 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { otlp_http: { $ref: "#/$defs/OtlpHttpExporter", description: `Configure exporter to be OTLP with HTTP transport. +If omitted, ignore. +` }, otlp_grpc: { $ref: "#/$defs/OtlpGrpcExporter", description: `Configure exporter to be OTLP with gRPC transport. +If omitted, ignore. +` }, "otlp_file/development": { $ref: "#/$defs/ExperimentalOtlpFileExporter", description: `Configure exporter to be OTLP with file transport. +If omitted, ignore. +` }, console: { $ref: "#/$defs/ConsoleExporter", description: `Configure exporter to be console. +If omitted, ignore. +` } } }; + function validate87(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate87.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate87.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate87.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "otlp_http" || key0 === "otlp_grpc" || key0 === "otlp_file/development" || key0 === "console")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate87.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema109.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.otlp_http !== undefined) { + const _errs4 = errors; + if (!validate25(data.otlp_http, { instancePath: instancePath + "/otlp_http", parentData: data, parentDataProperty: "otlp_http", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate25.errors : vErrors.concat(validate25.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.otlp_grpc !== undefined) { + const _errs5 = errors; + if (!validate27(data.otlp_grpc, { instancePath: instancePath + "/otlp_grpc", parentData: data, parentDataProperty: "otlp_grpc", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate27.errors : vErrors.concat(validate27.errors); + errors = vErrors.length; + } + var valid1 = _errs5 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data["otlp_file/development"] !== undefined) { + let data3 = data["otlp_file/development"]; + const _errs6 = errors; + const _errs7 = errors; + if (!(data3 && typeof data3 == "object" && !Array.isArray(data3)) && data3 !== null) { + validate87.errors = [{ instancePath: instancePath + "/otlp_file~1development", schemaPath: "#/$defs/ExperimentalOtlpFileExporter/type", keyword: "type", params: { type: schema45.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs7) { + if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { + const _errs9 = errors; + for (const key1 in data3) { + if (!(key1 === "output_stream")) { + validate87.errors = [{ instancePath: instancePath + "/otlp_file~1development", schemaPath: "#/$defs/ExperimentalOtlpFileExporter/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs9 === errors) { + if (data3.output_stream !== undefined) { + let data4 = data3.output_stream; + if (typeof data4 !== "string" && data4 !== null) { + validate87.errors = [{ instancePath: instancePath + "/otlp_file~1development/output_stream", schemaPath: "#/$defs/ExperimentalOtlpFileExporter/properties/output_stream/type", keyword: "type", params: { type: schema45.properties.output_stream.type }, message: "must be string,null" }]; + return false; + } + } + } + } + } + var valid1 = _errs6 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.console !== undefined) { + let data5 = data.console; + const _errs12 = errors; + const _errs13 = errors; + if (!(data5 && typeof data5 == "object" && !Array.isArray(data5)) && data5 !== null) { + validate87.errors = [{ instancePath: instancePath + "/console", schemaPath: "#/$defs/ConsoleExporter/type", keyword: "type", params: { type: schema46.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs13) { + if (data5 && typeof data5 == "object" && !Array.isArray(data5)) { + for (const key2 in data5) { + validate87.errors = [{ instancePath: instancePath + "/console", schemaPath: "#/$defs/ConsoleExporter/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs12 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } else { + validate87.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate87.errors = vErrors; + return errors === 0; + } + validate87.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate86(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate86.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.exporter === undefined && (missing0 = "exporter")) { + validate86.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "schedule_delay" || key0 === "export_timeout" || key0 === "max_queue_size" || key0 === "max_export_batch_size" || key0 === "exporter")) { + validate86.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.schedule_delay !== undefined) { + let data0 = data.schedule_delay; + const _errs2 = errors; + if (!(typeof data0 == "number" && (!(data0 % 1) && !isNaN(data0))) && data0 !== null) { + validate86.errors = [{ instancePath: instancePath + "/schedule_delay", schemaPath: "#/properties/schedule_delay/type", keyword: "type", params: { type: schema108.properties.schedule_delay.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs2) { + if (typeof data0 == "number") { + if (data0 < 0 || isNaN(data0)) { + validate86.errors = [{ instancePath: instancePath + "/schedule_delay", schemaPath: "#/properties/schedule_delay/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.export_timeout !== undefined) { + let data1 = data.export_timeout; + const _errs4 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate86.errors = [{ instancePath: instancePath + "/export_timeout", schemaPath: "#/properties/export_timeout/type", keyword: "type", params: { type: schema108.properties.export_timeout.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs4) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate86.errors = [{ instancePath: instancePath + "/export_timeout", schemaPath: "#/properties/export_timeout/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.max_queue_size !== undefined) { + let data2 = data.max_queue_size; + const _errs6 = errors; + if (!(typeof data2 == "number" && (!(data2 % 1) && !isNaN(data2))) && data2 !== null) { + validate86.errors = [{ instancePath: instancePath + "/max_queue_size", schemaPath: "#/properties/max_queue_size/type", keyword: "type", params: { type: schema108.properties.max_queue_size.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data2 == "number") { + if (data2 <= 0 || isNaN(data2)) { + validate86.errors = [{ instancePath: instancePath + "/max_queue_size", schemaPath: "#/properties/max_queue_size/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.max_export_batch_size !== undefined) { + let data3 = data.max_export_batch_size; + const _errs8 = errors; + if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3))) && data3 !== null) { + validate86.errors = [{ instancePath: instancePath + "/max_export_batch_size", schemaPath: "#/properties/max_export_batch_size/type", keyword: "type", params: { type: schema108.properties.max_export_batch_size.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs8) { + if (typeof data3 == "number") { + if (data3 <= 0 || isNaN(data3)) { + validate86.errors = [{ instancePath: instancePath + "/max_export_batch_size", schemaPath: "#/properties/max_export_batch_size/exclusiveMinimum", keyword: "exclusiveMinimum", params: { comparison: ">", limit: 0 }, message: "must be > 0" }]; + return false; + } + } + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.exporter !== undefined) { + const _errs10 = errors; + if (!validate87(data.exporter, { instancePath: instancePath + "/exporter", parentData: data, parentDataProperty: "exporter", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate87.errors : vErrors.concat(validate87.errors); + errors = vErrors.length; + } + var valid0 = _errs10 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } else { + validate86.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate86.errors = vErrors; + return errors === 0; + } + validate86.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate92(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate92.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.exporter === undefined && (missing0 = "exporter")) { + validate92.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "exporter")) { + validate92.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.exporter !== undefined) { + if (!validate87(data.exporter, { instancePath: instancePath + "/exporter", parentData: data, parentDataProperty: "exporter", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate87.errors : vErrors.concat(validate87.errors); + errors = vErrors.length; + } + } + } + } + } else { + validate92.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate92.errors = vErrors; + return errors === 0; + } + validate92.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate85(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate85.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate85.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate85.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "batch" || key0 === "simple")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate85.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema107.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.batch !== undefined) { + const _errs4 = errors; + if (!validate86(data.batch, { instancePath: instancePath + "/batch", parentData: data, parentDataProperty: "batch", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate86.errors : vErrors.concat(validate86.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.simple !== undefined) { + const _errs5 = errors; + if (!validate92(data.simple, { instancePath: instancePath + "/simple", parentData: data, parentDataProperty: "simple", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate92.errors : vErrors.concat(validate92.errors); + errors = vErrors.length; + } + var valid1 = _errs5 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } else { + validate85.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate85.errors = vErrors; + return errors === 0; + } + validate85.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema114 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { always_off: { $ref: "#/$defs/AlwaysOffSampler", description: `Configure sampler to be always_off. +If omitted, ignore. +` }, always_on: { $ref: "#/$defs/AlwaysOnSampler", description: `Configure sampler to be always_on. +If omitted, ignore. +` }, "composite/development": { $ref: "#/$defs/ExperimentalComposableSampler", description: `Configure sampler to be composite. +If omitted, ignore. +` }, "jaeger_remote/development": { $ref: "#/$defs/ExperimentalJaegerRemoteSampler", description: `Configure sampler to be jaeger_remote. +If omitted, ignore. +` }, parent_based: { $ref: "#/$defs/ParentBasedSampler", description: `Configure sampler to be parent_based. +If omitted, ignore. +` }, "probability/development": { $ref: "#/$defs/ExperimentalProbabilitySampler", description: `Configure sampler to be probability. +If omitted, ignore. +` }, trace_id_ratio_based: { $ref: "#/$defs/TraceIdRatioBasedSampler", description: `Configure sampler to be trace_id_ratio_based. +If omitted, ignore. +` } } }; + var schema115 = { type: ["object", "null"], additionalProperties: false }; + var schema116 = { type: ["object", "null"], additionalProperties: false }; + var schema130 = { type: ["object", "null"], additionalProperties: false, properties: { ratio: { type: ["number", "null"], minimum: 0, maximum: 1, description: `Configure ratio. +If omitted or null, 1.0 is used. +` } } }; + var schema131 = { type: ["object", "null"], additionalProperties: false, properties: { ratio: { type: ["number", "null"], minimum: 0, maximum: 1, description: `Configure trace_id_ratio. +If omitted or null, 1.0 is used. +` } } }; + var schema117 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { always_off: { $ref: "#/$defs/ExperimentalComposableAlwaysOffSampler", description: `Configure sampler to be always_off. +If omitted, ignore. +` }, always_on: { $ref: "#/$defs/ExperimentalComposableAlwaysOnSampler", description: `Configure sampler to be always_on. +If omitted, ignore. +` }, parent_threshold: { $ref: "#/$defs/ExperimentalComposableParentThresholdSampler", description: `Configure sampler to be parent_threshold. +If omitted, ignore. +` }, probability: { $ref: "#/$defs/ExperimentalComposableProbabilitySampler", description: `Configure sampler to be probability. +If omitted, ignore. +` }, rule_based: { $ref: "#/$defs/ExperimentalComposableRuleBasedSampler", description: `Configure sampler to be rule_based. +If omitted, ignore. +` } } }; + var schema118 = { type: ["object", "null"], additionalProperties: false }; + var schema119 = { type: ["object", "null"], additionalProperties: false }; + var schema121 = { type: ["object", "null"], additionalProperties: false, properties: { ratio: { type: ["number", "null"], minimum: 0, maximum: 1, description: `Configure ratio. +If omitted or null, 1.0 is used. +` } } }; + var schema120 = { type: ["object"], additionalProperties: false, properties: { root: { $ref: "#/$defs/ExperimentalComposableSampler", description: `Sampler to use when there is no parent. +Property is required and must be non-null. +` } }, required: ["root"] }; + var wrapper0 = { validate: validate97 }; + function validate98(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate98.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.root === undefined && (missing0 = "root")) { + validate98.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "root")) { + validate98.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.root !== undefined) { + if (!wrapper0.validate(data.root, { instancePath: instancePath + "/root", parentData: data, parentDataProperty: "root", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper0.validate.errors : vErrors.concat(wrapper0.validate.errors); + errors = vErrors.length; + } + } + } + } + } else { + validate98.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema120.type }, message: "must be object" }]; + return false; + } + } + validate98.errors = vErrors; + return errors === 0; + } + validate98.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema122 = { type: ["object", "null"], additionalProperties: false, properties: { rules: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalComposableRuleBasedSamplerRule" }, description: `The rules for the sampler, matched in order. +Each rule can have multiple match conditions. All conditions must match for the rule to match. +If no conditions are specified, the rule matches all spans that reach it. +If no rules match, the span is not sampled. +If omitted, no span is sampled. +` } } }; + var schema126 = { type: ["string", "null"], enum: ["internal", "server", "client", "producer", "consumer"] }; + var schema127 = { type: ["string", "null"], enum: ["none", "remote", "local"] }; + function validate101(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate101.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.sampler === undefined && (missing0 = "sampler")) { + validate101.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "attribute_values" || key0 === "attribute_patterns" || key0 === "span_kinds" || key0 === "parent" || key0 === "sampler")) { + validate101.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.attribute_values !== undefined) { + let data0 = data.attribute_values; + const _errs2 = errors; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + let missing1; + if (data0.key === undefined && (missing1 = "key") || data0.values === undefined && (missing1 = "values")) { + validate101.errors = [{ instancePath: instancePath + "/attribute_values", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; + return false; + } else { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "key" || key1 === "values")) { + validate101.errors = [{ instancePath: instancePath + "/attribute_values", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.key !== undefined) { + const _errs6 = errors; + if (typeof data0.key !== "string") { + validate101.errors = [{ instancePath: instancePath + "/attribute_values/key", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues/properties/key/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.values !== undefined) { + let data2 = data0.values; + const _errs8 = errors; + if (errors === _errs8) { + if (Array.isArray(data2)) { + if (data2.length < 1) { + validate101.errors = [{ instancePath: instancePath + "/attribute_values/values", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues/properties/values/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data2.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs10 = errors; + if (typeof data2[i0] !== "string") { + validate101.errors = [{ instancePath: instancePath + "/attribute_values/values/" + i0, schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues/properties/values/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid3 = _errs10 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate101.errors = [{ instancePath: instancePath + "/attribute_values/values", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues/properties/values/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + } + } + } + } else { + validate101.errors = [{ instancePath: instancePath + "/attribute_values", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributeValues/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.attribute_patterns !== undefined) { + let data4 = data.attribute_patterns; + const _errs12 = errors; + const _errs13 = errors; + if (errors === _errs13) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + let missing2; + if (data4.key === undefined && (missing2 = "key")) { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }]; + return false; + } else { + const _errs15 = errors; + for (const key2 in data4) { + if (!(key2 === "key" || key2 === "included" || key2 === "excluded")) { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs15 === errors) { + if (data4.key !== undefined) { + const _errs16 = errors; + if (typeof data4.key !== "string") { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns/key", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/properties/key/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid5 = _errs16 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data4.included !== undefined) { + let data6 = data4.included; + const _errs18 = errors; + if (errors === _errs18) { + if (Array.isArray(data6)) { + if (data6.length < 1) { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns/included", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/properties/included/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid6 = true; + const len1 = data6.length; + for (let i1 = 0;i1 < len1; i1++) { + const _errs20 = errors; + if (typeof data6[i1] !== "string") { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns/included/" + i1, schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/properties/included/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid6 = _errs20 === errors; + if (!valid6) { + break; + } + } + } + } else { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns/included", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/properties/included/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid5 = _errs18 === errors; + } else { + var valid5 = true; + } + if (valid5) { + if (data4.excluded !== undefined) { + let data8 = data4.excluded; + const _errs22 = errors; + if (errors === _errs22) { + if (Array.isArray(data8)) { + if (data8.length < 1) { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns/excluded", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/properties/excluded/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid7 = true; + const len2 = data8.length; + for (let i2 = 0;i2 < len2; i2++) { + const _errs24 = errors; + if (typeof data8[i2] !== "string") { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns/excluded/" + i2, schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/properties/excluded/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid7 = _errs24 === errors; + if (!valid7) { + break; + } + } + } + } else { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns/excluded", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/properties/excluded/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid5 = _errs22 === errors; + } else { + var valid5 = true; + } + } + } + } + } + } else { + validate101.errors = [{ instancePath: instancePath + "/attribute_patterns", schemaPath: "#/$defs/ExperimentalComposableRuleBasedSamplerRuleAttributePatterns/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs12 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.span_kinds !== undefined) { + let data10 = data.span_kinds; + const _errs26 = errors; + if (errors === _errs26) { + if (Array.isArray(data10)) { + if (data10.length < 1) { + validate101.errors = [{ instancePath: instancePath + "/span_kinds", schemaPath: "#/properties/span_kinds/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid8 = true; + const len3 = data10.length; + for (let i3 = 0;i3 < len3; i3++) { + let data11 = data10[i3]; + const _errs28 = errors; + if (typeof data11 !== "string" && data11 !== null) { + validate101.errors = [{ instancePath: instancePath + "/span_kinds/" + i3, schemaPath: "#/$defs/SpanKind/type", keyword: "type", params: { type: schema126.type }, message: "must be string,null" }]; + return false; + } + if (!(data11 === "internal" || data11 === "server" || data11 === "client" || data11 === "producer" || data11 === "consumer")) { + validate101.errors = [{ instancePath: instancePath + "/span_kinds/" + i3, schemaPath: "#/$defs/SpanKind/enum", keyword: "enum", params: { allowedValues: schema126.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid8 = _errs28 === errors; + if (!valid8) { + break; + } + } + } + } else { + validate101.errors = [{ instancePath: instancePath + "/span_kinds", schemaPath: "#/properties/span_kinds/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs26 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.parent !== undefined) { + let data12 = data.parent; + const _errs31 = errors; + if (errors === _errs31) { + if (Array.isArray(data12)) { + if (data12.length < 1) { + validate101.errors = [{ instancePath: instancePath + "/parent", schemaPath: "#/properties/parent/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid10 = true; + const len4 = data12.length; + for (let i4 = 0;i4 < len4; i4++) { + let data13 = data12[i4]; + const _errs33 = errors; + if (typeof data13 !== "string" && data13 !== null) { + validate101.errors = [{ instancePath: instancePath + "/parent/" + i4, schemaPath: "#/$defs/ExperimentalSpanParent/type", keyword: "type", params: { type: schema127.type }, message: "must be string,null" }]; + return false; + } + if (!(data13 === "none" || data13 === "remote" || data13 === "local")) { + validate101.errors = [{ instancePath: instancePath + "/parent/" + i4, schemaPath: "#/$defs/ExperimentalSpanParent/enum", keyword: "enum", params: { allowedValues: schema127.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid10 = _errs33 === errors; + if (!valid10) { + break; + } + } + } + } else { + validate101.errors = [{ instancePath: instancePath + "/parent", schemaPath: "#/properties/parent/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs31 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.sampler !== undefined) { + const _errs36 = errors; + if (!wrapper0.validate(data.sampler, { instancePath: instancePath + "/sampler", parentData: data, parentDataProperty: "sampler", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper0.validate.errors : vErrors.concat(wrapper0.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs36 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } else { + validate101.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate101.errors = vErrors; + return errors === 0; + } + validate101.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate100(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate100.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate100.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema122.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "rules")) { + validate100.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.rules !== undefined) { + let data0 = data.rules; + const _errs2 = errors; + if (errors === _errs2) { + if (Array.isArray(data0)) { + if (data0.length < 1) { + validate100.errors = [{ instancePath: instancePath + "/rules", schemaPath: "#/properties/rules/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data0.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs4 = errors; + if (!validate101(data0[i0], { instancePath: instancePath + "/rules/" + i0, parentData: data0, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate101.errors : vErrors.concat(validate101.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate100.errors = [{ instancePath: instancePath + "/rules", schemaPath: "#/properties/rules/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + } + } + } + } + validate100.errors = vErrors; + return errors === 0; + } + validate100.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate97(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate97.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate97.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate97.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "always_off" || key0 === "always_on" || key0 === "parent_threshold" || key0 === "probability" || key0 === "rule_based")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate97.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema117.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.always_off !== undefined) { + let data1 = data.always_off; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate97.errors = [{ instancePath: instancePath + "/always_off", schemaPath: "#/$defs/ExperimentalComposableAlwaysOffSampler/type", keyword: "type", params: { type: schema118.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + for (const key1 in data1) { + validate97.errors = [{ instancePath: instancePath + "/always_off", schemaPath: "#/$defs/ExperimentalComposableAlwaysOffSampler/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.always_on !== undefined) { + let data2 = data.always_on; + const _errs8 = errors; + const _errs9 = errors; + if (!(data2 && typeof data2 == "object" && !Array.isArray(data2)) && data2 !== null) { + validate97.errors = [{ instancePath: instancePath + "/always_on", schemaPath: "#/$defs/ExperimentalComposableAlwaysOnSampler/type", keyword: "type", params: { type: schema119.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs9) { + if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { + for (const key2 in data2) { + validate97.errors = [{ instancePath: instancePath + "/always_on", schemaPath: "#/$defs/ExperimentalComposableAlwaysOnSampler/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs8 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.parent_threshold !== undefined) { + const _errs12 = errors; + if (!validate98(data.parent_threshold, { instancePath: instancePath + "/parent_threshold", parentData: data, parentDataProperty: "parent_threshold", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate98.errors : vErrors.concat(validate98.errors); + errors = vErrors.length; + } + var valid1 = _errs12 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.probability !== undefined) { + let data4 = data.probability; + const _errs13 = errors; + const _errs14 = errors; + if (!(data4 && typeof data4 == "object" && !Array.isArray(data4)) && data4 !== null) { + validate97.errors = [{ instancePath: instancePath + "/probability", schemaPath: "#/$defs/ExperimentalComposableProbabilitySampler/type", keyword: "type", params: { type: schema121.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs14) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + const _errs16 = errors; + for (const key3 in data4) { + if (!(key3 === "ratio")) { + validate97.errors = [{ instancePath: instancePath + "/probability", schemaPath: "#/$defs/ExperimentalComposableProbabilitySampler/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs16 === errors) { + if (data4.ratio !== undefined) { + let data5 = data4.ratio; + const _errs17 = errors; + if (!(typeof data5 == "number") && data5 !== null) { + validate97.errors = [{ instancePath: instancePath + "/probability/ratio", schemaPath: "#/$defs/ExperimentalComposableProbabilitySampler/properties/ratio/type", keyword: "type", params: { type: schema121.properties.ratio.type }, message: "must be number,null" }]; + return false; + } + if (errors === _errs17) { + if (typeof data5 == "number") { + if (data5 > 1 || isNaN(data5)) { + validate97.errors = [{ instancePath: instancePath + "/probability/ratio", schemaPath: "#/$defs/ExperimentalComposableProbabilitySampler/properties/ratio/maximum", keyword: "maximum", params: { comparison: "<=", limit: 1 }, message: "must be <= 1" }]; + return false; + } else { + if (data5 < 0 || isNaN(data5)) { + validate97.errors = [{ instancePath: instancePath + "/probability/ratio", schemaPath: "#/$defs/ExperimentalComposableProbabilitySampler/properties/ratio/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + } + } + } + } + } + var valid1 = _errs13 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.rule_based !== undefined) { + const _errs19 = errors; + if (!validate100(data.rule_based, { instancePath: instancePath + "/rule_based", parentData: data, parentDataProperty: "rule_based", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate100.errors : vErrors.concat(validate100.errors); + errors = vErrors.length; + } + var valid1 = _errs19 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } + } else { + validate97.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate97.errors = vErrors; + return errors === 0; + } + validate97.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema128 = { type: ["object", "null"], additionalProperties: false, properties: { endpoint: { type: ["string"], description: `Configure the endpoint of the jaeger remote sampling service. +Property is required and must be non-null. +` }, interval: { type: ["integer", "null"], minimum: 0, description: `Configure the polling interval (in milliseconds) to fetch from the remote sampling service. +If omitted or null, 60000 is used. +` }, initial_sampler: { $ref: "#/$defs/Sampler", description: `Configure the initial sampler used before first configuration is fetched. +Property is required and must be non-null. +` } }, required: ["endpoint", "initial_sampler"] }; + var wrapper2 = { validate: validate96 }; + function validate105(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate105.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate105.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema128.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.endpoint === undefined && (missing0 = "endpoint") || data.initial_sampler === undefined && (missing0 = "initial_sampler")) { + validate105.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "endpoint" || key0 === "interval" || key0 === "initial_sampler")) { + validate105.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.endpoint !== undefined) { + const _errs2 = errors; + if (typeof data.endpoint !== "string") { + validate105.errors = [{ instancePath: instancePath + "/endpoint", schemaPath: "#/properties/endpoint/type", keyword: "type", params: { type: schema128.properties.endpoint.type }, message: "must be string" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.interval !== undefined) { + let data1 = data.interval; + const _errs4 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate105.errors = [{ instancePath: instancePath + "/interval", schemaPath: "#/properties/interval/type", keyword: "type", params: { type: schema128.properties.interval.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs4) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate105.errors = [{ instancePath: instancePath + "/interval", schemaPath: "#/properties/interval/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.initial_sampler !== undefined) { + const _errs6 = errors; + if (!wrapper2.validate(data.initial_sampler, { instancePath: instancePath + "/initial_sampler", parentData: data, parentDataProperty: "initial_sampler", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper2.validate.errors : vErrors.concat(wrapper2.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + validate105.errors = vErrors; + return errors === 0; + } + validate105.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema129 = { type: ["object", "null"], additionalProperties: false, properties: { root: { $ref: "#/$defs/Sampler", description: `Configure root sampler. +If omitted, always_on is used. +` }, remote_parent_sampled: { $ref: "#/$defs/Sampler", description: `Configure remote_parent_sampled sampler. +If omitted, always_on is used. +` }, remote_parent_not_sampled: { $ref: "#/$defs/Sampler", description: `Configure remote_parent_not_sampled sampler. +If omitted, always_off is used. +` }, local_parent_sampled: { $ref: "#/$defs/Sampler", description: `Configure local_parent_sampled sampler. +If omitted, always_on is used. +` }, local_parent_not_sampled: { $ref: "#/$defs/Sampler", description: `Configure local_parent_not_sampled sampler. +If omitted, always_off is used. +` } } }; + function validate107(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate107.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (!(data && typeof data == "object" && !Array.isArray(data)) && data !== null) { + validate107.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema129.type }, message: "must be object,null" }]; + return false; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "root" || key0 === "remote_parent_sampled" || key0 === "remote_parent_not_sampled" || key0 === "local_parent_sampled" || key0 === "local_parent_not_sampled")) { + validate107.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.root !== undefined) { + const _errs2 = errors; + if (!wrapper2.validate(data.root, { instancePath: instancePath + "/root", parentData: data, parentDataProperty: "root", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper2.validate.errors : vErrors.concat(wrapper2.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.remote_parent_sampled !== undefined) { + const _errs3 = errors; + if (!wrapper2.validate(data.remote_parent_sampled, { instancePath: instancePath + "/remote_parent_sampled", parentData: data, parentDataProperty: "remote_parent_sampled", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper2.validate.errors : vErrors.concat(wrapper2.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.remote_parent_not_sampled !== undefined) { + const _errs4 = errors; + if (!wrapper2.validate(data.remote_parent_not_sampled, { instancePath: instancePath + "/remote_parent_not_sampled", parentData: data, parentDataProperty: "remote_parent_not_sampled", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper2.validate.errors : vErrors.concat(wrapper2.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.local_parent_sampled !== undefined) { + const _errs5 = errors; + if (!wrapper2.validate(data.local_parent_sampled, { instancePath: instancePath + "/local_parent_sampled", parentData: data, parentDataProperty: "local_parent_sampled", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper2.validate.errors : vErrors.concat(wrapper2.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.local_parent_not_sampled !== undefined) { + const _errs6 = errors; + if (!wrapper2.validate(data.local_parent_not_sampled, { instancePath: instancePath + "/local_parent_not_sampled", parentData: data, parentDataProperty: "local_parent_not_sampled", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? wrapper2.validate.errors : vErrors.concat(wrapper2.validate.errors); + errors = vErrors.length; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + validate107.errors = vErrors; + return errors === 0; + } + validate107.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate96(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate96.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate96.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate96.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "always_off" || key0 === "always_on" || key0 === "composite/development" || key0 === "jaeger_remote/development" || key0 === "parent_based" || key0 === "probability/development" || key0 === "trace_id_ratio_based")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate96.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema114.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.always_off !== undefined) { + let data1 = data.always_off; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate96.errors = [{ instancePath: instancePath + "/always_off", schemaPath: "#/$defs/AlwaysOffSampler/type", keyword: "type", params: { type: schema115.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + for (const key1 in data1) { + validate96.errors = [{ instancePath: instancePath + "/always_off", schemaPath: "#/$defs/AlwaysOffSampler/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.always_on !== undefined) { + let data2 = data.always_on; + const _errs8 = errors; + const _errs9 = errors; + if (!(data2 && typeof data2 == "object" && !Array.isArray(data2)) && data2 !== null) { + validate96.errors = [{ instancePath: instancePath + "/always_on", schemaPath: "#/$defs/AlwaysOnSampler/type", keyword: "type", params: { type: schema116.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs9) { + if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { + for (const key2 in data2) { + validate96.errors = [{ instancePath: instancePath + "/always_on", schemaPath: "#/$defs/AlwaysOnSampler/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs8 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data["composite/development"] !== undefined) { + const _errs12 = errors; + if (!validate97(data["composite/development"], { instancePath: instancePath + "/composite~1development", parentData: data, parentDataProperty: "composite/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate97.errors : vErrors.concat(validate97.errors); + errors = vErrors.length; + } + var valid1 = _errs12 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data["jaeger_remote/development"] !== undefined) { + const _errs13 = errors; + if (!validate105(data["jaeger_remote/development"], { instancePath: instancePath + "/jaeger_remote~1development", parentData: data, parentDataProperty: "jaeger_remote/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate105.errors : vErrors.concat(validate105.errors); + errors = vErrors.length; + } + var valid1 = _errs13 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.parent_based !== undefined) { + const _errs14 = errors; + if (!validate107(data.parent_based, { instancePath: instancePath + "/parent_based", parentData: data, parentDataProperty: "parent_based", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate107.errors : vErrors.concat(validate107.errors); + errors = vErrors.length; + } + var valid1 = _errs14 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data["probability/development"] !== undefined) { + let data6 = data["probability/development"]; + const _errs15 = errors; + const _errs16 = errors; + if (!(data6 && typeof data6 == "object" && !Array.isArray(data6)) && data6 !== null) { + validate96.errors = [{ instancePath: instancePath + "/probability~1development", schemaPath: "#/$defs/ExperimentalProbabilitySampler/type", keyword: "type", params: { type: schema130.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs16) { + if (data6 && typeof data6 == "object" && !Array.isArray(data6)) { + const _errs18 = errors; + for (const key3 in data6) { + if (!(key3 === "ratio")) { + validate96.errors = [{ instancePath: instancePath + "/probability~1development", schemaPath: "#/$defs/ExperimentalProbabilitySampler/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs18 === errors) { + if (data6.ratio !== undefined) { + let data7 = data6.ratio; + const _errs19 = errors; + if (!(typeof data7 == "number") && data7 !== null) { + validate96.errors = [{ instancePath: instancePath + "/probability~1development/ratio", schemaPath: "#/$defs/ExperimentalProbabilitySampler/properties/ratio/type", keyword: "type", params: { type: schema130.properties.ratio.type }, message: "must be number,null" }]; + return false; + } + if (errors === _errs19) { + if (typeof data7 == "number") { + if (data7 > 1 || isNaN(data7)) { + validate96.errors = [{ instancePath: instancePath + "/probability~1development/ratio", schemaPath: "#/$defs/ExperimentalProbabilitySampler/properties/ratio/maximum", keyword: "maximum", params: { comparison: "<=", limit: 1 }, message: "must be <= 1" }]; + return false; + } else { + if (data7 < 0 || isNaN(data7)) { + validate96.errors = [{ instancePath: instancePath + "/probability~1development/ratio", schemaPath: "#/$defs/ExperimentalProbabilitySampler/properties/ratio/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + } + } + } + } + } + var valid1 = _errs15 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.trace_id_ratio_based !== undefined) { + let data8 = data.trace_id_ratio_based; + const _errs21 = errors; + const _errs22 = errors; + if (!(data8 && typeof data8 == "object" && !Array.isArray(data8)) && data8 !== null) { + validate96.errors = [{ instancePath: instancePath + "/trace_id_ratio_based", schemaPath: "#/$defs/TraceIdRatioBasedSampler/type", keyword: "type", params: { type: schema131.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs22) { + if (data8 && typeof data8 == "object" && !Array.isArray(data8)) { + const _errs24 = errors; + for (const key4 in data8) { + if (!(key4 === "ratio")) { + validate96.errors = [{ instancePath: instancePath + "/trace_id_ratio_based", schemaPath: "#/$defs/TraceIdRatioBasedSampler/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key4 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs24 === errors) { + if (data8.ratio !== undefined) { + let data9 = data8.ratio; + const _errs25 = errors; + if (!(typeof data9 == "number") && data9 !== null) { + validate96.errors = [{ instancePath: instancePath + "/trace_id_ratio_based/ratio", schemaPath: "#/$defs/TraceIdRatioBasedSampler/properties/ratio/type", keyword: "type", params: { type: schema131.properties.ratio.type }, message: "must be number,null" }]; + return false; + } + if (errors === _errs25) { + if (typeof data9 == "number") { + if (data9 > 1 || isNaN(data9)) { + validate96.errors = [{ instancePath: instancePath + "/trace_id_ratio_based/ratio", schemaPath: "#/$defs/TraceIdRatioBasedSampler/properties/ratio/maximum", keyword: "maximum", params: { comparison: "<=", limit: 1 }, message: "must be <= 1" }]; + return false; + } else { + if (data9 < 0 || isNaN(data9)) { + validate96.errors = [{ instancePath: instancePath + "/trace_id_ratio_based/ratio", schemaPath: "#/$defs/TraceIdRatioBasedSampler/properties/ratio/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + } + } + } + } + } + var valid1 = _errs21 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } + } + } + } else { + validate96.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate96.errors = vErrors; + return errors === 0; + } + validate96.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema132 = { type: ["object"], additionalProperties: false, properties: { default_config: { $ref: "#/$defs/ExperimentalTracerConfig", description: `Configure the default tracer config used there is no matching entry in .tracer_configurator/development.tracers. +If omitted, unmatched .tracers use default values as described in ExperimentalTracerConfig. +` }, tracers: { type: "array", minItems: 1, items: { $ref: "#/$defs/ExperimentalTracerMatcherAndConfig" }, description: `Configure tracers. +If omitted, all tracers use .default_config. +` } } }; + var schema133 = { type: ["object"], additionalProperties: false, properties: { enabled: { type: ["boolean"], description: `Configure if the tracer is enabled or not. +If omitted, true is used. +` } } }; + var schema134 = { type: ["object"], additionalProperties: false, properties: { name: { type: ["string"], description: `Configure tracer names to match, evaluated as follows: + + * If the tracer name exactly matches. + * If the tracer name matches the wildcard pattern, where '?' matches any single character and '*' matches any number of characters including none. +Property is required and must be non-null. +` }, config: { $ref: "#/$defs/ExperimentalTracerConfig", description: `The tracer config. +Property is required and must be non-null. +` } }, required: ["name", "config"] }; + function validate111(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate111.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.name === undefined && (missing0 = "name") || data.config === undefined && (missing0 = "config")) { + validate111.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "name" || key0 === "config")) { + validate111.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.name !== undefined) { + const _errs2 = errors; + if (typeof data.name !== "string") { + validate111.errors = [{ instancePath: instancePath + "/name", schemaPath: "#/properties/name/type", keyword: "type", params: { type: schema134.properties.name.type }, message: "must be string" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.config !== undefined) { + let data1 = data.config; + const _errs4 = errors; + const _errs5 = errors; + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + const _errs7 = errors; + for (const key1 in data1) { + if (!(key1 === "enabled")) { + validate111.errors = [{ instancePath: instancePath + "/config", schemaPath: "#/$defs/ExperimentalTracerConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs7 === errors) { + if (data1.enabled !== undefined) { + if (typeof data1.enabled !== "boolean") { + validate111.errors = [{ instancePath: instancePath + "/config/enabled", schemaPath: "#/$defs/ExperimentalTracerConfig/properties/enabled/type", keyword: "type", params: { type: schema133.properties.enabled.type }, message: "must be boolean" }]; + return false; + } + } + } + } else { + validate111.errors = [{ instancePath: instancePath + "/config", schemaPath: "#/$defs/ExperimentalTracerConfig/type", keyword: "type", params: { type: schema133.type }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + } + } + } + } else { + validate111.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema134.type }, message: "must be object" }]; + return false; + } + } + validate111.errors = vErrors; + return errors === 0; + } + validate111.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate110(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate110.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "default_config" || key0 === "tracers")) { + validate110.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.default_config !== undefined) { + let data0 = data.default_config; + const _errs2 = errors; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "enabled")) { + validate110.errors = [{ instancePath: instancePath + "/default_config", schemaPath: "#/$defs/ExperimentalTracerConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.enabled !== undefined) { + if (typeof data0.enabled !== "boolean") { + validate110.errors = [{ instancePath: instancePath + "/default_config/enabled", schemaPath: "#/$defs/ExperimentalTracerConfig/properties/enabled/type", keyword: "type", params: { type: schema133.properties.enabled.type }, message: "must be boolean" }]; + return false; + } + } + } + } else { + validate110.errors = [{ instancePath: instancePath + "/default_config", schemaPath: "#/$defs/ExperimentalTracerConfig/type", keyword: "type", params: { type: schema133.type }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.tracers !== undefined) { + let data2 = data.tracers; + const _errs8 = errors; + if (errors === _errs8) { + if (Array.isArray(data2)) { + if (data2.length < 1) { + validate110.errors = [{ instancePath: instancePath + "/tracers", schemaPath: "#/properties/tracers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data2.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs10 = errors; + if (!validate111(data2[i0], { instancePath: instancePath + "/tracers/" + i0, parentData: data2, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate111.errors : vErrors.concat(validate111.errors); + errors = vErrors.length; + } + var valid3 = _errs10 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate110.errors = [{ instancePath: instancePath + "/tracers", schemaPath: "#/properties/tracers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + } + } + } else { + validate110.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: schema132.type }, message: "must be object" }]; + return false; + } + } + validate110.errors = vErrors; + return errors === 0; + } + validate110.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate84(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate84.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.processors === undefined && (missing0 = "processors")) { + validate84.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "processors" || key0 === "limits" || key0 === "sampler" || key0 === "tracer_configurator/development")) { + validate84.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.processors !== undefined) { + let data0 = data.processors; + const _errs2 = errors; + if (errors === _errs2) { + if (Array.isArray(data0)) { + if (data0.length < 1) { + validate84.errors = [{ instancePath: instancePath + "/processors", schemaPath: "#/properties/processors/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data0.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs4 = errors; + if (!validate85(data0[i0], { instancePath: instancePath + "/processors/" + i0, parentData: data0, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate85.errors : vErrors.concat(validate85.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate84.errors = [{ instancePath: instancePath + "/processors", schemaPath: "#/properties/processors/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.limits !== undefined) { + let data2 = data.limits; + const _errs5 = errors; + const _errs6 = errors; + if (errors === _errs6) { + if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { + const _errs8 = errors; + for (const key1 in data2) { + if (!(key1 === "attribute_value_length_limit" || key1 === "attribute_count_limit" || key1 === "event_count_limit" || key1 === "link_count_limit" || key1 === "event_attribute_count_limit" || key1 === "link_attribute_count_limit")) { + validate84.errors = [{ instancePath: instancePath + "/limits", schemaPath: "#/$defs/SpanLimits/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs8 === errors) { + if (data2.attribute_value_length_limit !== undefined) { + let data3 = data2.attribute_value_length_limit; + const _errs9 = errors; + if (!(typeof data3 == "number" && (!(data3 % 1) && !isNaN(data3))) && data3 !== null) { + validate84.errors = [{ instancePath: instancePath + "/limits/attribute_value_length_limit", schemaPath: "#/$defs/SpanLimits/properties/attribute_value_length_limit/type", keyword: "type", params: { type: schema113.properties.attribute_value_length_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs9) { + if (typeof data3 == "number") { + if (data3 < 0 || isNaN(data3)) { + validate84.errors = [{ instancePath: instancePath + "/limits/attribute_value_length_limit", schemaPath: "#/$defs/SpanLimits/properties/attribute_value_length_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs9 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data2.attribute_count_limit !== undefined) { + let data4 = data2.attribute_count_limit; + const _errs11 = errors; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4))) && data4 !== null) { + validate84.errors = [{ instancePath: instancePath + "/limits/attribute_count_limit", schemaPath: "#/$defs/SpanLimits/properties/attribute_count_limit/type", keyword: "type", params: { type: schema113.properties.attribute_count_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs11) { + if (typeof data4 == "number") { + if (data4 < 0 || isNaN(data4)) { + validate84.errors = [{ instancePath: instancePath + "/limits/attribute_count_limit", schemaPath: "#/$defs/SpanLimits/properties/attribute_count_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs11 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data2.event_count_limit !== undefined) { + let data5 = data2.event_count_limit; + const _errs13 = errors; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5))) && data5 !== null) { + validate84.errors = [{ instancePath: instancePath + "/limits/event_count_limit", schemaPath: "#/$defs/SpanLimits/properties/event_count_limit/type", keyword: "type", params: { type: schema113.properties.event_count_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs13) { + if (typeof data5 == "number") { + if (data5 < 0 || isNaN(data5)) { + validate84.errors = [{ instancePath: instancePath + "/limits/event_count_limit", schemaPath: "#/$defs/SpanLimits/properties/event_count_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs13 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data2.link_count_limit !== undefined) { + let data6 = data2.link_count_limit; + const _errs15 = errors; + if (!(typeof data6 == "number" && (!(data6 % 1) && !isNaN(data6))) && data6 !== null) { + validate84.errors = [{ instancePath: instancePath + "/limits/link_count_limit", schemaPath: "#/$defs/SpanLimits/properties/link_count_limit/type", keyword: "type", params: { type: schema113.properties.link_count_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs15) { + if (typeof data6 == "number") { + if (data6 < 0 || isNaN(data6)) { + validate84.errors = [{ instancePath: instancePath + "/limits/link_count_limit", schemaPath: "#/$defs/SpanLimits/properties/link_count_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs15 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data2.event_attribute_count_limit !== undefined) { + let data7 = data2.event_attribute_count_limit; + const _errs17 = errors; + if (!(typeof data7 == "number" && (!(data7 % 1) && !isNaN(data7))) && data7 !== null) { + validate84.errors = [{ instancePath: instancePath + "/limits/event_attribute_count_limit", schemaPath: "#/$defs/SpanLimits/properties/event_attribute_count_limit/type", keyword: "type", params: { type: schema113.properties.event_attribute_count_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs17) { + if (typeof data7 == "number") { + if (data7 < 0 || isNaN(data7)) { + validate84.errors = [{ instancePath: instancePath + "/limits/event_attribute_count_limit", schemaPath: "#/$defs/SpanLimits/properties/event_attribute_count_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs17 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data2.link_attribute_count_limit !== undefined) { + let data8 = data2.link_attribute_count_limit; + const _errs19 = errors; + if (!(typeof data8 == "number" && (!(data8 % 1) && !isNaN(data8))) && data8 !== null) { + validate84.errors = [{ instancePath: instancePath + "/limits/link_attribute_count_limit", schemaPath: "#/$defs/SpanLimits/properties/link_attribute_count_limit/type", keyword: "type", params: { type: schema113.properties.link_attribute_count_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs19) { + if (typeof data8 == "number") { + if (data8 < 0 || isNaN(data8)) { + validate84.errors = [{ instancePath: instancePath + "/limits/link_attribute_count_limit", schemaPath: "#/$defs/SpanLimits/properties/link_attribute_count_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs19 === errors; + } else { + var valid3 = true; + } + } + } + } + } + } + } + } else { + validate84.errors = [{ instancePath: instancePath + "/limits", schemaPath: "#/$defs/SpanLimits/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.sampler !== undefined) { + const _errs21 = errors; + if (!validate96(data.sampler, { instancePath: instancePath + "/sampler", parentData: data, parentDataProperty: "sampler", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate96.errors : vErrors.concat(validate96.errors); + errors = vErrors.length; + } + var valid0 = _errs21 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data["tracer_configurator/development"] !== undefined) { + const _errs22 = errors; + if (!validate110(data["tracer_configurator/development"], { instancePath: instancePath + "/tracer_configurator~1development", parentData: data, parentDataProperty: "tracer_configurator/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate110.errors : vErrors.concat(validate110.errors); + errors = vErrors.length; + } + var valid0 = _errs22 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } else { + validate84.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate84.errors = vErrors; + return errors === 0; + } + validate84.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema136 = { type: "object", additionalProperties: false, properties: { attributes: { type: "array", minItems: 1, items: { $ref: "#/$defs/AttributeNameValue" }, description: `Configure resource attributes. Entries have higher priority than entries from .resource.attributes_list. +If omitted, no resource attributes are added. +` }, "detection/development": { $ref: "#/$defs/ExperimentalResourceDetection", description: `Configure resource detection. +If omitted, resource detection is disabled. +` }, schema_url: { type: ["string", "null"], description: `Configure resource schema URL. +If omitted or null, no schema URL is used. +` }, attributes_list: { type: ["string", "null"], description: `Configure resource attributes. Entries have lower priority than entries from .resource.attributes. +The value is a list of comma separated key-value pairs matching the format of OTEL_RESOURCE_ATTRIBUTES. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration for details. +If omitted or null, no resource attributes are added. +` } } }; + var schema138 = { type: ["string", "null"], enum: ["string", "bool", "int", "double", "string_array", "bool_array", "int_array", "double_array"] }; + function validate116(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate116.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.name === undefined && (missing0 = "name") || data.value === undefined && (missing0 = "value")) { + validate116.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "name" || key0 === "value" || key0 === "type")) { + validate116.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.name !== undefined) { + const _errs2 = errors; + if (typeof data.name !== "string") { + validate116.errors = [{ instancePath: instancePath + "/name", schemaPath: "#/properties/name/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.value !== undefined) { + let data1 = data.value; + const _errs4 = errors; + const _errs5 = errors; + let valid1 = false; + let passing0 = null; + const _errs6 = errors; + if (typeof data1 !== "string") { + const err0 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err0]; + } else { + vErrors.push(err0); + } + errors++; + } + var _valid0 = _errs6 === errors; + if (_valid0) { + valid1 = true; + passing0 = 0; + } + const _errs8 = errors; + if (!(typeof data1 == "number")) { + const err1 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/1/type", keyword: "type", params: { type: "number" }, message: "must be number" }; + if (vErrors === null) { + vErrors = [err1]; + } else { + vErrors.push(err1); + } + errors++; + } + var _valid0 = _errs8 === errors; + if (_valid0 && valid1) { + valid1 = false; + passing0 = [passing0, 1]; + } else { + if (_valid0) { + valid1 = true; + passing0 = 1; + } + const _errs10 = errors; + if (typeof data1 !== "boolean") { + const err2 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/2/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; + if (vErrors === null) { + vErrors = [err2]; + } else { + vErrors.push(err2); + } + errors++; + } + var _valid0 = _errs10 === errors; + if (_valid0 && valid1) { + valid1 = false; + passing0 = [passing0, 2]; + } else { + if (_valid0) { + valid1 = true; + passing0 = 2; + } + const _errs12 = errors; + if (data1 !== null) { + const err3 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/3/type", keyword: "type", params: { type: "null" }, message: "must be null" }; + if (vErrors === null) { + vErrors = [err3]; + } else { + vErrors.push(err3); + } + errors++; + } + var _valid0 = _errs12 === errors; + if (_valid0 && valid1) { + valid1 = false; + passing0 = [passing0, 3]; + } else { + if (_valid0) { + valid1 = true; + passing0 = 3; + } + const _errs14 = errors; + if (errors === _errs14) { + if (Array.isArray(data1)) { + if (data1.length < 1) { + const err4 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/4/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; + if (vErrors === null) { + vErrors = [err4]; + } else { + vErrors.push(err4); + } + errors++; + } else { + var valid2 = true; + const len0 = data1.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs16 = errors; + if (typeof data1[i0] !== "string") { + const err5 = { instancePath: instancePath + "/value/" + i0, schemaPath: "#/properties/value/oneOf/4/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }; + if (vErrors === null) { + vErrors = [err5]; + } else { + vErrors.push(err5); + } + errors++; + } + var valid2 = _errs16 === errors; + if (!valid2) { + break; + } + } + } + } else { + const err6 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/4/type", keyword: "type", params: { type: "array" }, message: "must be array" }; + if (vErrors === null) { + vErrors = [err6]; + } else { + vErrors.push(err6); + } + errors++; + } + } + var _valid0 = _errs14 === errors; + if (_valid0 && valid1) { + valid1 = false; + passing0 = [passing0, 4]; + } else { + if (_valid0) { + valid1 = true; + passing0 = 4; + var items0 = true; + } + const _errs18 = errors; + if (errors === _errs18) { + if (Array.isArray(data1)) { + if (data1.length < 1) { + const err7 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/5/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; + if (vErrors === null) { + vErrors = [err7]; + } else { + vErrors.push(err7); + } + errors++; + } else { + var valid3 = true; + const len1 = data1.length; + for (let i1 = 0;i1 < len1; i1++) { + const _errs20 = errors; + if (typeof data1[i1] !== "boolean") { + const err8 = { instancePath: instancePath + "/value/" + i1, schemaPath: "#/properties/value/oneOf/5/items/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; + if (vErrors === null) { + vErrors = [err8]; + } else { + vErrors.push(err8); + } + errors++; + } + var valid3 = _errs20 === errors; + if (!valid3) { + break; + } + } + } + } else { + const err9 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/5/type", keyword: "type", params: { type: "array" }, message: "must be array" }; + if (vErrors === null) { + vErrors = [err9]; + } else { + vErrors.push(err9); + } + errors++; + } + } + var _valid0 = _errs18 === errors; + if (_valid0 && valid1) { + valid1 = false; + passing0 = [passing0, 5]; + } else { + if (_valid0) { + valid1 = true; + passing0 = 5; + if (items0 !== true) { + items0 = true; + } + } + const _errs22 = errors; + if (errors === _errs22) { + if (Array.isArray(data1)) { + if (data1.length < 1) { + const err10 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/6/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; + if (vErrors === null) { + vErrors = [err10]; + } else { + vErrors.push(err10); + } + errors++; + } else { + var valid4 = true; + const len2 = data1.length; + for (let i2 = 0;i2 < len2; i2++) { + const _errs24 = errors; + if (!(typeof data1[i2] == "number")) { + const err11 = { instancePath: instancePath + "/value/" + i2, schemaPath: "#/properties/value/oneOf/6/items/type", keyword: "type", params: { type: "number" }, message: "must be number" }; + if (vErrors === null) { + vErrors = [err11]; + } else { + vErrors.push(err11); + } + errors++; + } + var valid4 = _errs24 === errors; + if (!valid4) { + break; + } + } + } + } else { + const err12 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf/6/type", keyword: "type", params: { type: "array" }, message: "must be array" }; + if (vErrors === null) { + vErrors = [err12]; + } else { + vErrors.push(err12); + } + errors++; + } + } + var _valid0 = _errs22 === errors; + if (_valid0 && valid1) { + valid1 = false; + passing0 = [passing0, 6]; + } else { + if (_valid0) { + valid1 = true; + passing0 = 6; + if (items0 !== true) { + items0 = true; + } + } + } + } + } + } + } + } + if (!valid1) { + const err13 = { instancePath: instancePath + "/value", schemaPath: "#/properties/value/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; + if (vErrors === null) { + vErrors = [err13]; + } else { + vErrors.push(err13); + } + errors++; + validate116.errors = vErrors; + return false; + } else { + errors = _errs5; + if (vErrors !== null) { + if (_errs5) { + vErrors.length = _errs5; + } else { + vErrors = null; + } + } + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.type !== undefined) { + let data5 = data.type; + const _errs26 = errors; + if (typeof data5 !== "string" && data5 !== null) { + validate116.errors = [{ instancePath: instancePath + "/type", schemaPath: "#/$defs/AttributeType/type", keyword: "type", params: { type: schema138.type }, message: "must be string,null" }]; + return false; + } + if (!(data5 === "string" || data5 === "bool" || data5 === "int" || data5 === "double" || data5 === "string_array" || data5 === "bool_array" || data5 === "int_array" || data5 === "double_array")) { + validate116.errors = [{ instancePath: instancePath + "/type", schemaPath: "#/$defs/AttributeType/enum", keyword: "enum", params: { allowedValues: schema138.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs26 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } else { + validate116.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate116.errors = vErrors; + return errors === 0; + } + validate116.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema141 = { type: "object", additionalProperties: { type: ["object", "null"] }, minProperties: 1, maxProperties: 1, properties: { container: { $ref: "#/$defs/ExperimentalContainerResourceDetector", description: `Enable the container resource detector, which populates container.* attributes. +If omitted, ignore. +` }, host: { $ref: "#/$defs/ExperimentalHostResourceDetector", description: `Enable the host resource detector, which populates host.* and os.* attributes. +If omitted, ignore. +` }, process: { $ref: "#/$defs/ExperimentalProcessResourceDetector", description: `Enable the process resource detector, which populates process.* attributes. +If omitted, ignore. +` }, service: { $ref: "#/$defs/ExperimentalServiceResourceDetector", description: `Enable the service detector, which populates service.name based on the OTEL_SERVICE_NAME environment variable and service.instance.id. +If omitted, ignore. +` } } }; + var schema142 = { type: ["object", "null"], additionalProperties: false }; + var schema143 = { type: ["object", "null"], additionalProperties: false }; + var schema144 = { type: ["object", "null"], additionalProperties: false }; + var schema145 = { type: ["object", "null"], additionalProperties: false }; + function validate119(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate119.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + if (Object.keys(data).length > 1) { + validate119.errors = [{ instancePath, schemaPath: "#/maxProperties", keyword: "maxProperties", params: { limit: 1 }, message: "must NOT have more than 1 properties" }]; + return false; + } else { + if (Object.keys(data).length < 1) { + validate119.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "container" || key0 === "host" || key0 === "process" || key0 === "service")) { + let data0 = data[key0]; + const _errs2 = errors; + if (!(data0 && typeof data0 == "object" && !Array.isArray(data0)) && data0 !== null) { + validate119.errors = [{ instancePath: instancePath + "/" + key0.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/additionalProperties/type", keyword: "type", params: { type: schema141.additionalProperties.type }, message: "must be object,null" }]; + return false; + } + var valid0 = _errs2 === errors; + if (!valid0) { + break; + } + } + } + if (_errs1 === errors) { + if (data.container !== undefined) { + let data1 = data.container; + const _errs4 = errors; + const _errs5 = errors; + if (!(data1 && typeof data1 == "object" && !Array.isArray(data1)) && data1 !== null) { + validate119.errors = [{ instancePath: instancePath + "/container", schemaPath: "#/$defs/ExperimentalContainerResourceDetector/type", keyword: "type", params: { type: schema142.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs5) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + for (const key1 in data1) { + validate119.errors = [{ instancePath: instancePath + "/container", schemaPath: "#/$defs/ExperimentalContainerResourceDetector/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs4 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.host !== undefined) { + let data2 = data.host; + const _errs8 = errors; + const _errs9 = errors; + if (!(data2 && typeof data2 == "object" && !Array.isArray(data2)) && data2 !== null) { + validate119.errors = [{ instancePath: instancePath + "/host", schemaPath: "#/$defs/ExperimentalHostResourceDetector/type", keyword: "type", params: { type: schema143.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs9) { + if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { + for (const key2 in data2) { + validate119.errors = [{ instancePath: instancePath + "/host", schemaPath: "#/$defs/ExperimentalHostResourceDetector/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs8 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.process !== undefined) { + let data3 = data.process; + const _errs12 = errors; + const _errs13 = errors; + if (!(data3 && typeof data3 == "object" && !Array.isArray(data3)) && data3 !== null) { + validate119.errors = [{ instancePath: instancePath + "/process", schemaPath: "#/$defs/ExperimentalProcessResourceDetector/type", keyword: "type", params: { type: schema144.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs13) { + if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { + for (const key3 in data3) { + validate119.errors = [{ instancePath: instancePath + "/process", schemaPath: "#/$defs/ExperimentalProcessResourceDetector/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs12 === errors; + } else { + var valid1 = true; + } + if (valid1) { + if (data.service !== undefined) { + let data4 = data.service; + const _errs16 = errors; + const _errs17 = errors; + if (!(data4 && typeof data4 == "object" && !Array.isArray(data4)) && data4 !== null) { + validate119.errors = [{ instancePath: instancePath + "/service", schemaPath: "#/$defs/ExperimentalServiceResourceDetector/type", keyword: "type", params: { type: schema145.type }, message: "must be object,null" }]; + return false; + } + if (errors === _errs17) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + for (const key4 in data4) { + validate119.errors = [{ instancePath: instancePath + "/service", schemaPath: "#/$defs/ExperimentalServiceResourceDetector/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key4 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + } + var valid1 = _errs16 === errors; + } else { + var valid1 = true; + } + } + } + } + } + } + } + } else { + validate119.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate119.errors = vErrors; + return errors === 0; + } + validate119.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate118(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate118.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "attributes" || key0 === "detectors")) { + validate118.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.attributes !== undefined) { + let data0 = data.attributes; + const _errs2 = errors; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "included" || key1 === "excluded")) { + validate118.errors = [{ instancePath: instancePath + "/attributes", schemaPath: "#/$defs/IncludeExclude/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.included !== undefined) { + let data1 = data0.included; + const _errs6 = errors; + if (errors === _errs6) { + if (Array.isArray(data1)) { + if (data1.length < 1) { + validate118.errors = [{ instancePath: instancePath + "/attributes/included", schemaPath: "#/$defs/IncludeExclude/properties/included/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data1.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs8 = errors; + if (typeof data1[i0] !== "string") { + validate118.errors = [{ instancePath: instancePath + "/attributes/included/" + i0, schemaPath: "#/$defs/IncludeExclude/properties/included/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid3 = _errs8 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate118.errors = [{ instancePath: instancePath + "/attributes/included", schemaPath: "#/$defs/IncludeExclude/properties/included/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.excluded !== undefined) { + let data3 = data0.excluded; + const _errs10 = errors; + if (errors === _errs10) { + if (Array.isArray(data3)) { + if (data3.length < 1) { + validate118.errors = [{ instancePath: instancePath + "/attributes/excluded", schemaPath: "#/$defs/IncludeExclude/properties/excluded/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid4 = true; + const len1 = data3.length; + for (let i1 = 0;i1 < len1; i1++) { + const _errs12 = errors; + if (typeof data3[i1] !== "string") { + validate118.errors = [{ instancePath: instancePath + "/attributes/excluded/" + i1, schemaPath: "#/$defs/IncludeExclude/properties/excluded/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid4 = _errs12 === errors; + if (!valid4) { + break; + } + } + } + } else { + validate118.errors = [{ instancePath: instancePath + "/attributes/excluded", schemaPath: "#/$defs/IncludeExclude/properties/excluded/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + } + } + } else { + validate118.errors = [{ instancePath: instancePath + "/attributes", schemaPath: "#/$defs/IncludeExclude/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.detectors !== undefined) { + let data5 = data.detectors; + const _errs14 = errors; + if (errors === _errs14) { + if (Array.isArray(data5)) { + if (data5.length < 1) { + validate118.errors = [{ instancePath: instancePath + "/detectors", schemaPath: "#/properties/detectors/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid5 = true; + const len2 = data5.length; + for (let i2 = 0;i2 < len2; i2++) { + const _errs16 = errors; + if (!validate119(data5[i2], { instancePath: instancePath + "/detectors/" + i2, parentData: data5, parentDataProperty: i2, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate119.errors : vErrors.concat(validate119.errors); + errors = vErrors.length; + } + var valid5 = _errs16 === errors; + if (!valid5) { + break; + } + } + } + } else { + validate118.errors = [{ instancePath: instancePath + "/detectors", schemaPath: "#/properties/detectors/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs14 === errors; + } else { + var valid0 = true; + } + } + } + } else { + validate118.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate118.errors = vErrors; + return errors === 0; + } + validate118.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate115(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate115.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "attributes" || key0 === "detection/development" || key0 === "schema_url" || key0 === "attributes_list")) { + validate115.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.attributes !== undefined) { + let data0 = data.attributes; + const _errs2 = errors; + if (errors === _errs2) { + if (Array.isArray(data0)) { + if (data0.length < 1) { + validate115.errors = [{ instancePath: instancePath + "/attributes", schemaPath: "#/properties/attributes/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid1 = true; + const len0 = data0.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs4 = errors; + if (!validate116(data0[i0], { instancePath: instancePath + "/attributes/" + i0, parentData: data0, parentDataProperty: i0, rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate116.errors : vErrors.concat(validate116.errors); + errors = vErrors.length; + } + var valid1 = _errs4 === errors; + if (!valid1) { + break; + } + } + } + } else { + validate115.errors = [{ instancePath: instancePath + "/attributes", schemaPath: "#/properties/attributes/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data["detection/development"] !== undefined) { + const _errs5 = errors; + if (!validate118(data["detection/development"], { instancePath: instancePath + "/detection~1development", parentData: data, parentDataProperty: "detection/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate118.errors : vErrors.concat(validate118.errors); + errors = vErrors.length; + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.schema_url !== undefined) { + let data3 = data.schema_url; + const _errs6 = errors; + if (typeof data3 !== "string" && data3 !== null) { + validate115.errors = [{ instancePath: instancePath + "/schema_url", schemaPath: "#/properties/schema_url/type", keyword: "type", params: { type: schema136.properties.schema_url.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.attributes_list !== undefined) { + let data4 = data.attributes_list; + const _errs8 = errors; + if (typeof data4 !== "string" && data4 !== null) { + validate115.errors = [{ instancePath: instancePath + "/attributes_list", schemaPath: "#/properties/attributes_list/type", keyword: "type", params: { type: schema136.properties.attributes_list.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } else { + validate115.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate115.errors = vErrors; + return errors === 0; + } + validate115.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + var schema146 = { type: "object", additionalProperties: false, properties: { general: { $ref: "#/$defs/ExperimentalGeneralInstrumentation", description: `Configure general SemConv options that may apply to multiple languages and instrumentations. +Instrumenation may merge general config options with the language specific configuration at .instrumentation.. +If omitted, default values as described in ExperimentalGeneralInstrumentation are used. +` }, cpp: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure C++ language-specific instrumentation libraries. +If omitted, instrumentation defaults are used. +` }, dotnet: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure .NET language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, erlang: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Erlang language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, go: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Go language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, java: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Java language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, js: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure JavaScript language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, php: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure PHP language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, python: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Python language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, ruby: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Ruby language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, rust: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Rust language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` }, swift: { $ref: "#/$defs/ExperimentalLanguageSpecificInstrumentation", description: `Configure Swift language-specific instrumentation libraries. +Each entry's key identifies a particular instrumentation library. The corresponding value configures it. +If omitted, instrumentation defaults are used. +` } } }; + var schema147 = { type: "object", additionalProperties: false, properties: { http: { $ref: "#/$defs/ExperimentalHttpInstrumentation", description: `Configure instrumentations following the http semantic conventions. +See http semantic conventions: https://opentelemetry.io/docs/specs/semconv/http/ +If omitted, defaults as described in ExperimentalHttpInstrumentation are used. +` }, code: { $ref: "#/$defs/ExperimentalCodeInstrumentation", description: `Configure instrumentations following the code semantic conventions. +See code semantic conventions: https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/ +If omitted, defaults as described in ExperimentalCodeInstrumentation are used. +` }, db: { $ref: "#/$defs/ExperimentalDbInstrumentation", description: `Configure instrumentations following the database semantic conventions. +See database semantic conventions: https://opentelemetry.io/docs/specs/semconv/database/ +If omitted, defaults as described in ExperimentalDbInstrumentation are used. +` }, gen_ai: { $ref: "#/$defs/ExperimentalGenAiInstrumentation", description: `Configure instrumentations following the GenAI semantic conventions. +See GenAI semantic conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/ +If omitted, defaults as described in ExperimentalGenAiInstrumentation are used. +` }, messaging: { $ref: "#/$defs/ExperimentalMessagingInstrumentation", description: `Configure instrumentations following the messaging semantic conventions. +See messaging semantic conventions: https://opentelemetry.io/docs/specs/semconv/messaging/ +If omitted, defaults as described in ExperimentalMessagingInstrumentation are used. +` }, rpc: { $ref: "#/$defs/ExperimentalRpcInstrumentation", description: `Configure instrumentations following the RPC semantic conventions. +See RPC semantic conventions: https://opentelemetry.io/docs/specs/semconv/rpc/ +If omitted, defaults as described in ExperimentalRpcInstrumentation are used. +` }, sanitization: { $ref: "#/$defs/ExperimentalSanitization", description: `Configure general sanitization options. +If omitted, defaults as described in ExperimentalSanitization are used. +` }, stability_opt_in_list: { type: ["string", "null"], description: `Configure semantic convention stability opt-in as a comma-separated list. +This property follows the format and semantics of the OTEL_SEMCONV_STABILITY_OPT_IN environment variable. +Controls the emission of stable vs. experimental semantic conventions for instrumentation. +This setting is only intended for migrating from experimental to stable semantic conventions. + +Known values include: +- http: Emit stable HTTP and networking conventions only +- http/dup: Emit both old and stable HTTP and networking conventions (for phased migration) +- database: Emit stable database conventions only +- database/dup: Emit both old and stable database conventions (for phased migration) +- rpc: Emit stable RPC conventions only +- rpc/dup: Emit both experimental and stable RPC conventions (for phased migration) +- messaging: Emit stable messaging conventions only +- messaging/dup: Emit both old and stable messaging conventions (for phased migration) +- code: Emit stable code conventions only +- code/dup: Emit both old and stable code conventions (for phased migration) + +Multiple values can be specified as a comma-separated list (e.g., "http,database/dup"). +Additional signal types may be supported in future versions. + +Domain-specific semconv properties (e.g., .instrumentation/development.general.db.semconv) take precedence over this general setting. + +See: +- HTTP migration: https://opentelemetry.io/docs/specs/semconv/non-normative/http-migration/ +- Database migration: https://opentelemetry.io/docs/specs/semconv/database/ +- RPC: https://opentelemetry.io/docs/specs/semconv/rpc/ +- Messaging: https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/ +If omitted or null, no opt-in is configured and instrumentations continue emitting their default semantic convention version. +` } } }; + var schema149 = { type: "object", additionalProperties: false, properties: { version: { type: ["integer", "null"], minimum: 0, description: `The target semantic convention version for this domain (e.g., 1). +If omitted or null, the latest stable version is used, or if no stable version is available and .experimental is true then the latest experimental version is used. +` }, experimental: { type: ["boolean", "null"], description: `Use latest experimental semantic conventions (before stable is available or to enable experimental features on top of stable conventions). +If omitted or null, false is used. +` }, dual_emit: { type: ["boolean", "null"], description: `When true, also emit the previous major version alongside the target version. +For version=1, the previous version refers to the pre-stable conventions that the instrumentation emitted before the first stable semantic convention version was defined. +For version=2 and above, the previous version is the prior stable major version (e.g., version=2, dual_emit=true emits both v2 and v1). +Enables dual-emit for phased migration between versions. +If omitted or null, false is used. +` } } }; + function validate125(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate125.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "semconv" || key0 === "client" || key0 === "server")) { + validate125.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.semconv !== undefined) { + let data0 = data.semconv; + const _errs2 = errors; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "version" || key1 === "experimental" || key1 === "dual_emit")) { + validate125.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.version !== undefined) { + let data1 = data0.version; + const _errs6 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate125.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/type", keyword: "type", params: { type: schema149.properties.version.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate125.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.experimental !== undefined) { + let data2 = data0.experimental; + const _errs8 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate125.errors = [{ instancePath: instancePath + "/semconv/experimental", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/experimental/type", keyword: "type", params: { type: schema149.properties.experimental.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.dual_emit !== undefined) { + let data3 = data0.dual_emit; + const _errs10 = errors; + if (typeof data3 !== "boolean" && data3 !== null) { + validate125.errors = [{ instancePath: instancePath + "/semconv/dual_emit", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/dual_emit/type", keyword: "type", params: { type: schema149.properties.dual_emit.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.client !== undefined) { + let data4 = data.client; + const _errs12 = errors; + const _errs13 = errors; + if (errors === _errs13) { + if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { + const _errs15 = errors; + for (const key2 in data4) { + if (!(key2 === "request_captured_headers" || key2 === "response_captured_headers" || key2 === "known_methods")) { + validate125.errors = [{ instancePath: instancePath + "/client", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs15 === errors) { + if (data4.request_captured_headers !== undefined) { + let data5 = data4.request_captured_headers; + const _errs16 = errors; + if (errors === _errs16) { + if (Array.isArray(data5)) { + if (data5.length < 1) { + validate125.errors = [{ instancePath: instancePath + "/client/request_captured_headers", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/request_captured_headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid5 = true; + const len0 = data5.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs18 = errors; + if (typeof data5[i0] !== "string") { + validate125.errors = [{ instancePath: instancePath + "/client/request_captured_headers/" + i0, schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/request_captured_headers/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid5 = _errs18 === errors; + if (!valid5) { + break; + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/client/request_captured_headers", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/request_captured_headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid4 = _errs16 === errors; + } else { + var valid4 = true; + } + if (valid4) { + if (data4.response_captured_headers !== undefined) { + let data7 = data4.response_captured_headers; + const _errs20 = errors; + if (errors === _errs20) { + if (Array.isArray(data7)) { + if (data7.length < 1) { + validate125.errors = [{ instancePath: instancePath + "/client/response_captured_headers", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/response_captured_headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid6 = true; + const len1 = data7.length; + for (let i1 = 0;i1 < len1; i1++) { + const _errs22 = errors; + if (typeof data7[i1] !== "string") { + validate125.errors = [{ instancePath: instancePath + "/client/response_captured_headers/" + i1, schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/response_captured_headers/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid6 = _errs22 === errors; + if (!valid6) { + break; + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/client/response_captured_headers", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/response_captured_headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid4 = _errs20 === errors; + } else { + var valid4 = true; + } + if (valid4) { + if (data4.known_methods !== undefined) { + let data9 = data4.known_methods; + const _errs24 = errors; + if (errors === _errs24) { + if (Array.isArray(data9)) { + if (data9.length < 0) { + validate125.errors = [{ instancePath: instancePath + "/client/known_methods", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/known_methods/minItems", keyword: "minItems", params: { limit: 0 }, message: "must NOT have fewer than 0 items" }]; + return false; + } else { + var valid7 = true; + const len2 = data9.length; + for (let i2 = 0;i2 < len2; i2++) { + const _errs26 = errors; + if (typeof data9[i2] !== "string") { + validate125.errors = [{ instancePath: instancePath + "/client/known_methods/" + i2, schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/known_methods/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid7 = _errs26 === errors; + if (!valid7) { + break; + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/client/known_methods", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/properties/known_methods/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid4 = _errs24 === errors; + } else { + var valid4 = true; + } + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/client", schemaPath: "#/$defs/ExperimentalHttpClientInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs12 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.server !== undefined) { + let data11 = data.server; + const _errs28 = errors; + const _errs29 = errors; + if (errors === _errs29) { + if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { + const _errs31 = errors; + for (const key3 in data11) { + if (!(key3 === "request_captured_headers" || key3 === "response_captured_headers" || key3 === "known_methods")) { + validate125.errors = [{ instancePath: instancePath + "/server", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs31 === errors) { + if (data11.request_captured_headers !== undefined) { + let data12 = data11.request_captured_headers; + const _errs32 = errors; + if (errors === _errs32) { + if (Array.isArray(data12)) { + if (data12.length < 1) { + validate125.errors = [{ instancePath: instancePath + "/server/request_captured_headers", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/request_captured_headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid10 = true; + const len3 = data12.length; + for (let i3 = 0;i3 < len3; i3++) { + const _errs34 = errors; + if (typeof data12[i3] !== "string") { + validate125.errors = [{ instancePath: instancePath + "/server/request_captured_headers/" + i3, schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/request_captured_headers/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid10 = _errs34 === errors; + if (!valid10) { + break; + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/server/request_captured_headers", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/request_captured_headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid9 = _errs32 === errors; + } else { + var valid9 = true; + } + if (valid9) { + if (data11.response_captured_headers !== undefined) { + let data14 = data11.response_captured_headers; + const _errs36 = errors; + if (errors === _errs36) { + if (Array.isArray(data14)) { + if (data14.length < 1) { + validate125.errors = [{ instancePath: instancePath + "/server/response_captured_headers", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/response_captured_headers/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; + return false; + } else { + var valid11 = true; + const len4 = data14.length; + for (let i4 = 0;i4 < len4; i4++) { + const _errs38 = errors; + if (typeof data14[i4] !== "string") { + validate125.errors = [{ instancePath: instancePath + "/server/response_captured_headers/" + i4, schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/response_captured_headers/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid11 = _errs38 === errors; + if (!valid11) { + break; + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/server/response_captured_headers", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/response_captured_headers/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid9 = _errs36 === errors; + } else { + var valid9 = true; + } + if (valid9) { + if (data11.known_methods !== undefined) { + let data16 = data11.known_methods; + const _errs40 = errors; + if (errors === _errs40) { + if (Array.isArray(data16)) { + if (data16.length < 0) { + validate125.errors = [{ instancePath: instancePath + "/server/known_methods", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/known_methods/minItems", keyword: "minItems", params: { limit: 0 }, message: "must NOT have fewer than 0 items" }]; + return false; + } else { + var valid12 = true; + const len5 = data16.length; + for (let i5 = 0;i5 < len5; i5++) { + const _errs42 = errors; + if (typeof data16[i5] !== "string") { + validate125.errors = [{ instancePath: instancePath + "/server/known_methods/" + i5, schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/known_methods/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid12 = _errs42 === errors; + if (!valid12) { + break; + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/server/known_methods", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/properties/known_methods/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + var valid9 = _errs40 === errors; + } else { + var valid9 = true; + } + } + } + } + } else { + validate125.errors = [{ instancePath: instancePath + "/server", schemaPath: "#/$defs/ExperimentalHttpServerInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs28 === errors; + } else { + var valid0 = true; + } + } + } + } + } else { + validate125.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate125.errors = vErrors; + return errors === 0; + } + validate125.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate127(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate127.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "semconv")) { + validate127.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.semconv !== undefined) { + let data0 = data.semconv; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "version" || key1 === "experimental" || key1 === "dual_emit")) { + validate127.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.version !== undefined) { + let data1 = data0.version; + const _errs6 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate127.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/type", keyword: "type", params: { type: schema149.properties.version.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate127.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.experimental !== undefined) { + let data2 = data0.experimental; + const _errs8 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate127.errors = [{ instancePath: instancePath + "/semconv/experimental", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/experimental/type", keyword: "type", params: { type: schema149.properties.experimental.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.dual_emit !== undefined) { + let data3 = data0.dual_emit; + const _errs10 = errors; + if (typeof data3 !== "boolean" && data3 !== null) { + validate127.errors = [{ instancePath: instancePath + "/semconv/dual_emit", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/dual_emit/type", keyword: "type", params: { type: schema149.properties.dual_emit.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + } + } + } + } else { + validate127.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + } + } + } else { + validate127.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate127.errors = vErrors; + return errors === 0; + } + validate127.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate129(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate129.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "semconv")) { + validate129.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.semconv !== undefined) { + let data0 = data.semconv; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "version" || key1 === "experimental" || key1 === "dual_emit")) { + validate129.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.version !== undefined) { + let data1 = data0.version; + const _errs6 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate129.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/type", keyword: "type", params: { type: schema149.properties.version.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate129.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.experimental !== undefined) { + let data2 = data0.experimental; + const _errs8 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate129.errors = [{ instancePath: instancePath + "/semconv/experimental", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/experimental/type", keyword: "type", params: { type: schema149.properties.experimental.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.dual_emit !== undefined) { + let data3 = data0.dual_emit; + const _errs10 = errors; + if (typeof data3 !== "boolean" && data3 !== null) { + validate129.errors = [{ instancePath: instancePath + "/semconv/dual_emit", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/dual_emit/type", keyword: "type", params: { type: schema149.properties.dual_emit.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + } + } + } + } else { + validate129.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + } + } + } else { + validate129.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate129.errors = vErrors; + return errors === 0; + } + validate129.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate131(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate131.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "semconv")) { + validate131.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.semconv !== undefined) { + let data0 = data.semconv; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "version" || key1 === "experimental" || key1 === "dual_emit")) { + validate131.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.version !== undefined) { + let data1 = data0.version; + const _errs6 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate131.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/type", keyword: "type", params: { type: schema149.properties.version.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate131.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.experimental !== undefined) { + let data2 = data0.experimental; + const _errs8 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate131.errors = [{ instancePath: instancePath + "/semconv/experimental", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/experimental/type", keyword: "type", params: { type: schema149.properties.experimental.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.dual_emit !== undefined) { + let data3 = data0.dual_emit; + const _errs10 = errors; + if (typeof data3 !== "boolean" && data3 !== null) { + validate131.errors = [{ instancePath: instancePath + "/semconv/dual_emit", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/dual_emit/type", keyword: "type", params: { type: schema149.properties.dual_emit.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + } + } + } + } else { + validate131.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + } + } + } else { + validate131.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate131.errors = vErrors; + return errors === 0; + } + validate131.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate133(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate133.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "semconv")) { + validate133.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.semconv !== undefined) { + let data0 = data.semconv; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "version" || key1 === "experimental" || key1 === "dual_emit")) { + validate133.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.version !== undefined) { + let data1 = data0.version; + const _errs6 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate133.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/type", keyword: "type", params: { type: schema149.properties.version.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate133.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.experimental !== undefined) { + let data2 = data0.experimental; + const _errs8 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate133.errors = [{ instancePath: instancePath + "/semconv/experimental", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/experimental/type", keyword: "type", params: { type: schema149.properties.experimental.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.dual_emit !== undefined) { + let data3 = data0.dual_emit; + const _errs10 = errors; + if (typeof data3 !== "boolean" && data3 !== null) { + validate133.errors = [{ instancePath: instancePath + "/semconv/dual_emit", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/dual_emit/type", keyword: "type", params: { type: schema149.properties.dual_emit.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + } + } + } + } else { + validate133.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + } + } + } else { + validate133.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate133.errors = vErrors; + return errors === 0; + } + validate133.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate135(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate135.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "semconv")) { + validate135.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.semconv !== undefined) { + let data0 = data.semconv; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "version" || key1 === "experimental" || key1 === "dual_emit")) { + validate135.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.version !== undefined) { + let data1 = data0.version; + const _errs6 = errors; + if (!(typeof data1 == "number" && (!(data1 % 1) && !isNaN(data1))) && data1 !== null) { + validate135.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/type", keyword: "type", params: { type: schema149.properties.version.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs6) { + if (typeof data1 == "number") { + if (data1 < 0 || isNaN(data1)) { + validate135.errors = [{ instancePath: instancePath + "/semconv/version", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/version/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid2 = _errs6 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.experimental !== undefined) { + let data2 = data0.experimental; + const _errs8 = errors; + if (typeof data2 !== "boolean" && data2 !== null) { + validate135.errors = [{ instancePath: instancePath + "/semconv/experimental", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/experimental/type", keyword: "type", params: { type: schema149.properties.experimental.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs8 === errors; + } else { + var valid2 = true; + } + if (valid2) { + if (data0.dual_emit !== undefined) { + let data3 = data0.dual_emit; + const _errs10 = errors; + if (typeof data3 !== "boolean" && data3 !== null) { + validate135.errors = [{ instancePath: instancePath + "/semconv/dual_emit", schemaPath: "#/$defs/ExperimentalSemconvConfig/properties/dual_emit/type", keyword: "type", params: { type: schema149.properties.dual_emit.type }, message: "must be boolean,null" }]; + return false; + } + var valid2 = _errs10 === errors; + } else { + var valid2 = true; + } + } + } + } + } else { + validate135.errors = [{ instancePath: instancePath + "/semconv", schemaPath: "#/$defs/ExperimentalSemconvConfig/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + } + } + } else { + validate135.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate135.errors = vErrors; + return errors === 0; + } + validate135.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate137(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate137.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "url")) { + validate137.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.url !== undefined) { + let data0 = data.url; + const _errs3 = errors; + if (errors === _errs3) { + if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { + const _errs5 = errors; + for (const key1 in data0) { + if (!(key1 === "sensitive_query_parameters")) { + validate137.errors = [{ instancePath: instancePath + "/url", schemaPath: "#/$defs/ExperimentalUrlSanitization/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs5 === errors) { + if (data0.sensitive_query_parameters !== undefined) { + let data1 = data0.sensitive_query_parameters; + const _errs6 = errors; + if (errors === _errs6) { + if (Array.isArray(data1)) { + if (data1.length < 0) { + validate137.errors = [{ instancePath: instancePath + "/url/sensitive_query_parameters", schemaPath: "#/$defs/ExperimentalUrlSanitization/properties/sensitive_query_parameters/minItems", keyword: "minItems", params: { limit: 0 }, message: "must NOT have fewer than 0 items" }]; + return false; + } else { + var valid3 = true; + const len0 = data1.length; + for (let i0 = 0;i0 < len0; i0++) { + const _errs8 = errors; + if (typeof data1[i0] !== "string") { + validate137.errors = [{ instancePath: instancePath + "/url/sensitive_query_parameters/" + i0, schemaPath: "#/$defs/ExperimentalUrlSanitization/properties/sensitive_query_parameters/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid3 = _errs8 === errors; + if (!valid3) { + break; + } + } + } + } else { + validate137.errors = [{ instancePath: instancePath + "/url/sensitive_query_parameters", schemaPath: "#/$defs/ExperimentalUrlSanitization/properties/sensitive_query_parameters/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; + return false; + } + } + } + } + } else { + validate137.errors = [{ instancePath: instancePath + "/url", schemaPath: "#/$defs/ExperimentalUrlSanitization/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + } + } + } else { + validate137.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate137.errors = vErrors; + return errors === 0; + } + validate137.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate124(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate124.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!(key0 === "http" || key0 === "code" || key0 === "db" || key0 === "gen_ai" || key0 === "messaging" || key0 === "rpc" || key0 === "sanitization" || key0 === "stability_opt_in_list")) { + validate124.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.http !== undefined) { + const _errs2 = errors; + if (!validate125(data.http, { instancePath: instancePath + "/http", parentData: data, parentDataProperty: "http", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate125.errors : vErrors.concat(validate125.errors); + errors = vErrors.length; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.code !== undefined) { + const _errs3 = errors; + if (!validate127(data.code, { instancePath: instancePath + "/code", parentData: data, parentDataProperty: "code", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate127.errors : vErrors.concat(validate127.errors); + errors = vErrors.length; + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.db !== undefined) { + const _errs4 = errors; + if (!validate129(data.db, { instancePath: instancePath + "/db", parentData: data, parentDataProperty: "db", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate129.errors : vErrors.concat(validate129.errors); + errors = vErrors.length; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.gen_ai !== undefined) { + const _errs5 = errors; + if (!validate131(data.gen_ai, { instancePath: instancePath + "/gen_ai", parentData: data, parentDataProperty: "gen_ai", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate131.errors : vErrors.concat(validate131.errors); + errors = vErrors.length; + } + var valid0 = _errs5 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.messaging !== undefined) { + const _errs6 = errors; + if (!validate133(data.messaging, { instancePath: instancePath + "/messaging", parentData: data, parentDataProperty: "messaging", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate133.errors : vErrors.concat(validate133.errors); + errors = vErrors.length; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.rpc !== undefined) { + const _errs7 = errors; + if (!validate135(data.rpc, { instancePath: instancePath + "/rpc", parentData: data, parentDataProperty: "rpc", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate135.errors : vErrors.concat(validate135.errors); + errors = vErrors.length; + } + var valid0 = _errs7 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.sanitization !== undefined) { + const _errs8 = errors; + if (!validate137(data.sanitization, { instancePath: instancePath + "/sanitization", parentData: data, parentDataProperty: "sanitization", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate137.errors : vErrors.concat(validate137.errors); + errors = vErrors.length; + } + var valid0 = _errs8 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.stability_opt_in_list !== undefined) { + let data7 = data.stability_opt_in_list; + const _errs9 = errors; + if (typeof data7 !== "string" && data7 !== null) { + validate124.errors = [{ instancePath: instancePath + "/stability_opt_in_list", schemaPath: "#/properties/stability_opt_in_list/type", keyword: "type", params: { type: schema147.properties.stability_opt_in_list.type }, message: "must be string,null" }]; + return false; + } + var valid0 = _errs9 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } else { + validate124.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate124.errors = vErrors; + return errors === 0; + } + validate124.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate123(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate123.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + const _errs1 = errors; + for (const key0 in data) { + if (!func1.call(schema146.properties, key0)) { + validate123.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs1 === errors) { + if (data.general !== undefined) { + const _errs2 = errors; + if (!validate124(data.general, { instancePath: instancePath + "/general", parentData: data, parentDataProperty: "general", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate124.errors : vErrors.concat(validate124.errors); + errors = vErrors.length; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.cpp !== undefined) { + let data1 = data.cpp; + const _errs3 = errors; + const _errs4 = errors; + if (errors === _errs4) { + if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { + for (const key1 in data1) { + let data2 = data1[key1]; + const _errs7 = errors; + if (!(data2 && typeof data2 == "object" && !Array.isArray(data2))) { + validate123.errors = [{ instancePath: instancePath + "/cpp/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid2 = _errs7 === errors; + if (!valid2) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/cpp", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs3 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.dotnet !== undefined) { + let data3 = data.dotnet; + const _errs9 = errors; + const _errs10 = errors; + if (errors === _errs10) { + if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { + for (const key2 in data3) { + let data4 = data3[key2]; + const _errs13 = errors; + if (!(data4 && typeof data4 == "object" && !Array.isArray(data4))) { + validate123.errors = [{ instancePath: instancePath + "/dotnet/" + key2.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid4 = _errs13 === errors; + if (!valid4) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/dotnet", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs9 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.erlang !== undefined) { + let data5 = data.erlang; + const _errs15 = errors; + const _errs16 = errors; + if (errors === _errs16) { + if (data5 && typeof data5 == "object" && !Array.isArray(data5)) { + for (const key3 in data5) { + let data6 = data5[key3]; + const _errs19 = errors; + if (!(data6 && typeof data6 == "object" && !Array.isArray(data6))) { + validate123.errors = [{ instancePath: instancePath + "/erlang/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid6 = _errs19 === errors; + if (!valid6) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/erlang", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs15 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.go !== undefined) { + let data7 = data.go; + const _errs21 = errors; + const _errs22 = errors; + if (errors === _errs22) { + if (data7 && typeof data7 == "object" && !Array.isArray(data7)) { + for (const key4 in data7) { + let data8 = data7[key4]; + const _errs25 = errors; + if (!(data8 && typeof data8 == "object" && !Array.isArray(data8))) { + validate123.errors = [{ instancePath: instancePath + "/go/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid8 = _errs25 === errors; + if (!valid8) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/go", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs21 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.java !== undefined) { + let data9 = data.java; + const _errs27 = errors; + const _errs28 = errors; + if (errors === _errs28) { + if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { + for (const key5 in data9) { + let data10 = data9[key5]; + const _errs31 = errors; + if (!(data10 && typeof data10 == "object" && !Array.isArray(data10))) { + validate123.errors = [{ instancePath: instancePath + "/java/" + key5.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid10 = _errs31 === errors; + if (!valid10) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/java", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs27 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.js !== undefined) { + let data11 = data.js; + const _errs33 = errors; + const _errs34 = errors; + if (errors === _errs34) { + if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { + for (const key6 in data11) { + let data12 = data11[key6]; + const _errs37 = errors; + if (!(data12 && typeof data12 == "object" && !Array.isArray(data12))) { + validate123.errors = [{ instancePath: instancePath + "/js/" + key6.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid12 = _errs37 === errors; + if (!valid12) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/js", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs33 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.php !== undefined) { + let data13 = data.php; + const _errs39 = errors; + const _errs40 = errors; + if (errors === _errs40) { + if (data13 && typeof data13 == "object" && !Array.isArray(data13)) { + for (const key7 in data13) { + let data14 = data13[key7]; + const _errs43 = errors; + if (!(data14 && typeof data14 == "object" && !Array.isArray(data14))) { + validate123.errors = [{ instancePath: instancePath + "/php/" + key7.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid14 = _errs43 === errors; + if (!valid14) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/php", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs39 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.python !== undefined) { + let data15 = data.python; + const _errs45 = errors; + const _errs46 = errors; + if (errors === _errs46) { + if (data15 && typeof data15 == "object" && !Array.isArray(data15)) { + for (const key8 in data15) { + let data16 = data15[key8]; + const _errs49 = errors; + if (!(data16 && typeof data16 == "object" && !Array.isArray(data16))) { + validate123.errors = [{ instancePath: instancePath + "/python/" + key8.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid16 = _errs49 === errors; + if (!valid16) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/python", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs45 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.ruby !== undefined) { + let data17 = data.ruby; + const _errs51 = errors; + const _errs52 = errors; + if (errors === _errs52) { + if (data17 && typeof data17 == "object" && !Array.isArray(data17)) { + for (const key9 in data17) { + let data18 = data17[key9]; + const _errs55 = errors; + if (!(data18 && typeof data18 == "object" && !Array.isArray(data18))) { + validate123.errors = [{ instancePath: instancePath + "/ruby/" + key9.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid18 = _errs55 === errors; + if (!valid18) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/ruby", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs51 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.rust !== undefined) { + let data19 = data.rust; + const _errs57 = errors; + const _errs58 = errors; + if (errors === _errs58) { + if (data19 && typeof data19 == "object" && !Array.isArray(data19)) { + for (const key10 in data19) { + let data20 = data19[key10]; + const _errs61 = errors; + if (!(data20 && typeof data20 == "object" && !Array.isArray(data20))) { + validate123.errors = [{ instancePath: instancePath + "/rust/" + key10.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid20 = _errs61 === errors; + if (!valid20) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/rust", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs57 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.swift !== undefined) { + let data21 = data.swift; + const _errs63 = errors; + const _errs64 = errors; + if (errors === _errs64) { + if (data21 && typeof data21 == "object" && !Array.isArray(data21)) { + for (const key11 in data21) { + let data22 = data21[key11]; + const _errs67 = errors; + if (!(data22 && typeof data22 == "object" && !Array.isArray(data22))) { + validate123.errors = [{ instancePath: instancePath + "/swift/" + key11.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid22 = _errs67 === errors; + if (!valid22) { + break; + } + } + } else { + validate123.errors = [{ instancePath: instancePath + "/swift", schemaPath: "#/$defs/ExperimentalLanguageSpecificInstrumentation/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs63 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } + } + } + } + } else { + validate123.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate123.errors = vErrors; + return errors === 0; + } + validate123.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; + function validate20(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { + let vErrors = null; + let errors = 0; + const evaluated0 = validate20.evaluated; + if (evaluated0.dynamicProps) { + evaluated0.props = undefined; + } + if (evaluated0.dynamicItems) { + evaluated0.items = undefined; + } + if (errors === 0) { + if (data && typeof data == "object" && !Array.isArray(data)) { + let missing0; + if (data.file_format === undefined && (missing0 = "file_format")) { + validate20.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; + return false; + } else { + if (data.file_format !== undefined) { + const _errs2 = errors; + if (typeof data.file_format !== "string") { + validate20.errors = [{ instancePath: instancePath + "/file_format", schemaPath: "#/properties/file_format/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; + return false; + } + var valid0 = _errs2 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.disabled !== undefined) { + let data1 = data.disabled; + const _errs4 = errors; + if (typeof data1 !== "boolean" && data1 !== null) { + validate20.errors = [{ instancePath: instancePath + "/disabled", schemaPath: "#/properties/disabled/type", keyword: "type", params: { type: schema31.properties.disabled.type }, message: "must be boolean,null" }]; + return false; + } + var valid0 = _errs4 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.log_level !== undefined) { + let data2 = data.log_level; + const _errs6 = errors; + if (typeof data2 !== "string" && data2 !== null) { + validate20.errors = [{ instancePath: instancePath + "/log_level", schemaPath: "#/$defs/SeverityNumber/type", keyword: "type", params: { type: schema32.type }, message: "must be string,null" }]; + return false; + } + if (!(data2 === "trace" || data2 === "trace2" || data2 === "trace3" || data2 === "trace4" || data2 === "debug" || data2 === "debug2" || data2 === "debug3" || data2 === "debug4" || data2 === "info" || data2 === "info2" || data2 === "info3" || data2 === "info4" || data2 === "warn" || data2 === "warn2" || data2 === "warn3" || data2 === "warn4" || data2 === "error" || data2 === "error2" || data2 === "error3" || data2 === "error4" || data2 === "fatal" || data2 === "fatal2" || data2 === "fatal3" || data2 === "fatal4")) { + validate20.errors = [{ instancePath: instancePath + "/log_level", schemaPath: "#/$defs/SeverityNumber/enum", keyword: "enum", params: { allowedValues: schema32.enum }, message: "must be equal to one of the allowed values" }]; + return false; + } + var valid0 = _errs6 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.attribute_limits !== undefined) { + let data3 = data.attribute_limits; + const _errs9 = errors; + const _errs10 = errors; + if (errors === _errs10) { + if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { + const _errs12 = errors; + for (const key0 in data3) { + if (!(key0 === "attribute_value_length_limit" || key0 === "attribute_count_limit")) { + validate20.errors = [{ instancePath: instancePath + "/attribute_limits", schemaPath: "#/$defs/AttributeLimits/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; + return false; + break; + } + } + if (_errs12 === errors) { + if (data3.attribute_value_length_limit !== undefined) { + let data4 = data3.attribute_value_length_limit; + const _errs13 = errors; + if (!(typeof data4 == "number" && (!(data4 % 1) && !isNaN(data4))) && data4 !== null) { + validate20.errors = [{ instancePath: instancePath + "/attribute_limits/attribute_value_length_limit", schemaPath: "#/$defs/AttributeLimits/properties/attribute_value_length_limit/type", keyword: "type", params: { type: schema33.properties.attribute_value_length_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs13) { + if (typeof data4 == "number") { + if (data4 < 0 || isNaN(data4)) { + validate20.errors = [{ instancePath: instancePath + "/attribute_limits/attribute_value_length_limit", schemaPath: "#/$defs/AttributeLimits/properties/attribute_value_length_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs13 === errors; + } else { + var valid3 = true; + } + if (valid3) { + if (data3.attribute_count_limit !== undefined) { + let data5 = data3.attribute_count_limit; + const _errs15 = errors; + if (!(typeof data5 == "number" && (!(data5 % 1) && !isNaN(data5))) && data5 !== null) { + validate20.errors = [{ instancePath: instancePath + "/attribute_limits/attribute_count_limit", schemaPath: "#/$defs/AttributeLimits/properties/attribute_count_limit/type", keyword: "type", params: { type: schema33.properties.attribute_count_limit.type }, message: "must be integer,null" }]; + return false; + } + if (errors === _errs15) { + if (typeof data5 == "number") { + if (data5 < 0 || isNaN(data5)) { + validate20.errors = [{ instancePath: instancePath + "/attribute_limits/attribute_count_limit", schemaPath: "#/$defs/AttributeLimits/properties/attribute_count_limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; + return false; + } + } + } + var valid3 = _errs15 === errors; + } else { + var valid3 = true; + } + } + } + } else { + validate20.errors = [{ instancePath: instancePath + "/attribute_limits", schemaPath: "#/$defs/AttributeLimits/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs9 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.logger_provider !== undefined) { + const _errs17 = errors; + if (!validate21(data.logger_provider, { instancePath: instancePath + "/logger_provider", parentData: data, parentDataProperty: "logger_provider", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate21.errors : vErrors.concat(validate21.errors); + errors = vErrors.length; + } + var valid0 = _errs17 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.meter_provider !== undefined) { + const _errs18 = errors; + if (!validate43(data.meter_provider, { instancePath: instancePath + "/meter_provider", parentData: data, parentDataProperty: "meter_provider", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate43.errors : vErrors.concat(validate43.errors); + errors = vErrors.length; + } + var valid0 = _errs18 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.propagator !== undefined) { + const _errs19 = errors; + if (!validate80(data.propagator, { instancePath: instancePath + "/propagator", parentData: data, parentDataProperty: "propagator", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate80.errors : vErrors.concat(validate80.errors); + errors = vErrors.length; + } + var valid0 = _errs19 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.tracer_provider !== undefined) { + const _errs20 = errors; + if (!validate84(data.tracer_provider, { instancePath: instancePath + "/tracer_provider", parentData: data, parentDataProperty: "tracer_provider", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate84.errors : vErrors.concat(validate84.errors); + errors = vErrors.length; + } + var valid0 = _errs20 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.resource !== undefined) { + const _errs21 = errors; + if (!validate115(data.resource, { instancePath: instancePath + "/resource", parentData: data, parentDataProperty: "resource", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate115.errors : vErrors.concat(validate115.errors); + errors = vErrors.length; + } + var valid0 = _errs21 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data["instrumentation/development"] !== undefined) { + const _errs22 = errors; + if (!validate123(data["instrumentation/development"], { instancePath: instancePath + "/instrumentation~1development", parentData: data, parentDataProperty: "instrumentation/development", rootData, dynamicAnchors })) { + vErrors = vErrors === null ? validate123.errors : vErrors.concat(validate123.errors); + errors = vErrors.length; + } + var valid0 = _errs22 === errors; + } else { + var valid0 = true; + } + if (valid0) { + if (data.distribution !== undefined) { + let data12 = data.distribution; + const _errs23 = errors; + const _errs24 = errors; + if (errors === _errs24) { + if (data12 && typeof data12 == "object" && !Array.isArray(data12)) { + if (Object.keys(data12).length < 1) { + validate20.errors = [{ instancePath: instancePath + "/distribution", schemaPath: "#/$defs/Distribution/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; + return false; + } else { + for (const key1 in data12) { + let data13 = data12[key1]; + const _errs27 = errors; + if (!(data13 && typeof data13 == "object" && !Array.isArray(data13))) { + validate20.errors = [{ instancePath: instancePath + "/distribution/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/$defs/Distribution/additionalProperties/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + var valid5 = _errs27 === errors; + if (!valid5) { + break; + } + } + } + } else { + validate20.errors = [{ instancePath: instancePath + "/distribution", schemaPath: "#/$defs/Distribution/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + var valid0 = _errs23 === errors; + } else { + var valid0 = true; + } + } + } + } + } + } + } + } + } + } + } + } + } else { + validate20.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; + return false; + } + } + validate20.errors = vErrors; + return errors === 0; + } + validate20.evaluated = { props: true, dynamicProps: false, dynamicItems: false }; +}); + +// node_modules/@opentelemetry/configuration/build/src/FileConfigFactory.js +var require_FileConfigFactory = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseConfigFile = exports.FileConfigFactory = undefined; + var core_1 = require_src3(); + var fs = __require("fs"); + var yaml = require_dist(); + var utils_1 = require_utils14(); + var validateConfig = require_validator(); + + class FileConfigFactory { + _config; + constructor() { + this._config = parseConfigFile(); + } + getConfigModel() { + return this._config; + } + } + exports.FileConfigFactory = FileConfigFactory; + function parseConfigFile() { + const supportedFileVersionPattern = /^1\.0$/; + const configFile = (0, core_1.getStringFromEnv)("OTEL_CONFIG_FILE") || ""; + const file = fs.readFileSync(configFile, "utf8"); + const doc = yaml.parseDocument(file, { version: "1.2" }); + (0, utils_1.substituteEnvVars)(doc); + const processed = doc.toJS(); + const fileFormat = processed?.file_format; + if (!fileFormat || !supportedFileVersionPattern.test(String(fileFormat))) { + throw new Error(`${configFile}: Unsupported file_format: "${fileFormat}". Must match ${supportedFileVersionPattern}.`); + } + const valid = validateConfig(processed); + if (!valid) { + let detail; + if (!validateConfig.errors) { + detail = "unknown error"; + } else if (validateConfig.errors.length === 1) { + const err = validateConfig.errors[0]; + detail = `${err.instancePath} ${err.message}`; + } else { + const sep = ` + `; + detail = sep + validateConfig.errors.map((e) => `${e.instancePath} ${e.message}`).join(sep); + } + throw new Error(`Invalid OpenTelemetry config file: ${configFile}: ${detail}`); + } + const data = processed; + delete data["file_format"]; + applyConfigDefaults(data); + mergeAttributesList(data); + mergeCompositeList(data); + applyBatchProcessorDefaults(data); + applyPeriodicReaderDefaults(data); + applyOtlpHttpEncodingDefaults(data); + return data; + } + exports.parseConfigFile = parseConfigFile; + function applyOtlpHttpEncodingDefaults(data) { + const applyEncoding = (exporter) => { + if (exporter && exporter.encoding == null) { + exporter.encoding = "protobuf"; + } + }; + for (const processor of data.tracer_provider?.processors ?? []) { + applyEncoding(processor.batch?.exporter?.otlp_http); + applyEncoding(processor.simple?.exporter?.otlp_http); + } + for (const reader of data.meter_provider?.readers ?? []) { + applyEncoding(reader.periodic?.exporter?.otlp_http); + } + for (const processor of data.logger_provider?.processors ?? []) { + applyEncoding(processor.batch?.exporter?.otlp_http); + applyEncoding(processor.simple?.exporter?.otlp_http); + } + } + function mergeAttributesList(data) { + const resource = data.resource; + const list = resource?.attributes_list; + if (typeof list !== "string" || !list.trim()) + return; + if (resource.attributes == null) { + resource.attributes = []; + } + const existingKeys = new Set(resource.attributes.map((a) => a.name)); + for (const pair of list.split(",")) { + const eqIdx = pair.indexOf("="); + if (eqIdx > 0) { + const key = pair.slice(0, eqIdx).trim(); + const value = pair.slice(eqIdx + 1).trim(); + if (key && !existingKeys.has(key)) { + resource.attributes.push({ name: key, value, type: "string" }); + } + } + } + } + function mergeCompositeList(data) { + const propagator = data.propagator; + const list = propagator?.composite_list; + if (typeof list !== "string" || !list.trim()) + return; + if (propagator.composite == null) { + propagator.composite = []; + } + const existingNames = new Set(propagator.composite.map((entry) => Object.keys(entry)[0])); + for (const name of list.split(",")) { + const trimmed = name.trim(); + if (trimmed && !existingNames.has(trimmed)) { + propagator.composite.push({ + [trimmed]: {} + }); + } + } + } + function applyBatchProcessorDefaults(data) { + const applyDefaults = (batch) => { + if (batch.schedule_delay == null) + batch.schedule_delay = 5000; + if (batch.export_timeout == null) + batch.export_timeout = 30000; + if (batch.max_queue_size == null) + batch.max_queue_size = 2048; + if (batch.max_export_batch_size == null) + batch.max_export_batch_size = 512; + }; + for (const processor of data.tracer_provider?.processors ?? []) { + if (processor.batch) + applyDefaults(processor.batch); + } + for (const processor of data.logger_provider?.processors ?? []) { + if (processor.batch) + applyDefaults(processor.batch); + } + } + function applyPeriodicReaderDefaults(data) { + for (const reader of data.meter_provider?.readers ?? []) { + const periodic = reader.periodic; + if (!periodic) + continue; + if (periodic.interval == null) + periodic.interval = 60000; + if (periodic.timeout == null) + periodic.timeout = 30000; + if (periodic.cardinality_limits == null) { + periodic.cardinality_limits = { default: 2000 }; + } + } + } + function applyConfigDefaults(data) { + if (data.disabled == null) { + data.disabled = false; + } + if (data.log_level == null) { + data.log_level = "info"; + } + if (data.attribute_limits == null) { + data.attribute_limits = { attribute_count_limit: 128 }; + } else if (data.attribute_limits.attribute_count_limit == null) { + data.attribute_limits.attribute_count_limit = 128; + } + } +}); + +// node_modules/@opentelemetry/configuration/build/src/ConfigFactory.js +var require_ConfigFactory = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createConfigFactory = undefined; + var core_1 = require_src3(); + var EnvironmentConfigFactory_1 = require_EnvironmentConfigFactory(); + var FileConfigFactory_1 = require_FileConfigFactory(); + function createConfigFactory() { + const configFile = (0, core_1.getStringFromEnv)("OTEL_CONFIG_FILE"); + if (configFile) { + return new FileConfigFactory_1.FileConfigFactory; + } + return new EnvironmentConfigFactory_1.EnvironmentConfigFactory; + } + exports.createConfigFactory = createConfigFactory; +}); + +// node_modules/@opentelemetry/configuration/build/src/index.js +var require_src32 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createConfigFactory = undefined; + var ConfigFactory_1 = require_ConfigFactory(); + Object.defineProperty(exports, "createConfigFactory", { enumerable: true, get: function() { + return ConfigFactory_1.createConfigFactory; + } }); +}); + +// node_modules/@opentelemetry/sdk-node/build/src/semconv.js +var require_semconv7 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_PROCESS_PID = exports.ATTR_HOST_NAME = undefined; + exports.ATTR_HOST_NAME = "host.name"; + exports.ATTR_PROCESS_PID = "process.pid"; + exports.ATTR_SERVICE_INSTANCE_ID = "service.instance.id"; + exports.ATTR_SERVICE_NAMESPACE = "service.namespace"; +}); + +// node_modules/@opentelemetry/sdk-node/build/src/diag.js +var require_diag2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.diagLogLevelFromSeverityNumberConfig = undefined; + var api_1 = require_src(); + function diagLogLevelFromSeverityNumberConfig(sevNum = "info") { + let level; + switch (sevNum) { + case "trace": + level = api_1.DiagLogLevel.ALL; + break; + case "trace2": + case "trace3": + case "trace4": + level = api_1.DiagLogLevel.VERBOSE; + break; + case "debug": + case "debug2": + case "debug3": + case "debug4": + level = api_1.DiagLogLevel.DEBUG; + break; + case "info": + case "info2": + case "info3": + case "info4": + level = api_1.DiagLogLevel.INFO; + break; + case "warn": + case "warn2": + case "warn3": + case "warn4": + level = api_1.DiagLogLevel.WARN; + break; + case "error": + case "error2": + case "error3": + case "error4": + level = api_1.DiagLogLevel.ERROR; + break; + case "fatal": + case "fatal2": + case "fatal3": + case "fatal4": + level = api_1.DiagLogLevel.NONE; + break; + default: + throw new Error(`unexpected SeverityNumberConfigModel value: ${sevNum}`); + } + return level; + } + exports.diagLogLevelFromSeverityNumberConfig = diagLogLevelFromSeverityNumberConfig; +}); + +// node_modules/@opentelemetry/sdk-node/build/src/start.js +var require_start = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.setupResource = exports.startNodeSDK = exports.NOOP_SDK = undefined; + var configuration_1 = require_src32(); + var api_1 = require_src(); + var utils_1 = require_utils13(); + var instrumentation_1 = require_src15(); + var sdk_logs_1 = require_src10(); + var sdk_metrics_1 = require_src7(); + var api_logs_1 = require_src5(); + var resources_1 = require_src6(); + var context_async_hooks_1 = require_src11(); + var semconv_1 = require_semconv7(); + var sdk_trace_base_1 = require_src12(); + var diag_1 = require_diag2(); + exports.NOOP_SDK = { + shutdown: async () => {} + }; + function startNodeSDK(sdkOptions) { + let config; + try { + const configFactory = (0, configuration_1.createConfigFactory)(); + config = configFactory.getConfigModel(); + } catch (configErr) { + const logLevel2 = (0, diag_1.diagLogLevelFromSeverityNumberConfig)(); + api_1.diag.setLogger(new api_1.DiagConsoleLogger, { logLevel: logLevel2 }); + api_1.diag.error(`Could not load OpenTelemetry configuration, SDK will not be setup: ${configErr.message}`); + return exports.NOOP_SDK; + } + if (config.disabled) { + return exports.NOOP_SDK; + } + const logLevel = (0, diag_1.diagLogLevelFromSeverityNumberConfig)(config.log_level); + api_1.diag.setLogger(new api_1.DiagConsoleLogger, { logLevel }); + (0, instrumentation_1.registerInstrumentations)({ + instrumentations: sdkOptions?.instrumentations?.flat() ?? [] + }); + const components = create(config, sdkOptions); + api_1.context.setGlobalContextManager(components.contextManager); + if (components.loggerProvider) { + api_logs_1.logs.setGlobalLoggerProvider(components.loggerProvider); + } + if (components.meterProvider) { + api_1.metrics.setGlobalMeterProvider(components.meterProvider); + } + if (components.tracerProvider) { + api_1.trace.setGlobalTracerProvider(components.tracerProvider); + } + if (components.propagator) { + api_1.propagation.setGlobalPropagator(components.propagator); + } + const shutdownFn = async () => { + const promises = []; + if (components.loggerProvider) { + promises.push(components.loggerProvider.shutdown()); + } + if (components.meterProvider) { + promises.push(components.meterProvider.shutdown()); + } + if (components.tracerProvider) { + promises.push(components.tracerProvider.shutdown()); + } + await Promise.all(promises); + }; + return { shutdown: shutdownFn }; + } + exports.startNodeSDK = startNodeSDK; + function create(config, sdkOptions) { + const defaultContextManager = new context_async_hooks_1.AsyncLocalStorageContextManager; + defaultContextManager.enable(); + const components = { + contextManager: defaultContextManager + }; + const resource = setupResource(config, sdkOptions); + const propagator = sdkOptions?.textMapPropagator === null ? null : sdkOptions?.textMapPropagator ?? (0, utils_1.getPropagatorFromConfiguration)(config); + if (propagator) { + components.propagator = propagator; + } + const logProcessors = (0, utils_1.getLogRecordProcessorsFromConfiguration)(config); + if (logProcessors) { + const loggerProvider = new sdk_logs_1.LoggerProvider({ + resource, + processors: logProcessors + }); + components.loggerProvider = loggerProvider; + } + const meterReaders = (0, utils_1.getMeterReadersFromConfiguration)(config); + if (meterReaders) { + const meterViews = (0, utils_1.getMeterViewsFromConfiguration)(config); + const meterProvider = new sdk_metrics_1.MeterProvider({ + resource, + readers: meterReaders, + views: meterViews ?? [] + }); + components.meterProvider = meterProvider; + } + const spanProcessors = (0, utils_1.getSpanProcessorsFromConfiguration)(config); + if (spanProcessors) { + const spanLimits = (0, utils_1.getSpanLimitsFromConfiguration)(config); + const tracerProvider = new sdk_trace_base_1.BasicTracerProvider({ + resource, + spanProcessors, + spanLimits, + generalLimits: { + attributeValueLengthLimit: config.attribute_limits?.attribute_value_length_limit ?? undefined, + attributeCountLimit: config.attribute_limits?.attribute_count_limit ?? undefined + } + }); + components.tracerProvider = tracerProvider; + } + return components; + } + function setupResource(config, sdkOptions) { + let resource = (0, utils_1.getResourceFromConfiguration)(config) ?? (0, resources_1.defaultResource)(); + let resourceDetectors = []; + if (sdkOptions?.resourceDetectors != null) { + resourceDetectors = sdkOptions.resourceDetectors; + } else if (config.resource?.["detection/development"]?.detectors) { + resourceDetectors = (0, utils_1.getResourceDetectorsFromConfiguration)(config); + } + if (resourceDetectors.length > 0) { + const internalConfig = { + detectors: resourceDetectors + }; + resource = resource.merge((0, resources_1.detectResources)(internalConfig)); + } + const instanceId = (0, utils_1.getInstanceID)(config); + resource = instanceId === undefined ? resource : resource.merge((0, resources_1.resourceFromAttributes)({ + [semconv_1.ATTR_SERVICE_INSTANCE_ID]: instanceId + })); + return resource; + } + exports.setupResource = setupResource; +}); + +// node_modules/@opentelemetry/sdk-node/build/src/index.js +var require_src33 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.startNodeSDK = exports.NodeSDK = exports.tracing = exports.resources = exports.node = exports.metrics = exports.logs = exports.core = exports.contextBase = exports.api = undefined; + exports.api = require_src(); + exports.contextBase = require_src(); + exports.core = require_src3(); + exports.logs = require_src10(); + exports.metrics = require_src7(); + exports.node = require_src13(); + exports.resources = require_src6(); + exports.tracing = require_src12(); + var sdk_1 = require_sdk(); + Object.defineProperty(exports, "NodeSDK", { enumerable: true, get: function() { + return sdk_1.NodeSDK; + } }); + var start_1 = require_start(); + Object.defineProperty(exports, "startNodeSDK", { enumerable: true, get: function() { + return start_1.startNodeSDK; + } }); +}); + +// node_modules/node-color-log/index.js +var require_node_color_log = __commonJS((exports, module) => { + var CONFIG = { + SYSTEM: { + reset: "\x1B[0m", + bold: "\x1B[1m", + dim: "\x1B[2m", + italic: "\x1B[3m", + underscore: "\x1B[4m", + reverse: "\x1B[7m", + strikethrough: "\x1B[9m", + backoneline: "\x1B[1A", + cleanthisline: "\x1B[K" + }, + FONT: { + black: "\x1B[30m", + red: "\x1B[31m", + green: "\x1B[32m", + yellow: "\x1B[33m", + blue: "\x1B[34m", + magenta: "\x1B[35m", + cyan: "\x1B[36m", + white: "\x1B[37m" + }, + BACKGROUND: { + black: "\x1B[40m", + red: "\x1B[41m", + green: "\x1B[42m", + yellow: "\x1B[43m", + blue: "\x1B[44m", + magenta: "\x1B[45m", + cyan: "\x1B[46m", + white: "\x1B[47m" + } + }; + var LEVELS = ["success", "debug", "info", "warn", "error", "disable"]; + + class Logger { + constructor(name) { + this.command = ""; + this.lastCommand = ""; + this.name = name || ""; + const level = typeof process !== "undefined" ? process.env.LOGGER : undefined; + if (this.isLevelValid(level)) { + this.level = level; + } + this.noColor = false; + this._getDate = () => new Date().toISOString(); + this._customizedConsole = console; + this._enableFileAndLine = { + enable: false, + isShortFile: false + }; + } + createNamedLogger(name) { + return new Logger(name); + } + setLevel(level) { + if (this.isLevelValid(level)) { + this.level = level; + } else { + throw new Error("Level you are trying to set is invalid"); + } + } + setLogStream(newStream) { + if (newStream && newStream.writable) { + this._customizedConsole = new console.Console(newStream); + } else { + throw new Error("invalid writable stream object"); + } + return this; + } + setLevelNoColor() { + this.noColor = true; + } + setLevelColor() { + this.noColor = false; + } + isLevelValid(level) { + return LEVELS.includes(level); + } + isAllowedLevel(level) { + return this.level ? LEVELS.indexOf(this.level) <= LEVELS.indexOf(level) : true; + } + enableFileAndLine(enable, isShortFile = false) { + if (typeof enable === "boolean") { + this._enableFileAndLine.enable = enable; + this._enableFileAndLine.isShortFile = isShortFile; + } else { + console.error("node-color-log warning: enableFileAndLine should be a boolean value."); + } + } + log(...args) { + this.append(...args); + if (!this.noColor) { + this.command += CONFIG.SYSTEM.reset; + } + this._print(this.command); + this.lastCommand = this.command; + this.command = ""; + return this; + } + joint() { + console.error("node-color-log warning: `joint` is deprecated, please use `append`"); + this._print(CONFIG.SYSTEM.backoneline + CONFIG.SYSTEM.cleanthisline); + this.command = ""; + this.lastCommand = this.lastCommand.replace(CONFIG.SYSTEM.backoneline, ""); + this.command += CONFIG.SYSTEM.backoneline; + this.command += this.lastCommand; + return this; + } + setDate(callback) { + this._getDate = callback; + } + getPrefix() { + let prefix = `${this._getDate()}`; + if (this.name) { + prefix += ` [${this.name}]`; + } + if (this._enableFileAndLine.enable) { + const fileAndLine = getFileAndLine(this._enableFileAndLine.isShortFile); + if (fileAndLine) { + prefix += `[${fileAndLine}]`; + } + } + return prefix; + } + color(ticket) { + if (ticket in CONFIG.FONT) { + this.command += CONFIG.FONT[ticket]; + } else { + console.error("node-color-log warning: Font color not found! Use the default."); + } + return this; + } + bgColor(ticket) { + if (ticket in CONFIG.BACKGROUND) { + this.command += CONFIG.BACKGROUND[ticket]; + } else { + console.error("node-color-log warning: Background color not found! Use the default."); + } + return this; + } + bold() { + this.command += CONFIG.SYSTEM.bold; + return this; + } + dim() { + this.command += CONFIG.SYSTEM.dim; + return this; + } + underscore() { + this.command += CONFIG.SYSTEM.underscore; + return this; + } + strikethrough() { + this.command += CONFIG.SYSTEM.strikethrough; + return this; + } + reverse() { + this.command += CONFIG.SYSTEM.reverse; + return this; + } + italic() { + this.command += CONFIG.SYSTEM.italic; + return this; + } + fontColorLog(ticket, text, setting) { + let command = ""; + if (setting) { + command += this.checkSetting(setting); + } + if (ticket in CONFIG.FONT) { + command += CONFIG.FONT[ticket]; + } else { + console.error("node-color-log warning: Font color not found! Use the default."); + } + command += text; + command += CONFIG.SYSTEM.reset; + this.lastCommand = command; + this._print(command); + } + bgColorLog(ticket, text, setting) { + let command = ""; + if (setting) { + command += this.checkSetting(setting); + } + if (ticket in CONFIG.BACKGROUND) { + command += CONFIG.BACKGROUND[ticket]; + } else { + console.error("node-color-log warning: Background color not found! Use the default."); + } + command += text; + command += CONFIG.SYSTEM.reset; + this.lastCommand = command; + this._print(command); + } + colorLog(ticketObj, text, setting) { + let command = ""; + if (setting) { + command += this.checkSetting(setting); + } + if (ticketObj.font !== undefined) { + if (ticketObj.font in CONFIG.FONT) { + command += CONFIG.FONT[ticketObj.font]; + } else { + console.error("node-color-log warning: Font color not found! Use the default."); + } + } + if (ticketObj.bg !== undefined) { + if (ticketObj.bg in CONFIG.BACKGROUND) { + command += CONFIG.BACKGROUND[ticketObj.bg]; + } else { + console.error("node-color-log warning: Background color not found! Use the default."); + } + } + command += text; + command += CONFIG.SYSTEM.reset; + this.lastCommand = command; + this._print(command); + } + error(...args) { + if (!this.isAllowedLevel("error")) + return; + if (this.noColor) { + const d = this.getPrefix(); + this.log(d, " [ERROR] ", ...args); + } else { + const d = this.getPrefix(); + this.append(d + " ").bgColor("red").append("[ERROR]").reset().append(" ").color("red").log(...args); + } + } + warn(...args) { + if (!this.isAllowedLevel("warn")) + return; + if (this.noColor) { + const d = this.getPrefix(); + this.log(d, " [WARN] ", ...args); + } else { + const d = this.getPrefix(); + this.append(d + " ").bgColor("yellow").color("black").append("[WARN]").reset().append(" ").color("yellow").log(...args); + } + } + info(...args) { + if (!this.isAllowedLevel("info")) + return; + if (this.noColor) { + const d = this.getPrefix(); + this.log(d, " [INFO] ", ...args); + } else { + const d = this.getPrefix(); + this.append(d + " ").bgColor("green").color("black").append("[INFO]").reset().append(" ").color("green").log(...args); + } + } + debug(...args) { + if (!this.isAllowedLevel("debug")) + return; + if (this.noColor) { + const d = this.getPrefix(); + this.log(d, " [DEBUG] ", ...args); + } else { + const d = this.getPrefix(); + this.append(d + " ").bgColor("cyan").color("black").append("[DEBUG]").reset().append(" ").color("cyan").log(...args); + } + } + success(...args) { + if (!this.isAllowedLevel("success")) + return; + if (this.noColor) { + const d = this.getPrefix(); + this.log(d, " [SUCCESS] ", ...args); + } else { + const d = this.getPrefix(); + this.append(d + " ").bgColor("green").color("black").append("[SUCCESS]").reset().append(" ").color("green").log(...args); + } + } + checkSetting(setting) { + const validSetting = ["bold", "italic", "dim", "underscore", "reverse", "strikethrough"]; + let command = ""; + for (const item in setting) { + if (validSetting.indexOf(item) !== -1) { + if (setting[item] === true) { + command += CONFIG.SYSTEM[item]; + } else if (setting[item] !== false) { + console.error(`node-color-log warning: The value ${item} should be boolean.`); + } + } else { + console.error(`node-color-log warning: ${item} is not valid in setting.`); + } + } + return command; + } + _print(...args) { + this._customizedConsole.error(...args); + } + append(...args) { + for (const idx in args) { + const arg = args[idx]; + if (typeof arg === "string") { + this.command += arg; + } else { + try { + this.command += JSON.stringify(arg); + } catch { + this.command += arg; + } + } + if (args.length > 1 && idx < args.length - 1) { + this.command += " "; + } + } + return this; + } + reset() { + this.command += CONFIG.SYSTEM.reset; + return this; + } + } + function parseStackFrame(line, isShortFile = false) { + if (typeof line !== "string" || line.length === 0) { + return ""; + } + let start = line.lastIndexOf("("); + let end = line.lastIndexOf(")"); + let fileAndLine; + if (start !== -1 && end !== -1 && start < end) { + fileAndLine = line.substring(start + 1, end); + } else { + const atPrefix = line.indexOf("at "); + fileAndLine = atPrefix !== -1 ? line.substring(atPrefix + 3).trim() : line.trim(); + } + const lastColon = fileAndLine.lastIndexOf(":"); + if (lastColon === -1) { + return ""; + } + const secondLastColon = fileAndLine.lastIndexOf(":", lastColon - 1); + const isDigits = (s) => s.length > 0 && /^\d+$/.test(s); + const lastSeg = fileAndLine.substring(lastColon + 1); + const midSeg = secondLastColon === -1 ? "" : fileAndLine.substring(secondLastColon + 1, lastColon); + let fileName; + let lineNumber; + if (secondLastColon !== -1 && isDigits(midSeg) && isDigits(lastSeg)) { + fileName = fileAndLine.substring(0, secondLastColon); + lineNumber = midSeg; + } else if (isDigits(lastSeg)) { + fileName = fileAndLine.substring(0, lastColon); + lineNumber = lastSeg; + } else { + return ""; + } + if (isShortFile) { + const segments = fileName.split(/[\\/]/); + fileName = segments[segments.length - 1]; + } + return `${fileName}:${lineNumber}`; + } + function getFileAndLine(isShortFile = false) { + const e = new Error; + const lines = e.stack.split(` +`); + let line = ""; + for (let i = lines.length - 1;i >= 0; i--) { + const currentLine = lines[i]; + if (currentLine.includes("Logger.") || currentLine.includes("node-color-log/index.js")) { + if (i + 1 >= lines.length) { + return ""; + } + line = lines[i + 1].trim(); + break; + } + } + return parseStackFrame(line, isShortFile); + } + var logger = new Logger; + logger._internal = { parseStackFrame }; + module.exports = logger; +}); + +// src/common/utils.ts +function isDeno() { + return typeof globalThis.Deno !== "undefined"; +} +function isBun() { + return typeof globalThis.Bun !== "undefined"; +} +var import_node_color_log, log = (stack) => import_node_color_log.default.bgColor("red").color("black").log(stack); +var init_utils = __esm(() => { + import_node_color_log = __toESM(require_node_color_log(), 1); +}); + +// src/common/errors/DaggerSDKError.ts +var DaggerSDKError; +var init_DaggerSDKError = __esm(() => { + init_utils(); + DaggerSDKError = class DaggerSDKError extends Error { + cause; + constructor(message, options) { + super(message); + this.cause = options?.cause; + } + get [Symbol.toStringTag]() { + return this.name; + } + printStackTrace() { + log(this.stack); + } + }; +}); + +// src/common/errors/errors-codes.ts +var ERROR_CODES, ERROR_NAMES; +var init_errors_codes = __esm(() => { + ERROR_CODES = { + GraphQLRequestError: "D100", + UnknownDaggerError: "D101", + TooManyNestedObjectsError: "D102", + EngineSessionConnectParamsParseError: "D103", + EngineSessionConnectionTimeoutError: "D104", + EngineSessionError: "D105", + InitEngineSessionBinaryError: "D106", + DockerImageRefValidationError: "D107", + NotAwaitedRequestError: "D108", + ExecError: "D109", + IntrospectionError: "D110" + }; + ERROR_NAMES = Object.keys(ERROR_CODES).reduce((obj, item) => ({ ...obj, [item]: item }), {}); +}); + +// src/common/errors/UnknownDaggerError.ts +var UnknownDaggerError; +var init_UnknownDaggerError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + UnknownDaggerError = class UnknownDaggerError extends DaggerSDKError { + name = ERROR_NAMES.UnknownDaggerError; + code = ERROR_CODES.UnknownDaggerError; + constructor(message, options) { + super(message, options); + } + }; +}); + +// src/common/errors/DockerImageRefValidationError.ts +var DockerImageRefValidationError; +var init_DockerImageRefValidationError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + DockerImageRefValidationError = class DockerImageRefValidationError extends DaggerSDKError { + name = ERROR_NAMES.DockerImageRefValidationError; + code = ERROR_CODES.DockerImageRefValidationError; + ref; + constructor(message, options) { + super(message, options); + this.ref = options?.ref; + } + }; +}); + +// src/common/errors/EngineSessionConnectParamsParseError.ts +var EngineSessionConnectParamsParseError; +var init_EngineSessionConnectParamsParseError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + EngineSessionConnectParamsParseError = class EngineSessionConnectParamsParseError extends DaggerSDKError { + name = ERROR_NAMES.EngineSessionConnectParamsParseError; + code = ERROR_CODES.EngineSessionConnectParamsParseError; + parsedLine; + constructor(message, options) { + super(message, options); + this.parsedLine = options.parsedLine; + } + }; +}); + +// src/common/errors/ExecError.ts +var ExecError; +var init_ExecError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + ExecError = class ExecError extends DaggerSDKError { + name = ERROR_NAMES.ExecError; + code = ERROR_CODES.ExecError; + cmd; + exitCode; + stdout; + stderr; + extensions; + constructor(message, options) { + super(message, options); + this.cmd = options.cmd; + this.exitCode = options.exitCode; + this.stdout = options.stdout; + this.stderr = options.stderr; + this.extensions = options.extensions; + } + }; +}); + +// src/common/errors/GraphQLRequestError.ts +var GraphQLRequestError; +var init_GraphQLRequestError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + GraphQLRequestError = class GraphQLRequestError extends DaggerSDKError { + name = ERROR_NAMES.GraphQLRequestError; + code = ERROR_CODES.GraphQLRequestError; + requestContext; + response; + extensions; + constructor(message, options) { + super(message, options); + this.requestContext = options.error.request; + this.response = options.error.response; + this.extensions = options.error.response.errors?.[0]?.extensions; + } + }; +}); + +// src/common/errors/InitEngineSessionBinaryError.ts +var InitEngineSessionBinaryError; +var init_InitEngineSessionBinaryError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + InitEngineSessionBinaryError = class InitEngineSessionBinaryError extends DaggerSDKError { + name = ERROR_NAMES.InitEngineSessionBinaryError; + code = ERROR_CODES.InitEngineSessionBinaryError; + constructor(message, options) { + super(message, options); + } + }; +}); + +// src/common/errors/TooManyNestedObjectsError.ts +var TooManyNestedObjectsError; +var init_TooManyNestedObjectsError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + TooManyNestedObjectsError = class TooManyNestedObjectsError extends DaggerSDKError { + name = ERROR_NAMES.TooManyNestedObjectsError; + code = ERROR_CODES.TooManyNestedObjectsError; + response; + constructor(message, options) { + super(message, options); + this.response = options.response; + } + }; +}); + +// src/common/errors/EngineSessionErrorOptions.ts +var EngineSessionError; +var init_EngineSessionErrorOptions = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + EngineSessionError = class EngineSessionError extends DaggerSDKError { + name = ERROR_NAMES.EngineSessionError; + code = ERROR_CODES.EngineSessionError; + constructor(message, options) { + super(message, options); + } + }; +}); + +// src/common/errors/EngineSessionConnectionTimeoutError.ts +var EngineSessionConnectionTimeoutError; +var init_EngineSessionConnectionTimeoutError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + EngineSessionConnectionTimeoutError = class EngineSessionConnectionTimeoutError extends DaggerSDKError { + name = ERROR_NAMES.EngineSessionConnectionTimeoutError; + code = ERROR_CODES.EngineSessionConnectionTimeoutError; + timeOutDuration; + constructor(message, options) { + super(message, options); + this.timeOutDuration = options.timeOutDuration; + } + }; +}); + +// src/common/errors/NotAwaitedRequestError.ts +var NotAwaitedRequestError; +var init_NotAwaitedRequestError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + NotAwaitedRequestError = class NotAwaitedRequestError extends DaggerSDKError { + name = ERROR_NAMES.NotAwaitedRequestError; + code = ERROR_CODES.NotAwaitedRequestError; + constructor(message, options) { + super(message, options); + } + }; +}); + +// src/common/errors/FunctionNotFound.ts +var FunctionNotFound; +var init_FunctionNotFound = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + FunctionNotFound = class FunctionNotFound extends DaggerSDKError { + name = ERROR_NAMES.ExecError; + code = ERROR_CODES.ExecError; + constructor(message, options) { + super(message, options); + } + }; +}); + +// src/common/errors/IntrospectionError.ts +var IntrospectionError; +var init_IntrospectionError = __esm(() => { + init_DaggerSDKError(); + init_errors_codes(); + IntrospectionError = class IntrospectionError extends DaggerSDKError { + name = ERROR_NAMES.IntrospectionError; + code = ERROR_CODES.IntrospectionError; + constructor(message, options) { + super(message, options); + } + }; +}); + +// src/common/errors/index.ts +var init_errors = __esm(() => { + init_DaggerSDKError(); + init_UnknownDaggerError(); + init_DockerImageRefValidationError(); + init_EngineSessionConnectParamsParseError(); + init_ExecError(); + init_GraphQLRequestError(); + init_InitEngineSessionBinaryError(); + init_TooManyNestedObjectsError(); + init_EngineSessionErrorOptions(); + init_EngineSessionConnectionTimeoutError(); + init_NotAwaitedRequestError(); + init_FunctionNotFound(); + init_IntrospectionError(); + init_errors_codes(); +}); + +// node_modules/data-uri-to-buffer/dist/index.js +function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + uri = uri.replace(/\r?\n/g, ""); + const firstComma = uri.indexOf(","); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError("malformed data: URI"); + } + const meta = uri.substring(5, firstComma).split(";"); + let charset = ""; + let base64 = false; + const type = meta[0] || "text/plain"; + let typeFull = type; + for (let i = 1;i < meta.length; i++) { + if (meta[i] === "base64") { + base64 = true; + } else if (meta[i]) { + typeFull += `;${meta[i]}`; + if (meta[i].indexOf("charset=") === 0) { + charset = meta[i].substring(8); + } + } + } + if (!meta[0] && !charset.length) { + typeFull += ";charset=US-ASCII"; + charset = "US-ASCII"; + } + const encoding = base64 ? "base64" : "ascii"; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + buffer.type = type; + buffer.typeFull = typeFull; + buffer.charset = charset; + return buffer; +} +var dist_default; +var init_dist = __esm(() => { + dist_default = dataUriToBuffer; +}); + +// node_modules/web-streams-polyfill/dist/ponyfill.es2018.js +var require_ponyfill_es2018 = __commonJS((exports, module) => { + (function(global2, factory) { + typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); + })(exports, function(exports2) { + function noop() { + return; + } + function typeIsObject(x) { + return typeof x === "object" && x !== null || typeof x === "function"; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, "name", { + value: name, + configurable: true + }); + } catch (_a2) {} + } + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return newPromise((resolve) => resolve(value)); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = (callback) => { + if (typeof queueMicrotask === "function") { + _queueMicrotask = queueMicrotask; + } else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== "function") { + throw new TypeError("Argument is not a function"); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } catch (value) { + return promiseRejectedWith(value); + } + } + const QUEUE_MAX_ARRAY_SIZE = 16384; + + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + this._cursor = 0; + this._size = 0; + } + get length() { + return this._size; + } + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + shift() { + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + elements[oldCursor] = undefined; + return element; + } + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + peek() { + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + const AbortSteps = Symbol("[[AbortSteps]]"); + const ErrorSteps = Symbol("[[ErrorSteps]]"); + const CancelSteps = Symbol("[[CancelSteps]]"); + const PullSteps = Symbol("[[PullSteps]]"); + const ReleaseSteps = Symbol("[[ReleaseSteps]]"); + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === "readable") { + defaultReaderClosedPromiseInitialize(reader); + } else if (stream._state === "closed") { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === "readable") { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + function readerLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released reader"); + } + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + const NumberIsFinite = Number.isFinite || function(x) { + return typeof x === "number" && isFinite(x); + }; + const MathTrunc = Math.trunc || function(v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + function isDictionary(x) { + return typeof x === "object" || typeof x === "function"; + } + function assertDictionary(obj, context2) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context2} is not an object.`); + } + } + function assertFunction(x, context2) { + if (typeof x !== "function") { + throw new TypeError(`${context2} is not a function.`); + } + } + function isObject(x) { + return typeof x === "object" && x !== null || typeof x === "function"; + } + function assertObject(x, context2) { + if (!isObject(x)) { + throw new TypeError(`${context2} is not an object.`); + } + } + function assertRequiredArgument(x, position, context2) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context2}'.`); + } + } + function assertRequiredField(x, field, context2) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context2}'.`); + } + } + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + function convertUnsignedLongLongWithEnforceRange(value, context2) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context2} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context2} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + return x; + } + function assertReadableStream(x, context2) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context2} is not a ReadableStream.`); + } + } + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue; + } + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("read")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: (e) => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel"); + setFunctionName(ReadableStreamDefaultReader.prototype.read, "read"); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, { + value: "ReadableStreamDefaultReader", + configurable: true + }); + } + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_readRequests")) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "closed") { + readRequest._closeSteps(); + } else if (stream._state === "errored") { + readRequest._errorSteps(stream._storedError); + } else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError("Reader was released"); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue; + readRequests.forEach((readRequest) => { + readRequest._errorSteps(e); + }); + } + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => { + this._ongoingPromise = undefined; + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: (reason) => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); + } + return this._asyncIteratorImpl.return(value); + } + }; + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_asyncIteratorImpl")) { + return false; + } + try { + return x._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; + } catch (_a2) { + return false; + } + } + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + const NumberIsNaN = Number.isNaN || function(x) { + return x !== x; + }; + var _a, _b, _c; + function CreateArrayFromList(elements) { + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === "function") { + TransferArrayBuffer = (buffer) => buffer.transfer(); + } else if (typeof structuredClone === "function") { + TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] }); + } else { + TransferArrayBuffer = (buffer) => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === "boolean") { + IsDetachedBuffer = (buffer) => buffer.detached; + } else { + IsDetachedBuffer = (buffer) => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return; + } + if (typeof func !== "function") { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + const syncIterable = { + [Symbol.iterator]: () => syncIteratorRecord.iterator + }; + const asyncIterator = async function* () { + return yield* syncIterable; + }(); + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== undefined ? _a : (_b = Symbol.for) === null || _b === undefined ? undefined : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== undefined ? _c : "@@asyncIterator"; + function GetIterator(obj, hint = "sync", method) { + if (method === undefined) { + if (hint === "async") { + method = GetMethod(obj, SymbolAsyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, Symbol.iterator); + const syncIteratorRecord = GetIterator(obj, "sync", syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } else { + method = GetMethod(obj, Symbol.iterator); + } + } + if (method === undefined) { + throw new TypeError("The object is not iterable"); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError("The iterator method must return an object"); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError("The iterator.next() method must return an object"); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + function IsNonNegativeNumber(v) { + if (typeof v !== "number") { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError("Size must be a finite, non-NaN, non-negative number."); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue; + container._queueTotalSize = 0; + } + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError("Illegal constructor"); + } + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("view"); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respond"); + } + assertRequiredArgument(bytesWritten, 1, "respond"); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respondWithNewView"); + } + assertRequiredArgument(view, 1, "respondWithNewView"); + if (!ArrayBuffer.isView(view)) { + throw new TypeError("You can only respond with array buffer views"); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError("The given view's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond"); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, { + value: "ReadableStreamBYOBRequest", + configurable: true + }); + } + + class ReadableByteStreamController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("byobRequest"); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("desiredSize"); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("close"); + } + if (this._closeRequested) { + throw new TypeError("The stream has already been closed; do not close it again!"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("enqueue"); + } + assertRequiredArgument(chunk, 1, "enqueue"); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError("chunk must be an array buffer view"); + } + if (chunk.byteLength === 0) { + throw new TypeError("chunk must have non-zero byteLength"); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError("stream is closed or draining"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("error"); + } + ReadableByteStreamControllerError(this, e); + } + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: "default" + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = "none"; + this._pendingPullIntos = new SimpleQueue; + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, "close"); + setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue"); + setFunctionName(ReadableByteStreamController.prototype.error, "error"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, { + value: "ReadableByteStreamController", + configurable: true + }); + } + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_controlledReadableByteStream")) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_associatedReadableByteStreamController")) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, (e) => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue; + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === "closed") { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "default") { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: "byob" + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === "closed") { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === "none") { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "none") { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError("chunk's buffer is detached and so cannot be enqueued"); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk"); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === "none") { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } else if (ReadableStreamHasBYOBReader(stream)) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (bytesWritten !== 0) { + throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); + } + } else { + if (bytesWritten === 0) { + throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError("bytesWritten out of range"); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (view.byteLength !== 0) { + throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); + } + } else { + if (view.byteLength === 0) { + throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError("The region specified by view does not match byobRequest"); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError("The buffer of view has different capacity than byobRequest"); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError("The region specified by view is larger than byobRequest"); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, (r) => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } else { + startAlgorithm = () => { + return; + }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); + } else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError("autoAllocateChunkSize must be greater than 0"); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request2, controller, view) { + request2._associatedReadableByteStreamController = controller; + request2._view = view; + } + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + function convertReaderOptions(options, context2) { + assertDictionary(options, context2); + const mode = options === null || options === undefined ? undefined : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context2} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context2) { + mode = `${mode}`; + if (mode !== "byob") { + throw new TypeError(`${context2} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context2) { + var _a2; + assertDictionary(options, context2); + const min = (_a2 = options === null || options === undefined ? undefined : options.min) !== null && _a2 !== undefined ? _a2 : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context2} has member 'min' that`) + }; + } + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte " + "source"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue; + } + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("read")); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError("view must be an array buffer view")); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError("view's buffer has been detached")); + } + let options; + try { + options = convertByobReadOptions(rawOptions, "options"); + } catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError("options.min must be greater than 0")); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's length")); + } + } else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError("options.min must be less than or equal to view's byteLength")); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), + _errorSteps: (e) => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel"); + setFunctionName(ReadableStreamBYOBReader.prototype.read, "read"); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, { + value: "ReadableStreamBYOBReader", + configurable: true + }); + } + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_readIntoRequests")) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "errored") { + readIntoRequest._errorSteps(stream._storedError); + } else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError("Reader was released"); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue; + readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._errorSteps(e); + }); + } + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError("Invalid highWaterMark"); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + function convertQueuingStrategy(init, context2) { + assertDictionary(init, context2); + const highWaterMark = init === null || init === undefined ? undefined : init.highWaterMark; + const size = init === null || init === undefined ? undefined : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context2} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context2) { + assertFunction(fn, context2); + return (chunk) => convertUnrestrictedDouble(fn(chunk)); + } + function convertUnderlyingSink(original, context2) { + assertDictionary(original, context2); + const abort = original === null || original === undefined ? undefined : original.abort; + const close2 = original === null || original === undefined ? undefined : original.close; + const start = original === null || original === undefined ? undefined : original.start; + const type = original === null || original === undefined ? undefined : original.type; + const write = original === null || original === undefined ? undefined : original.write; + return { + abort: abort === undefined ? undefined : convertUnderlyingSinkAbortCallback(abort, original, `${context2} has member 'abort' that`), + close: close2 === undefined ? undefined : convertUnderlyingSinkCloseCallback(close2, original, `${context2} has member 'close' that`), + start: start === undefined ? undefined : convertUnderlyingSinkStartCallback(start, original, `${context2} has member 'start' that`), + write: write === undefined ? undefined : convertUnderlyingSinkWriteCallback(write, original, `${context2} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context2) { + assertFunction(fn, context2); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context2) { + assertFunction(fn, context2); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context2) { + assertFunction(fn, context2); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function assertWritableStream(x, context2) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context2} is not a WritableStream.`); + } + } + function isAbortSignal(value) { + if (typeof value !== "object" || value === null) { + return false; + } + try { + return typeof value.aborted === "boolean"; + } catch (_a2) { + return false; + } + } + const supportsAbortController = typeof AbortController === "function"; + function createAbortController() { + if (supportsAbortController) { + return new AbortController; + } + return; + } + + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } else { + assertObject(rawUnderlyingSink, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError("Invalid type is specified"); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("locked"); + } + return IsWritableStreamLocked(this); + } + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("abort")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); + } + return WritableStreamAbort(this, reason); + } + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("close")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamClose(this); + } + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("getWriter"); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, "abort"); + setFunctionName(WritableStream.prototype.close, "close"); + setFunctionName(WritableStream.prototype.getWriter, "getWriter"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, { + value: "WritableStream", + configurable: true + }); + } + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = "writable"; + stream._storedError = undefined; + stream._writer = undefined; + stream._writableStreamController = undefined; + stream._writeRequests = new SimpleQueue; + stream._inFlightWriteRequest = undefined; + stream._closeRequest = undefined; + stream._inFlightCloseRequest = undefined; + stream._pendingAbortRequest = undefined; + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_writableStreamController")) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a2; + if (stream._state === "closed" || stream._state === "errored") { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a2 = stream._writableStreamController._abortController) === null || _a2 === undefined || _a2.abort(reason); + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === "erroring") { + wasAlreadyErroring = true; + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === "writable") { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === "writable") { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = "erroring"; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = "errored"; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach((writeRequest) => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue; + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === "erroring") { + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = "closed"; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter"); + assertWritableStream(stream, "First parameter"); + if (IsWritableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive writing by another writer"); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === "writable") { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } else if (state === "erroring") { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } else if (state === "closed") { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("closed")); + } + return this._closedPromise; + } + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("desiredSize"); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException("desiredSize"); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("ready")); + } + return this._readyPromise; + } + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("abort")); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException("abort")); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("close")); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException("close")); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamDefaultWriterClose(this); + } + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("releaseLock"); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("write")); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort"); + setFunctionName(WritableStreamDefaultWriter.prototype.close, "close"); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock"); + setFunctionName(WritableStreamDefaultWriter.prototype.write, "write"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, { + value: "WritableStreamDefaultWriter", + configurable: true + }); + } + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_ownerWritableStream")) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseResolvedWith(undefined); + } + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === "pending") { + defaultWriterClosedPromiseReject(writer, error); + } else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === "pending") { + defaultWriterReadyPromiseReject(writer, error); + } else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === "errored" || state === "erroring") { + return null; + } + if (state === "closed") { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + const state = stream._state; + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); + } + if (state === "erroring") { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + + class WritableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("abortReason"); + } + return this._abortReason; + } + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("signal"); + } + if (this._abortController === undefined) { + throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); + } + return this._abortController.signal; + } + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("error"); + } + const state = this._controlledWritableStream._state; + if (state !== "writable") { + return; + } + WritableStreamDefaultControllerError(this, e); + } + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, { + value: "WritableStreamDefaultController", + configurable: true + }); + } + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_controlledWritableStream")) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, (r) => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } else { + startAlgorithm = () => { + return; + }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); + } else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = (reason) => underlyingSink.abort(reason); + } else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === "erroring") { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === "writable") { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, (reason) => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, (reason) => { + if (stream._state === "writable") { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released writer"); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = "pending"; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = "rejected"; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = "resolved"; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = "pending"; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = "rejected"; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = "fulfilled"; + } + function getGlobals() { + if (typeof globalThis !== "undefined") { + return globalThis; + } else if (typeof self !== "undefined") { + return self; + } else if (typeof global !== "undefined") { + return global; + } + return; + } + const globals = getGlobals(); + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === "function" || typeof ctor === "object")) { + return false; + } + if (ctor.name !== "DOMException") { + return false; + } + try { + new ctor; + return true; + } catch (_a2) { + return false; + } + } + function getFromGlobal() { + const ctor = globals === null || globals === undefined ? undefined : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + function createPolyfill() { + const ctor = function DOMException(message, name) { + this.message = message || ""; + this.name = name || "Error"; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, "DOMException"); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); + return ctor; + } + const DOMException2 = getFromGlobal() || createPolyfill(); + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException2("Aborted", "AbortError"); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === "writable") { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === "readable") { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener("abort", abortAlgorithm); + } + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } else { + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: (chunk) => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + isOrBecomesErrored(source, reader._closedPromise, (storedError) => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + return null; + }); + isOrBecomesErrored(dest, writer._closedPromise, (storedError) => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + return null; + }); + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } else { + shutdown(); + } + return null; + }); + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { + const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === "errored") { + action(stream._storedError); + } else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === "closed") { + action(); + } else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener("abort", abortAlgorithm); + } + if (isError) { + reject(error); + } else { + resolve(undefined); + } + return null; + } + }); + } + + class ReadableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("desiredSize"); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("close"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits close"); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("enqueue"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits enqueue"); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("error"); + } + ReadableStreamDefaultControllerError(this, e); + } + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + [ReleaseSteps]() {} + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, "close"); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue"); + setFunctionName(ReadableStreamDefaultController.prototype.error, "error"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, { + value: "ReadableStreamDefaultController", + configurable: true + }); + } + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_controlledReadableStream")) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, (e) => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== "readable") { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === "readable") { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, (r) => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } else { + startAlgorithm = () => { + return; + }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = (reason) => underlyingSource.cancel(reason); + } else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: (chunk) => { + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() {} + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, (r) => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: (chunk) => { + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: (chunk) => { + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: (chunk) => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== "undefined"; + } + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, "async"); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, (iterResult) => { + if (!typeIsObject(iterResult)) { + throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object"); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, "return"); + } catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, (iterResult) => { + if (!typeIsObject(iterResult)) { + throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object"); + } + return; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, (readResult) => { + if (!typeIsObject(readResult)) { + throw new TypeError("The promise returned by the reader.read() method must fulfill with an object"); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function convertUnderlyingDefaultOrByteSource(source, context2) { + assertDictionary(source, context2); + const original = source; + const autoAllocateChunkSize = original === null || original === undefined ? undefined : original.autoAllocateChunkSize; + const cancel = original === null || original === undefined ? undefined : original.cancel; + const pull = original === null || original === undefined ? undefined : original.pull; + const start = original === null || original === undefined ? undefined : original.start; + const type = original === null || original === undefined ? undefined : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? undefined : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context2} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? undefined : convertUnderlyingSourceCancelCallback(cancel, original, `${context2} has member 'cancel' that`), + pull: pull === undefined ? undefined : convertUnderlyingSourcePullCallback(pull, original, `${context2} has member 'pull' that`), + start: start === undefined ? undefined : convertUnderlyingSourceStartCallback(start, original, `${context2} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context2} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context2) { + assertFunction(fn, context2); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context2) { + type = `${type}`; + if (type !== "bytes") { + throw new TypeError(`${context2} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + function convertIteratorOptions(options, context2) { + assertDictionary(options, context2); + const preventCancel = options === null || options === undefined ? undefined : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + function convertPipeOptions(options, context2) { + assertDictionary(options, context2); + const preventAbort = options === null || options === undefined ? undefined : options.preventAbort; + const preventCancel = options === null || options === undefined ? undefined : options.preventCancel; + const preventClose = options === null || options === undefined ? undefined : options.preventClose; + const signal = options === null || options === undefined ? undefined : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context2} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context2) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context2} is not an AbortSignal.`); + } + } + function convertReadableWritablePair(pair, context2) { + assertDictionary(pair, context2); + const readable = pair === null || pair === undefined ? undefined : pair.readable; + assertRequiredField(readable, "readable", "ReadableWritablePair"); + assertReadableStream(readable, `${context2} has member 'readable' that`); + const writable = pair === null || pair === undefined ? undefined : pair.writable; + assertRequiredField(writable, "writable", "ReadableWritablePair"); + assertWritableStream(writable, `${context2} has member 'writable' that`); + return { readable, writable }; + } + + class ReadableStream2 { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } else { + assertObject(rawUnderlyingSource, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter"); + InitializeReadableStream(this); + if (underlyingSource.type === "bytes") { + if (strategy.size !== undefined) { + throw new RangeError("The strategy for a byte stream cannot have a size function"); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("locked"); + } + return IsReadableStreamLocked(this); + } + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("cancel")); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader")); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("getReader"); + } + const options = convertReaderOptions(rawOptions, "First parameter"); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("pipeThrough"); + } + assertRequiredArgument(rawTransform, 1, "pipeThrough"); + const transform = convertReadableWritablePair(rawTransform, "First parameter"); + const options = convertPipeOptions(rawOptions, "Second parameter"); + if (IsReadableStreamLocked(this)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream"); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream"); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("pipeTo")); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, "Second parameter"); + } catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("tee"); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("values"); + } + const options = convertIteratorOptions(rawOptions, "First parameter"); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + [SymbolAsyncIterator](options) { + return this.values(options); + } + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream2, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream2.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream2.from, "from"); + setFunctionName(ReadableStream2.prototype.cancel, "cancel"); + setFunctionName(ReadableStream2.prototype.getReader, "getReader"); + setFunctionName(ReadableStream2.prototype.pipeThrough, "pipeThrough"); + setFunctionName(ReadableStream2.prototype.pipeTo, "pipeTo"); + setFunctionName(ReadableStream2.prototype.tee, "tee"); + setFunctionName(ReadableStream2.prototype.values, "values"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ReadableStream2.prototype, Symbol.toStringTag, { + value: "ReadableStream", + configurable: true + }); + } + Object.defineProperty(ReadableStream2.prototype, SymbolAsyncIterator, { + value: ReadableStream2.prototype.values, + writable: true, + configurable: true + }); + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = "readable"; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_readableStreamController")) { + return false; + } + return x instanceof ReadableStream2; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === "closed") { + return promiseResolvedWith(undefined); + } + if (stream._state === "errored") { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue; + readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = "closed"; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue; + readRequests.forEach((readRequest) => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = "errored"; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + function convertQueuingStrategyInit(init, context2) { + assertDictionary(init, context2); + const highWaterMark = init === null || init === undefined ? undefined : init.highWaterMark; + assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, "size"); + + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("highWaterMark"); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("size"); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, { + value: "ByteLengthQueuingStrategy", + configurable: true + }); + } + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_byteLengthQueuingStrategyHighWaterMark")) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, "size"); + + class CountQueuingStrategy2 { + constructor(options) { + assertRequiredArgument(options, 1, "CountQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("highWaterMark"); + } + return this._countQueuingStrategyHighWaterMark; + } + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("size"); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy2.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(CountQueuingStrategy2.prototype, Symbol.toStringTag, { + value: "CountQueuingStrategy", + configurable: true + }); + } + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_countQueuingStrategyHighWaterMark")) { + return false; + } + return x instanceof CountQueuingStrategy2; + } + function convertTransformer(original, context2) { + assertDictionary(original, context2); + const cancel = original === null || original === undefined ? undefined : original.cancel; + const flush = original === null || original === undefined ? undefined : original.flush; + const readableType = original === null || original === undefined ? undefined : original.readableType; + const start = original === null || original === undefined ? undefined : original.start; + const transform = original === null || original === undefined ? undefined : original.transform; + const writableType = original === null || original === undefined ? undefined : original.writableType; + return { + cancel: cancel === undefined ? undefined : convertTransformerCancelCallback(cancel, original, `${context2} has member 'cancel' that`), + flush: flush === undefined ? undefined : convertTransformerFlushCallback(flush, original, `${context2} has member 'flush' that`), + readableType, + start: start === undefined ? undefined : convertTransformerStartCallback(start, original, `${context2} has member 'start' that`), + transform: transform === undefined ? undefined : convertTransformerTransformCallback(transform, original, `${context2} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context2) { + assertFunction(fn, context2); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context2) { + assertFunction(fn, context2); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context2) { + assertFunction(fn, context2); + return (reason) => promiseCall(fn, original, [reason]); + } + + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); + const transformer = convertTransformer(rawTransformer, "First parameter"); + if (transformer.readableType !== undefined) { + throw new RangeError("Invalid readableType specified"); + } + if (transformer.writableType !== undefined) { + throw new RangeError("Invalid writableType specified"); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise((resolve) => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } else { + startPromise_resolve(undefined); + } + } + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("readable"); + } + return this._readable; + } + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("writable"); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, { + value: "TransformStream", + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_transformStreamController")) { + return false; + } + return x instanceof TransformStream; + } + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise((resolve) => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + + class TransformStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("desiredSize"); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("enqueue"); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("error"); + } + TransformStreamDefaultControllerError(this, reason); + } + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("terminate"); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue"); + setFunctionName(TransformStreamDefaultController.prototype.error, "error"); + setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate"); + if (typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, { + value: "TransformStreamDefaultController", + configurable: true + }); + } + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, "_controlledTransformStream")) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = (chunk) => transformer.transform(chunk, controller); + } else { + transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = (reason) => transformer.cancel(reason); + } else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError("Readable side is not in a state that permits enqueue"); + } + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } catch (e) { + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, (r) => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError("TransformStream terminated"); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === "erroring") { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + const readable = stream._readable; + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === "errored") { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, (r) => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + const readable = stream._readable; + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === "errored") { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, (r) => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSourcePullAlgorithm(stream) { + TransformStreamSetBackpressure(stream, false); + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + const writable = stream._writable; + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === "errored") { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, (r) => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + exports2.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports2.CountQueuingStrategy = CountQueuingStrategy2; + exports2.ReadableByteStreamController = ReadableByteStreamController; + exports2.ReadableStream = ReadableStream2; + exports2.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports2.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports2.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports2.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports2.TransformStream = TransformStream; + exports2.TransformStreamDefaultController = TransformStreamDefaultController; + exports2.WritableStream = WritableStream; + exports2.WritableStreamDefaultController = WritableStreamDefaultController; + exports2.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + }); +}); + +// node_modules/fetch-blob/streams.cjs +var require_streams = __commonJS(() => { + var POOL_SIZE = 65536; + if (!globalThis.ReadableStream) { + try { + const process2 = __require("node:process"); + const { emitWarning } = process2; + try { + process2.emitWarning = () => {}; + Object.assign(globalThis, __require("node:stream/web")); + process2.emitWarning = emitWarning; + } catch (error) { + process2.emitWarning = emitWarning; + throw error; + } + } catch (error) { + Object.assign(globalThis, require_ponyfill_es2018()); + } + } + try { + const { Blob } = __require("buffer"); + if (Blob && !Blob.prototype.stream) { + Blob.prototype.stream = function name(params) { + let position = 0; + const blob = this; + return new ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + ctrl.enqueue(new Uint8Array(buffer)); + if (position === blob.size) { + ctrl.close(); + } + } + }); + }; + } + } catch (error) {} +}); + +// node_modules/fetch-blob/index.js +async function* toIterator(parts, clone = true) { + for (const part of parts) { + if ("stream" in part) { + yield* part.stream(); + } else if (ArrayBuffer.isView(part)) { + if (clone) { + let position = part.byteOffset; + const end = part.byteOffset + part.byteLength; + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } + } else { + yield part; + } + } else { + let position = 0, b = part; + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); + } + } + } +} +var import_streams, POOL_SIZE = 65536, _Blob, Blob2, fetch_blob_default; +var init_fetch_blob = __esm(() => { + import_streams = __toESM(require_streams(), 1); + /*! fetch-blob. MIT License. Jimmy Wärting */ + _Blob = class Blob { + #parts = []; + #type = ""; + #size = 0; + #endings = "transparent"; + constructor(blobParts = [], options = {}) { + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence."); + } + if (typeof blobParts[Symbol.iterator] !== "function") { + throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property."); + } + if (typeof options !== "object" && typeof options !== "function") { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + if (options === null) + options = {}; + const encoder = new TextEncoder; + for (const element of blobParts) { + let part; + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)); + } else if (element instanceof Blob) { + part = element; + } else { + part = encoder.encode(`${element}`); + } + this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size; + this.#parts.push(part); + } + this.#endings = `${options.endings === undefined ? "transparent" : options.endings}`; + const type = options.type === undefined ? "" : String(options.type); + this.#type = /^[\x20-\x7E]*$/.test(type) ? type : ""; + } + get size() { + return this.#size; + } + get type() { + return this.#type; + } + async text() { + const decoder = new TextDecoder; + let str = ""; + for await (const part of toIterator(this.#parts, false)) { + str += decoder.decode(part, { stream: true }); + } + str += decoder.decode(); + return str; + } + async arrayBuffer() { + const data = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of toIterator(this.#parts, false)) { + data.set(chunk, offset); + offset += chunk.length; + } + return data.buffer; + } + stream() { + const it = toIterator(this.#parts, true); + return new globalThis.ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = await it.next(); + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value); + }, + async cancel() { + await it.return(); + } + }); + } + slice(start = 0, end = this.size, type = "") { + const { size } = this; + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + const span = Math.max(relativeEnd - relativeStart, 0); + const parts = this.#parts; + const blobParts = []; + let added = 0; + for (const part of parts) { + if (added >= span) { + break; + } + const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && size2 <= relativeStart) { + relativeStart -= size2; + relativeEnd -= size2; + } else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.byteLength; + } else { + chunk = part.slice(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.size; + } + relativeEnd -= size2; + blobParts.push(chunk); + relativeStart = 0; + } + } + const blob = new Blob([], { type: String(type).toLowerCase() }); + blob.#size = span; + blob.#parts = blobParts; + return blob; + } + get [Symbol.toStringTag]() { + return "Blob"; + } + static [Symbol.hasInstance](object) { + return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]); + } + }; + Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } + }); + Blob2 = _Blob; + fetch_blob_default = Blob2; +}); + +// node_modules/fetch-blob/file.js +var _File, File3, file_default; +var init_file = __esm(() => { + init_fetch_blob(); + _File = class File2 extends fetch_blob_default { + #lastModified = 0; + #name = ""; + constructor(fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`); + } + super(fileBits, options); + if (options === null) + options = {}; + const lastModified = options.lastModified === undefined ? Date.now() : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + this.#lastModified = lastModified; + } + this.#name = String(fileName); + } + get name() { + return this.#name; + } + get lastModified() { + return this.#lastModified; + } + get [Symbol.toStringTag]() { + return "File"; + } + static [Symbol.hasInstance](object) { + return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]); + } + }; + File3 = _File; + file_default = File3; +}); + +// node_modules/formdata-polyfill/esm.min.js +function formDataToBlob(F, B = fetch_blob_default) { + var b = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c = [], p = `--${b}\r +Content-Disposition: form-data; name="`; + F.forEach((v, n) => typeof v == "string" ? c.push(p + e(n) + `"\r +\r +${v.replace(/\r(?!\n)|(? (a += "", /^(Blob|File)$/.test(b && b[t]) ? [(c = c !== undefined ? c + "" : b[t] == "File" ? b.name : "blob", a), b.name !== c || b[t] == "blob" ? new file_default([b], c, b) : b] : [a, b + ""]), e = (c, f2) => (f2 ? c : c.replace(/\r?\n|\r/g, `\r +`)).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), x = (n, a, e2) => { + if (a.length < e2) { + throw new TypeError(`Failed to execute '${n}' on 'FormData': ${e2} arguments required, but only ${a.length} present.`); + } +}, FormData; +var init_esm_min = __esm(() => { + init_fetch_blob(); + init_file(); + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + ({ toStringTag: t, iterator: i, hasInstance: h } = Symbol); + r = Math.random; + m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","); + FormData = class FormData2 { + #d = []; + constructor(...a) { + if (a.length) + throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`); + } + get [t]() { + return "FormData"; + } + [i]() { + return this.entries(); + } + static [h](o) { + return o && typeof o === "object" && o[t] === "FormData" && !m.some((m2) => typeof o[m2] != "function"); + } + append(...a) { + x("append", arguments, 2); + this.#d.push(f(...a)); + } + delete(a) { + x("delete", arguments, 1); + a += ""; + this.#d = this.#d.filter(([b]) => b !== a); + } + get(a) { + x("get", arguments, 1); + a += ""; + for (var b = this.#d, l = b.length, c = 0;c < l; c++) + if (b[c][0] === a) + return b[c][1]; + return null; + } + getAll(a, b) { + x("getAll", arguments, 1); + b = []; + a += ""; + this.#d.forEach((c) => c[0] === a && b.push(c[1])); + return b; + } + has(a) { + x("has", arguments, 1); + a += ""; + return this.#d.some((b) => b[0] === a); + } + forEach(a, b) { + x("forEach", arguments, 1); + for (var [c, d] of this) + a.call(b, d, c, this); + } + set(...a) { + x("set", arguments, 2); + var b = [], c = true; + a = f(...a); + this.#d.forEach((d) => { + d[0] === a[0] ? c && (c = !b.push(a)) : b.push(d); + }); + c && b.push(a); + this.#d = b; + } + *entries() { + yield* this.#d; + } + *keys() { + for (var [a] of this) + yield a; + } + *values() { + for (var [, a] of this) + yield a; + } + }; +}); + +// node_modules/node-fetch/src/errors/base.js +var FetchBaseError; +var init_base = __esm(() => { + FetchBaseError = class FetchBaseError extends Error { + constructor(message, type) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.type = type; + } + get name() { + return this.constructor.name; + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } + }; +}); + +// node_modules/node-fetch/src/errors/fetch-error.js +var FetchError; +var init_fetch_error = __esm(() => { + init_base(); + FetchError = class FetchError extends FetchBaseError { + constructor(message, type, systemError) { + super(message, type); + if (systemError) { + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } + }; +}); + +// node_modules/node-fetch/src/utils/is.js +var NAME, isURLSearchParameters = (object) => { + return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams"; +}, isBlob = (object) => { + return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]); +}, isAbortSignal = (object) => { + return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget"); +}, isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + return orig === dest || orig.endsWith(`.${dest}`); +}, isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + return orig === dest; +}; +var init_is = __esm(() => { + NAME = Symbol.toStringTag; +}); + +// node_modules/node-domexception/index.js +var require_node_domexception = __commonJS((exports, module) => { + /*! node-domexception. MIT License. Jimmy Wärting */ + if (!globalThis.DOMException) { + try { + const { MessageChannel } = __require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer; + port.postMessage(ab, [ab, ab]); + } catch (err) { + err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor); + } + } + module.exports = globalThis.DOMException; +}); + +// node_modules/fetch-blob/from.js +import { statSync, createReadStream, promises as fs } from "node:fs"; +var import_node_domexception, stat, BlobDataItem; +var init_from = __esm(() => { + init_file(); + init_fetch_blob(); + import_node_domexception = __toESM(require_node_domexception(), 1); + ({ stat } = fs); + BlobDataItem = class BlobDataItem { + #path; + #start; + constructor(options) { + this.#path = options.path; + this.#start = options.start; + this.size = options.size; + this.lastModified = options.lastModified; + } + slice(start, end) { + return new BlobDataItem({ + path: this.#path, + lastModified: this.lastModified, + size: end - start, + start: this.#start + start + }); + } + async* stream() { + const { mtimeMs } = await stat(this.#path); + if (mtimeMs > this.lastModified) { + throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError"); + } + yield* createReadStream(this.#path, { + start: this.#start, + end: this.#start + this.size - 1 + }); + } + get [Symbol.toStringTag]() { + return "Blob"; + } + }; +}); + +// node_modules/node-fetch/src/utils/multipart-parser.js +var exports_multipart_parser = {}; +__export(exports_multipart_parser, { + toFormData: () => toFormData +}); + +class MultipartParser { + constructor(boundary) { + this.index = 0; + this.flags = 0; + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + this.boundaryChars = {}; + boundary = `\r +--` + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i2 = 0;i2 < boundary.length; i2++) { + ui8a[i2] = boundary.charCodeAt(i2); + this.boundaryChars[ui8a[i2]] = true; + } + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + write(data) { + let i2 = 0; + const length_ = data.length; + let previousIndex = this.index; + let { lookbehind, boundary, boundaryChars, index, state, flags } = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + const mark = (name) => { + this[name + "Mark"] = i2; + }; + const clear = (name) => { + delete this[name + "Mark"]; + }; + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === undefined || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + const dataCallback = (name, clear2) => { + const markSymbol = name + "Mark"; + if (!(markSymbol in this)) { + return; + } + if (clear2) { + callback(name, this[markSymbol], i2, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + for (i2 = 0;i2 < length_; i2++) { + c = data[i2]; + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + } else { + return; + } + break; + } + if (c !== boundary[index + 2]) { + index = -2; + } + if (c === boundary[index + 2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark("onHeaderField"); + index = 0; + case S.HEADER_FIELD: + if (c === CR) { + clear("onHeaderField"); + state = S.HEADERS_ALMOST_DONE; + break; + } + index++; + if (c === HYPHEN) { + break; + } + if (c === COLON) { + if (index === 1) { + return; + } + dataCallback("onHeaderField", true); + state = S.HEADER_VALUE_START; + break; + } + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + mark("onHeaderValue"); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c === CR) { + dataCallback("onHeaderValue", true); + callback("onHeaderEnd"); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + callback("onHeadersEnd"); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark("onPartData"); + case S.PART_DATA: + previousIndex = index; + if (index === 0) { + i2 += boundaryEnd; + while (i2 < bufferLength && !(data[i2] in boundaryChars)) { + i2 += boundaryLength; + } + i2 -= boundaryEnd; + c = data[i2]; + } + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback("onPartData", true); + } + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + flags &= ~F.PART_BOUNDARY; + callback("onPartEnd"); + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback("onPartEnd"); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + if (index > 0) { + lookbehind[index - 1] = c; + } else if (previousIndex > 0) { + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback("onPartData", 0, previousIndex, _lookbehind); + previousIndex = 0; + mark("onPartData"); + i2--; + } + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + dataCallback("onHeaderField"); + dataCallback("onHeaderValue"); + dataCallback("onPartData"); + this.index = index; + this.state = state; + this.flags = flags; + } + end() { + if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error("MultipartParser.end(): stream ended unexpectedly"); + } + } +} +function _fileName(headerValue) { + const m2 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m2) { + return; + } + const match = m2[2] || m2[3] || ""; + let filename = match.slice(match.lastIndexOf("\\") + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m3, code) => { + return String.fromCharCode(code); + }); + return filename; +} +async function toFormData(Body, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError("Failed to fetch"); + } + const m2 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (!m2) { + throw new TypeError("no or bad content-type header, no multipart boundary"); + } + const parser = new MultipartParser(m2[1] || m2[2]); + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData; + const onPartData = (ui8a) => { + entryValue += decoder.decode(ui8a, { stream: true }); + }; + const appendToFile = (ui8a) => { + entryChunks.push(ui8a); + }; + const appendFileToFormData = () => { + const file = new file_default(entryChunks, filename, { type: contentType }); + formData.append(entryName, file); + }; + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + const decoder = new TextDecoder("utf-8"); + decoder.decode(); + parser.onPartBegin = function() { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + headerField = ""; + headerValue = ""; + entryValue = ""; + entryName = ""; + contentType = ""; + filename = null; + entryChunks.length = 0; + }; + parser.onHeaderField = function(ui8a) { + headerField += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderValue = function(ui8a) { + headerValue += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderEnd = function() { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + if (headerField === "content-disposition") { + const m3 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + if (m3) { + entryName = m3[2] || m3[3] || ""; + } + filename = _fileName(headerValue); + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === "content-type") { + contentType = headerValue; + } + headerValue = ""; + headerField = ""; + }; + for await (const chunk of Body) { + parser.write(chunk); + } + parser.end(); + return formData; +} +var s = 0, S, f2 = 1, F, LF = 10, CR = 13, SPACE = 32, HYPHEN = 45, COLON = 58, A = 97, Z = 122, lower = (c) => c | 32, noop = () => {}; +var init_multipart_parser = __esm(() => { + init_from(); + init_esm_min(); + S = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ + }; + F = { + PART_BOUNDARY: f2, + LAST_BOUNDARY: f2 *= 2 + }; +}); + +// node_modules/node-fetch/src/body.js +import Stream, { PassThrough } from "node:stream"; +import { types, deprecate, promisify } from "node:util"; +import { Buffer as Buffer2 } from "node:buffer"; + +class Body { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + if (body === null) { + body = null; + } else if (isURLSearchParameters(body)) { + body = Buffer2.from(body.toString()); + } else if (isBlob(body)) {} else if (Buffer2.isBuffer(body)) {} else if (types.isAnyArrayBuffer(body)) { + body = Buffer2.from(body); + } else if (ArrayBuffer.isView(body)) { + body = Buffer2.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) {} else if (body instanceof FormData) { + body = formDataToBlob(body); + boundary = body.type.split("=")[1]; + } else { + body = Buffer2.from(String(body)); + } + let stream = body; + if (Buffer2.isBuffer(body)) { + stream = Stream.Readable.from(body); + } else if (isBlob(body)) { + stream = Stream.Readable.from(body.stream()); + } + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + if (body instanceof Stream) { + body.on("error", (error_) => { + const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); + this[INTERNALS].error = error; + }); + } + } + get body() { + return this[INTERNALS].stream; + } + get bodyUsed() { + return this[INTERNALS].disturbed; + } + async arrayBuffer() { + const { buffer, byteOffset, byteLength } = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + async formData() { + const ct = this.headers.get("content-type"); + if (ct.startsWith("application/x-www-form-urlencoded")) { + const formData = new FormData; + const parameters = new URLSearchParams(await this.text()); + for (const [name, value] of parameters) { + formData.append(name, value); + } + return formData; + } + const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), exports_multipart_parser)); + return toFormData2(this.body, ct); + } + async blob() { + const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; + const buf = await this.arrayBuffer(); + return new fetch_blob_default([buf], { + type: ct + }); + } + async json() { + const text = await this.text(); + return JSON.parse(text); + } + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + buffer() { + return consumeBody(this); + } +} +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + data[INTERNALS].disturbed = true; + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + const { body } = data; + if (body === null) { + return Buffer2.alloc(0); + } + if (!(body instanceof Stream)) { + return Buffer2.alloc(0); + } + const accum = []; + let accumBytes = 0; + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); + body.destroy(error); + throw error; + } + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, "system", error); + throw error_; + } + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every((c) => typeof c === "string")) { + return Buffer2.from(accum.join("")); + } + return Buffer2.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, "system", error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} +var pipeline, INTERNALS, clone = (instance, highWaterMark) => { + let p1; + let p2; + let { body } = instance[INTERNALS]; + if (instance.bodyUsed) { + throw new Error("cannot clone body after it is used"); + } + if (body instanceof Stream && typeof body.getBoundary !== "function") { + p1 = new PassThrough({ highWaterMark }); + p2 = new PassThrough({ highWaterMark }); + body.pipe(p1); + body.pipe(p2); + instance[INTERNALS].stream = p1; + body = p2; + } + return body; +}, getNonSpecFormDataBoundary, extractContentType = (body, request2) => { + if (body === null) { + return null; + } + if (typeof body === "string") { + return "text/plain;charset=UTF-8"; + } + if (isURLSearchParameters(body)) { + return "application/x-www-form-urlencoded;charset=UTF-8"; + } + if (isBlob(body)) { + return body.type || null; + } + if (Buffer2.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + if (body instanceof FormData) { + return `multipart/form-data; boundary=${request2[INTERNALS].boundary}`; + } + if (body && typeof body.getBoundary === "function") { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + if (body instanceof Stream) { + return null; + } + return "text/plain;charset=UTF-8"; +}, getTotalBytes = (request2) => { + const { body } = request2[INTERNALS]; + if (body === null) { + return 0; + } + if (isBlob(body)) { + return body.size; + } + if (Buffer2.isBuffer(body)) { + return body.length; + } + if (body && typeof body.getLengthSync === "function") { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + return null; +}, writeToStream = async (dest, { body }) => { + if (body === null) { + dest.end(); + } else { + await pipeline(body, dest); + } +}; +var init_body = __esm(() => { + init_fetch_blob(); + init_esm_min(); + init_fetch_error(); + init_base(); + init_is(); + pipeline = promisify(Stream.pipeline); + INTERNALS = Symbol("Body internals"); + Body.prototype.buffer = deprecate(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); + Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true }, + data: { get: deprecate(() => {}, "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (response)") } + }); + getNonSpecFormDataBoundary = deprecate((body) => body.getBoundary(), "form-data doesn't follow the spec and requires special treatment. Use alternative package", "https://github.com/node-fetch/node-fetch/issues/1167"); +}); + +// node_modules/node-fetch/src/headers.js +import { types as types2 } from "node:util"; +import http from "node:http"; +function fromRawHeaders(headers = []) { + return new Headers2(headers.reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + return result; + }, []).filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch { + return false; + } + })); +} +var validateHeaderName, validateHeaderValue, Headers2; +var init_headers = __esm(() => { + validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name) => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" }); + throw error; + } + }; + validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" }); + throw error; + } + }; + Headers2 = class Headers2 extends URLSearchParams { + constructor(init) { + let result = []; + if (init instanceof Headers2) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map((value) => [name, value])); + } + } else if (init == null) {} else if (typeof init === "object" && !types2.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + if (method == null) { + result.push(...Object.entries(init)); + } else { + if (typeof method !== "function") { + throw new TypeError("Header pairs must be iterable"); + } + result = [...init].map((pair) => { + if (typeof pair !== "object" || types2.isBoxedPrimitive(pair)) { + throw new TypeError("Each header pair must be an iterable object"); + } + return [...pair]; + }).map((pair) => { + if (pair.length !== 2) { + throw new TypeError("Each header pair must be a name/value tuple"); + } + return [...pair]; + }); + } + } else { + throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)"); + } + result = result.length > 0 ? result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : undefined; + super(result); + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case "append": + case "set": + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call(target, String(name).toLowerCase(), String(value)); + }; + case "delete": + case "has": + case "getAll": + return (name) => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call(target, String(name).toLowerCase()); + }; + case "keys": + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + default: + return Reflect.get(target, p, receiver); + } + } + }); + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } + toString() { + return Object.prototype.toString.call(this); + } + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + let value = values.join(", "); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + return value; + } + forEach(callback, thisArg = undefined) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + *values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + *entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + [Symbol.iterator]() { + return this.entries(); + } + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + if (key === "host") { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + return result; + }, {}); + } + }; + Object.defineProperties(Headers2.prototype, ["get", "entries", "forEach", "values"].reduce((result, property) => { + result[property] = { enumerable: true }; + return result; + }, {})); +}); + +// node_modules/node-fetch/src/utils/is-redirect.js +var redirectStatus, isRedirect = (code) => { + return redirectStatus.has(code); +}; +var init_is_redirect = __esm(() => { + redirectStatus = new Set([301, 302, 303, 307, 308]); +}); + +// node_modules/node-fetch/src/response.js +var INTERNALS2, Response; +var init_response = __esm(() => { + init_headers(); + init_body(); + init_is_redirect(); + INTERNALS2 = Symbol("Response internals"); + Response = class Response extends Body { + constructor(body = null, options = {}) { + super(body, options); + const status = options.status != null ? options.status : 200; + const headers = new Headers2(options.headers); + if (body !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append("Content-Type", contentType); + } + } + this[INTERNALS2] = { + type: "default", + url: options.url, + status, + statusText: options.statusText || "", + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + get type() { + return this[INTERNALS2].type; + } + get url() { + return this[INTERNALS2].url || ""; + } + get status() { + return this[INTERNALS2].status; + } + get ok() { + return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300; + } + get redirected() { + return this[INTERNALS2].counter > 0; + } + get statusText() { + return this[INTERNALS2].statusText; + } + get headers() { + return this[INTERNALS2].headers; + } + get highWaterMark() { + return this[INTERNALS2].highWaterMark; + } + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + static redirect(url, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + return new Response(null, { + headers: { + location: new URL(url).toString() + }, + status + }); + } + static error() { + const response = new Response(null, { status: 0, statusText: "" }); + response[INTERNALS2].type = "error"; + return response; + } + static json(data = undefined, init = {}) { + const body = JSON.stringify(data); + if (body === undefined) { + throw new TypeError("data is not JSON serializable"); + } + const headers = new Headers2(init && init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + return new Response(body, { + ...init, + headers + }); + } + get [Symbol.toStringTag]() { + return "Response"; + } + }; + Object.defineProperties(Response.prototype, { + type: { enumerable: true }, + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } + }); +}); + +// node_modules/node-fetch/src/utils/get-search.js +var getSearch = (parsedURL) => { + if (parsedURL.search) { + return parsedURL.search; + } + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : ""); + return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : ""; +}; + +// node_modules/node-fetch/src/utils/referrer.js +import { isIP } from "node:net"; +function stripURLForUseAsAReferrer(url, originOnly = false) { + if (url == null) { + return "no-referrer"; + } + url = new URL(url); + if (/^(about|blob|data):$/.test(url.protocol)) { + return "no-referrer"; + } + url.username = ""; + url.password = ""; + url.hash = ""; + if (originOnly) { + url.pathname = ""; + url.search = ""; + } + return url; +} +function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + return referrerPolicy; +} +function isOriginPotentiallyTrustworthy(url) { + if (/^(http|ws)s:$/.test(url.protocol)) { + return true; + } + const hostIp = url.host.replace(/(^\[)|(]$)/g, ""); + const hostIPVersion = isIP(hostIp); + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + if (url.host === "localhost" || url.host.endsWith(".localhost")) { + return false; + } + if (url.protocol === "file:") { + return true; + } + return false; +} +function isUrlPotentiallyTrustworthy(url) { + if (/^about:(blank|srcdoc)$/.test(url)) { + return true; + } + if (url.protocol === "data:") { + return true; + } + if (/^(blob|filesystem):$/.test(url.protocol)) { + return true; + } + return isOriginPotentiallyTrustworthy(url); +} +function determineRequestsReferrer(request2, { referrerURLCallback, referrerOriginCallback } = {}) { + if (request2.referrer === "no-referrer" || request2.referrerPolicy === "") { + return null; + } + const policy = request2.referrerPolicy; + if (request2.referrer === "about:client") { + return "no-referrer"; + } + const referrerSource = request2.referrer; + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + const currentURL = new URL(request2.url); + switch (policy) { + case "no-referrer": + return "no-referrer"; + case "origin": + return referrerOrigin; + case "unsafe-url": + return referrerURL; + case "strict-origin": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin.toString(); + case "strict-origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin; + case "same-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return "no-referrer"; + case "origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return referrerOrigin; + case "no-referrer-when-downgrade": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerURL; + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} +function parseReferrerPolicyFromHeader(headers) { + const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); + let policy = ""; + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + return policy; +} +var ReferrerPolicy, DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin"; +var init_referrer = __esm(() => { + ReferrerPolicy = new Set([ + "", + "no-referrer", + "no-referrer-when-downgrade", + "same-origin", + "origin", + "strict-origin", + "origin-when-cross-origin", + "strict-origin-when-cross-origin", + "unsafe-url" + ]); +}); + +// node_modules/node-fetch/src/request.js +import { format as formatUrl } from "node:url"; +import { deprecate as deprecate2 } from "node:util"; +var INTERNALS3, isRequest = (object) => { + return typeof object === "object" && typeof object[INTERNALS3] === "object"; +}, doBadDataWarn, Request, getNodeRequestOptions = (request2) => { + const { parsedURL } = request2[INTERNALS3]; + const headers = new Headers2(request2[INTERNALS3].headers); + if (!headers.has("Accept")) { + headers.set("Accept", "*/*"); + } + let contentLengthValue = null; + if (request2.body === null && /^(post|put)$/i.test(request2.method)) { + contentLengthValue = "0"; + } + if (request2.body !== null) { + const totalBytes = getTotalBytes(request2); + if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set("Content-Length", contentLengthValue); + } + if (request2.referrerPolicy === "") { + request2.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + if (request2.referrer && request2.referrer !== "no-referrer") { + request2[INTERNALS3].referrer = determineRequestsReferrer(request2); + } else { + request2[INTERNALS3].referrer = "no-referrer"; + } + if (request2[INTERNALS3].referrer instanceof URL) { + headers.set("Referer", request2.referrer); + } + if (!headers.has("User-Agent")) { + headers.set("User-Agent", "node-fetch"); + } + if (request2.compress && !headers.has("Accept-Encoding")) { + headers.set("Accept-Encoding", "gzip, deflate, br"); + } + let { agent } = request2; + if (typeof agent === "function") { + agent = agent(parsedURL); + } + const search = getSearch(parsedURL); + const options = { + path: parsedURL.pathname + search, + method: request2.method, + headers: headers[Symbol.for("nodejs.util.inspect.custom")](), + insecureHTTPParser: request2.insecureHTTPParser, + agent + }; + return { + parsedURL, + options + }; +}; +var init_request2 = __esm(() => { + init_headers(); + init_body(); + init_is(); + init_referrer(); + INTERNALS3 = Symbol("Request internals"); + doBadDataWarn = deprecate2(() => {}, ".data is not a valid RequestInit property, use .body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (request)"); + Request = class Request extends Body { + constructor(input, init = {}) { + let parsedURL; + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + if (parsedURL.username !== "" || parsedURL.password !== "") { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + let method = init.method || input.method || "GET"; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + if (!isRequest(init) && "data" in init) { + doBadDataWarn(); + } + if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) { + throw new TypeError("Request with GET/HEAD method cannot have body"); + } + const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + super(inputBody, { + size: init.size || input.size || 0 + }); + const headers = new Headers2(init.headers || input.headers || {}); + if (inputBody !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set("Content-Type", contentType); + } + } + let signal = isRequest(input) ? input.signal : null; + if ("signal" in init) { + signal = init.signal; + } + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget"); + } + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === "") { + referrer = "no-referrer"; + } else if (referrer) { + const parsedReferrer = new URL(referrer); + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer; + } else { + referrer = undefined; + } + this[INTERNALS3] = { + method, + redirect: init.redirect || input.redirect || "follow", + headers, + parsedURL, + signal, + referrer + }; + this.follow = init.follow === undefined ? input.follow === undefined ? 20 : input.follow : init.follow; + this.compress = init.compress === undefined ? input.compress === undefined ? true : input.compress : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ""; + } + get method() { + return this[INTERNALS3].method; + } + get url() { + return formatUrl(this[INTERNALS3].parsedURL); + } + get headers() { + return this[INTERNALS3].headers; + } + get redirect() { + return this[INTERNALS3].redirect; + } + get signal() { + return this[INTERNALS3].signal; + } + get referrer() { + if (this[INTERNALS3].referrer === "no-referrer") { + return ""; + } + if (this[INTERNALS3].referrer === "client") { + return "about:client"; + } + if (this[INTERNALS3].referrer) { + return this[INTERNALS3].referrer.toString(); + } + return; + } + get referrerPolicy() { + return this[INTERNALS3].referrerPolicy; + } + set referrerPolicy(referrerPolicy) { + this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + clone() { + return new Request(this); + } + get [Symbol.toStringTag]() { + return "Request"; + } + }; + Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true }, + referrer: { enumerable: true }, + referrerPolicy: { enumerable: true } + }); +}); + +// node_modules/node-fetch/src/errors/abort-error.js +var AbortError; +var init_abort_error = __esm(() => { + init_base(); + AbortError = class AbortError extends FetchBaseError { + constructor(message, type = "aborted") { + super(message, type); + } + }; +}); + +// node_modules/node-fetch/src/index.js +import http2 from "node:http"; +import https from "node:https"; +import zlib from "node:zlib"; +import Stream2, { PassThrough as PassThrough2, pipeline as pump } from "node:stream"; +import { Buffer as Buffer3 } from "node:buffer"; +async function fetch2(url, options_) { + return new Promise((resolve, reject) => { + const request2 = new Request(url, options_); + const { parsedURL, options } = getNodeRequestOptions(request2); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`); + } + if (parsedURL.protocol === "data:") { + const data = dist_default(request2.url); + const response2 = new Response(data, { headers: { "Content-Type": data.typeFull } }); + resolve(response2); + return; + } + const send = (parsedURL.protocol === "https:" ? https : http2).request; + const { signal } = request2; + let response = null; + const abort = () => { + const error = new AbortError("The operation was aborted."); + reject(error); + if (request2.body && request2.body instanceof Stream2.Readable) { + request2.body.destroy(error); + } + if (!response || !response.body) { + return; + } + response.body.emit("error", error); + }; + if (signal && signal.aborted) { + abort(); + return; + } + const abortAndFinalize = () => { + abort(); + finalize(); + }; + const request_ = send(parsedURL.toString(), options); + if (signal) { + signal.addEventListener("abort", abortAndFinalize); + } + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener("abort", abortAndFinalize); + } + }; + request_.on("error", (error) => { + reject(new FetchError(`request to ${request2.url} failed, reason: ${error.message}`, "system", error)); + finalize(); + }); + fixResponseChunkedTransferBadEnding(request_, (error) => { + if (response && response.body) { + response.body.destroy(error); + } + }); + if (process.version < "v14") { + request_.on("socket", (s2) => { + let endedWithEventsCount; + s2.prependListener("end", () => { + endedWithEventsCount = s2._eventsCount; + }); + s2.prependListener("close", (hadError) => { + if (response && endedWithEventsCount < s2._eventsCount && !hadError) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + response.body.emit("error", error); + } + }); + }); + } + request_.on("response", (response_) => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + if (isRedirect(response_.statusCode)) { + const location = headers.get("Location"); + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request2.url); + } catch { + if (request2.redirect !== "manual") { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect")); + finalize(); + return; + } + } + switch (request2.redirect) { + case "error": + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request2.url}`, "no-redirect")); + finalize(); + return; + case "manual": + break; + case "follow": { + if (locationURL === null) { + break; + } + if (request2.counter >= request2.follow) { + reject(new FetchError(`maximum redirect reached at: ${request2.url}`, "max-redirect")); + finalize(); + return; + } + const requestOptions = { + headers: new Headers2(request2.headers), + follow: request2.follow, + counter: request2.counter + 1, + agent: request2.agent, + compress: request2.compress, + method: request2.method, + body: clone(request2), + signal: request2.signal, + size: request2.size, + referrer: request2.referrer, + referrerPolicy: request2.referrerPolicy + }; + if (!isDomainOrSubdomain(request2.url, locationURL) || !isSameProtocol(request2.url, locationURL)) { + for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) { + requestOptions.headers.delete(name); + } + } + if (response_.statusCode !== 303 && request2.body && options_.body instanceof Stream2.Readable) { + reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect")); + finalize(); + return; + } + if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request2.method === "POST") { + requestOptions.method = "GET"; + requestOptions.body = undefined; + requestOptions.headers.delete("content-length"); + } + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + resolve(fetch2(new Request(locationURL, requestOptions))); + finalize(); + return; + } + default: + return reject(new TypeError(`Redirect option '${request2.redirect}' is not a valid value of RequestRedirect`)); + } + } + if (signal) { + response_.once("end", () => { + signal.removeEventListener("abort", abortAndFinalize); + }); + } + let body = pump(response_, new PassThrough2, (error) => { + if (error) { + reject(error); + } + }); + if (process.version < "v12.10") { + response_.on("aborted", abortAndFinalize); + } + const responseOptions = { + url: request2.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request2.size, + counter: request2.counter, + highWaterMark: request2.highWaterMark + }; + const codings = headers.get("Content-Encoding"); + if (!request2.compress || request2.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + if (codings === "gzip" || codings === "x-gzip") { + body = pump(body, zlib.createGunzip(zlibOptions), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + if (codings === "deflate" || codings === "x-deflate") { + const raw = pump(response_, new PassThrough2, (error) => { + if (error) { + reject(error); + } + }); + raw.once("data", (chunk) => { + if ((chunk[0] & 15) === 8) { + body = pump(body, zlib.createInflate(), (error) => { + if (error) { + reject(error); + } + }); + } else { + body = pump(body, zlib.createInflateRaw(), (error) => { + if (error) { + reject(error); + } + }); + } + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once("end", () => { + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + if (codings === "br") { + body = pump(body, zlib.createBrotliDecompress(), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + response = new Response(body, responseOptions); + resolve(response); + }); + writeToStream(request_, request2).catch(reject); + }); +} +function fixResponseChunkedTransferBadEnding(request2, errorCallback) { + const LAST_CHUNK = Buffer3.from(`0\r +\r +`); + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + request2.on("response", (response) => { + const { headers } = response; + isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"]; + }); + request2.on("socket", (socket) => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + errorCallback(error); + } + }; + const onData = (buf) => { + properLastChunkReceived = Buffer3.compare(buf.slice(-5), LAST_CHUNK) === 0; + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = Buffer3.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && Buffer3.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0; + } + previousChunk = buf; + }; + socket.prependListener("close", onSocketClose); + socket.on("data", onData); + request2.on("close", () => { + socket.removeListener("close", onSocketClose); + socket.removeListener("data", onData); + }); + }); +} +var supportedSchemas; +var init_src = __esm(() => { + init_dist(); + init_body(); + init_response(); + init_headers(); + init_request2(); + init_fetch_error(); + init_abort_error(); + init_is_redirect(); + init_esm_min(); + init_is(); + init_referrer(); + init_from(); + supportedSchemas = new Set(["data:", "http:", "https:"]); +}); + +// src/common/graphql/client.ts +class CustomSetter { + set(carrier, key, value) { + carrier.set(key, value); + } +} +function createGQLClient(port, token) { + const client = new GraphQLClient(`http://127.0.0.1:${port}/query`, { + fetch: createFetchWithTimeout(1000 * 60 * 60 * 24 * 7), + headers: { + Authorization: "Basic " + Buffer.from(token + ":").toString("base64") + }, + requestMiddleware: async (req) => { + opentelemetry3.propagation.inject(opentelemetry3.context.active(), req.headers, new CustomSetter); + return req; + } + }); + return client; +} +var opentelemetry3, createFetchWithTimeout = (timeout) => async (input, init) => { + if (init?.signal) { + throw new Error("Internal error: could not create fetch client with timeout"); + } + const controller = new AbortController; + const timerId = setTimeout(() => { + controller.abort(); + }, timeout); + try { + if (isBun()) { + return await fetch(input, { + ...init, + signal: controller.signal, + timeout: false + }); + } + if (isDeno()) { + return await fetch(input, { + ...init, + signal: controller.signal + }); + } + return await fetch2(input, { + ...init, + signal: controller.signal + }); + } finally { + clearTimeout(timerId); + } +}; +var init_client = __esm(() => { + init_main(); + init_src(); + init_utils(); + opentelemetry3 = __toESM(require_src(), 1); +}); + +// node_modules/adm-zip/util/constants.js +var require_constants4 = __commonJS((exports, module) => { + module.exports = { + LOCHDR: 30, + LOCSIG: 67324752, + LOCVER: 4, + LOCFLG: 6, + LOCHOW: 8, + LOCTIM: 10, + LOCCRC: 14, + LOCSIZ: 18, + LOCLEN: 22, + LOCNAM: 26, + LOCEXT: 28, + EXTSIG: 134695760, + EXTHDR: 16, + EXTCRC: 4, + EXTSIZ: 8, + EXTLEN: 12, + CENHDR: 46, + CENSIG: 33639248, + CENVEM: 4, + CENVER: 6, + CENFLG: 8, + CENHOW: 10, + CENTIM: 12, + CENCRC: 16, + CENSIZ: 20, + CENLEN: 24, + CENNAM: 28, + CENEXT: 30, + CENCOM: 32, + CENDSK: 34, + CENATT: 36, + CENATX: 38, + CENOFF: 42, + ENDHDR: 22, + ENDSIG: 101010256, + ENDSUB: 8, + ENDTOT: 10, + ENDSIZ: 12, + ENDOFF: 16, + ENDCOM: 20, + END64HDR: 20, + END64SIG: 117853008, + END64START: 4, + END64OFF: 8, + END64NUMDISKS: 16, + ZIP64SIG: 101075792, + ZIP64HDR: 56, + ZIP64LEAD: 12, + ZIP64SIZE: 4, + ZIP64VEM: 12, + ZIP64VER: 14, + ZIP64DSK: 16, + ZIP64DSKDIR: 20, + ZIP64SUB: 24, + ZIP64TOT: 32, + ZIP64SIZB: 40, + ZIP64OFF: 48, + ZIP64EXTRA: 56, + STORED: 0, + SHRUNK: 1, + REDUCED1: 2, + REDUCED2: 3, + REDUCED3: 4, + REDUCED4: 5, + IMPLODED: 6, + DEFLATED: 8, + ENHANCED_DEFLATED: 9, + PKWARE: 10, + BZIP2: 12, + LZMA: 14, + IBM_TERSE: 18, + IBM_LZ77: 19, + AES_ENCRYPT: 99, + FLG_ENC: 1, + FLG_COMP1: 2, + FLG_COMP2: 4, + FLG_DESC: 8, + FLG_ENH: 16, + FLG_PATCH: 32, + FLG_STR: 64, + FLG_EFS: 2048, + FLG_MSK: 4096, + FILE: 2, + BUFFER: 1, + NONE: 0, + EF_ID: 0, + EF_SIZE: 2, + ID_ZIP64: 1, + ID_AVINFO: 7, + ID_PFS: 8, + ID_OS2: 9, + ID_NTFS: 10, + ID_OPENVMS: 12, + ID_UNIX: 13, + ID_FORK: 14, + ID_PATCH: 15, + ID_X509_PKCS7: 20, + ID_X509_CERTID_F: 21, + ID_X509_CERTID_C: 22, + ID_STRONGENC: 23, + ID_RECORD_MGT: 24, + ID_X509_PKCS7_RL: 25, + ID_IBM1: 101, + ID_IBM2: 102, + ID_POSZIP: 18064, + EF_ZIP64_OR_32: 4294967295, + EF_ZIP64_OR_16: 65535, + EF_ZIP64_SUNCOMP: 0, + EF_ZIP64_SCOMP: 8, + EF_ZIP64_RHO: 16, + EF_ZIP64_DSN: 24 + }; +}); + +// node_modules/adm-zip/util/errors.js +var require_errors2 = __commonJS((exports) => { + var errors = { + INVALID_LOC: "Invalid LOC header (bad signature)", + INVALID_CEN: "Invalid CEN header (bad signature)", + INVALID_END: "Invalid END header (bad signature)", + DESCRIPTOR_NOT_EXIST: "No descriptor present", + DESCRIPTOR_UNKNOWN: "Unknown descriptor format", + DESCRIPTOR_FAULTY: "Descriptor data is malformed", + NO_DATA: "Nothing to decompress", + BAD_CRC: "CRC32 checksum failed {0}", + FILE_IN_THE_WAY: "There is a file in the way: {0}", + UNKNOWN_METHOD: "Invalid/unsupported compression method", + AVAIL_DATA: "inflate::Available inflate data did not terminate", + INVALID_DISTANCE: "inflate::Invalid literal/length or distance code in fixed or dynamic block", + TO_MANY_CODES: "inflate::Dynamic block code description: too many length or distance codes", + INVALID_REPEAT_LEN: "inflate::Dynamic block code description: repeat more than specified lengths", + INVALID_REPEAT_FIRST: "inflate::Dynamic block code description: repeat lengths with no first length", + INCOMPLETE_CODES: "inflate::Dynamic block code description: code lengths codes incomplete", + INVALID_DYN_DISTANCE: "inflate::Dynamic block code description: invalid distance code lengths", + INVALID_CODES_LEN: "inflate::Dynamic block code description: invalid literal/length code lengths", + INVALID_STORE_BLOCK: "inflate::Stored block length did not match one's complement", + INVALID_BLOCK_TYPE: "inflate::Invalid block type (type == 3)", + CANT_EXTRACT_FILE: "Could not extract the file", + CANT_OVERRIDE: "Target file already exists", + DISK_ENTRY_TOO_LARGE: "Number of disk entries is too large", + NO_ZIP: "No zip file was loaded", + NO_ENTRY: "Entry doesn't exist", + DIRECTORY_CONTENT_ERROR: "A directory cannot have content", + FILE_NOT_FOUND: 'File not found: "{0}"', + NOT_IMPLEMENTED: "Not implemented", + INVALID_FILENAME: "Invalid filename", + INVALID_FORMAT: "Invalid or unsupported zip format. No END header found", + INVALID_PASS_PARAM: "Incompatible password parameter", + WRONG_PASSWORD: "Wrong Password", + COMMENT_TOO_LONG: "Comment is too long", + EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error" + }; + function E(message) { + return function(...args) { + if (args.length) { + message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || ""); + } + return new Error("ADM-ZIP: " + message); + }; + } + for (const msg of Object.keys(errors)) { + exports[msg] = E(errors[msg]); + } +}); + +// node_modules/adm-zip/util/utils.js +var require_utils15 = __commonJS((exports, module) => { + var fsystem = __require("fs"); + var pth = __require("path"); + var Constants = require_constants4(); + var Errors = require_errors2(); + var isWin = typeof process === "object" && process.platform === "win32"; + var is_Obj = (obj) => typeof obj === "object" && obj !== null; + var crcTable = new Uint32Array(256).map((t2, c) => { + for (let k = 0;k < 8; k++) { + if ((c & 1) !== 0) { + c = 3988292384 ^ c >>> 1; + } else { + c >>>= 1; + } + } + return c >>> 0; + }); + function Utils(opts) { + this.sep = pth.sep; + this.fs = fsystem; + if (is_Obj(opts)) { + if (is_Obj(opts.fs) && typeof opts.fs.statSync === "function") { + this.fs = opts.fs; + } + } + } + module.exports = Utils; + Utils.prototype.makeDir = function(folder) { + const self2 = this; + function mkdirSync(fpath) { + let resolvedPath = fpath.split(self2.sep)[0]; + fpath.split(self2.sep).forEach(function(name) { + if (!name || name.substr(-1, 1) === ":") + return; + resolvedPath += self2.sep + name; + var stat2; + try { + stat2 = self2.fs.statSync(resolvedPath); + } catch (e2) { + if (e2.message && e2.message.startsWith("ENOENT")) { + self2.fs.mkdirSync(resolvedPath); + } else { + throw e2; + } + } + if (stat2 && stat2.isFile()) + throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`); + }); + } + mkdirSync(folder); + }; + Utils.prototype.writeFileTo = function(path, content, overwrite, attr) { + const self2 = this; + if (self2.fs.existsSync(path)) { + if (!overwrite) + return false; + var stat2 = self2.fs.statSync(path); + if (stat2.isDirectory()) { + return false; + } + } + var folder = pth.dirname(path); + if (!self2.fs.existsSync(folder)) { + self2.makeDir(folder); + } + var fd; + try { + fd = self2.fs.openSync(path, "w", 438); + } catch (e2) { + self2.fs.chmodSync(path, 438); + fd = self2.fs.openSync(path, "w", 438); + } + if (fd) { + try { + self2.fs.writeSync(fd, content, 0, content.length, 0); + } finally { + self2.fs.closeSync(fd); + } + } + self2.fs.chmodSync(path, attr || 438); + return true; + }; + Utils.prototype.writeFileToAsync = function(path, content, overwrite, attr, callback) { + if (typeof attr === "function") { + callback = attr; + attr = undefined; + } + const self2 = this; + self2.fs.exists(path, function(exist) { + if (exist && !overwrite) + return callback(false); + self2.fs.stat(path, function(err, stat2) { + if (exist && stat2.isDirectory()) { + return callback(false); + } + var folder = pth.dirname(path); + self2.fs.exists(folder, function(exists) { + if (!exists) + self2.makeDir(folder); + self2.fs.open(path, "w", 438, function(err2, fd) { + if (err2) { + self2.fs.chmod(path, 438, function() { + self2.fs.open(path, "w", 438, function(err3, fd2) { + self2.fs.write(fd2, content, 0, content.length, 0, function() { + self2.fs.close(fd2, function() { + self2.fs.chmod(path, attr || 438, function() { + callback(true); + }); + }); + }); + }); + }); + } else if (fd) { + self2.fs.write(fd, content, 0, content.length, 0, function() { + self2.fs.close(fd, function() { + self2.fs.chmod(path, attr || 438, function() { + callback(true); + }); + }); + }); + } else { + self2.fs.chmod(path, attr || 438, function() { + callback(true); + }); + } + }); + }); + }); + }); + }; + Utils.prototype.findFiles = function(path) { + const self2 = this; + function findSync(dir, pattern, recursive) { + if (typeof pattern === "boolean") { + recursive = pattern; + pattern = undefined; + } + let files2 = []; + self2.fs.readdirSync(dir).forEach(function(file) { + const path2 = pth.join(dir, file); + const stat2 = self2.fs.statSync(path2); + if (!pattern || pattern.test(path2)) { + files2.push(pth.normalize(path2) + (stat2.isDirectory() ? self2.sep : "")); + } + if (stat2.isDirectory() && recursive) + files2 = files2.concat(findSync(path2, pattern, recursive)); + }); + return files2; + } + return findSync(path, undefined, true); + }; + Utils.prototype.findFilesAsync = function(dir, cb) { + const self2 = this; + let results = []; + self2.fs.readdir(dir, function(err, list) { + if (err) + return cb(err); + let list_length = list.length; + if (!list_length) + return cb(null, results); + list.forEach(function(file) { + file = pth.join(dir, file); + self2.fs.stat(file, function(err2, stat2) { + if (err2) + return cb(err2); + if (stat2) { + results.push(pth.normalize(file) + (stat2.isDirectory() ? self2.sep : "")); + if (stat2.isDirectory()) { + self2.findFilesAsync(file, function(err3, res) { + if (err3) + return cb(err3); + results = results.concat(res); + if (!--list_length) + cb(null, results); + }); + } else { + if (!--list_length) + cb(null, results); + } + } + }); + }); + }); + }; + Utils.prototype.getAttributes = function() {}; + Utils.prototype.setAttributes = function() {}; + Utils.crc32update = function(crc, byte) { + return crcTable[(crc ^ byte) & 255] ^ crc >>> 8; + }; + Utils.crc32 = function(buf) { + if (typeof buf === "string") { + buf = Buffer.from(buf, "utf8"); + } + let len = buf.length; + let crc = ~0; + for (let off = 0;off < len; ) + crc = Utils.crc32update(crc, buf[off++]); + return ~crc >>> 0; + }; + Utils.methodToString = function(method) { + switch (method) { + case Constants.STORED: + return "STORED (" + method + ")"; + case Constants.DEFLATED: + return "DEFLATED (" + method + ")"; + default: + return "UNSUPPORTED (" + method + ")"; + } + }; + Utils.canonical = function(path) { + if (!path) + return ""; + const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); + return pth.join(".", safeSuffix); + }; + Utils.zipnamefix = function(path) { + if (!path) + return ""; + const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); + return pth.posix.join(".", safeSuffix); + }; + Utils.findLast = function(arr, callback) { + if (!Array.isArray(arr)) + throw new TypeError("arr is not array"); + const len = arr.length >>> 0; + for (let i2 = len - 1;i2 >= 0; i2--) { + if (callback(arr[i2], i2, arr)) { + return arr[i2]; + } + } + return; + }; + Utils.sanitize = function(prefix, name) { + prefix = pth.resolve(pth.normalize(prefix)); + var parts = name.split("/"); + for (var i2 = 0, l = parts.length;i2 < l; i2++) { + var path = pth.normalize(pth.join(prefix, parts.slice(i2, l).join(pth.sep))); + if (path === prefix || path.startsWith(prefix + pth.sep)) { + return path; + } + } + return pth.normalize(pth.join(prefix, pth.basename(name))); + }; + Utils.toBuffer = function toBuffer(input, encoder) { + if (Buffer.isBuffer(input)) { + return input; + } else if (input instanceof Uint8Array) { + return Buffer.from(input); + } else { + return typeof input === "string" ? encoder(input) : Buffer.alloc(0); + } + }; + Utils.readBigUInt64LE = function(buffer, index) { + const lo = buffer.readUInt32LE(index); + const hi = buffer.readUInt32LE(index + 4); + return hi * 4294967296 + lo; + }; + Utils.writeBigUInt64LE = function(buffer, value, index) { + const lo = value >>> 0; + const hi = Math.floor(value / 4294967296) >>> 0; + buffer.writeUInt32LE(lo, index); + buffer.writeUInt32LE(hi, index + 4); + }; + Utils.fromDOS2Date = function(val) { + return new Date((val >> 25 & 127) + 1980, Math.max((val >> 21 & 15) - 1, 0), Math.max(val >> 16 & 31, 1), val >> 11 & 31, val >> 5 & 63, (val & 31) << 1); + }; + Utils.fromDate2DOS = function(val) { + let date = 0; + let time = 0; + if (val.getFullYear() > 1979) { + date = (val.getFullYear() - 1980 & 127) << 9 | val.getMonth() + 1 << 5 | val.getDate(); + time = val.getHours() << 11 | val.getMinutes() << 5 | val.getSeconds() >> 1; + } + return date << 16 | time; + }; + Utils.isWin = isWin; + Utils.crcTable = crcTable; +}); + +// node_modules/adm-zip/util/fattr.js +var require_fattr = __commonJS((exports, module) => { + var pth = __require("path"); + module.exports = function(path, { fs: fs2 }) { + var _path = path || "", _obj = newAttr(), _stat = null; + function newAttr() { + return { + directory: false, + readonly: false, + hidden: false, + executable: false, + mtime: 0, + atime: 0 + }; + } + if (_path && fs2.existsSync(_path)) { + _stat = fs2.statSync(_path); + _obj.directory = _stat.isDirectory(); + _obj.mtime = _stat.mtime; + _obj.atime = _stat.atime; + _obj.executable = (73 & _stat.mode) !== 0; + _obj.readonly = (128 & _stat.mode) === 0; + _obj.hidden = pth.basename(_path)[0] === "."; + } else { + console.warn("Invalid path: " + _path); + } + return { + get directory() { + return _obj.directory; + }, + get readOnly() { + return _obj.readonly; + }, + get hidden() { + return _obj.hidden; + }, + get mtime() { + return _obj.mtime; + }, + get atime() { + return _obj.atime; + }, + get executable() { + return _obj.executable; + }, + decodeAttributes: function() {}, + encodeAttributes: function() {}, + toJSON: function() { + return { + path: _path, + isDirectory: _obj.directory, + isReadOnly: _obj.readonly, + isHidden: _obj.hidden, + isExecutable: _obj.executable, + mTime: _obj.mtime, + aTime: _obj.atime + }; + }, + toString: function() { + return JSON.stringify(this.toJSON(), null, "\t"); + } + }; + }; +}); + +// node_modules/adm-zip/util/decoder.js +var require_decoder2 = __commonJS((exports, module) => { + module.exports = { + efs: true, + encode: (data) => Buffer.from(data, "utf8"), + decode: (data) => data.toString("utf8") + }; +}); + +// node_modules/adm-zip/util/index.js +var require_util6 = __commonJS((exports, module) => { + module.exports = require_utils15(); + module.exports.Constants = require_constants4(); + module.exports.Errors = require_errors2(); + module.exports.FileAttr = require_fattr(); + module.exports.decoder = require_decoder2(); +}); + +// node_modules/adm-zip/headers/entryHeader.js +var require_entryHeader = __commonJS((exports, module) => { + var Utils = require_util6(); + var Constants = Utils.Constants; + module.exports = function() { + var _verMade = 20, _version = 10, _flags = 0, _method = 0, _time = 0, _crc = 0, _compressedSize = 0, _size = 0, _fnameLen = 0, _extraLen = 0, _comLen = 0, _diskStart = 0, _inattr = 0, _attr = 0, _offset = 0; + _verMade |= Utils.isWin ? 2560 : 768; + _flags |= Constants.FLG_EFS; + const _localHeader = { + extraLen: 0 + }; + const uint32 = (val) => Math.max(0, val) >>> 0; + const uint16 = (val) => Math.max(0, val) & 65535; + const uint8 = (val) => Math.max(0, val) & 255; + _time = Utils.fromDate2DOS(new Date); + return { + get made() { + return _verMade; + }, + set made(val) { + _verMade = val; + }, + get version() { + return _version; + }, + set version(val) { + _version = val; + }, + get flags() { + return _flags; + }, + set flags(val) { + _flags = val; + }, + get flags_efs() { + return (_flags & Constants.FLG_EFS) > 0; + }, + set flags_efs(val) { + if (val) { + _flags |= Constants.FLG_EFS; + } else { + _flags &= ~Constants.FLG_EFS; + } + }, + get flags_desc() { + return (_flags & Constants.FLG_DESC) > 0; + }, + set flags_desc(val) { + if (val) { + _flags |= Constants.FLG_DESC; + } else { + _flags &= ~Constants.FLG_DESC; + } + }, + get method() { + return _method; + }, + set method(val) { + switch (val) { + case Constants.STORED: + this.version = 10; + break; + case Constants.DEFLATED: + default: + this.version = 20; + } + _method = val; + }, + get time() { + return Utils.fromDOS2Date(this.timeval); + }, + set time(val) { + val = new Date(val); + this.timeval = Utils.fromDate2DOS(val); + }, + get timeval() { + return _time; + }, + set timeval(val) { + _time = uint32(val); + }, + get timeHighByte() { + return uint8(_time >>> 8); + }, + get crc() { + return _crc; + }, + set crc(val) { + _crc = uint32(val); + }, + get compressedSize() { + return _compressedSize; + }, + set compressedSize(val) { + _compressedSize = uint32(val); + }, + get size() { + return _size; + }, + set size(val) { + _size = uint32(val); + }, + get fileNameLength() { + return _fnameLen; + }, + set fileNameLength(val) { + _fnameLen = val; + }, + get extraLength() { + return _extraLen; + }, + set extraLength(val) { + _extraLen = val; + }, + get extraLocalLength() { + return _localHeader.extraLen; + }, + set extraLocalLength(val) { + _localHeader.extraLen = val; + }, + get commentLength() { + return _comLen; + }, + set commentLength(val) { + _comLen = val; + }, + get diskNumStart() { + return _diskStart; + }, + set diskNumStart(val) { + _diskStart = uint32(val); + }, + get inAttr() { + return _inattr; + }, + set inAttr(val) { + _inattr = uint32(val); + }, + get attr() { + return _attr; + }, + set attr(val) { + _attr = uint32(val); + }, + get fileAttr() { + return (_attr || 0) >> 16 & 4095; + }, + get offset() { + return _offset; + }, + set offset(val) { + _offset = uint32(val); + }, + get encrypted() { + return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC; + }, + get centralHeaderSize() { + return Constants.CENHDR + _fnameLen + _extraLen + _comLen; + }, + get realDataOffset() { + return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen; + }, + get localHeader() { + return _localHeader; + }, + loadLocalHeaderFromBinary: function(input) { + var data = input.slice(_offset, _offset + Constants.LOCHDR); + if (data.readUInt32LE(0) !== Constants.LOCSIG) { + throw Utils.Errors.INVALID_LOC(); + } + _localHeader.version = data.readUInt16LE(Constants.LOCVER); + _localHeader.flags = data.readUInt16LE(Constants.LOCFLG); + _localHeader.flags_desc = (_localHeader.flags & Constants.FLG_DESC) > 0; + _localHeader.method = data.readUInt16LE(Constants.LOCHOW); + _localHeader.time = data.readUInt32LE(Constants.LOCTIM); + _localHeader.crc = data.readUInt32LE(Constants.LOCCRC); + _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ); + _localHeader.size = data.readUInt32LE(Constants.LOCLEN); + _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM); + _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT); + const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen; + const extraEnd = extraStart + _localHeader.extraLen; + return input.slice(extraStart, extraEnd); + }, + loadFromBinary: function(data) { + if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { + throw Utils.Errors.INVALID_CEN(); + } + _verMade = data.readUInt16LE(Constants.CENVEM); + _version = data.readUInt16LE(Constants.CENVER); + _flags = data.readUInt16LE(Constants.CENFLG); + _method = data.readUInt16LE(Constants.CENHOW); + _time = data.readUInt32LE(Constants.CENTIM); + _crc = data.readUInt32LE(Constants.CENCRC); + _compressedSize = data.readUInt32LE(Constants.CENSIZ); + _size = data.readUInt32LE(Constants.CENLEN); + _fnameLen = data.readUInt16LE(Constants.CENNAM); + _extraLen = data.readUInt16LE(Constants.CENEXT); + _comLen = data.readUInt16LE(Constants.CENCOM); + _diskStart = data.readUInt16LE(Constants.CENDSK); + _inattr = data.readUInt16LE(Constants.CENATT); + _attr = data.readUInt32LE(Constants.CENATX); + _offset = data.readUInt32LE(Constants.CENOFF); + }, + localHeaderToBinary: function() { + var data = Buffer.alloc(Constants.LOCHDR); + data.writeUInt32LE(Constants.LOCSIG, 0); + data.writeUInt16LE(_version, Constants.LOCVER); + data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.LOCFLG); + data.writeUInt16LE(_method, Constants.LOCHOW); + data.writeUInt32LE(_time, Constants.LOCTIM); + data.writeUInt32LE(_crc, Constants.LOCCRC); + data.writeUInt32LE(_compressedSize, Constants.LOCSIZ); + data.writeUInt32LE(_size, Constants.LOCLEN); + data.writeUInt16LE(_fnameLen, Constants.LOCNAM); + data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT); + return data; + }, + centralHeaderToBinary: function() { + var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen); + data.writeUInt32LE(Constants.CENSIG, 0); + data.writeUInt16LE(_verMade, Constants.CENVEM); + data.writeUInt16LE(_version, Constants.CENVER); + data.writeUInt16LE(_flags & ~Constants.FLG_DESC, Constants.CENFLG); + data.writeUInt16LE(_method, Constants.CENHOW); + data.writeUInt32LE(_time, Constants.CENTIM); + data.writeUInt32LE(_crc, Constants.CENCRC); + data.writeUInt32LE(_compressedSize, Constants.CENSIZ); + data.writeUInt32LE(_size, Constants.CENLEN); + data.writeUInt16LE(_fnameLen, Constants.CENNAM); + data.writeUInt16LE(_extraLen, Constants.CENEXT); + data.writeUInt16LE(_comLen, Constants.CENCOM); + data.writeUInt16LE(_diskStart, Constants.CENDSK); + data.writeUInt16LE(_inattr, Constants.CENATT); + data.writeUInt32LE(_attr, Constants.CENATX); + data.writeUInt32LE(_offset, Constants.CENOFF); + return data; + }, + toJSON: function() { + const bytes = function(nr) { + return nr + " bytes"; + }; + return { + made: _verMade, + version: _version, + flags: _flags, + method: Utils.methodToString(_method), + time: this.time, + crc: "0x" + _crc.toString(16).toUpperCase(), + compressedSize: bytes(_compressedSize), + size: bytes(_size), + fileNameLength: bytes(_fnameLen), + extraLength: bytes(_extraLen), + commentLength: bytes(_comLen), + diskNumStart: _diskStart, + inAttr: _inattr, + attr: _attr, + offset: _offset, + centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen) + }; + }, + toString: function() { + return JSON.stringify(this.toJSON(), null, "\t"); + } + }; + }; +}); + +// node_modules/adm-zip/headers/mainHeader.js +var require_mainHeader = __commonJS((exports, module) => { + var Utils = require_util6(); + var Constants = Utils.Constants; + module.exports = function() { + var _volumeEntries = 0, _totalEntries = 0, _size = 0, _offset = 0, _commentLength = 0; + const needsZip64 = () => _volumeEntries > Constants.EF_ZIP64_OR_16 || _totalEntries > Constants.EF_ZIP64_OR_16 || _size > Constants.EF_ZIP64_OR_32 || _offset > Constants.EF_ZIP64_OR_32; + return { + get diskEntries() { + return _volumeEntries; + }, + set diskEntries(val) { + _volumeEntries = _totalEntries = val; + }, + get totalEntries() { + return _totalEntries; + }, + set totalEntries(val) { + _totalEntries = _volumeEntries = val; + }, + get size() { + return _size; + }, + set size(val) { + _size = val; + }, + get offset() { + return _offset; + }, + set offset(val) { + _offset = val; + }, + get commentLength() { + return _commentLength; + }, + set commentLength(val) { + _commentLength = val; + }, + get mainHeaderSize() { + return (needsZip64() ? Constants.ZIP64HDR + Constants.END64HDR : 0) + Constants.ENDHDR + _commentLength; + }, + loadFromBinary: function(data) { + if ((data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)) { + throw Utils.Errors.INVALID_END(); + } + if (data.readUInt32LE(0) === Constants.ENDSIG) { + _volumeEntries = data.readUInt16LE(Constants.ENDSUB); + _totalEntries = data.readUInt16LE(Constants.ENDTOT); + _size = data.readUInt32LE(Constants.ENDSIZ); + _offset = data.readUInt32LE(Constants.ENDOFF); + _commentLength = data.readUInt16LE(Constants.ENDCOM); + } else { + _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB); + _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT); + _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZB); + _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF); + _commentLength = 0; + } + }, + toBinary: function() { + if (!needsZip64()) { + var b = Buffer.alloc(Constants.ENDHDR + _commentLength); + b.writeUInt32LE(Constants.ENDSIG, 0); + b.writeUInt32LE(0, 4); + b.writeUInt16LE(_volumeEntries, Constants.ENDSUB); + b.writeUInt16LE(_totalEntries, Constants.ENDTOT); + b.writeUInt32LE(_size, Constants.ENDSIZ); + b.writeUInt32LE(_offset, Constants.ENDOFF); + b.writeUInt16LE(_commentLength, Constants.ENDCOM); + b.fill(" ", Constants.ENDHDR); + return b; + } + var b = Buffer.alloc(this.mainHeaderSize); + let offset = 0; + b.writeUInt32LE(Constants.ZIP64SIG, offset); + Utils.writeBigUInt64LE(b, Constants.ZIP64HDR - Constants.ZIP64LEAD, offset + Constants.ZIP64SIZE); + b.writeUInt16LE(45, offset + Constants.ZIP64VEM); + b.writeUInt16LE(45, offset + Constants.ZIP64VER); + b.writeUInt32LE(0, offset + Constants.ZIP64DSK); + b.writeUInt32LE(0, offset + Constants.ZIP64DSKDIR); + Utils.writeBigUInt64LE(b, _volumeEntries, offset + Constants.ZIP64SUB); + Utils.writeBigUInt64LE(b, _totalEntries, offset + Constants.ZIP64TOT); + Utils.writeBigUInt64LE(b, _size, offset + Constants.ZIP64SIZB); + Utils.writeBigUInt64LE(b, _offset, offset + Constants.ZIP64OFF); + const zip64EndOffset = _offset + _size; + offset += Constants.ZIP64HDR; + b.writeUInt32LE(Constants.END64SIG, offset); + b.writeUInt32LE(0, offset + Constants.END64START); + Utils.writeBigUInt64LE(b, zip64EndOffset, offset + Constants.END64OFF); + b.writeUInt32LE(1, offset + Constants.END64NUMDISKS); + offset += Constants.END64HDR; + b.writeUInt32LE(Constants.ENDSIG, offset); + b.writeUInt32LE(0, offset + 4); + b.writeUInt16LE(Math.min(_volumeEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDSUB); + b.writeUInt16LE(Math.min(_totalEntries, Constants.EF_ZIP64_OR_16), offset + Constants.ENDTOT); + b.writeUInt32LE(Math.min(_size, Constants.EF_ZIP64_OR_32), offset + Constants.ENDSIZ); + b.writeUInt32LE(Math.min(_offset, Constants.EF_ZIP64_OR_32), offset + Constants.ENDOFF); + b.writeUInt16LE(_commentLength, offset + Constants.ENDCOM); + b.fill(" ", offset + Constants.ENDHDR); + return b; + }, + toJSON: function() { + const offset = function(nr, len) { + let offs = nr.toString(16).toUpperCase(); + while (offs.length < len) + offs = "0" + offs; + return "0x" + offs; + }; + return { + diskEntries: _volumeEntries, + totalEntries: _totalEntries, + size: _size + " bytes", + offset: offset(_offset, 4), + commentLength: _commentLength + }; + }, + toString: function() { + return JSON.stringify(this.toJSON(), null, "\t"); + } + }; + }; +}); + +// node_modules/adm-zip/headers/index.js +var require_headers = __commonJS((exports) => { + exports.EntryHeader = require_entryHeader(); + exports.MainHeader = require_mainHeader(); +}); + +// node_modules/adm-zip/methods/deflater.js +var require_deflater = __commonJS((exports, module) => { + module.exports = function(inbuf) { + var zlib2 = __require("zlib"); + var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 }; + return { + deflate: function() { + return zlib2.deflateRawSync(inbuf, opts); + }, + deflateAsync: function(callback) { + var tmp = zlib2.createDeflateRaw(opts), parts = [], total = 0; + tmp.on("data", function(data) { + parts.push(data); + total += data.length; + }); + tmp.on("end", function() { + var buf = Buffer.alloc(total), written = 0; + buf.fill(0); + for (var i2 = 0;i2 < parts.length; i2++) { + var part = parts[i2]; + part.copy(buf, written); + written += part.length; + } + callback && callback(buf); + }); + tmp.end(inbuf); + } + }; + }; +}); + +// node_modules/adm-zip/methods/inflater.js +var require_inflater = __commonJS((exports, module) => { + var version = +(process?.versions?.node ?? "").split(".")[0] || 0; + module.exports = function(inbuf, expectedLength) { + var zlib2 = __require("zlib"); + const option = version >= 15 && expectedLength > 0 ? { maxOutputLength: expectedLength } : {}; + return { + inflate: function() { + return zlib2.inflateRawSync(inbuf, option); + }, + inflateAsync: function(callback) { + var tmp = zlib2.createInflateRaw(option), parts = [], total = 0; + tmp.on("data", function(data) { + parts.push(data); + total += data.length; + }); + tmp.on("end", function() { + var buf = Buffer.alloc(total), written = 0; + buf.fill(0); + for (var i2 = 0;i2 < parts.length; i2++) { + var part = parts[i2]; + part.copy(buf, written); + written += part.length; + } + callback && callback(buf); + }); + tmp.end(inbuf); + } + }; + }; +}); + +// node_modules/adm-zip/methods/zipcrypto.js +var require_zipcrypto = __commonJS((exports, module) => { + var { randomFillSync } = __require("crypto"); + var Errors = require_errors2(); + var crctable = new Uint32Array(256).map((t2, crc) => { + for (let j = 0;j < 8; j++) { + if ((crc & 1) !== 0) { + crc = crc >>> 1 ^ 3988292384; + } else { + crc >>>= 1; + } + } + return crc >>> 0; + }); + var uMul = (a, b) => Math.imul(a, b) >>> 0; + var crc32update = (pCrc32, bval) => { + return crctable[(pCrc32 ^ bval) & 255] ^ pCrc32 >>> 8; + }; + var genSalt = () => { + if (typeof randomFillSync === "function") { + return randomFillSync(Buffer.alloc(12)); + } else { + return genSalt.node(); + } + }; + genSalt.node = () => { + const salt = Buffer.alloc(12); + const len = salt.length; + for (let i2 = 0;i2 < len; i2++) + salt[i2] = Math.random() * 256 & 255; + return salt; + }; + var config = { + genSalt + }; + function Initkeys(pw) { + const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw); + this.keys = new Uint32Array([305419896, 591751049, 878082192]); + for (let i2 = 0;i2 < pass.length; i2++) { + this.updateKeys(pass[i2]); + } + } + Initkeys.prototype.updateKeys = function(byteValue) { + const keys = this.keys; + keys[0] = crc32update(keys[0], byteValue); + keys[1] += keys[0] & 255; + keys[1] = uMul(keys[1], 134775813) + 1; + keys[2] = crc32update(keys[2], keys[1] >>> 24); + return byteValue; + }; + Initkeys.prototype.next = function() { + const k = (this.keys[2] | 2) >>> 0; + return uMul(k, k ^ 1) >> 8 & 255; + }; + function make_decrypter(pwd) { + const keys = new Initkeys(pwd); + return function(data) { + const result = Buffer.alloc(data.length); + let pos = 0; + for (let c of data) { + result[pos++] = keys.updateKeys(c ^ keys.next()); + } + return result; + }; + } + function make_encrypter(pwd) { + const keys = new Initkeys(pwd); + return function(data, result, pos = 0) { + if (!result) + result = Buffer.alloc(data.length); + for (let c of data) { + const k = keys.next(); + result[pos++] = c ^ k; + keys.updateKeys(c); + } + return result; + }; + } + function decrypt(data, header, pwd) { + if (!data || !Buffer.isBuffer(data) || data.length < 12) { + return Buffer.alloc(0); + } + const decrypter = make_decrypter(pwd); + const salt = decrypter(data.slice(0, 12)); + const verifyByte = (header.flags & 8) === 8 ? header.timeHighByte : header.crc >>> 24; + if (salt[11] !== verifyByte) { + throw Errors.WRONG_PASSWORD(); + } + return decrypter(data.slice(12)); + } + function _salter(data) { + if (Buffer.isBuffer(data) && data.length >= 12) { + config.genSalt = function() { + return data.slice(0, 12); + }; + } else if (data === "node") { + config.genSalt = genSalt.node; + } else { + config.genSalt = genSalt; + } + } + function encrypt(data, header, pwd, oldlike = false) { + if (data == null) + data = Buffer.alloc(0); + if (!Buffer.isBuffer(data)) + data = Buffer.from(data.toString()); + const encrypter = make_encrypter(pwd); + const salt = config.genSalt(); + salt[11] = header.crc >>> 24 & 255; + if (oldlike) + salt[10] = header.crc >>> 16 & 255; + const result = Buffer.alloc(data.length + 12); + encrypter(salt, result); + return encrypter(data, result, 12); + } + module.exports = { decrypt, encrypt, _salter }; +}); + +// node_modules/adm-zip/methods/index.js +var require_methods = __commonJS((exports) => { + exports.Deflater = require_deflater(); + exports.Inflater = require_inflater(); + exports.ZipCrypto = require_zipcrypto(); +}); + +// node_modules/adm-zip/zipEntry.js +var require_zipEntry = __commonJS((exports, module) => { + var Utils = require_util6(); + var Headers3 = require_headers(); + var Constants = Utils.Constants; + var Methods = require_methods(); + module.exports = function(options, input) { + var _centralHeader = new Headers3.EntryHeader, _entryName = Buffer.alloc(0), _comment = Buffer.alloc(0), _isDirectory = false, uncompressedData = null, _extra = Buffer.alloc(0), _extralocal = Buffer.alloc(0), _efs = true; + const opts = options; + const decoder = typeof opts.decoder === "object" ? opts.decoder : Utils.decoder; + _efs = decoder.hasOwnProperty("efs") ? decoder.efs : false; + function getCompressedDataFromZip() { + if (!input || !(input instanceof Uint8Array)) { + return Buffer.alloc(0); + } + _extralocal = _centralHeader.loadLocalHeaderFromBinary(input); + return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize); + } + function crc32OK(data) { + if (!_centralHeader.flags_desc && !_centralHeader.localHeader.flags_desc) { + if (Utils.crc32(data) !== _centralHeader.localHeader.crc) { + return false; + } + } else { + const descriptor = {}; + const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize; + if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) { + throw Utils.Errors.DESCRIPTOR_NOT_EXIST(); + } + if (input.readUInt32LE(dataEndOffset) == Constants.EXTSIG) { + descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC); + descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ); + descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN); + } else if (input.readUInt16LE(dataEndOffset + 12) === 19280) { + descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC - 4); + descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4); + descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4); + } else { + throw Utils.Errors.DESCRIPTOR_UNKNOWN(); + } + if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) { + throw Utils.Errors.DESCRIPTOR_FAULTY(); + } + if (Utils.crc32(data) !== descriptor.crc) { + return false; + } + } + return true; + } + function decompress(async, callback, pass) { + if (typeof callback === "undefined" && typeof async === "string") { + pass = async; + async = undefined; + } + if (_isDirectory) { + if (async && callback) { + callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); + } + return Buffer.alloc(0); + } + var compressedData = getCompressedDataFromZip(); + if (compressedData.length === 0) { + if (async && callback) + callback(compressedData); + return compressedData; + } + if (_centralHeader.encrypted) { + if (typeof pass !== "string" && !Buffer.isBuffer(pass)) { + throw Utils.Errors.INVALID_PASS_PARAM(); + } + compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass); + } + var data = Buffer.alloc(_centralHeader.size); + switch (_centralHeader.method) { + case Utils.Constants.STORED: + compressedData.copy(data); + if (!crc32OK(data)) { + if (async && callback) + callback(data, Utils.Errors.BAD_CRC()); + throw Utils.Errors.BAD_CRC(); + } else { + if (async && callback) + callback(data); + return data; + } + case Utils.Constants.DEFLATED: + var inflater = new Methods.Inflater(compressedData, _centralHeader.size); + if (!async) { + const result = inflater.inflate(data); + result.copy(data, 0); + if (!crc32OK(data)) { + throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`); + } + return data; + } else { + inflater.inflateAsync(function(result) { + result.copy(result, 0); + if (callback) { + if (!crc32OK(result)) { + callback(result, Utils.Errors.BAD_CRC()); + } else { + callback(result); + } + } + }); + } + break; + default: + if (async && callback) + callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD()); + throw Utils.Errors.UNKNOWN_METHOD(); + } + } + function compress(async, callback) { + if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) { + if (async && callback) + callback(getCompressedDataFromZip()); + return getCompressedDataFromZip(); + } + if (uncompressedData.length && !_isDirectory) { + var compressedData; + switch (_centralHeader.method) { + case Utils.Constants.STORED: + _centralHeader.compressedSize = _centralHeader.size; + compressedData = Buffer.alloc(uncompressedData.length); + uncompressedData.copy(compressedData); + if (async && callback) + callback(compressedData); + return compressedData; + default: + case Utils.Constants.DEFLATED: + var deflater = new Methods.Deflater(uncompressedData); + if (!async) { + var deflated = deflater.deflate(); + _centralHeader.compressedSize = deflated.length; + return deflated; + } else { + deflater.deflateAsync(function(data) { + compressedData = Buffer.alloc(data.length); + _centralHeader.compressedSize = data.length; + data.copy(compressedData); + callback && callback(compressedData); + }); + } + deflater = null; + break; + } + } else if (async && callback) { + callback(Buffer.alloc(0)); + } else { + return Buffer.alloc(0); + } + } + function readUInt64LE(buffer, offset) { + return Utils.readBigUInt64LE(buffer, offset); + } + function parseExtra(data) { + try { + var offset = 0; + var signature, size, part; + while (offset + 4 < data.length) { + signature = data.readUInt16LE(offset); + offset += 2; + size = data.readUInt16LE(offset); + offset += 2; + part = data.slice(offset, offset + size); + offset += size; + if (Constants.ID_ZIP64 === signature) { + parseZip64ExtendedInformation(part); + } + } + } catch (error) { + throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR(); + } + } + function parseZip64ExtendedInformation(data) { + var size, compressedSize, offset, diskNumStart; + if (data.length >= Constants.EF_ZIP64_SCOMP) { + size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP); + if (_centralHeader.size === Constants.EF_ZIP64_OR_32) { + _centralHeader.size = size; + } + } + if (data.length >= Constants.EF_ZIP64_RHO) { + compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP); + if (_centralHeader.compressedSize === Constants.EF_ZIP64_OR_32) { + _centralHeader.compressedSize = compressedSize; + } + } + if (data.length >= Constants.EF_ZIP64_DSN) { + offset = readUInt64LE(data, Constants.EF_ZIP64_RHO); + if (_centralHeader.offset === Constants.EF_ZIP64_OR_32) { + _centralHeader.offset = offset; + } + } + if (data.length >= Constants.EF_ZIP64_DSN + 4) { + diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN); + if (_centralHeader.diskNumStart === Constants.EF_ZIP64_OR_16) { + _centralHeader.diskNumStart = diskNumStart; + } + } + } + return { + get entryName() { + return decoder.decode(_entryName); + }, + get rawEntryName() { + return _entryName; + }, + set entryName(val) { + _entryName = Utils.toBuffer(val, decoder.encode); + var lastChar = _entryName[_entryName.length - 1]; + _isDirectory = lastChar === 47 || lastChar === 92; + _centralHeader.fileNameLength = _entryName.length; + }, + get efs() { + if (typeof _efs === "function") { + return _efs(this.entryName); + } else { + return _efs; + } + }, + get extra() { + return _extra; + }, + set extra(val) { + _extra = val; + _centralHeader.extraLength = val.length; + parseExtra(val); + }, + get comment() { + return decoder.decode(_comment); + }, + set comment(val) { + _comment = Utils.toBuffer(val, decoder.encode); + _centralHeader.commentLength = _comment.length; + if (_comment.length > 65535) + throw Utils.Errors.COMMENT_TOO_LONG(); + }, + get name() { + var n = decoder.decode(_entryName); + return _isDirectory ? n.substr(n.length - 1).split("/").pop() : n.split("/").pop(); + }, + get isDirectory() { + return _isDirectory; + }, + getCompressedData: function() { + return compress(false, null); + }, + getCompressedDataAsync: function(callback) { + compress(true, callback); + }, + setData: function(value) { + uncompressedData = Utils.toBuffer(value, Utils.decoder.encode); + if (!_isDirectory && uncompressedData.length) { + _centralHeader.size = uncompressedData.length; + _centralHeader.method = Utils.Constants.DEFLATED; + _centralHeader.crc = Utils.crc32(value); + _centralHeader.changed = true; + } else { + _centralHeader.method = Utils.Constants.STORED; + } + }, + getData: function(pass) { + if (_centralHeader.changed) { + return uncompressedData; + } else { + return decompress(false, null, pass); + } + }, + getDataAsync: function(callback, pass) { + if (_centralHeader.changed) { + callback(uncompressedData); + } else { + decompress(true, callback, pass); + } + }, + set attr(attr) { + _centralHeader.attr = attr; + }, + get attr() { + return _centralHeader.attr; + }, + set header(data) { + _centralHeader.loadFromBinary(data); + }, + get header() { + return _centralHeader; + }, + packCentralHeader: function() { + _centralHeader.flags_efs = this.efs; + _centralHeader.extraLength = _extra.length; + var header = _centralHeader.centralHeaderToBinary(); + var addpos = Utils.Constants.CENHDR; + _entryName.copy(header, addpos); + addpos += _entryName.length; + _extra.copy(header, addpos); + addpos += _centralHeader.extraLength; + _comment.copy(header, addpos); + return header; + }, + packLocalHeader: function() { + let addpos = 0; + _centralHeader.flags_efs = this.efs; + _centralHeader.extraLocalLength = _extralocal.length; + const localHeaderBuf = _centralHeader.localHeaderToBinary(); + const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength); + localHeaderBuf.copy(localHeader, addpos); + addpos += localHeaderBuf.length; + _entryName.copy(localHeader, addpos); + addpos += _entryName.length; + _extralocal.copy(localHeader, addpos); + addpos += _extralocal.length; + return localHeader; + }, + toJSON: function() { + const bytes = function(nr) { + return "<" + (nr && nr.length + " bytes buffer" || "null") + ">"; + }; + return { + entryName: this.entryName, + name: this.name, + comment: this.comment, + isDirectory: this.isDirectory, + header: _centralHeader.toJSON(), + compressedData: bytes(input), + data: bytes(uncompressedData) + }; + }, + toString: function() { + return JSON.stringify(this.toJSON(), null, "\t"); + } + }; + }; +}); + +// node_modules/adm-zip/zipFile.js +var require_zipFile = __commonJS((exports, module) => { + var ZipEntry = require_zipEntry(); + var Headers3 = require_headers(); + var Utils = require_util6(); + module.exports = function(inBuffer, options) { + var entryList = [], entryTable = {}, _comment = Buffer.alloc(0), mainHeader = new Headers3.MainHeader, loadedEntries = false; + var password = null; + const temporary = new Set; + const opts = options; + const { noSort, decoder } = opts; + if (inBuffer) { + readMainHeader(opts.readEntries); + } else { + loadedEntries = true; + } + function makeTemporaryFolders() { + const foldersList = new Set; + for (const elem of Object.keys(entryTable)) { + const elements = elem.split("/"); + elements.pop(); + if (!elements.length) + continue; + for (let i2 = 0;i2 < elements.length; i2++) { + const sub = elements.slice(0, i2 + 1).join("/") + "/"; + foldersList.add(sub); + } + } + for (const elem of foldersList) { + if (!(elem in entryTable)) { + const tempfolder = new ZipEntry(opts); + tempfolder.entryName = elem; + tempfolder.attr = 16; + tempfolder.temporary = true; + entryList.push(tempfolder); + entryTable[tempfolder.entryName] = tempfolder; + temporary.add(tempfolder); + } + } + } + function readEntries() { + loadedEntries = true; + entryTable = {}; + if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) { + throw Utils.Errors.DISK_ENTRY_TOO_LARGE(); + } + entryList = new Array(mainHeader.diskEntries); + var index = mainHeader.offset; + for (var i2 = 0;i2 < entryList.length; i2++) { + var tmp = index, entry = new ZipEntry(opts, inBuffer); + entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR); + entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength); + if (entry.header.extraLength) { + entry.extra = inBuffer.slice(tmp, tmp += entry.header.extraLength); + } + if (entry.header.commentLength) + entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength); + index += entry.header.centralHeaderSize; + entryList[i2] = entry; + entryTable[entry.entryName] = entry; + } + temporary.clear(); + makeTemporaryFolders(); + } + function readMainHeader(readNow) { + var i2 = inBuffer.length - Utils.Constants.ENDHDR, max = Math.max(0, i2 - 65535), n = max, endStart = inBuffer.length, endOffset = -1, commentEnd = 0; + const trailingSpace = typeof opts.trailingSpace === "boolean" ? opts.trailingSpace : false; + if (trailingSpace) + max = 0; + for (i2;i2 >= n; i2--) { + if (inBuffer[i2] !== 80) + continue; + if (inBuffer.readUInt32LE(i2) === Utils.Constants.ENDSIG) { + endOffset = i2; + commentEnd = i2; + endStart = i2 + Utils.Constants.ENDHDR; + n = i2 - Utils.Constants.END64HDR; + continue; + } + if (inBuffer.readUInt32LE(i2) === Utils.Constants.END64SIG) { + n = max; + continue; + } + if (inBuffer.readUInt32LE(i2) === Utils.Constants.ZIP64SIG) { + endOffset = i2; + endStart = i2 + Utils.readBigUInt64LE(inBuffer, i2 + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD; + break; + } + } + if (endOffset == -1) + throw Utils.Errors.INVALID_FORMAT(); + mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart)); + if (mainHeader.commentLength) { + _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR); + } + if (readNow) + readEntries(); + } + function sortEntries() { + if (entryList.length > 1 && !noSort) { + entryList.sort((a, b) => a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase())); + } + } + return { + get entries() { + if (!loadedEntries) { + readEntries(); + } + return entryList.filter((e2) => !temporary.has(e2)); + }, + get comment() { + return decoder.decode(_comment); + }, + set comment(val) { + _comment = Utils.toBuffer(val, decoder.encode); + mainHeader.commentLength = _comment.length; + }, + getEntryCount: function() { + if (!loadedEntries) { + return mainHeader.diskEntries; + } + return entryList.length; + }, + forEach: function(callback) { + this.entries.forEach(callback); + }, + getEntry: function(entryName) { + if (!loadedEntries) { + readEntries(); + } + return entryTable[entryName] || null; + }, + setEntry: function(entry) { + if (!loadedEntries) { + readEntries(); + } + entryList.push(entry); + entryTable[entry.entryName] = entry; + mainHeader.totalEntries = entryList.length; + }, + deleteFile: function(entryName, withsubfolders = true) { + if (!loadedEntries) { + readEntries(); + } + const entry = entryTable[entryName]; + const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName); + list.forEach(this.deleteEntry); + }, + deleteEntry: function(entryName) { + if (!loadedEntries) { + readEntries(); + } + const entry = entryTable[entryName]; + const index = entryList.indexOf(entry); + if (index >= 0) { + entryList.splice(index, 1); + delete entryTable[entryName]; + mainHeader.totalEntries = entryList.length; + } + }, + getEntryChildren: function(entry, subfolders = true) { + if (!loadedEntries) { + readEntries(); + } + if (typeof entry === "object") { + if (entry.isDirectory && subfolders) { + const list = []; + const name = entry.entryName; + for (const zipEntry of entryList) { + if (zipEntry.entryName.startsWith(name)) { + list.push(zipEntry); + } + } + return list; + } else { + return [entry]; + } + } + return []; + }, + getChildCount: function(entry) { + if (entry && entry.isDirectory) { + const list = this.getEntryChildren(entry); + return list.includes(entry) ? list.length - 1 : list.length; + } + return 0; + }, + compressToBuffer: function() { + if (!loadedEntries) { + readEntries(); + } + sortEntries(); + const dataBlock = []; + const headerBlocks = []; + let totalSize = 0; + let dindex = 0; + mainHeader.size = 0; + mainHeader.offset = 0; + let totalEntries = 0; + for (const entry of this.entries) { + const compressedData = entry.getCompressedData(); + entry.header.offset = dindex; + const localHeader = entry.packLocalHeader(); + const dataLength = localHeader.length + compressedData.length; + dindex += dataLength; + dataBlock.push(localHeader); + dataBlock.push(compressedData); + const centralHeader = entry.packCentralHeader(); + headerBlocks.push(centralHeader); + mainHeader.size += centralHeader.length; + totalSize += dataLength + centralHeader.length; + totalEntries++; + } + totalSize += mainHeader.mainHeaderSize; + mainHeader.offset = dindex; + mainHeader.totalEntries = totalEntries; + dindex = 0; + const outBuffer = Buffer.alloc(totalSize); + for (const content of dataBlock) { + content.copy(outBuffer, dindex); + dindex += content.length; + } + for (const content of headerBlocks) { + content.copy(outBuffer, dindex); + dindex += content.length; + } + const mh = mainHeader.toBinary(); + if (_comment) { + _comment.copy(mh, mh.length - _comment.length); + } + mh.copy(outBuffer, dindex); + inBuffer = outBuffer; + loadedEntries = false; + return outBuffer; + }, + toAsyncBuffer: function(onSuccess, onFail, onItemStart, onItemEnd) { + try { + if (!loadedEntries) { + readEntries(); + } + sortEntries(); + const dataBlock = []; + const centralHeaders = []; + let totalSize = 0; + let dindex = 0; + let totalEntries = 0; + mainHeader.size = 0; + mainHeader.offset = 0; + const compress2Buffer = function(entryLists) { + if (entryLists.length > 0) { + const entry = entryLists.shift(); + const name = entry.entryName + entry.extra.toString(); + if (onItemStart) + onItemStart(name); + entry.getCompressedDataAsync(function(compressedData) { + if (onItemEnd) + onItemEnd(name); + entry.header.offset = dindex; + const localHeader = entry.packLocalHeader(); + const dataLength = localHeader.length + compressedData.length; + dindex += dataLength; + dataBlock.push(localHeader); + dataBlock.push(compressedData); + const centalHeader = entry.packCentralHeader(); + centralHeaders.push(centalHeader); + mainHeader.size += centalHeader.length; + totalSize += dataLength + centalHeader.length; + totalEntries++; + compress2Buffer(entryLists); + }); + } else { + totalSize += mainHeader.mainHeaderSize; + mainHeader.offset = dindex; + mainHeader.totalEntries = totalEntries; + dindex = 0; + const outBuffer = Buffer.alloc(totalSize); + dataBlock.forEach(function(content) { + content.copy(outBuffer, dindex); + dindex += content.length; + }); + centralHeaders.forEach(function(content) { + content.copy(outBuffer, dindex); + dindex += content.length; + }); + const mh = mainHeader.toBinary(); + if (_comment) { + _comment.copy(mh, mh.length - _comment.length); + } + mh.copy(outBuffer, dindex); + inBuffer = outBuffer; + loadedEntries = false; + onSuccess(outBuffer); + } + }; + compress2Buffer(Array.from(this.entries)); + } catch (e2) { + onFail(e2); + } + } + }; + }; +}); + +// node_modules/adm-zip/adm-zip.js +var require_adm_zip = __commonJS((exports, module) => { + var Utils = require_util6(); + var pth = __require("path"); + var ZipEntry = require_zipEntry(); + var ZipFile = require_zipFile(); + var get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean"); + var get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string"); + var get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function"); + var defaultOptions = { + noSort: false, + readEntries: false, + method: Utils.Constants.NONE, + fs: null + }; + module.exports = function(input, options) { + let inBuffer = null; + const opts = Object.assign(Object.create(null), defaultOptions); + if (input && typeof input === "object") { + if (!(input instanceof Uint8Array)) { + Object.assign(opts, input); + input = opts.input ? opts.input : undefined; + if (opts.input) + delete opts.input; + } + if (Buffer.isBuffer(input)) { + inBuffer = input; + opts.method = Utils.Constants.BUFFER; + input = undefined; + } + } + Object.assign(opts, options); + const filetools = new Utils(opts); + if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") { + opts.decoder = Utils.decoder; + } + if (input && typeof input === "string") { + if (filetools.fs.existsSync(input)) { + opts.method = Utils.Constants.FILE; + opts.filename = input; + inBuffer = filetools.fs.readFileSync(input); + } else { + throw Utils.Errors.INVALID_FILENAME(); + } + } + const _zip = new ZipFile(inBuffer, opts); + const { canonical, sanitize, zipnamefix } = Utils; + function getEntry(entry) { + if (entry && _zip) { + var item; + if (typeof entry === "string") + item = _zip.getEntry(pth.posix.normalize(entry)); + if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") + item = _zip.getEntry(entry.entryName); + if (item) { + return item; + } + } + return null; + } + function fixPath(zipPath) { + const { join, normalize, sep } = pth.posix; + return join(pth.isAbsolute(zipPath) ? "/" : ".", normalize(sep + zipPath.split("\\").join(sep) + sep)); + } + function filenameFilter(filterfn) { + if (filterfn instanceof RegExp) { + return function(rx) { + return function(filename) { + return rx.test(filename); + }; + }(filterfn); + } else if (typeof filterfn !== "function") { + return () => true; + } + return filterfn; + } + const relativePath = (local, entry) => { + let lastChar = entry.slice(-1); + lastChar = lastChar === filetools.sep ? filetools.sep : ""; + return pth.relative(local, entry) + lastChar; + }; + return { + readFile: function(entry, pass) { + var item = getEntry(entry); + return item && item.getData(pass) || null; + }, + childCount: function(entry) { + const item = getEntry(entry); + if (item) { + return _zip.getChildCount(item); + } + }, + readFileAsync: function(entry, callback) { + var item = getEntry(entry); + if (item) { + item.getDataAsync(callback); + } else { + callback(null, "getEntry failed for:" + entry); + } + }, + readAsText: function(entry, encoding) { + var item = getEntry(entry); + if (item) { + var data = item.getData(); + if (data && data.length) { + return data.toString(encoding || "utf8"); + } + } + return ""; + }, + readAsTextAsync: function(entry, callback, encoding) { + var item = getEntry(entry); + if (item) { + item.getDataAsync(function(data, err) { + if (err) { + callback(data, err); + return; + } + if (data && data.length) { + callback(data.toString(encoding || "utf8")); + } else { + callback(""); + } + }); + } else { + callback(""); + } + }, + deleteFile: function(entry, withsubfolders = true) { + var item = getEntry(entry); + if (item) { + _zip.deleteFile(item.entryName, withsubfolders); + } + }, + deleteEntry: function(entry) { + var item = getEntry(entry); + if (item) { + _zip.deleteEntry(item.entryName); + } + }, + addZipComment: function(comment) { + _zip.comment = comment; + }, + getZipComment: function() { + return _zip.comment || ""; + }, + addZipEntryComment: function(entry, comment) { + var item = getEntry(entry); + if (item) { + item.comment = comment; + } + }, + getZipEntryComment: function(entry) { + var item = getEntry(entry); + if (item) { + return item.comment || ""; + } + return ""; + }, + updateFile: function(entry, content) { + var item = getEntry(entry); + if (item) { + item.setData(content); + } + }, + addLocalFile: function(localPath, zipPath, zipName, comment) { + if (filetools.fs.existsSync(localPath)) { + zipPath = zipPath ? fixPath(zipPath) : ""; + const p = pth.win32.basename(pth.win32.normalize(localPath)); + zipPath += zipName ? zipName : p; + const _attr = filetools.fs.statSync(localPath); + const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0); + if (_attr.isDirectory()) + zipPath += filetools.sep; + this.addFile(zipPath, data, comment, _attr); + } else { + throw Utils.Errors.FILE_NOT_FOUND(localPath); + } + }, + addLocalFileAsync: function(options2, callback) { + options2 = typeof options2 === "object" ? options2 : { localPath: options2 }; + const localPath = pth.resolve(options2.localPath); + const { comment } = options2; + let { zipPath, zipName } = options2; + const self2 = this; + filetools.fs.stat(localPath, function(err, stats) { + if (err) + return callback(err, false); + zipPath = zipPath ? fixPath(zipPath) : ""; + const p = pth.win32.basename(pth.win32.normalize(localPath)); + zipPath += zipName ? zipName : p; + if (stats.isFile()) { + filetools.fs.readFile(localPath, function(err2, data) { + if (err2) + return callback(err2, false); + self2.addFile(zipPath, data, comment, stats); + return setImmediate(callback, undefined, true); + }); + } else if (stats.isDirectory()) { + zipPath += filetools.sep; + self2.addFile(zipPath, Buffer.alloc(0), comment, stats); + return setImmediate(callback, undefined, true); + } + }); + }, + addLocalFolder: function(localPath, zipPath, filter) { + filter = filenameFilter(filter); + zipPath = zipPath ? fixPath(zipPath) : ""; + localPath = pth.normalize(localPath); + if (filetools.fs.existsSync(localPath)) { + const items = filetools.findFiles(localPath); + const self2 = this; + if (items.length) { + for (const filepath of items) { + const p = pth.join(zipPath, relativePath(localPath, filepath)); + if (filter(p)) { + self2.addLocalFile(filepath, pth.dirname(p)); + } + } + } + } else { + throw Utils.Errors.FILE_NOT_FOUND(localPath); + } + }, + addLocalFolderAsync: function(localPath, callback, zipPath, filter) { + filter = filenameFilter(filter); + zipPath = zipPath ? fixPath(zipPath) : ""; + localPath = pth.normalize(localPath); + var self2 = this; + filetools.fs.open(localPath, "r", function(err) { + if (err && err.code === "ENOENT") { + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); + } else if (err) { + callback(undefined, err); + } else { + var items = filetools.findFiles(localPath); + var i2 = -1; + var next = function() { + i2 += 1; + if (i2 < items.length) { + var filepath = items[i2]; + var p = relativePath(localPath, filepath).split("\\").join("/"); + p = p.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\x20-\x7E]/g, ""); + if (filter(p)) { + filetools.fs.stat(filepath, function(er0, stats) { + if (er0) + callback(undefined, er0); + if (stats.isFile()) { + filetools.fs.readFile(filepath, function(er1, data) { + if (er1) { + callback(undefined, er1); + } else { + self2.addFile(zipPath + p, data, "", stats); + next(); + } + }); + } else { + self2.addFile(zipPath + p + "/", Buffer.alloc(0), "", stats); + next(); + } + }); + } else { + process.nextTick(() => { + next(); + }); + } + } else { + callback(true, undefined); + } + }; + next(); + } + }); + }, + addLocalFolderAsync2: function(options2, callback) { + const self2 = this; + options2 = typeof options2 === "object" ? options2 : { localPath: options2 }; + const localPath = pth.resolve(fixPath(options2.localPath)); + let { zipPath, filter, namefix } = options2; + if (filter instanceof RegExp) { + filter = function(rx) { + return function(filename) { + return rx.test(filename); + }; + }(filter); + } else if (typeof filter !== "function") { + filter = function() { + return true; + }; + } + zipPath = zipPath ? fixPath(zipPath) : ""; + if (namefix === "latin1") { + namefix = (str) => str.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^\x20-\x7E]/g, ""); + } + if (typeof namefix !== "function") + namefix = (str) => str; + const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry))); + const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry))); + filetools.fs.open(localPath, "r", function(err) { + if (err && err.code === "ENOENT") { + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); + } else if (err) { + callback(undefined, err); + } else { + filetools.findFilesAsync(localPath, function(err2, fileEntries) { + if (err2) + return callback(err2); + fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir))); + if (!fileEntries.length) + callback(undefined, false); + setImmediate(fileEntries.reverse().reduce(function(next, entry) { + return function(err3, done) { + if (err3 || done === false) + return setImmediate(next, err3, false); + self2.addLocalFileAsync({ + localPath: entry, + zipPath: pth.dirname(relPathFix(entry)), + zipName: fileNameFix(entry) + }, next); + }; + }, callback)); + }); + } + }); + }, + addLocalFolderPromise: function(localPath, props) { + return new Promise((resolve, reject) => { + this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => { + if (err) + reject(err); + if (done) + resolve(this); + }); + }); + }, + addFile: function(entryName, content, comment, attr) { + entryName = zipnamefix(entryName); + let entry = getEntry(entryName); + const update = entry != null; + if (!update) { + entry = new ZipEntry(opts); + entry.entryName = entryName; + } + entry.comment = comment || ""; + const isStat = typeof attr === "object" && attr instanceof filetools.fs.Stats; + if (isStat) { + entry.header.time = attr.mtime; + } + var fileattr = entry.isDirectory ? 16 : 0; + let unix = entry.isDirectory ? 16384 : 32768; + if (isStat) { + unix |= 4095 & attr.mode; + } else if (typeof attr === "number") { + unix |= 4095 & attr; + } else { + unix |= entry.isDirectory ? 493 : 420; + } + fileattr = (fileattr | unix << 16) >>> 0; + entry.attr = fileattr; + entry.setData(content); + if (!update) + _zip.setEntry(entry); + return entry; + }, + getEntries: function(password) { + _zip.password = password; + return _zip ? _zip.entries : []; + }, + getEntry: function(name) { + return getEntry(name); + }, + getEntryCount: function() { + return _zip.getEntryCount(); + }, + forEach: function(callback) { + return _zip.forEach(callback); + }, + extractEntryTo: function(entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) { + overwrite = get_Bool(false, overwrite); + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + maintainEntryPath = get_Bool(true, maintainEntryPath); + outFileName = get_Str(keepOriginalPermission, outFileName); + var item = getEntry(entry); + if (!item) { + throw Utils.Errors.NO_ENTRY(); + } + var entryName = canonical(item.entryName); + var target = sanitize(targetPath, outFileName && !item.isDirectory ? canonical(outFileName) : maintainEntryPath ? entryName : pth.basename(entryName)); + if (item.isDirectory) { + var children = _zip.getEntryChildren(item); + children.forEach(function(child) { + if (child.isDirectory) + return; + var content2 = child.getData(); + if (!content2) { + throw Utils.Errors.CANT_EXTRACT_FILE(); + } + var name = canonical(child.entryName); + var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name)); + const fileAttr2 = keepOriginalPermission ? child.header.fileAttr : undefined; + filetools.writeFileTo(childName, content2, overwrite, fileAttr2); + }); + return true; + } + var content = item.getData(_zip.password); + if (!content) + throw Utils.Errors.CANT_EXTRACT_FILE(); + if (filetools.fs.existsSync(target) && !overwrite) { + throw Utils.Errors.CANT_OVERRIDE(); + } + const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + filetools.writeFileTo(target, content, overwrite, fileAttr); + return true; + }, + test: function(pass) { + if (!_zip) { + return false; + } + for (var entry of _zip.entries) { + try { + if (entry.isDirectory) { + continue; + } + var content = _zip.entries[entry].getData(pass); + if (!content) { + return false; + } + } catch (err) { + return false; + } + } + return true; + }, + extractAllTo: function(targetPath, overwrite, keepOriginalPermission, pass) { + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + pass = get_Str(keepOriginalPermission, pass); + overwrite = get_Bool(false, overwrite); + if (!_zip) + throw Utils.Errors.NO_ZIP(); + _zip.entries.forEach(function(entry) { + var entryName = sanitize(targetPath, canonical(entry.entryName)); + if (entry.isDirectory) { + filetools.makeDir(entryName); + return; + } + var content = entry.getData(pass); + if (!content) { + throw Utils.Errors.CANT_EXTRACT_FILE(); + } + const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + filetools.writeFileTo(entryName, content, overwrite, fileAttr); + try { + filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time); + } catch (err) { + throw Utils.Errors.CANT_EXTRACT_FILE(); + } + }); + }, + extractAllToAsync: function(targetPath, overwrite, keepOriginalPermission, callback) { + callback = get_Fun(overwrite, keepOriginalPermission, callback); + keepOriginalPermission = get_Bool(false, keepOriginalPermission); + overwrite = get_Bool(false, overwrite); + if (!callback) { + return new Promise((resolve, reject) => { + this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function(err) { + if (err) { + reject(err); + } else { + resolve(this); + } + }); + }); + } + if (!_zip) { + callback(Utils.Errors.NO_ZIP()); + return; + } + targetPath = pth.resolve(targetPath); + const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName))); + const getError = (msg, file) => new Error(msg + ': "' + file + '"'); + const dirEntries = []; + const fileEntries = []; + _zip.entries.forEach((e2) => { + if (e2.isDirectory) { + dirEntries.push(e2); + } else { + fileEntries.push(e2); + } + }); + for (const entry of dirEntries) { + const dirPath = getPath(entry); + const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + try { + filetools.makeDir(dirPath); + if (dirAttr) + filetools.fs.chmodSync(dirPath, dirAttr); + filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time); + } catch (er) { + callback(getError("Unable to create folder", dirPath)); + } + } + fileEntries.reverse().reduce(function(next, entry) { + return function(err) { + if (err) { + next(err); + } else { + const entryName = pth.normalize(canonical(entry.entryName)); + const filePath = sanitize(targetPath, entryName); + entry.getDataAsync(function(content, err_1) { + if (err_1) { + next(err_1); + } else if (!content) { + next(Utils.Errors.CANT_EXTRACT_FILE()); + } else { + const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; + filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function(succ) { + if (!succ) { + next(getError("Unable to write file", filePath)); + } + filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function(err_2) { + if (err_2) { + next(getError("Unable to set times", filePath)); + } else { + next(); + } + }); + }); + } + }); + } + }; + }, callback)(); + }, + writeZip: function(targetFileName, callback) { + if (arguments.length === 1) { + if (typeof targetFileName === "function") { + callback = targetFileName; + targetFileName = ""; + } + } + if (!targetFileName && opts.filename) { + targetFileName = opts.filename; + } + if (!targetFileName) + return; + var zipData = _zip.compressToBuffer(); + if (zipData) { + var ok = filetools.writeFileTo(targetFileName, zipData, true); + if (typeof callback === "function") + callback(!ok ? new Error("failed") : null, ""); + } + }, + writeZipPromise: function(targetFileName, props) { + const { overwrite, perm } = Object.assign({ overwrite: true }, props); + return new Promise((resolve, reject) => { + if (!targetFileName && opts.filename) + targetFileName = opts.filename; + if (!targetFileName) + reject("ADM-ZIP: ZIP File Name Missing"); + this.toBufferPromise().then((zipData) => { + const ret = (done) => done ? resolve(done) : reject("ADM-ZIP: Wasn't able to write zip file"); + filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret); + }, reject); + }); + }, + toBufferPromise: function() { + return new Promise((resolve, reject) => { + _zip.toAsyncBuffer(resolve, reject); + }); + }, + toBuffer: function(onSuccess, onFail, onItemStart, onItemEnd) { + if (typeof onSuccess === "function") { + _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd); + return null; + } + return _zip.compressToBuffer(); + } + }; + }; +}); + +// node_modules/is-safe-filename/index.js +function isSafeFilename(filename) { + if (typeof filename !== "string") { + return false; + } + const trimmed = filename.trim(); + return trimmed !== "" && trimmed !== "." && trimmed !== ".." && !filename.includes("/") && !filename.includes("\\") && !filename.includes("\x00"); +} +function assertSafeFilename(filename) { + if (typeof filename !== "string") { + throw new TypeError("Expected a string"); + } + if (!isSafeFilename(filename)) { + throw new Error(`Unsafe filename: ${JSON.stringify(filename)}`); + } +} +var unsafeFilenameFixtures; +var init_is_safe_filename = __esm(() => { + unsafeFilenameFixtures = Object.freeze([ + "", + " ", + ".", + "..", + " .", + ". ", + " ..", + ".. ", + "../", + "../foo", + "foo/../bar", + "foo/bar", + "foo\\bar", + "foo\x00bar" + ]); +}); + +// node_modules/env-paths/index.js +import path from "node:path"; +import os from "node:os"; +import process2 from "node:process"; +function envPaths(name, { suffix = "nodejs" } = {}) { + assertSafeFilename(name); + if (suffix) { + name += `-${suffix}`; + } + assertSafeFilename(name); + if (process2.platform === "darwin") { + return macos(name); + } + if (process2.platform === "win32") { + return windows(name); + } + return linux(name); +} +var homedir, tmpdir, env, macos = (name) => { + const library = path.join(homedir, "Library"); + return { + data: path.join(library, "Application Support", name), + config: path.join(library, "Preferences", name), + cache: path.join(library, "Caches", name), + log: path.join(library, "Logs", name), + temp: path.join(tmpdir, name) + }; +}, windows = (name) => { + const appData = env.APPDATA || path.join(homedir, "AppData", "Roaming"); + const localAppData = env.LOCALAPPDATA || path.join(homedir, "AppData", "Local"); + return { + data: path.join(localAppData, name, "Data"), + config: path.join(appData, name, "Config"), + cache: path.join(localAppData, name, "Cache"), + log: path.join(localAppData, name, "Log"), + temp: path.join(tmpdir, name) + }; +}, linux = (name) => { + const username = path.basename(homedir); + return { + data: path.join(env.XDG_DATA_HOME || path.join(homedir, ".local", "share"), name), + config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, ".config"), name), + cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, ".cache"), name), + log: path.join(env.XDG_STATE_HOME || path.join(homedir, ".local", "state"), name), + temp: path.join(tmpdir, username, name) + }; +}; +var init_env_paths = __esm(() => { + init_is_safe_filename(); + homedir = os.homedir(); + tmpdir = os.tmpdir(); + ({ env } = process2); +}); + +// node_modules/is-plain-obj/index.js +function isPlainObject2(value) { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); +} + +// node_modules/execa/lib/arguments/file-url.js +import { fileURLToPath } from "node:url"; +var safeNormalizeFileUrl = (file, name) => { + const fileString = normalizeFileUrl(normalizeDenoExecPath(file)); + if (typeof fileString !== "string") { + throw new TypeError(`${name} must be a string or a file URL: ${fileString}.`); + } + return fileString; +}, normalizeDenoExecPath = (file) => isDenoExecPath(file) ? file.toString() : file, isDenoExecPath = (file) => typeof file !== "string" && file && Object.getPrototypeOf(file) === String.prototype, normalizeFileUrl = (file) => file instanceof URL ? fileURLToPath(file) : file; +var init_file_url = () => {}; + +// node_modules/execa/lib/methods/parameters.js +var normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => { + const filePath = safeNormalizeFileUrl(rawFile, "First argument"); + const [commandArguments, options] = isPlainObject2(rawArguments) ? [[], rawArguments] : [rawArguments, rawOptions]; + if (!Array.isArray(commandArguments)) { + throw new TypeError(`Second argument must be either an array of arguments or an options object: ${commandArguments}`); + } + if (commandArguments.some((commandArgument) => typeof commandArgument === "object" && commandArgument !== null)) { + throw new TypeError(`Second argument must be an array of strings: ${commandArguments}`); + } + const normalizedArguments = commandArguments.map(String); + const nullByteArgument = normalizedArguments.find((normalizedArgument) => normalizedArgument.includes("\x00")); + if (nullByteArgument !== undefined) { + throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArgument}`); + } + if (!isPlainObject2(options)) { + throw new TypeError(`Last argument must be an options object: ${options}`); + } + return [filePath, normalizedArguments, options]; +}; +var init_parameters = __esm(() => { + init_file_url(); +}); + +// node_modules/execa/lib/utils/uint-array.js +import { StringDecoder } from "node:string_decoder"; +var objectToString, isArrayBuffer = (value) => objectToString.call(value) === "[object ArrayBuffer]", isUint8Array = (value) => objectToString.call(value) === "[object Uint8Array]", bufferToUint8Array = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength), textEncoder, stringToUint8Array = (string) => textEncoder.encode(string), textDecoder, uint8ArrayToString = (uint8Array) => textDecoder.decode(uint8Array), joinToString = (uint8ArraysOrStrings, encoding) => { + const strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding); + return strings.join(""); +}, uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => { + if (encoding === "utf8" && uint8ArraysOrStrings.every((uint8ArrayOrString) => typeof uint8ArrayOrString === "string")) { + return uint8ArraysOrStrings; + } + const decoder = new StringDecoder(encoding); + const strings = uint8ArraysOrStrings.map((uint8ArrayOrString) => typeof uint8ArrayOrString === "string" ? stringToUint8Array(uint8ArrayOrString) : uint8ArrayOrString).map((uint8Array) => decoder.write(uint8Array)); + const finalString = decoder.end(); + return finalString === "" ? strings : [...strings, finalString]; +}, joinToUint8Array = (uint8ArraysOrStrings) => { + if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) { + return uint8ArraysOrStrings[0]; + } + return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings)); +}, stringsToUint8Arrays = (uint8ArraysOrStrings) => uint8ArraysOrStrings.map((uint8ArrayOrString) => typeof uint8ArrayOrString === "string" ? stringToUint8Array(uint8ArrayOrString) : uint8ArrayOrString), concatUint8Arrays = (uint8Arrays) => { + const result = new Uint8Array(getJoinLength(uint8Arrays)); + let index = 0; + for (const uint8Array of uint8Arrays) { + result.set(uint8Array, index); + index += uint8Array.length; + } + return result; +}, getJoinLength = (uint8Arrays) => { + let joinLength = 0; + for (const uint8Array of uint8Arrays) { + joinLength += uint8Array.length; + } + return joinLength; +}; +var init_uint_array = __esm(() => { + ({ toString: objectToString } = Object.prototype); + textEncoder = new TextEncoder; + textDecoder = new TextDecoder; +}); + +// node_modules/execa/lib/methods/template.js +import { ChildProcess } from "node:child_process"; +var isTemplateString = (templates) => Array.isArray(templates) && Array.isArray(templates.raw), parseTemplates = (templates, expressions) => { + let tokens = []; + for (const [index, template] of templates.entries()) { + tokens = parseTemplate({ + templates, + expressions, + tokens, + index, + template + }); + } + if (tokens.length === 0) { + throw new TypeError("Template script must not be empty"); + } + const [file, ...commandArguments] = tokens; + return [file, commandArguments, {}]; +}, parseTemplate = ({ templates, expressions, tokens, index, template }) => { + if (template === undefined) { + throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`); + } + const { nextTokens, leadingWhitespaces, trailingWhitespaces } = splitByWhitespaces(template, templates.raw[index]); + const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces); + if (index === expressions.length) { + return newTokens; + } + const expression2 = expressions[index]; + const expressionTokens = Array.isArray(expression2) ? expression2.map((expression3) => parseExpression(expression3)) : [parseExpression(expression2)]; + return concatTokens(newTokens, expressionTokens, trailingWhitespaces); +}, splitByWhitespaces = (template, rawTemplate) => { + if (rawTemplate.length === 0) { + return { nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false }; + } + const nextTokens = []; + let templateStart = 0; + const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]); + for (let templateIndex = 0, rawIndex = 0;templateIndex < template.length; templateIndex += 1, rawIndex += 1) { + const rawCharacter = rawTemplate[rawIndex]; + if (DELIMITERS.has(rawCharacter)) { + if (templateStart !== templateIndex) { + nextTokens.push(template.slice(templateStart, templateIndex)); + } + templateStart = templateIndex + 1; + } else if (rawCharacter === "\\") { + const nextRawCharacter = rawTemplate[rawIndex + 1]; + if (nextRawCharacter === ` +`) { + templateIndex -= 1; + rawIndex += 1; + } else if (nextRawCharacter === "u" && rawTemplate[rawIndex + 2] === "{") { + rawIndex = rawTemplate.indexOf("}", rawIndex + 3); + } else { + rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1; + } + } + } + const trailingWhitespaces = templateStart === template.length; + if (!trailingWhitespaces) { + nextTokens.push(template.slice(templateStart)); + } + return { nextTokens, leadingWhitespaces, trailingWhitespaces }; +}, DELIMITERS, ESCAPE_LENGTH, concatTokens = (tokens, nextTokens, isSeparated) => isSeparated || tokens.length === 0 || nextTokens.length === 0 ? [...tokens, ...nextTokens] : [ + ...tokens.slice(0, -1), + `${tokens.at(-1)}${nextTokens[0]}`, + ...nextTokens.slice(1) +], parseExpression = (expression2) => { + const typeOfExpression = typeof expression2; + if (typeOfExpression === "string") { + return expression2; + } + if (typeOfExpression === "number") { + return String(expression2); + } + if (isPlainObject2(expression2) && (("stdout" in expression2) || ("isMaxBuffer" in expression2))) { + return getSubprocessResult(expression2); + } + if (expression2 instanceof ChildProcess || Object.prototype.toString.call(expression2) === "[object Promise]") { + throw new TypeError("Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}."); + } + throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`); +}, getSubprocessResult = ({ stdout }) => { + if (typeof stdout === "string") { + return stdout; + } + if (isUint8Array(stdout)) { + return uint8ArrayToString(stdout); + } + if (stdout === undefined) { + throw new TypeError(`Missing result.stdout in template expression. This is probably due to the previous subprocess' "stdout" option.`); + } + throw new TypeError(`Unexpected "${typeof stdout}" stdout in template expression`); +}; +var init_template = __esm(() => { + init_uint_array(); + DELIMITERS = new Set([" ", "\t", "\r", ` +`]); + ESCAPE_LENGTH = { x: 3, u: 5 }; +}); + +// node_modules/execa/lib/utils/standard-stream.js +import process3 from "node:process"; +var isStandardStream = (stream) => STANDARD_STREAMS.includes(stream), STANDARD_STREAMS, STANDARD_STREAMS_ALIASES, getStreamName = (fdNumber) => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`; +var init_standard_stream = __esm(() => { + STANDARD_STREAMS = [process3.stdin, process3.stdout, process3.stderr]; + STANDARD_STREAMS_ALIASES = ["stdin", "stdout", "stderr"]; +}); + +// node_modules/execa/lib/arguments/specific.js +import { debuglog } from "node:util"; +var normalizeFdSpecificOptions = (options) => { + const optionsCopy = { ...options }; + for (const optionName of FD_SPECIFIC_OPTIONS) { + optionsCopy[optionName] = normalizeFdSpecificOption(options, optionName); + } + return optionsCopy; +}, normalizeFdSpecificOption = (options, optionName) => { + const optionBaseArray = Array.from({ length: getStdioLength(options) + 1 }); + const optionArray = normalizeFdSpecificValue(options[optionName], optionBaseArray, optionName); + return addDefaultValue(optionArray, optionName); +}, getStdioLength = ({ stdio }) => Array.isArray(stdio) ? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length) : STANDARD_STREAMS_ALIASES.length, normalizeFdSpecificValue = (optionValue, optionArray, optionName) => isPlainObject2(optionValue) ? normalizeOptionObject(optionValue, optionArray, optionName) : optionArray.fill(optionValue), normalizeOptionObject = (optionValue, optionArray, optionName) => { + for (const fdName of Object.keys(optionValue).sort(compareFdName)) { + for (const fdNumber of parseFdName(fdName, optionName, optionArray)) { + optionArray[fdNumber] = optionValue[fdName]; + } + } + return optionArray; +}, compareFdName = (fdNameA, fdNameB) => getFdNameOrder(fdNameA) < getFdNameOrder(fdNameB) ? 1 : -1, getFdNameOrder = (fdName) => { + if (fdName === "stdout" || fdName === "stderr") { + return 0; + } + return fdName === "all" ? 2 : 1; +}, parseFdName = (fdName, optionName, optionArray) => { + if (fdName === "ipc") { + return [optionArray.length - 1]; + } + const fdNumber = parseFd(fdName); + if (fdNumber === undefined || fdNumber === 0) { + throw new TypeError(`"${optionName}.${fdName}" is invalid. +It must be "${optionName}.stdout", "${optionName}.stderr", "${optionName}.all", "${optionName}.ipc", or "${optionName}.fd3", "${optionName}.fd4" (and so on).`); + } + if (fdNumber >= optionArray.length) { + throw new TypeError(`"${optionName}.${fdName}" is invalid: that file descriptor does not exist. +Please set the "stdio" option to ensure that file descriptor exists.`); + } + return fdNumber === "all" ? [1, 2] : [fdNumber]; +}, parseFd = (fdName) => { + if (fdName === "all") { + return fdName; + } + if (STANDARD_STREAMS_ALIASES.includes(fdName)) { + return STANDARD_STREAMS_ALIASES.indexOf(fdName); + } + const regexpResult = FD_REGEXP.exec(fdName); + if (regexpResult !== null) { + return Number(regexpResult[1]); + } +}, FD_REGEXP, addDefaultValue = (optionArray, optionName) => optionArray.map((optionValue) => optionValue === undefined ? DEFAULT_OPTIONS[optionName] : optionValue), verboseDefault, DEFAULT_OPTIONS, FD_SPECIFIC_OPTIONS, getFdSpecificValue = (optionArray, fdNumber) => fdNumber === "ipc" ? optionArray.at(-1) : optionArray[fdNumber]; +var init_specific = __esm(() => { + init_standard_stream(); + FD_REGEXP = /^fd(\d+)$/; + verboseDefault = debuglog("execa").enabled ? "full" : "none"; + DEFAULT_OPTIONS = { + lines: false, + buffer: true, + maxBuffer: 1000 * 1000 * 100, + verbose: verboseDefault, + stripFinalNewline: true + }; + FD_SPECIFIC_OPTIONS = ["lines", "buffer", "maxBuffer", "verbose", "stripFinalNewline"]; +}); + +// node_modules/execa/lib/verbose/values.js +var isVerbose = ({ verbose }, fdNumber) => getFdVerbose(verbose, fdNumber) !== "none", isFullVerbose = ({ verbose }, fdNumber) => !["none", "short"].includes(getFdVerbose(verbose, fdNumber)), getVerboseFunction = ({ verbose }, fdNumber) => { + const fdVerbose = getFdVerbose(verbose, fdNumber); + return isVerboseFunction(fdVerbose) ? fdVerbose : undefined; +}, getFdVerbose = (verbose, fdNumber) => fdNumber === undefined ? getFdGenericVerbose(verbose) : getFdSpecificValue(verbose, fdNumber), getFdGenericVerbose = (verbose) => verbose.find((fdVerbose) => isVerboseFunction(fdVerbose)) ?? VERBOSE_VALUES.findLast((fdVerbose) => verbose.includes(fdVerbose)), isVerboseFunction = (fdVerbose) => typeof fdVerbose === "function", VERBOSE_VALUES; +var init_values = __esm(() => { + init_specific(); + VERBOSE_VALUES = ["none", "short", "full"]; +}); + +// node_modules/execa/lib/arguments/escape.js +import { platform } from "node:process"; +import { stripVTControlCharacters } from "node:util"; +var joinCommand = (filePath, rawArguments) => { + const fileAndArguments = [filePath, ...rawArguments]; + const command = fileAndArguments.join(" "); + const escapedCommand = fileAndArguments.map((fileAndArgument) => quoteString(escapeControlCharacters(fileAndArgument))).join(" "); + return { command, escapedCommand }; +}, escapeLines = (lines) => stripVTControlCharacters(lines).split(` +`).map((line) => escapeControlCharacters(line)).join(` +`), escapeControlCharacters = (line) => line.replaceAll(SPECIAL_CHAR_REGEXP, (character) => escapeControlCharacter(character)), escapeControlCharacter = (character) => { + const commonEscape = COMMON_ESCAPES[character]; + if (commonEscape !== undefined) { + return commonEscape; + } + const codepoint = character.codePointAt(0); + const codepointHex = codepoint.toString(16); + return codepoint <= ASTRAL_START ? `\\u${codepointHex.padStart(4, "0")}` : `\\U${codepointHex}`; +}, getSpecialCharRegExp = () => { + try { + return new RegExp("\\p{Separator}|\\p{Other}", "gu"); + } catch { + return /[\s\u0000-\u001F\u007F-\u009F\u00AD]/g; + } +}, SPECIAL_CHAR_REGEXP, COMMON_ESCAPES, ASTRAL_START = 65535, quoteString = (escapedArgument) => { + if (NO_ESCAPE_REGEXP.test(escapedArgument)) { + return escapedArgument; + } + return platform === "win32" ? `"${escapedArgument.replaceAll('"', '""')}"` : `'${escapedArgument.replaceAll("'", "'\\''")}'`; +}, NO_ESCAPE_REGEXP; +var init_escape = __esm(() => { + SPECIAL_CHAR_REGEXP = getSpecialCharRegExp(); + COMMON_ESCAPES = { + " ": " ", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t" + }; + NO_ESCAPE_REGEXP = /^[\w./-]+$/; +}); + +// node_modules/figures/node_modules/is-unicode-supported/index.js +import process4 from "node:process"; +function isUnicodeSupported() { + if (process4.platform !== "win32") { + return process4.env.TERM !== "linux"; + } + return Boolean(process4.env.WT_SESSION) || Boolean(process4.env.TERMINUS_SUBLIME) || process4.env.ConEmuTask === "{cmd::Cmder}" || process4.env.TERM_PROGRAM === "Terminus-Sublime" || process4.env.TERM_PROGRAM === "vscode" || process4.env.TERM === "xterm-256color" || process4.env.TERM === "alacritty" || process4.env.TERMINAL_EMULATOR === "JetBrains-JediTerm"; +} +var init_is_unicode_supported = () => {}; + +// node_modules/figures/index.js +var common, specialMainSymbols, specialFallbackSymbols, mainSymbols, fallbackSymbols, shouldUseMain, figures, figures_default, replacements; +var init_figures = __esm(() => { + init_is_unicode_supported(); + common = { + circleQuestionMark: "(?)", + questionMarkPrefix: "(?)", + square: "█", + squareDarkShade: "▓", + squareMediumShade: "▒", + squareLightShade: "░", + squareTop: "▀", + squareBottom: "▄", + squareLeft: "▌", + squareRight: "▐", + squareCenter: "■", + bullet: "●", + dot: "․", + ellipsis: "…", + pointerSmall: "›", + triangleUp: "▲", + triangleUpSmall: "▴", + triangleDown: "▼", + triangleDownSmall: "▾", + triangleLeftSmall: "◂", + triangleRightSmall: "▸", + home: "⌂", + heart: "♥", + musicNote: "♪", + musicNoteBeamed: "♫", + arrowUp: "↑", + arrowDown: "↓", + arrowLeft: "←", + arrowRight: "→", + arrowLeftRight: "↔", + arrowUpDown: "↕", + almostEqual: "≈", + notEqual: "≠", + lessOrEqual: "≤", + greaterOrEqual: "≥", + identical: "≡", + infinity: "∞", + subscriptZero: "₀", + subscriptOne: "₁", + subscriptTwo: "₂", + subscriptThree: "₃", + subscriptFour: "₄", + subscriptFive: "₅", + subscriptSix: "₆", + subscriptSeven: "₇", + subscriptEight: "₈", + subscriptNine: "₉", + oneHalf: "½", + oneThird: "⅓", + oneQuarter: "¼", + oneFifth: "⅕", + oneSixth: "⅙", + oneEighth: "⅛", + twoThirds: "⅔", + twoFifths: "⅖", + threeQuarters: "¾", + threeFifths: "⅗", + threeEighths: "⅜", + fourFifths: "⅘", + fiveSixths: "⅚", + fiveEighths: "⅝", + sevenEighths: "⅞", + line: "─", + lineBold: "━", + lineDouble: "═", + lineDashed0: "┄", + lineDashed1: "┅", + lineDashed2: "┈", + lineDashed3: "┉", + lineDashed4: "╌", + lineDashed5: "╍", + lineDashed6: "╴", + lineDashed7: "╶", + lineDashed8: "╸", + lineDashed9: "╺", + lineDashed10: "╼", + lineDashed11: "╾", + lineDashed12: "−", + lineDashed13: "–", + lineDashed14: "‐", + lineDashed15: "⁃", + lineVertical: "│", + lineVerticalBold: "┃", + lineVerticalDouble: "║", + lineVerticalDashed0: "┆", + lineVerticalDashed1: "┇", + lineVerticalDashed2: "┊", + lineVerticalDashed3: "┋", + lineVerticalDashed4: "╎", + lineVerticalDashed5: "╏", + lineVerticalDashed6: "╵", + lineVerticalDashed7: "╷", + lineVerticalDashed8: "╹", + lineVerticalDashed9: "╻", + lineVerticalDashed10: "╽", + lineVerticalDashed11: "╿", + lineDownLeft: "┐", + lineDownLeftArc: "╮", + lineDownBoldLeftBold: "┓", + lineDownBoldLeft: "┒", + lineDownLeftBold: "┑", + lineDownDoubleLeftDouble: "╗", + lineDownDoubleLeft: "╖", + lineDownLeftDouble: "╕", + lineDownRight: "┌", + lineDownRightArc: "╭", + lineDownBoldRightBold: "┏", + lineDownBoldRight: "┎", + lineDownRightBold: "┍", + lineDownDoubleRightDouble: "╔", + lineDownDoubleRight: "╓", + lineDownRightDouble: "╒", + lineUpLeft: "┘", + lineUpLeftArc: "╯", + lineUpBoldLeftBold: "┛", + lineUpBoldLeft: "┚", + lineUpLeftBold: "┙", + lineUpDoubleLeftDouble: "╝", + lineUpDoubleLeft: "╜", + lineUpLeftDouble: "╛", + lineUpRight: "└", + lineUpRightArc: "╰", + lineUpBoldRightBold: "┗", + lineUpBoldRight: "┖", + lineUpRightBold: "┕", + lineUpDoubleRightDouble: "╚", + lineUpDoubleRight: "╙", + lineUpRightDouble: "╘", + lineUpDownLeft: "┤", + lineUpBoldDownBoldLeftBold: "┫", + lineUpBoldDownBoldLeft: "┨", + lineUpDownLeftBold: "┥", + lineUpBoldDownLeftBold: "┩", + lineUpDownBoldLeftBold: "┪", + lineUpDownBoldLeft: "┧", + lineUpBoldDownLeft: "┦", + lineUpDoubleDownDoubleLeftDouble: "╣", + lineUpDoubleDownDoubleLeft: "╢", + lineUpDownLeftDouble: "╡", + lineUpDownRight: "├", + lineUpBoldDownBoldRightBold: "┣", + lineUpBoldDownBoldRight: "┠", + lineUpDownRightBold: "┝", + lineUpBoldDownRightBold: "┡", + lineUpDownBoldRightBold: "┢", + lineUpDownBoldRight: "┟", + lineUpBoldDownRight: "┞", + lineUpDoubleDownDoubleRightDouble: "╠", + lineUpDoubleDownDoubleRight: "╟", + lineUpDownRightDouble: "╞", + lineDownLeftRight: "┬", + lineDownBoldLeftBoldRightBold: "┳", + lineDownLeftBoldRightBold: "┯", + lineDownBoldLeftRight: "┰", + lineDownBoldLeftBoldRight: "┱", + lineDownBoldLeftRightBold: "┲", + lineDownLeftRightBold: "┮", + lineDownLeftBoldRight: "┭", + lineDownDoubleLeftDoubleRightDouble: "╦", + lineDownDoubleLeftRight: "╥", + lineDownLeftDoubleRightDouble: "╤", + lineUpLeftRight: "┴", + lineUpBoldLeftBoldRightBold: "┻", + lineUpLeftBoldRightBold: "┷", + lineUpBoldLeftRight: "┸", + lineUpBoldLeftBoldRight: "┹", + lineUpBoldLeftRightBold: "┺", + lineUpLeftRightBold: "┶", + lineUpLeftBoldRight: "┵", + lineUpDoubleLeftDoubleRightDouble: "╩", + lineUpDoubleLeftRight: "╨", + lineUpLeftDoubleRightDouble: "╧", + lineUpDownLeftRight: "┼", + lineUpBoldDownBoldLeftBoldRightBold: "╋", + lineUpDownBoldLeftBoldRightBold: "╈", + lineUpBoldDownLeftBoldRightBold: "╇", + lineUpBoldDownBoldLeftRightBold: "╊", + lineUpBoldDownBoldLeftBoldRight: "╉", + lineUpBoldDownLeftRight: "╀", + lineUpDownBoldLeftRight: "╁", + lineUpDownLeftBoldRight: "┽", + lineUpDownLeftRightBold: "┾", + lineUpBoldDownBoldLeftRight: "╂", + lineUpDownLeftBoldRightBold: "┿", + lineUpBoldDownLeftBoldRight: "╃", + lineUpBoldDownLeftRightBold: "╄", + lineUpDownBoldLeftBoldRight: "╅", + lineUpDownBoldLeftRightBold: "╆", + lineUpDoubleDownDoubleLeftDoubleRightDouble: "╬", + lineUpDoubleDownDoubleLeftRight: "╫", + lineUpDownLeftDoubleRightDouble: "╪", + lineCross: "╳", + lineBackslash: "╲", + lineSlash: "╱" + }; + specialMainSymbols = { + tick: "✔", + info: "ℹ", + warning: "⚠", + cross: "✘", + squareSmall: "◻", + squareSmallFilled: "◼", + circle: "◯", + circleFilled: "◉", + circleDotted: "◌", + circleDouble: "◎", + circleCircle: "ⓞ", + circleCross: "ⓧ", + circlePipe: "Ⓘ", + radioOn: "◉", + radioOff: "◯", + checkboxOn: "☒", + checkboxOff: "☐", + checkboxCircleOn: "ⓧ", + checkboxCircleOff: "Ⓘ", + pointer: "❯", + triangleUpOutline: "△", + triangleLeft: "◀", + triangleRight: "▶", + lozenge: "◆", + lozengeOutline: "◇", + hamburger: "☰", + smiley: "㋡", + mustache: "෴", + star: "★", + play: "▶", + nodejs: "⬢", + oneSeventh: "⅐", + oneNinth: "⅑", + oneTenth: "⅒" + }; + specialFallbackSymbols = { + tick: "√", + info: "i", + warning: "‼", + cross: "×", + squareSmall: "□", + squareSmallFilled: "■", + circle: "( )", + circleFilled: "(*)", + circleDotted: "( )", + circleDouble: "( )", + circleCircle: "(○)", + circleCross: "(×)", + circlePipe: "(│)", + radioOn: "(*)", + radioOff: "( )", + checkboxOn: "[×]", + checkboxOff: "[ ]", + checkboxCircleOn: "(×)", + checkboxCircleOff: "( )", + pointer: ">", + triangleUpOutline: "∆", + triangleLeft: "◄", + triangleRight: "►", + lozenge: "♦", + lozengeOutline: "◊", + hamburger: "≡", + smiley: "☺", + mustache: "┌─┐", + star: "✶", + play: "►", + nodejs: "♦", + oneSeventh: "1/7", + oneNinth: "1/9", + oneTenth: "1/10" + }; + mainSymbols = { ...common, ...specialMainSymbols }; + fallbackSymbols = { ...common, ...specialFallbackSymbols }; + shouldUseMain = isUnicodeSupported(); + figures = shouldUseMain ? mainSymbols : fallbackSymbols; + figures_default = figures; + replacements = Object.entries(specialMainSymbols); +}); + +// node_modules/yoctocolors/base.js +import tty from "node:tty"; +var hasColors, format = (open, close2) => { + if (!hasColors) { + return (input) => input; + } + const openCode = `\x1B[${open}m`; + const closeCode = `\x1B[${close2}m`; + return (input) => { + const string = input + ""; + let index = string.indexOf(closeCode); + if (index === -1) { + return openCode + string + closeCode; + } + let result = openCode; + let lastIndex = 0; + while (index !== -1) { + result += string.slice(lastIndex, index) + openCode; + lastIndex = index + closeCode.length; + index = string.indexOf(closeCode, lastIndex); + } + result += string.slice(lastIndex) + closeCode; + return result; + }; +}, reset, bold, dim, italic, underline, overline, inverse, hidden, strikethrough, black, red, green, yellow, blue, magenta, cyan, white, gray, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite, bgGray, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, whiteBright, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, bgWhiteBright; +var init_base2 = __esm(() => { + hasColors = tty?.WriteStream?.prototype?.hasColors?.() ?? false; + reset = format(0, 0); + bold = format(1, 22); + dim = format(2, 22); + italic = format(3, 23); + underline = format(4, 24); + overline = format(53, 55); + inverse = format(7, 27); + hidden = format(8, 28); + strikethrough = format(9, 29); + black = format(30, 39); + red = format(31, 39); + green = format(32, 39); + yellow = format(33, 39); + blue = format(34, 39); + magenta = format(35, 39); + cyan = format(36, 39); + white = format(37, 39); + gray = format(90, 39); + bgBlack = format(40, 49); + bgRed = format(41, 49); + bgGreen = format(42, 49); + bgYellow = format(43, 49); + bgBlue = format(44, 49); + bgMagenta = format(45, 49); + bgCyan = format(46, 49); + bgWhite = format(47, 49); + bgGray = format(100, 49); + redBright = format(91, 39); + greenBright = format(92, 39); + yellowBright = format(93, 39); + blueBright = format(94, 39); + magentaBright = format(95, 39); + cyanBright = format(96, 39); + whiteBright = format(97, 39); + bgRedBright = format(101, 49); + bgGreenBright = format(102, 49); + bgYellowBright = format(103, 49); + bgBlueBright = format(104, 49); + bgMagentaBright = format(105, 49); + bgCyanBright = format(106, 49); + bgWhiteBright = format(107, 49); +}); + +// node_modules/yoctocolors/index.js +var init_yoctocolors = __esm(() => { + init_base2(); + init_base2(); +}); + +// node_modules/execa/lib/verbose/default.js +var defaultVerboseFunction = ({ + type, + message, + timestamp, + piped, + commandId, + result: { failed = false } = {}, + options: { reject = true } +}) => { + const timestampString = serializeTimestamp(timestamp); + const icon = ICONS[type]({ failed, reject, piped }); + const color = COLORS[type]({ reject }); + return `${gray(`[${timestampString}]`)} ${gray(`[${commandId}]`)} ${color(icon)} ${color(message)}`; +}, serializeTimestamp = (timestamp) => `${padField(timestamp.getHours(), 2)}:${padField(timestamp.getMinutes(), 2)}:${padField(timestamp.getSeconds(), 2)}.${padField(timestamp.getMilliseconds(), 3)}`, padField = (field, padding) => String(field).padStart(padding, "0"), getFinalIcon = ({ failed, reject }) => { + if (!failed) { + return figures_default.tick; + } + return reject ? figures_default.cross : figures_default.warning; +}, ICONS, identity = (string) => string, COLORS; +var init_default = __esm(() => { + init_figures(); + init_yoctocolors(); + ICONS = { + command: ({ piped }) => piped ? "|" : "$", + output: () => " ", + ipc: () => "*", + error: getFinalIcon, + duration: getFinalIcon + }; + COLORS = { + command: () => bold, + output: () => identity, + ipc: () => identity, + error: ({ reject }) => reject ? redBright : yellowBright, + duration: () => gray + }; +}); + +// node_modules/execa/lib/verbose/custom.js +var applyVerboseOnLines = (printedLines, verboseInfo, fdNumber) => { + const verboseFunction = getVerboseFunction(verboseInfo, fdNumber); + return printedLines.map(({ verboseLine, verboseObject }) => applyVerboseFunction(verboseLine, verboseObject, verboseFunction)).filter((printedLine) => printedLine !== undefined).map((printedLine) => appendNewline(printedLine)).join(""); +}, applyVerboseFunction = (verboseLine, verboseObject, verboseFunction) => { + if (verboseFunction === undefined) { + return verboseLine; + } + const printedLine = verboseFunction(verboseLine, verboseObject); + if (typeof printedLine === "string") { + return printedLine; + } +}, appendNewline = (printedLine) => printedLine.endsWith(` +`) ? printedLine : `${printedLine} +`; +var init_custom = __esm(() => { + init_values(); +}); + +// node_modules/execa/lib/verbose/log.js +import { inspect } from "node:util"; +var verboseLog = ({ type, verboseMessage, fdNumber, verboseInfo, result }) => { + const verboseObject = getVerboseObject({ type, result, verboseInfo }); + const printedLines = getPrintedLines(verboseMessage, verboseObject); + const finalLines = applyVerboseOnLines(printedLines, verboseInfo, fdNumber); + if (finalLines !== "") { + console.warn(finalLines.slice(0, -1)); + } +}, getVerboseObject = ({ + type, + result, + verboseInfo: { escapedCommand, commandId, rawOptions: { piped = false, ...options } } +}) => ({ + type, + escapedCommand, + commandId: `${commandId}`, + timestamp: new Date, + piped, + result, + options +}), getPrintedLines = (verboseMessage, verboseObject) => verboseMessage.split(` +`).map((message) => getPrintedLine({ ...verboseObject, message })), getPrintedLine = (verboseObject) => { + const verboseLine = defaultVerboseFunction(verboseObject); + return { verboseLine, verboseObject }; +}, serializeVerboseMessage = (message) => { + const messageString = typeof message === "string" ? message : inspect(message); + const escapedMessage = escapeLines(messageString); + return escapedMessage.replaceAll("\t", " ".repeat(TAB_SIZE)); +}, TAB_SIZE = 2; +var init_log = __esm(() => { + init_escape(); + init_default(); + init_custom(); +}); + +// node_modules/execa/lib/verbose/start.js +var logCommand = (escapedCommand, verboseInfo) => { + if (!isVerbose(verboseInfo)) { + return; + } + verboseLog({ + type: "command", + verboseMessage: escapedCommand, + verboseInfo + }); +}; +var init_start = __esm(() => { + init_values(); + init_log(); +}); + +// node_modules/execa/lib/verbose/info.js +var getVerboseInfo = (verbose, escapedCommand, rawOptions) => { + validateVerbose(verbose); + const commandId = getCommandId(verbose); + return { + verbose, + escapedCommand, + commandId, + rawOptions + }; +}, getCommandId = (verbose) => isVerbose({ verbose }) ? COMMAND_ID++ : undefined, COMMAND_ID = 0n, validateVerbose = (verbose) => { + for (const fdVerbose of verbose) { + if (fdVerbose === false) { + throw new TypeError(`The "verbose: false" option was renamed to "verbose: 'none'".`); + } + if (fdVerbose === true) { + throw new TypeError(`The "verbose: true" option was renamed to "verbose: 'short'".`); + } + if (!VERBOSE_VALUES.includes(fdVerbose) && !isVerboseFunction(fdVerbose)) { + const allowedValues = VERBOSE_VALUES.map((allowedValue) => `'${allowedValue}'`).join(", "); + throw new TypeError(`The "verbose" option must not be ${fdVerbose}. Allowed values are: ${allowedValues} or a function.`); + } + } +}; +var init_info = __esm(() => { + init_values(); +}); + +// node_modules/execa/lib/return/duration.js +import { hrtime } from "node:process"; +var getStartTime = () => hrtime.bigint(), getDurationMs = (startTime) => Number(hrtime.bigint() - startTime) / 1e6; +var init_duration = () => {}; + +// node_modules/execa/lib/arguments/command.js +var handleCommand = (filePath, rawArguments, rawOptions) => { + const startTime = getStartTime(); + const { command, escapedCommand } = joinCommand(filePath, rawArguments); + const verbose = normalizeFdSpecificOption(rawOptions, "verbose"); + const verboseInfo = getVerboseInfo(verbose, escapedCommand, { ...rawOptions }); + logCommand(escapedCommand, verboseInfo); + return { + command, + escapedCommand, + startTime, + verboseInfo + }; +}; +var init_command = __esm(() => { + init_start(); + init_info(); + init_duration(); + init_escape(); + init_specific(); +}); + +// node_modules/isexe/windows.js +var require_windows = __commonJS((exports, module) => { + module.exports = isexe; + isexe.sync = sync; + var fs2 = __require("fs"); + function checkPathExt(path2, options) { + var pathext = options.pathExt !== undefined ? options.pathExt : process.env.PATHEXT; + if (!pathext) { + return true; + } + pathext = pathext.split(";"); + if (pathext.indexOf("") !== -1) { + return true; + } + for (var i2 = 0;i2 < pathext.length; i2++) { + var p = pathext[i2].toLowerCase(); + if (p && path2.substr(-p.length).toLowerCase() === p) { + return true; + } + } + return false; + } + function checkStat(stat2, path2, options) { + if (!stat2.isSymbolicLink() && !stat2.isFile()) { + return false; + } + return checkPathExt(path2, options); + } + function isexe(path2, options, cb) { + fs2.stat(path2, function(er, stat2) { + cb(er, er ? false : checkStat(stat2, path2, options)); + }); + } + function sync(path2, options) { + return checkStat(fs2.statSync(path2), path2, options); + } +}); + +// node_modules/isexe/mode.js +var require_mode = __commonJS((exports, module) => { + module.exports = isexe; + isexe.sync = sync; + var fs2 = __require("fs"); + function isexe(path2, options, cb) { + fs2.stat(path2, function(er, stat2) { + cb(er, er ? false : checkStat(stat2, options)); + }); + } + function sync(path2, options) { + return checkStat(fs2.statSync(path2), options); + } + function checkStat(stat2, options) { + return stat2.isFile() && checkMode(stat2, options); + } + function checkMode(stat2, options) { + var mod = stat2.mode; + var uid = stat2.uid; + var gid = stat2.gid; + var myUid = options.uid !== undefined ? options.uid : process.getuid && process.getuid(); + var myGid = options.gid !== undefined ? options.gid : process.getgid && process.getgid(); + var u = parseInt("100", 8); + var g = parseInt("010", 8); + var o = parseInt("001", 8); + var ug = u | g; + var ret = mod & o || mod & g && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0; + return ret; + } +}); + +// node_modules/isexe/index.js +var require_isexe = __commonJS((exports, module) => { + var fs2 = __require("fs"); + var core; + if (process.platform === "win32" || global.TESTING_WINDOWS) { + core = require_windows(); + } else { + core = require_mode(); + } + module.exports = isexe; + isexe.sync = sync; + function isexe(path2, options, cb) { + if (typeof options === "function") { + cb = options; + options = {}; + } + if (!cb) { + if (typeof Promise !== "function") { + throw new TypeError("callback not provided"); + } + return new Promise(function(resolve, reject) { + isexe(path2, options || {}, function(er, is) { + if (er) { + reject(er); + } else { + resolve(is); + } + }); + }); + } + core(path2, options || {}, function(er, is) { + if (er) { + if (er.code === "EACCES" || options && options.ignoreErrors) { + er = null; + is = false; + } + } + cb(er, is); + }); + } + function sync(path2, options) { + try { + return core.sync(path2, options || {}); + } catch (er) { + if (options && options.ignoreErrors || er.code === "EACCES") { + return false; + } else { + throw er; + } + } + } +}); + +// node_modules/which/which.js +var require_which = __commonJS((exports, module) => { + var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys"; + var path2 = __require("path"); + var COLON2 = isWindows ? ";" : ":"; + var isexe = require_isexe(); + var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" }); + var getPathInfo = (cmd, opt) => { + const colon = opt.colon || COLON2; + const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [""] : [ + ...isWindows ? [process.cwd()] : [], + ...(opt.path || process.env.PATH || "").split(colon) + ]; + const pathExtExe = isWindows ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : ""; + const pathExt = isWindows ? pathExtExe.split(colon) : [""]; + if (isWindows) { + if (cmd.indexOf(".") !== -1 && pathExt[0] !== "") + pathExt.unshift(""); + } + return { + pathEnv, + pathExt, + pathExtExe + }; + }; + var which = (cmd, opt, cb) => { + if (typeof opt === "function") { + cb = opt; + opt = {}; + } + if (!opt) + opt = {}; + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + const step = (i2) => new Promise((resolve, reject) => { + if (i2 === pathEnv.length) + return opt.all && found.length ? resolve(found) : reject(getNotFoundError(cmd)); + const ppRaw = pathEnv[i2]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + const pCmd = path2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; + resolve(subStep(p, i2, 0)); + }); + const subStep = (p, i2, ii) => new Promise((resolve, reject) => { + if (ii === pathExt.length) + return resolve(step(i2 + 1)); + const ext = pathExt[ii]; + isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { + if (!er && is) { + if (opt.all) + found.push(p + ext); + else + return resolve(p + ext); + } + return resolve(subStep(p, i2, ii + 1)); + }); + }); + return cb ? step(0).then((res) => cb(null, res), cb) : step(0); + }; + var whichSync = (cmd, opt) => { + opt = opt || {}; + const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); + const found = []; + for (let i2 = 0;i2 < pathEnv.length; i2++) { + const ppRaw = pathEnv[i2]; + const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; + const pCmd = path2.join(pathPart, cmd); + const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd; + for (let j = 0;j < pathExt.length; j++) { + const cur = p + pathExt[j]; + try { + const is = isexe.sync(cur, { pathExt: pathExtExe }); + if (is) { + if (opt.all) + found.push(cur); + else + return cur; + } + } catch (ex) {} + } + } + if (opt.all && found.length) + return found; + if (opt.nothrow) + return null; + throw getNotFoundError(cmd); + }; + module.exports = which; + which.sync = whichSync; +}); + +// node_modules/path-key/index.js +var require_path_key = __commonJS((exports, module) => { + var pathKey = (options = {}) => { + const environment = options.env || process.env; + const platform2 = options.platform || process.platform; + if (platform2 !== "win32") { + return "PATH"; + } + return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path"; + }; + module.exports = pathKey; + module.exports.default = pathKey; +}); + +// node_modules/cross-spawn/lib/util/resolveCommand.js +var require_resolveCommand = __commonJS((exports, module) => { + var path2 = __require("path"); + var which = require_which(); + var getPathKey = require_path_key(); + function resolveCommandAttempt(parsed, withoutPathExt) { + const env2 = parsed.options.env || process.env; + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; + if (shouldSwitchCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) {} + } + let resolved; + try { + resolved = which.sync(parsed.command, { + path: env2[getPathKey({ env: env2 })], + pathExt: withoutPathExt ? path2.delimiter : undefined + }); + } catch (e2) {} finally { + if (shouldSwitchCwd) { + process.chdir(cwd); + } + } + if (resolved) { + resolved = path2.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved); + } + return resolved; + } + function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); + } + module.exports = resolveCommand; +}); + +// node_modules/cross-spawn/lib/util/escape.js +var require_escape = __commonJS((exports, module) => { + var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + function escapeCommand(arg) { + arg = arg.replace(metaCharsRegExp, "^$1"); + return arg; + } + function escapeArgument(arg, doubleEscapeMetaChars) { + arg = `${arg}`; + arg = arg.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\""); + arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1"); + arg = `"${arg}"`; + arg = arg.replace(metaCharsRegExp, "^$1"); + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, "^$1"); + } + return arg; + } + exports.command = escapeCommand; + exports.argument = escapeArgument; +}); + +// node_modules/shebang-regex/index.js +var require_shebang_regex = __commonJS((exports, module) => { + module.exports = /^#!(.*)/; +}); + +// node_modules/shebang-command/index.js +var require_shebang_command = __commonJS((exports, module) => { + var shebangRegex = require_shebang_regex(); + module.exports = (string = "") => { + const match = string.match(shebangRegex); + if (!match) { + return null; + } + const [path2, argument] = match[0].replace(/#! ?/, "").split(" "); + const binary = path2.split("/").pop(); + if (binary === "env") { + return argument; + } + return argument ? `${binary} ${argument}` : binary; + }; +}); + +// node_modules/cross-spawn/lib/util/readShebang.js +var require_readShebang = __commonJS((exports, module) => { + var fs2 = __require("fs"); + var shebangCommand = require_shebang_command(); + function readShebang(command) { + const size = 150; + const buffer = Buffer.alloc(size); + let fd; + try { + fd = fs2.openSync(command, "r"); + fs2.readSync(fd, buffer, 0, size, 0); + fs2.closeSync(fd); + } catch (e2) {} + return shebangCommand(buffer.toString()); + } + module.exports = readShebang; +}); + +// node_modules/cross-spawn/lib/parse.js +var require_parse2 = __commonJS((exports, module) => { + var path2 = __require("path"); + var resolveCommand = require_resolveCommand(); + var escape = require_escape(); + var readShebang = require_readShebang(); + var isWin = process.platform === "win32"; + var isExecutableRegExp = /\.(?:com|exe)$/i; + var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + const shebang = parsed.file && readShebang(parsed.file); + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + return resolveCommand(parsed); + } + return parsed.file; + } + function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } + const commandFile = detectShebang(parsed); + const needsShell = !isExecutableRegExp.test(commandFile); + if (parsed.options.forceShell || needsShell) { + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + parsed.command = path2.normalize(parsed.command); + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + const shellCommand = [parsed.command].concat(parsed.args).join(" "); + parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`]; + parsed.command = process.env.comspec || "cmd.exe"; + parsed.options.windowsVerbatimArguments = true; + } + return parsed; + } + function parse2(command, args, options) { + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + args = args ? args.slice(0) : []; + options = Object.assign({}, options); + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args + } + }; + return options.shell ? parsed : parseNonShell(parsed); + } + module.exports = parse2; +}); + +// node_modules/cross-spawn/lib/enoent.js +var require_enoent = __commonJS((exports, module) => { + var isWin = process.platform === "win32"; + function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: "ENOENT", + errno: "ENOENT", + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args + }); + } + function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + const originalEmit = cp.emit; + cp.emit = function(name, arg1) { + if (name === "exit") { + const err = verifyENOENT(arg1, parsed); + if (err) { + return originalEmit.call(cp, "error", err); + } + } + return originalEmit.apply(cp, arguments); + }; + } + function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, "spawn"); + } + return null; + } + function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, "spawnSync"); + } + return null; + } + module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError + }; +}); + +// node_modules/cross-spawn/index.js +var require_cross_spawn = __commonJS((exports, module) => { + var cp = __require("child_process"); + var parse2 = require_parse2(); + var enoent = require_enoent(); + function spawn(command, args, options) { + const parsed = parse2(command, args, options); + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + enoent.hookChildProcess(spawned, parsed); + return spawned; + } + function spawnSync(command, args, options) { + const parsed = parse2(command, args, options); + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + return result; + } + module.exports = spawn; + module.exports.spawn = spawn; + module.exports.sync = spawnSync; + module.exports._parse = parse2; + module.exports._enoent = enoent; +}); + +// node_modules/npm-run-path/node_modules/path-key/index.js +function pathKey(options = {}) { + const { + env: env2 = process.env, + platform: platform2 = process.platform + } = options; + if (platform2 !== "win32") { + return "PATH"; + } + return Object.keys(env2).reverse().find((key) => key.toUpperCase() === "PATH") || "Path"; +} + +// node_modules/unicorn-magic/node.js +import { promisify as promisify2 } from "node:util"; +import { execFile as execFileCallback, execFileSync as execFileSyncOriginal } from "node:child_process"; +import path2 from "node:path"; +import { fileURLToPath as fileURLToPath2 } from "node:url"; +function toPath(urlOrPath) { + return urlOrPath instanceof URL ? fileURLToPath2(urlOrPath) : urlOrPath; +} +function traversePathUp(startPath) { + return { + *[Symbol.iterator]() { + let currentPath = path2.resolve(toPath(startPath)); + let previousPath; + while (previousPath !== currentPath) { + yield currentPath; + previousPath = currentPath; + currentPath = path2.resolve(currentPath, ".."); + } + } + }; +} +var execFileOriginal, TEN_MEGABYTES_IN_BYTES; +var init_node = __esm(() => { + execFileOriginal = promisify2(execFileCallback); + TEN_MEGABYTES_IN_BYTES = 10 * 1024 * 1024; +}); + +// node_modules/npm-run-path/index.js +import process5 from "node:process"; +import path3 from "node:path"; +var npmRunPath = ({ + cwd = process5.cwd(), + path: pathOption = process5.env[pathKey()], + preferLocal = true, + execPath = process5.execPath, + addExecPath = true +} = {}) => { + const cwdPath = path3.resolve(toPath(cwd)); + const result = []; + const pathParts = pathOption.split(path3.delimiter); + if (preferLocal) { + applyPreferLocal(result, pathParts, cwdPath); + } + if (addExecPath) { + applyExecPath(result, pathParts, execPath, cwdPath); + } + return pathOption === "" || pathOption === path3.delimiter ? `${result.join(path3.delimiter)}${pathOption}` : [...result, pathOption].join(path3.delimiter); +}, applyPreferLocal = (result, pathParts, cwdPath) => { + for (const directory of traversePathUp(cwdPath)) { + const pathPart = path3.join(directory, "node_modules/.bin"); + if (!pathParts.includes(pathPart)) { + result.push(pathPart); + } + } +}, applyExecPath = (result, pathParts, execPath, cwdPath) => { + const pathPart = path3.resolve(cwdPath, toPath(execPath), ".."); + if (!pathParts.includes(pathPart)) { + result.push(pathPart); + } +}, npmRunPathEnv = ({ env: env2 = process5.env, ...options } = {}) => { + env2 = { ...env2 }; + const pathName = pathKey({ env: env2 }); + options.path = env2[pathName]; + env2[pathName] = npmRunPath(options); + return env2; +}; +var init_npm_run_path = __esm(() => { + init_node(); +}); + +// node_modules/execa/lib/return/final-error.js +var getFinalError = (originalError, message, isSync) => { + const ErrorClass = isSync ? ExecaSyncError : ExecaError; + const options = originalError instanceof DiscardedError ? {} : { cause: originalError }; + return new ErrorClass(message, options); +}, DiscardedError, setErrorName = (ErrorClass, value) => { + Object.defineProperty(ErrorClass.prototype, "name", { + value, + writable: true, + enumerable: false, + configurable: true + }); + Object.defineProperty(ErrorClass.prototype, execaErrorSymbol, { + value: true, + writable: false, + enumerable: false, + configurable: false + }); +}, isExecaError = (error) => isErrorInstance(error) && (execaErrorSymbol in error), execaErrorSymbol, isErrorInstance = (value) => Object.prototype.toString.call(value) === "[object Error]", ExecaError, ExecaSyncError; +var init_final_error = __esm(() => { + DiscardedError = class DiscardedError extends Error { + }; + execaErrorSymbol = Symbol("isExecaError"); + ExecaError = class ExecaError extends Error { + }; + setErrorName(ExecaError, ExecaError.name); + ExecaSyncError = class ExecaSyncError extends Error { + }; + setErrorName(ExecaSyncError, ExecaSyncError.name); +}); + +// node_modules/human-signals/build/src/realtime.js +var getRealtimeSignals = () => { + const length = SIGRTMAX - SIGRTMIN + 1; + return Array.from({ length }, getRealtimeSignal); +}, getRealtimeSignal = (value, index) => ({ + name: `SIGRT${index + 1}`, + number: SIGRTMIN + index, + action: "terminate", + description: "Application-specific signal (realtime)", + standard: "posix" +}), SIGRTMIN = 34, SIGRTMAX = 64; + +// node_modules/human-signals/build/src/core.js +var SIGNALS; +var init_core = __esm(() => { + SIGNALS = [ + { + name: "SIGHUP", + number: 1, + action: "terminate", + description: "Terminal closed", + standard: "posix" + }, + { + name: "SIGINT", + number: 2, + action: "terminate", + description: "User interruption with CTRL-C", + standard: "ansi" + }, + { + name: "SIGQUIT", + number: 3, + action: "core", + description: "User interruption with CTRL-\\", + standard: "posix" + }, + { + name: "SIGILL", + number: 4, + action: "core", + description: "Invalid machine instruction", + standard: "ansi" + }, + { + name: "SIGTRAP", + number: 5, + action: "core", + description: "Debugger breakpoint", + standard: "posix" + }, + { + name: "SIGABRT", + number: 6, + action: "core", + description: "Aborted", + standard: "ansi" + }, + { + name: "SIGIOT", + number: 6, + action: "core", + description: "Aborted", + standard: "bsd" + }, + { + name: "SIGBUS", + number: 7, + action: "core", + description: "Bus error due to misaligned, non-existing address or paging error", + standard: "bsd" + }, + { + name: "SIGEMT", + number: 7, + action: "terminate", + description: "Command should be emulated but is not implemented", + standard: "other" + }, + { + name: "SIGFPE", + number: 8, + action: "core", + description: "Floating point arithmetic error", + standard: "ansi" + }, + { + name: "SIGKILL", + number: 9, + action: "terminate", + description: "Forced termination", + standard: "posix", + forced: true + }, + { + name: "SIGUSR1", + number: 10, + action: "terminate", + description: "Application-specific signal", + standard: "posix" + }, + { + name: "SIGSEGV", + number: 11, + action: "core", + description: "Segmentation fault", + standard: "ansi" + }, + { + name: "SIGUSR2", + number: 12, + action: "terminate", + description: "Application-specific signal", + standard: "posix" + }, + { + name: "SIGPIPE", + number: 13, + action: "terminate", + description: "Broken pipe or socket", + standard: "posix" + }, + { + name: "SIGALRM", + number: 14, + action: "terminate", + description: "Timeout or timer", + standard: "posix" + }, + { + name: "SIGTERM", + number: 15, + action: "terminate", + description: "Termination", + standard: "ansi" + }, + { + name: "SIGSTKFLT", + number: 16, + action: "terminate", + description: "Stack is empty or overflowed", + standard: "other" + }, + { + name: "SIGCHLD", + number: 17, + action: "ignore", + description: "Child process terminated, paused or unpaused", + standard: "posix" + }, + { + name: "SIGCLD", + number: 17, + action: "ignore", + description: "Child process terminated, paused or unpaused", + standard: "other" + }, + { + name: "SIGCONT", + number: 18, + action: "unpause", + description: "Unpaused", + standard: "posix", + forced: true + }, + { + name: "SIGSTOP", + number: 19, + action: "pause", + description: "Paused", + standard: "posix", + forced: true + }, + { + name: "SIGTSTP", + number: 20, + action: "pause", + description: 'Paused using CTRL-Z or "suspend"', + standard: "posix" + }, + { + name: "SIGTTIN", + number: 21, + action: "pause", + description: "Background process cannot read terminal input", + standard: "posix" + }, + { + name: "SIGBREAK", + number: 21, + action: "terminate", + description: "User interruption with CTRL-BREAK", + standard: "other" + }, + { + name: "SIGTTOU", + number: 22, + action: "pause", + description: "Background process cannot write to terminal output", + standard: "posix" + }, + { + name: "SIGURG", + number: 23, + action: "ignore", + description: "Socket received out-of-band data", + standard: "bsd" + }, + { + name: "SIGXCPU", + number: 24, + action: "core", + description: "Process timed out", + standard: "bsd" + }, + { + name: "SIGXFSZ", + number: 25, + action: "core", + description: "File too big", + standard: "bsd" + }, + { + name: "SIGVTALRM", + number: 26, + action: "terminate", + description: "Timeout or timer", + standard: "bsd" + }, + { + name: "SIGPROF", + number: 27, + action: "terminate", + description: "Timeout or timer", + standard: "bsd" + }, + { + name: "SIGWINCH", + number: 28, + action: "ignore", + description: "Terminal window size changed", + standard: "bsd" + }, + { + name: "SIGIO", + number: 29, + action: "terminate", + description: "I/O is available", + standard: "other" + }, + { + name: "SIGPOLL", + number: 29, + action: "terminate", + description: "Watched event", + standard: "other" + }, + { + name: "SIGINFO", + number: 29, + action: "ignore", + description: "Request for process information", + standard: "other" + }, + { + name: "SIGPWR", + number: 30, + action: "terminate", + description: "Device running out of power", + standard: "systemv" + }, + { + name: "SIGSYS", + number: 31, + action: "core", + description: "Invalid system call", + standard: "other" + }, + { + name: "SIGUNUSED", + number: 31, + action: "terminate", + description: "Invalid system call", + standard: "other" + } + ]; +}); + +// node_modules/human-signals/build/src/signals.js +import { constants } from "node:os"; +var getSignals = () => { + const realtimeSignals = getRealtimeSignals(); + const signals = [...SIGNALS, ...realtimeSignals].map(normalizeSignal); + return signals; +}, normalizeSignal = ({ + name, + number: defaultNumber, + description, + action, + forced = false, + standard +}) => { + const { + signals: { [name]: constantSignal } + } = constants; + const supported = constantSignal !== undefined; + const number = supported ? constantSignal : defaultNumber; + return { name, number, description, supported, action, forced, standard }; +}; +var init_signals = __esm(() => { + init_core(); +}); + +// node_modules/human-signals/build/src/main.js +import { constants as constants2 } from "node:os"; +var getSignalsByName = () => { + const signals = getSignals(); + return Object.fromEntries(signals.map(getSignalByName)); +}, getSignalByName = ({ + name, + number, + description, + supported, + action, + forced, + standard +}) => [name, { name, number, description, supported, action, forced, standard }], signalsByName, getSignalsByNumber = () => { + const signals = getSignals(); + const length = SIGRTMAX + 1; + const signalsA = Array.from({ length }, (value, number) => getSignalByNumber(number, signals)); + return Object.assign({}, ...signalsA); +}, getSignalByNumber = (number, signals) => { + const signal = findSignalByNumber(number, signals); + if (signal === undefined) { + return {}; + } + const { name, description, supported, action, forced, standard } = signal; + return { + [number]: { + name, + number, + description, + supported, + action, + forced, + standard + } + }; +}, findSignalByNumber = (number, signals) => { + const signal = signals.find(({ name }) => constants2.signals[name] === number); + if (signal !== undefined) { + return signal; + } + return signals.find((signalA) => signalA.number === number); +}, signalsByNumber; +var init_main2 = __esm(() => { + init_signals(); + signalsByName = getSignalsByName(); + signalsByNumber = getSignalsByNumber(); +}); + +// node_modules/execa/lib/terminate/signal.js +import { constants as constants3 } from "node:os"; +var normalizeKillSignal = (killSignal) => { + const optionName = "option `killSignal`"; + if (killSignal === 0) { + throw new TypeError(`Invalid ${optionName}: 0 cannot be used.`); + } + return normalizeSignal2(killSignal, optionName); +}, normalizeSignalArgument = (signal) => signal === 0 ? signal : normalizeSignal2(signal, "`subprocess.kill()`'s argument"), normalizeSignal2 = (signalNameOrInteger, optionName) => { + if (Number.isInteger(signalNameOrInteger)) { + return normalizeSignalInteger(signalNameOrInteger, optionName); + } + if (typeof signalNameOrInteger === "string") { + return normalizeSignalName(signalNameOrInteger, optionName); + } + throw new TypeError(`Invalid ${optionName} ${String(signalNameOrInteger)}: it must be a string or an integer. +${getAvailableSignals()}`); +}, normalizeSignalInteger = (signalInteger, optionName) => { + if (signalsIntegerToName.has(signalInteger)) { + return signalsIntegerToName.get(signalInteger); + } + throw new TypeError(`Invalid ${optionName} ${signalInteger}: this signal integer does not exist. +${getAvailableSignals()}`); +}, getSignalsIntegerToName = () => new Map(Object.entries(constants3.signals).reverse().map(([signalName, signalInteger]) => [signalInteger, signalName])), signalsIntegerToName, normalizeSignalName = (signalName, optionName) => { + if (signalName in constants3.signals) { + return signalName; + } + if (signalName.toUpperCase() in constants3.signals) { + throw new TypeError(`Invalid ${optionName} '${signalName}': please rename it to '${signalName.toUpperCase()}'.`); + } + throw new TypeError(`Invalid ${optionName} '${signalName}': this signal name does not exist. +${getAvailableSignals()}`); +}, getAvailableSignals = () => `Available signal names: ${getAvailableSignalNames()}. +Available signal numbers: ${getAvailableSignalIntegers()}.`, getAvailableSignalNames = () => Object.keys(constants3.signals).sort().map((signalName) => `'${signalName}'`).join(", "), getAvailableSignalIntegers = () => [...new Set(Object.values(constants3.signals).sort((signalInteger, signalIntegerTwo) => signalInteger - signalIntegerTwo))].join(", "), getSignalDescription = (signal) => signalsByName[signal].description; +var init_signal = __esm(() => { + init_main2(); + signalsIntegerToName = getSignalsIntegerToName(); +}); + +// node_modules/execa/lib/terminate/kill.js +import { setTimeout as setTimeout2 } from "node:timers/promises"; +var normalizeForceKillAfterDelay = (forceKillAfterDelay) => { + if (forceKillAfterDelay === false) { + return forceKillAfterDelay; + } + if (forceKillAfterDelay === true) { + return DEFAULT_FORCE_KILL_TIMEOUT; + } + if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) { + throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`); + } + return forceKillAfterDelay; +}, DEFAULT_FORCE_KILL_TIMEOUT, subprocessKill = ({ kill, options: { forceKillAfterDelay, killSignal }, onInternalError, context: context3, controller }, signalOrError, errorArgument) => { + const { signal, error } = parseKillArguments(signalOrError, errorArgument, killSignal); + emitKillError(error, onInternalError); + const killResult = kill(signal); + setKillTimeout({ + kill, + signal, + forceKillAfterDelay, + killSignal, + killResult, + context: context3, + controller + }); + return killResult; +}, parseKillArguments = (signalOrError, errorArgument, killSignal) => { + const [signal = killSignal, error] = isErrorInstance(signalOrError) ? [undefined, signalOrError] : [signalOrError, errorArgument]; + if (typeof signal !== "string" && !Number.isInteger(signal)) { + throw new TypeError(`The first argument must be an error instance or a signal name string/integer: ${String(signal)}`); + } + if (error !== undefined && !isErrorInstance(error)) { + throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`); + } + return { signal: normalizeSignalArgument(signal), error }; +}, emitKillError = (error, onInternalError) => { + if (error !== undefined) { + onInternalError.reject(error); + } +}, setKillTimeout = async ({ kill, signal, forceKillAfterDelay, killSignal, killResult, context: context3, controller }) => { + if (signal === killSignal && killResult) { + killOnTimeout({ + kill, + forceKillAfterDelay, + context: context3, + controllerSignal: controller.signal + }); + } +}, killOnTimeout = async ({ kill, forceKillAfterDelay, context: context3, controllerSignal }) => { + if (forceKillAfterDelay === false) { + return; + } + try { + await setTimeout2(forceKillAfterDelay, undefined, { signal: controllerSignal }); + if (kill("SIGKILL")) { + context3.isForcefullyTerminated ??= true; + } + } catch {} +}; +var init_kill = __esm(() => { + init_final_error(); + init_signal(); + DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; +}); + +// node_modules/execa/lib/utils/abort-signal.js +import { once } from "node:events"; +var onAbortedSignal = async (mainSignal, stopSignal) => { + if (!mainSignal.aborted) { + await once(mainSignal, "abort", { signal: stopSignal }); + } +}; +var init_abort_signal = () => {}; + +// node_modules/execa/lib/terminate/cancel.js +var validateCancelSignal = ({ cancelSignal }) => { + if (cancelSignal !== undefined && Object.prototype.toString.call(cancelSignal) !== "[object AbortSignal]") { + throw new Error(`The \`cancelSignal\` option must be an AbortSignal: ${String(cancelSignal)}`); + } +}, throwOnCancel = ({ subprocess, cancelSignal, gracefulCancel, context: context3, controller }) => cancelSignal === undefined || gracefulCancel ? [] : [terminateOnCancel(subprocess, cancelSignal, context3, controller)], terminateOnCancel = async (subprocess, cancelSignal, context3, { signal }) => { + await onAbortedSignal(cancelSignal, signal); + context3.terminationReason ??= "cancel"; + subprocess.kill(); + throw cancelSignal.reason; +}; +var init_cancel = __esm(() => { + init_abort_signal(); +}); + +// node_modules/execa/lib/ipc/validation.js +var validateIpcMethod = ({ methodName, isSubprocess, ipc, isConnected }) => { + validateIpcOption(methodName, isSubprocess, ipc); + validateConnection(methodName, isSubprocess, isConnected); +}, validateIpcOption = (methodName, isSubprocess, ipc) => { + if (!ipc) { + throw new Error(`${getMethodName(methodName, isSubprocess)} can only be used if the \`ipc\` option is \`true\`.`); + } +}, validateConnection = (methodName, isSubprocess, isConnected) => { + if (!isConnected) { + throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`); + } +}, throwOnEarlyDisconnect = (isSubprocess) => { + throw new Error(`${getMethodName("getOneMessage", isSubprocess)} could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`); +}, throwOnStrictDeadlockError = (isSubprocess) => { + throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is sending a message too, instead of listening to incoming messages. +This can be fixed by both sending a message and listening to incoming messages at the same time: + +const [receivedMessage] = await Promise.all([ + ${getMethodName("getOneMessage", isSubprocess)}, + ${getMethodName("sendMessage", isSubprocess, "message, {strict: true}")}, +]);`); +}, getStrictResponseError = (error, isSubprocess) => new Error(`${getMethodName("sendMessage", isSubprocess)} failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, { cause: error }), throwOnMissingStrict = (isSubprocess) => { + throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`); +}, throwOnStrictDisconnect = (isSubprocess) => { + throw new Error(`${getMethodName("sendMessage", isSubprocess)} failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`); +}, getAbortDisconnectError = () => new Error(`\`cancelSignal\` aborted: the ${getOtherProcessName(true)} disconnected.`), throwOnMissingParent = () => { + throw new Error("`getCancelSignal()` cannot be used without setting the `cancelSignal` subprocess option."); +}, handleEpipeError = ({ error, methodName, isSubprocess }) => { + if (error.code === "EPIPE") { + throw new Error(`${getMethodName(methodName, isSubprocess)} cannot be used: the ${getOtherProcessName(isSubprocess)} is disconnecting.`, { cause: error }); + } +}, handleSerializationError = ({ error, methodName, isSubprocess, message }) => { + if (isSerializationError(error)) { + throw new Error(`${getMethodName(methodName, isSubprocess)}'s argument type is invalid: the message cannot be serialized: ${String(message)}.`, { cause: error }); + } +}, isSerializationError = ({ code, message }) => SERIALIZATION_ERROR_CODES.has(code) || SERIALIZATION_ERROR_MESSAGES.some((serializationErrorMessage) => message.includes(serializationErrorMessage)), SERIALIZATION_ERROR_CODES, SERIALIZATION_ERROR_MESSAGES, getMethodName = (methodName, isSubprocess, parameters = "") => methodName === "cancelSignal" ? "`cancelSignal`'s `controller.abort()`" : `${getNamespaceName(isSubprocess)}${methodName}(${parameters})`, getNamespaceName = (isSubprocess) => isSubprocess ? "" : "subprocess.", getOtherProcessName = (isSubprocess) => isSubprocess ? "parent process" : "subprocess", disconnect = (anyProcess) => { + if (anyProcess.connected) { + anyProcess.disconnect(); + } +}; +var init_validation = __esm(() => { + SERIALIZATION_ERROR_CODES = new Set([ + "ERR_MISSING_ARGS", + "ERR_INVALID_ARG_TYPE" + ]); + SERIALIZATION_ERROR_MESSAGES = [ + "could not be cloned", + "circular structure", + "call stack size exceeded" + ]; +}); + +// node_modules/execa/lib/utils/deferred.js +var createDeferred = () => { + const methods = {}; + const promise = new Promise((resolve, reject) => { + Object.assign(methods, { resolve, reject }); + }); + return Object.assign(promise, methods); +}; + +// node_modules/execa/lib/arguments/fd-options.js +var getToStream = (destination, to = "stdin") => { + const isWritable = true; + const { options, fileDescriptors } = SUBPROCESS_OPTIONS.get(destination); + const fdNumber = getFdNumber(fileDescriptors, to, isWritable); + const destinationStream = destination.stdio[fdNumber]; + if (destinationStream === null) { + throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable)); + } + return destinationStream; +}, getFromStream = (source, from = "stdout") => { + const isWritable = false; + const { options, fileDescriptors } = SUBPROCESS_OPTIONS.get(source); + const fdNumber = getFdNumber(fileDescriptors, from, isWritable); + const sourceStream = fdNumber === "all" ? source.all : source.stdio[fdNumber]; + if (sourceStream === null || sourceStream === undefined) { + throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable)); + } + return sourceStream; +}, SUBPROCESS_OPTIONS, getFdNumber = (fileDescriptors, fdName, isWritable) => { + const fdNumber = parseFdNumber(fdName, isWritable); + validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors); + return fdNumber; +}, parseFdNumber = (fdName, isWritable) => { + const fdNumber = parseFd(fdName); + if (fdNumber !== undefined) { + return fdNumber; + } + const { validOptions, defaultValue } = isWritable ? { validOptions: '"stdin"', defaultValue: "stdin" } : { validOptions: '"stdout", "stderr", "all"', defaultValue: "stdout" }; + throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}". +It must be ${validOptions} or "fd3", "fd4" (and so on). +It is optional and defaults to "${defaultValue}".`); +}, validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => { + const fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)]; + if (fileDescriptor === undefined) { + throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist. +Please set the "stdio" option to ensure that file descriptor exists.`); + } + if (fileDescriptor.direction === "input" && !isWritable) { + throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`); + } + if (fileDescriptor.direction !== "input" && isWritable) { + throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`); + } +}, getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => { + if (fdNumber === "all" && !options.all) { + return `The "all" option must be true to use "from: 'all'".`; + } + const { optionName, optionValue } = getInvalidStdioOption(fdNumber, options); + return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}". +Please set this option with "pipe" instead.`; +}, getInvalidStdioOption = (fdNumber, { stdin, stdout, stderr, stdio }) => { + const usedDescriptor = getUsedDescriptor(fdNumber); + if (usedDescriptor === 0 && stdin !== undefined) { + return { optionName: "stdin", optionValue: stdin }; + } + if (usedDescriptor === 1 && stdout !== undefined) { + return { optionName: "stdout", optionValue: stdout }; + } + if (usedDescriptor === 2 && stderr !== undefined) { + return { optionName: "stderr", optionValue: stderr }; + } + return { optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor] }; +}, getUsedDescriptor = (fdNumber) => fdNumber === "all" ? 1 : fdNumber, getOptionName = (isWritable) => isWritable ? "to" : "from", serializeOptionValue = (value) => { + if (typeof value === "string") { + return `'${value}'`; + } + return typeof value === "number" ? `${value}` : "Stream"; +}; +var init_fd_options = __esm(() => { + init_specific(); + SUBPROCESS_OPTIONS = new WeakMap; +}); + +// node_modules/execa/lib/utils/max-listeners.js +import { addAbortListener } from "node:events"; +var incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => { + const maxListeners = eventEmitter.getMaxListeners(); + if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) { + return; + } + eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement); + addAbortListener(signal, () => { + eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement); + }); +}; +var init_max_listeners = () => {}; + +// node_modules/execa/lib/ipc/reference.js +var addReference = (channel, reference) => { + if (reference) { + addReferenceCount(channel); + } +}, addReferenceCount = (channel) => { + channel.refCounted(); +}, removeReference = (channel, reference) => { + if (reference) { + removeReferenceCount(channel); + } +}, removeReferenceCount = (channel) => { + channel.unrefCounted(); +}, undoAddedReferences = (channel, isSubprocess) => { + if (isSubprocess) { + removeReferenceCount(channel); + removeReferenceCount(channel); + } +}, redoAddedReferences = (channel, isSubprocess) => { + if (isSubprocess) { + addReferenceCount(channel); + addReferenceCount(channel); + } +}; + +// node_modules/execa/lib/ipc/incoming.js +import { once as once2 } from "node:events"; +import { scheduler } from "node:timers/promises"; +var onMessage = async ({ anyProcess, channel, isSubprocess, ipcEmitter }, wrappedMessage) => { + if (handleStrictResponse(wrappedMessage) || handleAbort(wrappedMessage)) { + return; + } + if (!INCOMING_MESSAGES.has(anyProcess)) { + INCOMING_MESSAGES.set(anyProcess, []); + } + const incomingMessages = INCOMING_MESSAGES.get(anyProcess); + incomingMessages.push(wrappedMessage); + if (incomingMessages.length > 1) { + return; + } + while (incomingMessages.length > 0) { + await waitForOutgoingMessages(anyProcess, ipcEmitter, wrappedMessage); + await scheduler.yield(); + const message = await handleStrictRequest({ + wrappedMessage: incomingMessages[0], + anyProcess, + channel, + isSubprocess, + ipcEmitter + }); + incomingMessages.shift(); + ipcEmitter.emit("message", message); + ipcEmitter.emit("message:done"); + } +}, onDisconnect = async ({ anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage }) => { + abortOnDisconnect(); + const incomingMessages = INCOMING_MESSAGES.get(anyProcess); + while (incomingMessages?.length > 0) { + await once2(ipcEmitter, "message:done"); + } + anyProcess.removeListener("message", boundOnMessage); + redoAddedReferences(channel, isSubprocess); + ipcEmitter.connected = false; + ipcEmitter.emit("disconnect"); +}, INCOMING_MESSAGES; +var init_incoming = __esm(() => { + init_outgoing(); + init_strict(); + init_graceful(); + INCOMING_MESSAGES = new WeakMap; +}); + +// node_modules/execa/lib/ipc/forward.js +import { EventEmitter } from "node:events"; +var getIpcEmitter = (anyProcess, channel, isSubprocess) => { + if (IPC_EMITTERS.has(anyProcess)) { + return IPC_EMITTERS.get(anyProcess); + } + const ipcEmitter = new EventEmitter; + ipcEmitter.connected = true; + IPC_EMITTERS.set(anyProcess, ipcEmitter); + forwardEvents({ + ipcEmitter, + anyProcess, + channel, + isSubprocess + }); + return ipcEmitter; +}, IPC_EMITTERS, forwardEvents = ({ ipcEmitter, anyProcess, channel, isSubprocess }) => { + const boundOnMessage = onMessage.bind(undefined, { + anyProcess, + channel, + isSubprocess, + ipcEmitter + }); + anyProcess.on("message", boundOnMessage); + anyProcess.once("disconnect", onDisconnect.bind(undefined, { + anyProcess, + channel, + isSubprocess, + ipcEmitter, + boundOnMessage + })); + undoAddedReferences(channel, isSubprocess); +}, isConnected = (anyProcess) => { + const ipcEmitter = IPC_EMITTERS.get(anyProcess); + return ipcEmitter === undefined ? anyProcess.channel !== null : ipcEmitter.connected; +}; +var init_forward = __esm(() => { + init_incoming(); + IPC_EMITTERS = new WeakMap; +}); + +// node_modules/execa/lib/ipc/strict.js +import { once as once3 } from "node:events"; +var handleSendStrict = ({ anyProcess, channel, isSubprocess, message, strict }) => { + if (!strict) { + return message; + } + const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess); + const hasListeners = hasMessageListeners(anyProcess, ipcEmitter); + return { + id: count++, + type: REQUEST_TYPE, + message, + hasListeners + }; +}, count = 0n, validateStrictDeadlock = (outgoingMessages, wrappedMessage) => { + if (wrappedMessage?.type !== REQUEST_TYPE || wrappedMessage.hasListeners) { + return; + } + for (const { id } of outgoingMessages) { + if (id !== undefined) { + STRICT_RESPONSES[id].resolve({ isDeadlock: true, hasListeners: false }); + } + } +}, handleStrictRequest = async ({ wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter }) => { + if (wrappedMessage?.type !== REQUEST_TYPE || !anyProcess.connected) { + return wrappedMessage; + } + const { id, message } = wrappedMessage; + const response = { id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter) }; + try { + await sendMessage({ + anyProcess, + channel, + isSubprocess, + ipc: true + }, response); + } catch (error) { + ipcEmitter.emit("strict:error", error); + } + return message; +}, handleStrictResponse = (wrappedMessage) => { + if (wrappedMessage?.type !== RESPONSE_TYPE) { + return false; + } + const { id, message: hasListeners } = wrappedMessage; + STRICT_RESPONSES[id]?.resolve({ isDeadlock: false, hasListeners }); + return true; +}, waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => { + if (wrappedMessage?.type !== REQUEST_TYPE) { + return; + } + const deferred = createDeferred(); + STRICT_RESPONSES[wrappedMessage.id] = deferred; + const controller = new AbortController; + try { + const { isDeadlock, hasListeners } = await Promise.race([ + deferred, + throwOnDisconnect(anyProcess, isSubprocess, controller) + ]); + if (isDeadlock) { + throwOnStrictDeadlockError(isSubprocess); + } + if (!hasListeners) { + throwOnMissingStrict(isSubprocess); + } + } finally { + controller.abort(); + delete STRICT_RESPONSES[wrappedMessage.id]; + } +}, STRICT_RESPONSES, throwOnDisconnect = async (anyProcess, isSubprocess, { signal }) => { + incrementMaxListeners(anyProcess, 1, signal); + await once3(anyProcess, "disconnect", { signal }); + throwOnStrictDisconnect(isSubprocess); +}, REQUEST_TYPE = "execa:ipc:request", RESPONSE_TYPE = "execa:ipc:response"; +var init_strict = __esm(() => { + init_max_listeners(); + init_send(); + init_validation(); + init_forward(); + init_outgoing(); + STRICT_RESPONSES = {}; +}); + +// node_modules/execa/lib/ipc/outgoing.js +var startSendMessage = (anyProcess, wrappedMessage, strict) => { + if (!OUTGOING_MESSAGES.has(anyProcess)) { + OUTGOING_MESSAGES.set(anyProcess, new Set); + } + const outgoingMessages = OUTGOING_MESSAGES.get(anyProcess); + const onMessageSent = createDeferred(); + const id = strict ? wrappedMessage.id : undefined; + const outgoingMessage = { onMessageSent, id }; + outgoingMessages.add(outgoingMessage); + return { outgoingMessages, outgoingMessage }; +}, endSendMessage = ({ outgoingMessages, outgoingMessage }) => { + outgoingMessages.delete(outgoingMessage); + outgoingMessage.onMessageSent.resolve(); +}, waitForOutgoingMessages = async (anyProcess, ipcEmitter, wrappedMessage) => { + while (!hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0) { + const outgoingMessages = [...OUTGOING_MESSAGES.get(anyProcess)]; + validateStrictDeadlock(outgoingMessages, wrappedMessage); + await Promise.all(outgoingMessages.map(({ onMessageSent }) => onMessageSent)); + } +}, OUTGOING_MESSAGES, hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount("message") > getMinListenerCount(anyProcess), getMinListenerCount = (anyProcess) => SUBPROCESS_OPTIONS.has(anyProcess) && !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, "ipc") ? 1 : 0; +var init_outgoing = __esm(() => { + init_specific(); + init_fd_options(); + init_strict(); + OUTGOING_MESSAGES = new WeakMap; +}); + +// node_modules/execa/lib/ipc/send.js +import { promisify as promisify3 } from "node:util"; +var sendMessage = ({ anyProcess, channel, isSubprocess, ipc }, message, { strict = false } = {}) => { + const methodName = "sendMessage"; + validateIpcMethod({ + methodName, + isSubprocess, + ipc, + isConnected: anyProcess.connected + }); + return sendMessageAsync({ + anyProcess, + channel, + methodName, + isSubprocess, + message, + strict + }); +}, sendMessageAsync = async ({ anyProcess, channel, methodName, isSubprocess, message, strict }) => { + const wrappedMessage = handleSendStrict({ + anyProcess, + channel, + isSubprocess, + message, + strict + }); + const outgoingMessagesState = startSendMessage(anyProcess, wrappedMessage, strict); + try { + await sendOneMessage({ + anyProcess, + methodName, + isSubprocess, + wrappedMessage, + message + }); + } catch (error) { + disconnect(anyProcess); + throw error; + } finally { + endSendMessage(outgoingMessagesState); + } +}, sendOneMessage = async ({ anyProcess, methodName, isSubprocess, wrappedMessage, message }) => { + const sendMethod = getSendMethod(anyProcess); + try { + await Promise.all([ + waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess), + sendMethod(wrappedMessage) + ]); + } catch (error) { + handleEpipeError({ error, methodName, isSubprocess }); + handleSerializationError({ + error, + methodName, + isSubprocess, + message + }); + throw error; + } +}, getSendMethod = (anyProcess) => { + if (PROCESS_SEND_METHODS.has(anyProcess)) { + return PROCESS_SEND_METHODS.get(anyProcess); + } + const sendMethod = promisify3(anyProcess.send.bind(anyProcess)); + PROCESS_SEND_METHODS.set(anyProcess, sendMethod); + return sendMethod; +}, PROCESS_SEND_METHODS; +var init_send = __esm(() => { + init_validation(); + init_outgoing(); + init_strict(); + PROCESS_SEND_METHODS = new WeakMap; +}); + +// node_modules/execa/lib/ipc/graceful.js +import { scheduler as scheduler2 } from "node:timers/promises"; +var sendAbort = (subprocess, message) => { + const methodName = "cancelSignal"; + validateConnection(methodName, false, subprocess.connected); + return sendOneMessage({ + anyProcess: subprocess, + methodName, + isSubprocess: false, + wrappedMessage: { type: GRACEFUL_CANCEL_TYPE, message }, + message + }); +}, getCancelSignal = async ({ anyProcess, channel, isSubprocess, ipc }) => { + await startIpc({ + anyProcess, + channel, + isSubprocess, + ipc + }); + return cancelController.signal; +}, startIpc = async ({ anyProcess, channel, isSubprocess, ipc }) => { + if (cancelListening) { + return; + } + cancelListening = true; + if (!ipc) { + throwOnMissingParent(); + return; + } + if (channel === null) { + abortOnDisconnect(); + return; + } + getIpcEmitter(anyProcess, channel, isSubprocess); + await scheduler2.yield(); +}, cancelListening = false, handleAbort = (wrappedMessage) => { + if (wrappedMessage?.type !== GRACEFUL_CANCEL_TYPE) { + return false; + } + cancelController.abort(wrappedMessage.message); + return true; +}, GRACEFUL_CANCEL_TYPE = "execa:ipc:cancel", abortOnDisconnect = () => { + cancelController.abort(getAbortDisconnectError()); +}, cancelController; +var init_graceful = __esm(() => { + init_send(); + init_forward(); + init_validation(); + cancelController = new AbortController; +}); + +// node_modules/execa/lib/terminate/graceful.js +var validateGracefulCancel = ({ gracefulCancel, cancelSignal, ipc, serialization }) => { + if (!gracefulCancel) { + return; + } + if (cancelSignal === undefined) { + throw new Error("The `cancelSignal` option must be defined when setting the `gracefulCancel` option."); + } + if (!ipc) { + throw new Error("The `ipc` option cannot be false when setting the `gracefulCancel` option."); + } + if (serialization === "json") { + throw new Error("The `serialization` option cannot be 'json' when setting the `gracefulCancel` option."); + } +}, throwOnGracefulCancel = ({ + subprocess, + cancelSignal, + gracefulCancel, + forceKillAfterDelay, + context: context3, + controller +}) => gracefulCancel ? [sendOnAbort({ + subprocess, + cancelSignal, + forceKillAfterDelay, + context: context3, + controller +})] : [], sendOnAbort = async ({ subprocess, cancelSignal, forceKillAfterDelay, context: context3, controller: { signal } }) => { + await onAbortedSignal(cancelSignal, signal); + const reason = getReason(cancelSignal); + await sendAbort(subprocess, reason); + killOnTimeout({ + kill: subprocess.kill, + forceKillAfterDelay, + context: context3, + controllerSignal: signal + }); + context3.terminationReason ??= "gracefulCancel"; + throw cancelSignal.reason; +}, getReason = ({ reason }) => { + if (!(reason instanceof DOMException)) { + return reason; + } + const error = new Error(reason.message); + Object.defineProperty(error, "stack", { + value: reason.stack, + enumerable: false, + configurable: true, + writable: true + }); + return error; +}; +var init_graceful2 = __esm(() => { + init_abort_signal(); + init_graceful(); + init_kill(); +}); + +// node_modules/execa/lib/terminate/timeout.js +import { setTimeout as setTimeout3 } from "node:timers/promises"; +var validateTimeout = ({ timeout }) => { + if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { + throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); + } +}, throwOnTimeout = (subprocess, timeout, context3, controller) => timeout === 0 || timeout === undefined ? [] : [killAfterTimeout(subprocess, timeout, context3, controller)], killAfterTimeout = async (subprocess, timeout, context3, { signal }) => { + await setTimeout3(timeout, undefined, { signal }); + context3.terminationReason ??= "timeout"; + subprocess.kill(); + throw new DiscardedError; +}; +var init_timeout = __esm(() => { + init_final_error(); +}); + +// node_modules/execa/lib/methods/node.js +import { execPath, execArgv } from "node:process"; +import path4 from "node:path"; +var mapNode = ({ options }) => { + if (options.node === false) { + throw new TypeError('The "node" option cannot be false with `execaNode()`.'); + } + return { options: { ...options, node: true } }; +}, handleNodeOption = (file, commandArguments, { + node: shouldHandleNode = false, + nodePath = execPath, + nodeOptions = execArgv.filter((nodeOption) => !nodeOption.startsWith("--inspect")), + cwd, + execPath: formerNodePath, + ...options +}) => { + if (formerNodePath !== undefined) { + throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.'); + } + const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option'); + const resolvedNodePath = path4.resolve(cwd, normalizedNodePath); + const newOptions = { + ...options, + nodePath: resolvedNodePath, + node: shouldHandleNode, + cwd + }; + if (!shouldHandleNode) { + return [file, commandArguments, newOptions]; + } + if (path4.basename(file, ".exe") === "node") { + throw new TypeError('When the "node" option is true, the first argument does not need to be "node".'); + } + return [ + resolvedNodePath, + [...nodeOptions, file, ...commandArguments], + { ipc: true, ...newOptions, shell: false } + ]; +}; +var init_node2 = __esm(() => { + init_file_url(); +}); + +// node_modules/execa/lib/ipc/ipc-input.js +import { serialize } from "node:v8"; +var validateIpcInputOption = ({ ipcInput, ipc, serialization }) => { + if (ipcInput === undefined) { + return; + } + if (!ipc) { + throw new Error("The `ipcInput` option cannot be set unless the `ipc` option is `true`."); + } + validateIpcInput[serialization](ipcInput); +}, validateAdvancedInput = (ipcInput) => { + try { + serialize(ipcInput); + } catch (error) { + throw new Error("The `ipcInput` option is not serializable with a structured clone.", { cause: error }); + } +}, validateJsonInput = (ipcInput) => { + try { + JSON.stringify(ipcInput); + } catch (error) { + throw new Error("The `ipcInput` option is not serializable with JSON.", { cause: error }); + } +}, validateIpcInput, sendIpcInput = async (subprocess, ipcInput) => { + if (ipcInput === undefined) { + return; + } + await subprocess.sendMessage(ipcInput); +}; +var init_ipc_input = __esm(() => { + validateIpcInput = { + advanced: validateAdvancedInput, + json: validateJsonInput + }; +}); + +// node_modules/execa/lib/arguments/encoding-option.js +var validateEncoding = ({ encoding }) => { + if (ENCODINGS.has(encoding)) { + return; + } + const correctEncoding = getCorrectEncoding(encoding); + if (correctEncoding !== undefined) { + throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`. +Please rename it to ${serializeEncoding(correctEncoding)}.`); + } + const correctEncodings = [...ENCODINGS].map((correctEncoding2) => serializeEncoding(correctEncoding2)).join(", "); + throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`. +Please rename it to one of: ${correctEncodings}.`); +}, TEXT_ENCODINGS, BINARY_ENCODINGS, ENCODINGS, getCorrectEncoding = (encoding) => { + if (encoding === null) { + return "buffer"; + } + if (typeof encoding !== "string") { + return; + } + const lowerEncoding = encoding.toLowerCase(); + if (lowerEncoding in ENCODING_ALIASES) { + return ENCODING_ALIASES[lowerEncoding]; + } + if (ENCODINGS.has(lowerEncoding)) { + return lowerEncoding; + } +}, ENCODING_ALIASES, serializeEncoding = (encoding) => typeof encoding === "string" ? `"${encoding}"` : String(encoding); +var init_encoding_option = __esm(() => { + TEXT_ENCODINGS = new Set(["utf8", "utf16le"]); + BINARY_ENCODINGS = new Set(["buffer", "hex", "base64", "base64url", "latin1", "ascii"]); + ENCODINGS = new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]); + ENCODING_ALIASES = { + "utf-8": "utf8", + "utf-16le": "utf16le", + "ucs-2": "utf16le", + ucs2: "utf16le", + binary: "latin1" + }; +}); + +// node_modules/execa/lib/arguments/cwd.js +import { statSync as statSync2 } from "node:fs"; +import path5 from "node:path"; +import process6 from "node:process"; +var normalizeCwd = (cwd = getDefaultCwd()) => { + const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option'); + return path5.resolve(cwdString); +}, getDefaultCwd = () => { + try { + return process6.cwd(); + } catch (error) { + error.message = `The current directory does not exist. +${error.message}`; + throw error; + } +}, fixCwdError = (originalMessage, cwd) => { + if (cwd === getDefaultCwd()) { + return originalMessage; + } + let cwdStat; + try { + cwdStat = statSync2(cwd); + } catch (error) { + return `The "cwd" option is invalid: ${cwd}. +${error.message} +${originalMessage}`; + } + if (!cwdStat.isDirectory()) { + return `The "cwd" option is not a directory: ${cwd}. +${originalMessage}`; + } + return originalMessage; +}; +var init_cwd = __esm(() => { + init_file_url(); +}); + +// node_modules/execa/lib/arguments/options.js +import path6 from "node:path"; +import process7 from "node:process"; +var import_cross_spawn, normalizeOptions = (filePath, rawArguments, rawOptions) => { + rawOptions.cwd = normalizeCwd(rawOptions.cwd); + const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, rawOptions); + const { command: file, args: commandArguments, options: initialOptions } = import_cross_spawn.default._parse(processedFile, processedArguments, processedOptions); + const fdOptions = normalizeFdSpecificOptions(initialOptions); + const options = addDefaultOptions(fdOptions); + validateTimeout(options); + validateEncoding(options); + validateIpcInputOption(options); + validateCancelSignal(options); + validateGracefulCancel(options); + options.shell = normalizeFileUrl(options.shell); + options.env = getEnv(options); + options.killSignal = normalizeKillSignal(options.killSignal); + options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay); + options.lines = options.lines.map((lines, fdNumber) => lines && !BINARY_ENCODINGS.has(options.encoding) && options.buffer[fdNumber]); + if (process7.platform === "win32" && path6.basename(file, ".exe") === "cmd") { + commandArguments.unshift("/q"); + } + return { file, commandArguments, options }; +}, addDefaultOptions = ({ + extendEnv = true, + preferLocal = false, + cwd, + localDir: localDirectory = cwd, + encoding = "utf8", + reject = true, + cleanup = true, + all = false, + windowsHide = true, + killSignal = "SIGTERM", + forceKillAfterDelay = true, + gracefulCancel = false, + ipcInput, + ipc = ipcInput !== undefined || gracefulCancel, + serialization = "advanced", + ...options +}) => ({ + ...options, + extendEnv, + preferLocal, + cwd, + localDirectory, + encoding, + reject, + cleanup, + all, + windowsHide, + killSignal, + forceKillAfterDelay, + gracefulCancel, + ipcInput, + ipc, + serialization +}), getEnv = ({ env: envOption, extendEnv, preferLocal, node, localDirectory, nodePath }) => { + const env2 = extendEnv ? { ...process7.env, ...envOption } : envOption; + if (preferLocal || node) { + return npmRunPathEnv({ + env: env2, + cwd: localDirectory, + execPath: nodePath, + preferLocal, + addExecPath: node + }); + } + return env2; +}; +var init_options = __esm(() => { + init_npm_run_path(); + init_kill(); + init_signal(); + init_cancel(); + init_graceful2(); + init_timeout(); + init_node2(); + init_ipc_input(); + init_encoding_option(); + init_cwd(); + init_file_url(); + init_specific(); + import_cross_spawn = __toESM(require_cross_spawn(), 1); +}); + +// node_modules/execa/lib/arguments/shell.js +var concatenateShell = (file, commandArguments, options) => options.shell && commandArguments.length > 0 ? [[file, ...commandArguments].join(" "), [], options] : [file, commandArguments, options]; + +// node_modules/strip-final-newline/index.js +function stripFinalNewline(input) { + if (typeof input === "string") { + return stripFinalNewlineString(input); + } + if (!(ArrayBuffer.isView(input) && input.BYTES_PER_ELEMENT === 1)) { + throw new Error("Input must be a string or a Uint8Array"); + } + return stripFinalNewlineBinary(input); +} +var stripFinalNewlineString = (input) => input.at(-1) === LF2 ? input.slice(0, input.at(-2) === CR2 ? -2 : -1) : input, stripFinalNewlineBinary = (input) => input.at(-1) === LF_BINARY ? input.subarray(0, input.at(-2) === CR_BINARY ? -2 : -1) : input, LF2 = ` +`, LF_BINARY, CR2 = "\r", CR_BINARY; +var init_strip_final_newline = __esm(() => { + LF_BINARY = LF2.codePointAt(0); + CR_BINARY = CR2.codePointAt(0); +}); + +// node_modules/is-stream/index.js +function isStream(stream, { checkOpen = true } = {}) { + return stream !== null && typeof stream === "object" && (stream.writable || stream.readable || !checkOpen || stream.writable === undefined && stream.readable === undefined) && typeof stream.pipe === "function"; +} +function isWritableStream(stream, { checkOpen = true } = {}) { + return isStream(stream, { checkOpen }) && (stream.writable || !checkOpen) && typeof stream.write === "function" && typeof stream.end === "function" && typeof stream.writable === "boolean" && typeof stream.writableObjectMode === "boolean" && typeof stream.destroy === "function" && typeof stream.destroyed === "boolean"; +} +function isReadableStream(stream, { checkOpen = true } = {}) { + return isStream(stream, { checkOpen }) && (stream.readable || !checkOpen) && typeof stream.read === "function" && typeof stream.readable === "boolean" && typeof stream.readableObjectMode === "boolean" && typeof stream.destroy === "function" && typeof stream.destroyed === "boolean"; +} +function isDuplexStream(stream, options) { + return isWritableStream(stream, options) && isReadableStream(stream, options); +} + +// node_modules/@sec-ant/readable-stream/dist/ponyfill/asyncIterator.js +class c { + #t; + #n; + #r = false; + #e = undefined; + constructor(e2, t2) { + this.#t = e2, this.#n = t2; + } + next() { + const e2 = () => this.#s(); + return this.#e = this.#e ? this.#e.then(e2, e2) : e2(), this.#e; + } + return(e2) { + const t2 = () => this.#i(e2); + return this.#e ? this.#e.then(t2, t2) : t2(); + } + async#s() { + if (this.#r) + return { + done: true, + value: undefined + }; + let e2; + try { + e2 = await this.#t.read(); + } catch (t2) { + throw this.#e = undefined, this.#r = true, this.#t.releaseLock(), t2; + } + return e2.done && (this.#e = undefined, this.#r = true, this.#t.releaseLock()), e2; + } + async#i(e2) { + if (this.#r) + return { + done: true, + value: e2 + }; + if (this.#r = true, !this.#n) { + const t2 = this.#t.cancel(e2); + return this.#t.releaseLock(), await t2, { + done: true, + value: e2 + }; + } + return this.#t.releaseLock(), { + done: true, + value: e2 + }; + } +} +function i2() { + return this[n].next(); +} +function o(r2) { + return this[n].return(r2); +} +function h2({ preventCancel: r2 = false } = {}) { + const e2 = this.getReader(), t2 = new c(e2, r2), s2 = Object.create(u); + return s2[n] = t2, s2; +} +var a, n, u; +var init_asyncIterator = __esm(() => { + a = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype); + n = Symbol(); + Object.defineProperty(i2, "name", { value: "next" }); + Object.defineProperty(o, "name", { value: "return" }); + u = Object.create(a, { + next: { + enumerable: true, + configurable: true, + writable: true, + value: i2 + }, + return: { + enumerable: true, + configurable: true, + writable: true, + value: o + } + }); +}); + +// node_modules/@sec-ant/readable-stream/dist/ponyfill/fromAnyIterable.js +var init_fromAnyIterable = () => {}; + +// node_modules/@sec-ant/readable-stream/dist/ponyfill/index.js +var init_ponyfill = __esm(() => { + init_asyncIterator(); + init_fromAnyIterable(); +}); + +// node_modules/get-stream/source/stream.js +var getAsyncIterable = (stream) => { + if (isReadableStream(stream, { checkOpen: false }) && nodeImports.on !== undefined) { + return getStreamIterable(stream); + } + if (typeof stream?.[Symbol.asyncIterator] === "function") { + return stream; + } + if (toString.call(stream) === "[object ReadableStream]") { + return h2.call(stream); + } + throw new TypeError("The first argument must be a Readable, a ReadableStream, or an async iterable."); +}, toString, getStreamIterable = async function* (stream) { + const controller = new AbortController; + const state = {}; + handleStreamEnd(stream, controller, state); + try { + for await (const [chunk] of nodeImports.on(stream, "data", { signal: controller.signal })) { + yield chunk; + } + } catch (error) { + if (state.error !== undefined) { + throw state.error; + } else if (!controller.signal.aborted) { + throw error; + } + } finally { + stream.destroy(); + } +}, handleStreamEnd = async (stream, controller, state) => { + try { + await nodeImports.finished(stream, { + cleanup: true, + readable: true, + writable: false, + error: false + }); + } catch (error) { + state.error = error; + } finally { + controller.abort(); + } +}, nodeImports; +var init_stream = __esm(() => { + init_ponyfill(); + ({ toString } = Object.prototype); + nodeImports = {}; +}); + +// node_modules/get-stream/source/contents.js +var getStreamContents = async (stream, { init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize }, { maxBuffer = Number.POSITIVE_INFINITY } = {}) => { + const asyncIterable = getAsyncIterable(stream); + const state = init(); + state.length = 0; + try { + for await (const chunk of asyncIterable) { + const chunkType = getChunkType(chunk); + const convertedChunk = convertChunk[chunkType](chunk, state); + appendChunk({ + convertedChunk, + state, + getSize, + truncateChunk, + addChunk, + maxBuffer + }); + } + appendFinalChunk({ + state, + convertChunk, + getSize, + truncateChunk, + addChunk, + getFinalChunk, + maxBuffer + }); + return finalize(state); + } catch (error) { + const normalizedError = typeof error === "object" && error !== null ? error : new Error(error); + normalizedError.bufferedData = finalize(state); + throw normalizedError; + } +}, appendFinalChunk = ({ state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer }) => { + const convertedChunk = getFinalChunk(state); + if (convertedChunk !== undefined) { + appendChunk({ + convertedChunk, + state, + getSize, + truncateChunk, + addChunk, + maxBuffer + }); + } +}, appendChunk = ({ convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer }) => { + const chunkSize = getSize(convertedChunk); + const newLength = state.length + chunkSize; + if (newLength <= maxBuffer) { + addNewChunk(convertedChunk, state, addChunk, newLength); + return; + } + const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length); + if (truncatedChunk !== undefined) { + addNewChunk(truncatedChunk, state, addChunk, maxBuffer); + } + throw new MaxBufferError; +}, addNewChunk = (convertedChunk, state, addChunk, newLength) => { + state.contents = addChunk(convertedChunk, state, newLength); + state.length = newLength; +}, getChunkType = (chunk) => { + const typeOfChunk = typeof chunk; + if (typeOfChunk === "string") { + return "string"; + } + if (typeOfChunk !== "object" || chunk === null) { + return "others"; + } + if (globalThis.Buffer?.isBuffer(chunk)) { + return "buffer"; + } + const prototypeName = objectToString2.call(chunk); + if (prototypeName === "[object ArrayBuffer]") { + return "arrayBuffer"; + } + if (prototypeName === "[object DataView]") { + return "dataView"; + } + if (Number.isInteger(chunk.byteLength) && Number.isInteger(chunk.byteOffset) && objectToString2.call(chunk.buffer) === "[object ArrayBuffer]") { + return "typedArray"; + } + return "others"; +}, objectToString2, MaxBufferError; +var init_contents = __esm(() => { + init_stream(); + ({ toString: objectToString2 } = Object.prototype); + MaxBufferError = class MaxBufferError extends Error { + name = "MaxBufferError"; + constructor() { + super("maxBuffer exceeded"); + } + }; +}); + +// node_modules/get-stream/source/utils.js +var identity2 = (value) => value, noop2 = () => { + return; +}, getContentsProperty = ({ contents }) => contents, throwObjectStream = (chunk) => { + throw new Error(`Streams in object mode are not supported: ${String(chunk)}`); +}, getLengthProperty = (convertedChunk) => convertedChunk.length; + +// node_modules/get-stream/source/array.js +async function getStreamAsArray(stream, options) { + return getStreamContents(stream, arrayMethods, options); +} +var initArray = () => ({ contents: [] }), increment = () => 1, addArrayChunk = (convertedChunk, { contents }) => { + contents.push(convertedChunk); + return contents; +}, arrayMethods; +var init_array = __esm(() => { + init_contents(); + arrayMethods = { + init: initArray, + convertChunk: { + string: identity2, + buffer: identity2, + arrayBuffer: identity2, + dataView: identity2, + typedArray: identity2, + others: identity2 + }, + getSize: increment, + truncateChunk: noop2, + addChunk: addArrayChunk, + getFinalChunk: noop2, + finalize: getContentsProperty + }; +}); + +// node_modules/get-stream/source/array-buffer.js +async function getStreamAsArrayBuffer(stream, options) { + return getStreamContents(stream, arrayBufferMethods, options); +} +var initArrayBuffer = () => ({ contents: new ArrayBuffer(0) }), useTextEncoder = (chunk) => textEncoder2.encode(chunk), textEncoder2, useUint8Array = (chunk) => new Uint8Array(chunk), useUint8ArrayWithOffset = (chunk) => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength), truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize), addArrayBufferChunk = (convertedChunk, { contents, length: previousLength }, length) => { + const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length); + new Uint8Array(newContents).set(convertedChunk, previousLength); + return newContents; +}, resizeArrayBufferSlow = (contents, length) => { + if (length <= contents.byteLength) { + return contents; + } + const arrayBuffer = new ArrayBuffer(getNewContentsLength(length)); + new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); + return arrayBuffer; +}, resizeArrayBuffer = (contents, length) => { + if (length <= contents.maxByteLength) { + contents.resize(length); + return contents; + } + const arrayBuffer = new ArrayBuffer(length, { maxByteLength: getNewContentsLength(length) }); + new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); + return arrayBuffer; +}, getNewContentsLength = (length) => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)), SCALE_FACTOR = 2, finalizeArrayBuffer = ({ contents, length }) => hasArrayBufferResize() ? contents : contents.slice(0, length), hasArrayBufferResize = () => ("resize" in ArrayBuffer.prototype), arrayBufferMethods; +var init_array_buffer = __esm(() => { + init_contents(); + textEncoder2 = new TextEncoder; + arrayBufferMethods = { + init: initArrayBuffer, + convertChunk: { + string: useTextEncoder, + buffer: useUint8Array, + arrayBuffer: useUint8Array, + dataView: useUint8ArrayWithOffset, + typedArray: useUint8ArrayWithOffset, + others: throwObjectStream + }, + getSize: getLengthProperty, + truncateChunk: truncateArrayBufferChunk, + addChunk: addArrayBufferChunk, + getFinalChunk: noop2, + finalize: finalizeArrayBuffer + }; +}); + +// node_modules/get-stream/source/string.js +async function getStreamAsString(stream, options) { + return getStreamContents(stream, stringMethods, options); +} +var initString = () => ({ contents: "", textDecoder: new TextDecoder }), useTextDecoder = (chunk, { textDecoder: textDecoder2 }) => textDecoder2.decode(chunk, { stream: true }), addStringChunk = (convertedChunk, { contents }) => contents + convertedChunk, truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize), getFinalStringChunk = ({ textDecoder: textDecoder2 }) => { + const finalChunk = textDecoder2.decode(); + return finalChunk === "" ? undefined : finalChunk; +}, stringMethods; +var init_string = __esm(() => { + init_contents(); + stringMethods = { + init: initString, + convertChunk: { + string: identity2, + buffer: useTextDecoder, + arrayBuffer: useTextDecoder, + dataView: useTextDecoder, + typedArray: useTextDecoder, + others: throwObjectStream + }, + getSize: getLengthProperty, + truncateChunk: truncateStringChunk, + addChunk: addStringChunk, + getFinalChunk: getFinalStringChunk, + finalize: getContentsProperty + }; +}); + +// node_modules/get-stream/source/exports.js +var init_exports = __esm(() => { + init_array(); + init_array_buffer(); + init_string(); + init_contents(); +}); + +// node_modules/get-stream/source/index.js +import { on } from "node:events"; +import { finished } from "node:stream/promises"; +var init_source = __esm(() => { + init_stream(); + init_exports(); + Object.assign(nodeImports, { on, finished }); +}); + +// node_modules/execa/lib/io/max-buffer.js +var handleMaxBuffer = ({ error, stream, readableObjectMode, lines, encoding, fdNumber }) => { + if (!(error instanceof MaxBufferError)) { + throw error; + } + if (fdNumber === "all") { + return error; + } + const unit = getMaxBufferUnit(readableObjectMode, lines, encoding); + error.maxBufferInfo = { fdNumber, unit }; + stream.destroy(); + throw error; +}, getMaxBufferUnit = (readableObjectMode, lines, encoding) => { + if (readableObjectMode) { + return "objects"; + } + if (lines) { + return "lines"; + } + if (encoding === "buffer") { + return "bytes"; + } + return "characters"; +}, checkIpcMaxBuffer = (subprocess, ipcOutput, maxBuffer) => { + if (ipcOutput.length !== maxBuffer) { + return; + } + const error = new MaxBufferError; + error.maxBufferInfo = { fdNumber: "ipc" }; + throw error; +}, getMaxBufferMessage = (error, maxBuffer) => { + const { streamName, threshold, unit } = getMaxBufferInfo(error, maxBuffer); + return `Command's ${streamName} was larger than ${threshold} ${unit}`; +}, getMaxBufferInfo = (error, maxBuffer) => { + if (error?.maxBufferInfo === undefined) { + return { streamName: "output", threshold: maxBuffer[1], unit: "bytes" }; + } + const { maxBufferInfo: { fdNumber, unit } } = error; + delete error.maxBufferInfo; + const threshold = getFdSpecificValue(maxBuffer, fdNumber); + if (fdNumber === "ipc") { + return { streamName: "IPC output", threshold, unit: "messages" }; + } + return { streamName: getStreamName(fdNumber), threshold, unit }; +}, isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === "ENOBUFS" && output !== null && output.some((result) => result !== null && result.length > getMaxBufferSync(maxBuffer)), truncateMaxBufferSync = (result, isMaxBuffer, maxBuffer) => { + if (!isMaxBuffer) { + return result; + } + const maxBufferValue = getMaxBufferSync(maxBuffer); + return result.length > maxBufferValue ? result.slice(0, maxBufferValue) : result; +}, getMaxBufferSync = ([, stdoutMaxBuffer]) => stdoutMaxBuffer; +var init_max_buffer = __esm(() => { + init_source(); + init_standard_stream(); + init_specific(); +}); + +// node_modules/execa/lib/return/message.js +import { inspect as inspect2 } from "node:util"; +var createMessages = ({ + stdio, + all, + ipcOutput, + originalError, + signal, + signalDescription, + exitCode, + escapedCommand, + timedOut, + isCanceled, + isGracefullyCanceled, + isMaxBuffer, + isForcefullyTerminated, + forceKillAfterDelay, + killSignal, + maxBuffer, + timeout, + cwd +}) => { + const errorCode = originalError?.code; + const prefix = getErrorPrefix({ + originalError, + timedOut, + timeout, + isMaxBuffer, + maxBuffer, + errorCode, + signal, + signalDescription, + exitCode, + isCanceled, + isGracefullyCanceled, + isForcefullyTerminated, + forceKillAfterDelay, + killSignal + }); + const originalMessage = getOriginalMessage(originalError, cwd); + const suffix = originalMessage === undefined ? "" : ` +${originalMessage}`; + const shortMessage = `${prefix}: ${escapedCommand}${suffix}`; + const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all]; + const message = [ + shortMessage, + ...messageStdio, + ...stdio.slice(3), + ipcOutput.map((ipcMessage) => serializeIpcMessage(ipcMessage)).join(` +`) + ].map((messagePart) => escapeLines(stripFinalNewline(serializeMessagePart(messagePart)))).filter(Boolean).join(` + +`); + return { originalMessage, shortMessage, message }; +}, getErrorPrefix = ({ + originalError, + timedOut, + timeout, + isMaxBuffer, + maxBuffer, + errorCode, + signal, + signalDescription, + exitCode, + isCanceled, + isGracefullyCanceled, + isForcefullyTerminated, + forceKillAfterDelay, + killSignal +}) => { + const forcefulSuffix = getForcefulSuffix(isForcefullyTerminated, forceKillAfterDelay); + if (timedOut) { + return `Command timed out after ${timeout} milliseconds${forcefulSuffix}`; + } + if (isGracefullyCanceled) { + if (signal === undefined) { + return `Command was gracefully canceled with exit code ${exitCode}`; + } + return isForcefullyTerminated ? `Command was gracefully canceled${forcefulSuffix}` : `Command was gracefully canceled with ${signal} (${signalDescription})`; + } + if (isCanceled) { + return `Command was canceled${forcefulSuffix}`; + } + if (isMaxBuffer) { + return `${getMaxBufferMessage(originalError, maxBuffer)}${forcefulSuffix}`; + } + if (errorCode !== undefined) { + return `Command failed with ${errorCode}${forcefulSuffix}`; + } + if (isForcefullyTerminated) { + return `Command was killed with ${killSignal} (${getSignalDescription(killSignal)})${forcefulSuffix}`; + } + if (signal !== undefined) { + return `Command was killed with ${signal} (${signalDescription})`; + } + if (exitCode !== undefined) { + return `Command failed with exit code ${exitCode}`; + } + return "Command failed"; +}, getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated ? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds` : "", getOriginalMessage = (originalError, cwd) => { + if (originalError instanceof DiscardedError) { + return; + } + const originalMessage = isExecaError(originalError) ? originalError.originalMessage : String(originalError?.message ?? originalError); + const escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd)); + return escapedOriginalMessage === "" ? undefined : escapedOriginalMessage; +}, serializeIpcMessage = (ipcMessage) => typeof ipcMessage === "string" ? ipcMessage : inspect2(ipcMessage), serializeMessagePart = (messagePart) => Array.isArray(messagePart) ? messagePart.map((messageItem) => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join(` +`) : serializeMessageItem(messagePart), serializeMessageItem = (messageItem) => { + if (typeof messageItem === "string") { + return messageItem; + } + if (isUint8Array(messageItem)) { + return uint8ArrayToString(messageItem); + } + return ""; +}; +var init_message = __esm(() => { + init_strip_final_newline(); + init_uint_array(); + init_cwd(); + init_escape(); + init_max_buffer(); + init_signal(); + init_final_error(); +}); + +// node_modules/execa/lib/return/result.js +var makeSuccessResult = ({ + command, + escapedCommand, + stdio, + all, + ipcOutput, + options: { cwd }, + startTime +}) => omitUndefinedProperties({ + command, + escapedCommand, + cwd, + durationMs: getDurationMs(startTime), + failed: false, + timedOut: false, + isCanceled: false, + isGracefullyCanceled: false, + isTerminated: false, + isMaxBuffer: false, + isForcefullyTerminated: false, + exitCode: 0, + stdout: stdio[1], + stderr: stdio[2], + all, + stdio, + ipcOutput, + pipedFrom: [] +}), makeEarlyError = ({ + error, + command, + escapedCommand, + fileDescriptors, + options, + startTime, + isSync +}) => makeError({ + error, + command, + escapedCommand, + startTime, + timedOut: false, + isCanceled: false, + isGracefullyCanceled: false, + isMaxBuffer: false, + isForcefullyTerminated: false, + stdio: Array.from({ length: fileDescriptors.length }), + ipcOutput: [], + options, + isSync +}), makeError = ({ + error: originalError, + command, + escapedCommand, + startTime, + timedOut, + isCanceled, + isGracefullyCanceled, + isMaxBuffer, + isForcefullyTerminated, + exitCode: rawExitCode, + signal: rawSignal, + stdio, + all, + ipcOutput, + options: { + timeoutDuration, + timeout = timeoutDuration, + forceKillAfterDelay, + killSignal, + cwd, + maxBuffer + }, + isSync +}) => { + const { exitCode, signal, signalDescription } = normalizeExitPayload(rawExitCode, rawSignal); + const { originalMessage, shortMessage, message } = createMessages({ + stdio, + all, + ipcOutput, + originalError, + signal, + signalDescription, + exitCode, + escapedCommand, + timedOut, + isCanceled, + isGracefullyCanceled, + isMaxBuffer, + isForcefullyTerminated, + forceKillAfterDelay, + killSignal, + maxBuffer, + timeout, + cwd + }); + const error = getFinalError(originalError, message, isSync); + Object.assign(error, getErrorProperties({ + error, + command, + escapedCommand, + startTime, + timedOut, + isCanceled, + isGracefullyCanceled, + isMaxBuffer, + isForcefullyTerminated, + exitCode, + signal, + signalDescription, + stdio, + all, + ipcOutput, + cwd, + originalMessage, + shortMessage + })); + return error; +}, getErrorProperties = ({ + error, + command, + escapedCommand, + startTime, + timedOut, + isCanceled, + isGracefullyCanceled, + isMaxBuffer, + isForcefullyTerminated, + exitCode, + signal, + signalDescription, + stdio, + all, + ipcOutput, + cwd, + originalMessage, + shortMessage +}) => omitUndefinedProperties({ + shortMessage, + originalMessage, + command, + escapedCommand, + cwd, + durationMs: getDurationMs(startTime), + failed: true, + timedOut, + isCanceled, + isGracefullyCanceled, + isTerminated: signal !== undefined, + isMaxBuffer, + isForcefullyTerminated, + exitCode, + signal, + signalDescription, + code: error.cause?.code, + stdout: stdio[1], + stderr: stdio[2], + all, + stdio, + ipcOutput, + pipedFrom: [] +}), omitUndefinedProperties = (result) => Object.fromEntries(Object.entries(result).filter(([, value]) => value !== undefined)), normalizeExitPayload = (rawExitCode, rawSignal) => { + const exitCode = rawExitCode === null ? undefined : rawExitCode; + const signal = rawSignal === null ? undefined : rawSignal; + const signalDescription = signal === undefined ? undefined : getSignalDescription(rawSignal); + return { exitCode, signal, signalDescription }; +}; +var init_result = __esm(() => { + init_signal(); + init_duration(); + init_final_error(); + init_message(); +}); + +// node_modules/parse-ms/index.js +function parseNumber(milliseconds) { + return { + days: Math.trunc(milliseconds / 86400000), + hours: Math.trunc(milliseconds / 3600000 % 24), + minutes: Math.trunc(milliseconds / 60000 % 60), + seconds: Math.trunc(milliseconds / 1000 % 60), + milliseconds: Math.trunc(milliseconds % 1000), + microseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1000) % 1000), + nanoseconds: Math.trunc(toZeroIfInfinity(milliseconds * 1e6) % 1000) + }; +} +function parseBigint(milliseconds) { + return { + days: milliseconds / 86400000n, + hours: milliseconds / 3600000n % 24n, + minutes: milliseconds / 60000n % 60n, + seconds: milliseconds / 1000n % 60n, + milliseconds: milliseconds % 1000n, + microseconds: 0n, + nanoseconds: 0n + }; +} +function parseMilliseconds(milliseconds) { + switch (typeof milliseconds) { + case "number": { + if (Number.isFinite(milliseconds)) { + return parseNumber(milliseconds); + } + break; + } + case "bigint": { + return parseBigint(milliseconds); + } + } + throw new TypeError("Expected a finite number or bigint"); +} +var toZeroIfInfinity = (value) => Number.isFinite(value) ? value : 0; + +// node_modules/pretty-ms/index.js +function prettyMilliseconds(milliseconds, options) { + const isBigInt = typeof milliseconds === "bigint"; + if (!isBigInt && !Number.isFinite(milliseconds)) { + throw new TypeError("Expected a finite number or bigint"); + } + options = { ...options }; + const sign = milliseconds < 0 ? "-" : ""; + milliseconds = milliseconds < 0 ? -milliseconds : milliseconds; + if (options.colonNotation) { + options.compact = false; + options.formatSubMilliseconds = false; + options.separateMilliseconds = false; + options.verbose = false; + } + if (options.compact) { + options.unitCount = 1; + options.secondsDecimalDigits = 0; + options.millisecondsDecimalDigits = 0; + } + let result = []; + const floorDecimals = (value, decimalDigits) => { + const flooredInterimValue = Math.floor(value * 10 ** decimalDigits + SECOND_ROUNDING_EPSILON); + const flooredValue = Math.round(flooredInterimValue) / 10 ** decimalDigits; + return flooredValue.toFixed(decimalDigits); + }; + const add = (value, long, short, valueString) => { + if ((result.length === 0 || !options.colonNotation) && isZero(value) && !(options.colonNotation && short === "m")) { + return; + } + valueString ??= String(value); + if (options.colonNotation) { + const wholeDigits = valueString.includes(".") ? valueString.split(".")[0].length : valueString.length; + const minLength = result.length > 0 ? 2 : 1; + valueString = "0".repeat(Math.max(0, minLength - wholeDigits)) + valueString; + } else { + valueString += options.verbose ? " " + pluralize(long, value) : short; + } + result.push(valueString); + }; + const parsed = parseMilliseconds(milliseconds); + const days = BigInt(parsed.days); + if (options.hideYearAndDays) { + add(BigInt(days) * 24n + BigInt(parsed.hours), "hour", "h"); + } else { + if (options.hideYear) { + add(days, "day", "d"); + } else { + add(days / 365n, "year", "y"); + add(days % 365n, "day", "d"); + } + add(Number(parsed.hours), "hour", "h"); + } + add(Number(parsed.minutes), "minute", "m"); + if (!options.hideSeconds) { + if (options.separateMilliseconds || options.formatSubMilliseconds || !options.colonNotation && milliseconds < 1000) { + const seconds = Number(parsed.seconds); + const milliseconds2 = Number(parsed.milliseconds); + const microseconds = Number(parsed.microseconds); + const nanoseconds = Number(parsed.nanoseconds); + add(seconds, "second", "s"); + if (options.formatSubMilliseconds) { + add(milliseconds2, "millisecond", "ms"); + add(microseconds, "microsecond", "µs"); + add(nanoseconds, "nanosecond", "ns"); + } else { + const millisecondsAndBelow = milliseconds2 + microseconds / 1000 + nanoseconds / 1e6; + const millisecondsDecimalDigits = typeof options.millisecondsDecimalDigits === "number" ? options.millisecondsDecimalDigits : 0; + const roundedMilliseconds = millisecondsAndBelow >= 1 ? Math.round(millisecondsAndBelow) : Math.ceil(millisecondsAndBelow); + const millisecondsString = millisecondsDecimalDigits ? millisecondsAndBelow.toFixed(millisecondsDecimalDigits) : roundedMilliseconds; + add(Number.parseFloat(millisecondsString), "millisecond", "ms", millisecondsString); + } + } else { + const seconds = (isBigInt ? Number(milliseconds % ONE_DAY_IN_MILLISECONDS) : milliseconds) / 1000 % 60; + const secondsDecimalDigits = typeof options.secondsDecimalDigits === "number" ? options.secondsDecimalDigits : 1; + const secondsFixed = floorDecimals(seconds, secondsDecimalDigits); + const secondsString = options.keepDecimalsOnWholeSeconds ? secondsFixed : secondsFixed.replace(/\.0+$/, ""); + add(Number.parseFloat(secondsString), "second", "s", secondsString); + } + } + if (result.length === 0) { + return sign + "0" + (options.verbose ? " milliseconds" : "ms"); + } + const separator = options.colonNotation ? ":" : " "; + if (typeof options.unitCount === "number") { + result = result.slice(0, Math.max(options.unitCount, 1)); + } + return sign + result.join(separator); +} +var isZero = (value) => value === 0 || value === 0n, pluralize = (word, count2) => count2 === 1 || count2 === 1n ? word : `${word}s`, SECOND_ROUNDING_EPSILON = 0.0000001, ONE_DAY_IN_MILLISECONDS; +var init_pretty_ms = __esm(() => { + ONE_DAY_IN_MILLISECONDS = 24n * 60n * 60n * 1000n; +}); + +// node_modules/execa/lib/verbose/error.js +var logError = (result, verboseInfo) => { + if (result.failed) { + verboseLog({ + type: "error", + verboseMessage: result.shortMessage, + verboseInfo, + result + }); + } +}; +var init_error = __esm(() => { + init_log(); +}); + +// node_modules/execa/lib/verbose/complete.js +var logResult = (result, verboseInfo) => { + if (!isVerbose(verboseInfo)) { + return; + } + logError(result, verboseInfo); + logDuration(result, verboseInfo); +}, logDuration = (result, verboseInfo) => { + const verboseMessage = `(done in ${prettyMilliseconds(result.durationMs)})`; + verboseLog({ + type: "duration", + verboseMessage, + verboseInfo, + result + }); +}; +var init_complete = __esm(() => { + init_pretty_ms(); + init_values(); + init_log(); + init_error(); +}); + +// node_modules/execa/lib/return/reject.js +var handleResult = (result, verboseInfo, { reject }) => { + logResult(result, verboseInfo); + if (result.failed && reject) { + throw result; + } + return result; +}; +var init_reject = __esm(() => { + init_complete(); +}); + +// node_modules/execa/lib/stdio/type.js +var getStdioItemType = (value, optionName) => { + if (isAsyncGenerator(value)) { + return "asyncGenerator"; + } + if (isSyncGenerator(value)) { + return "generator"; + } + if (isUrl(value)) { + return "fileUrl"; + } + if (isFilePathObject(value)) { + return "filePath"; + } + if (isWebStream(value)) { + return "webStream"; + } + if (isStream(value, { checkOpen: false })) { + return "native"; + } + if (isUint8Array(value)) { + return "uint8Array"; + } + if (isAsyncIterableObject(value)) { + return "asyncIterable"; + } + if (isIterableObject(value)) { + return "iterable"; + } + if (isTransformStream(value)) { + return getTransformStreamType({ transform: value }, optionName); + } + if (isTransformOptions(value)) { + return getTransformObjectType(value, optionName); + } + return "native"; +}, getTransformObjectType = (value, optionName) => { + if (isDuplexStream(value.transform, { checkOpen: false })) { + return getDuplexType(value, optionName); + } + if (isTransformStream(value.transform)) { + return getTransformStreamType(value, optionName); + } + return getGeneratorObjectType(value, optionName); +}, getDuplexType = (value, optionName) => { + validateNonGeneratorType(value, optionName, "Duplex stream"); + return "duplex"; +}, getTransformStreamType = (value, optionName) => { + validateNonGeneratorType(value, optionName, "web TransformStream"); + return "webTransform"; +}, validateNonGeneratorType = ({ final, binary, objectMode }, optionName, typeName) => { + checkUndefinedOption(final, `${optionName}.final`, typeName); + checkUndefinedOption(binary, `${optionName}.binary`, typeName); + checkBooleanOption(objectMode, `${optionName}.objectMode`); +}, checkUndefinedOption = (value, optionName, typeName) => { + if (value !== undefined) { + throw new TypeError(`The \`${optionName}\` option can only be defined when using a generator, not a ${typeName}.`); + } +}, getGeneratorObjectType = ({ transform, final, binary, objectMode }, optionName) => { + if (transform !== undefined && !isGenerator(transform)) { + throw new TypeError(`The \`${optionName}.transform\` option must be a generator, a Duplex stream or a web TransformStream.`); + } + if (isDuplexStream(final, { checkOpen: false })) { + throw new TypeError(`The \`${optionName}.final\` option must not be a Duplex stream.`); + } + if (isTransformStream(final)) { + throw new TypeError(`The \`${optionName}.final\` option must not be a web TransformStream.`); + } + if (final !== undefined && !isGenerator(final)) { + throw new TypeError(`The \`${optionName}.final\` option must be a generator.`); + } + checkBooleanOption(binary, `${optionName}.binary`); + checkBooleanOption(objectMode, `${optionName}.objectMode`); + return isAsyncGenerator(transform) || isAsyncGenerator(final) ? "asyncGenerator" : "generator"; +}, checkBooleanOption = (value, optionName) => { + if (value !== undefined && typeof value !== "boolean") { + throw new TypeError(`The \`${optionName}\` option must use a boolean.`); + } +}, isGenerator = (value) => isAsyncGenerator(value) || isSyncGenerator(value), isAsyncGenerator = (value) => Object.prototype.toString.call(value) === "[object AsyncGeneratorFunction]", isSyncGenerator = (value) => Object.prototype.toString.call(value) === "[object GeneratorFunction]", isTransformOptions = (value) => isPlainObject2(value) && (value.transform !== undefined || value.final !== undefined), isUrl = (value) => Object.prototype.toString.call(value) === "[object URL]", isRegularUrl = (value) => isUrl(value) && value.protocol !== "file:", isFilePathObject = (value) => isPlainObject2(value) && Object.keys(value).length > 0 && Object.keys(value).every((key) => FILE_PATH_KEYS.has(key)) && isFilePathString(value.file), FILE_PATH_KEYS, isFilePathString = (file) => typeof file === "string", isUnknownStdioString = (type, value) => type === "native" && typeof value === "string" && !KNOWN_STDIO_STRINGS.has(value), KNOWN_STDIO_STRINGS, isReadableStream2 = (value) => Object.prototype.toString.call(value) === "[object ReadableStream]", isWritableStream2 = (value) => Object.prototype.toString.call(value) === "[object WritableStream]", isWebStream = (value) => isReadableStream2(value) || isWritableStream2(value), isTransformStream = (value) => isReadableStream2(value?.readable) && isWritableStream2(value?.writable), isAsyncIterableObject = (value) => isObject(value) && typeof value[Symbol.asyncIterator] === "function", isIterableObject = (value) => isObject(value) && typeof value[Symbol.iterator] === "function", isObject = (value) => typeof value === "object" && value !== null, TRANSFORM_TYPES, FILE_TYPES, SPECIAL_DUPLICATE_TYPES_SYNC, SPECIAL_DUPLICATE_TYPES, FORBID_DUPLICATE_TYPES, TYPE_TO_MESSAGE; +var init_type = __esm(() => { + init_uint_array(); + FILE_PATH_KEYS = new Set(["file", "append"]); + KNOWN_STDIO_STRINGS = new Set(["ipc", "ignore", "inherit", "overlapped", "pipe"]); + TRANSFORM_TYPES = new Set(["generator", "asyncGenerator", "duplex", "webTransform"]); + FILE_TYPES = new Set(["fileUrl", "filePath", "fileNumber"]); + SPECIAL_DUPLICATE_TYPES_SYNC = new Set(["fileUrl", "filePath"]); + SPECIAL_DUPLICATE_TYPES = new Set([...SPECIAL_DUPLICATE_TYPES_SYNC, "webStream", "nodeStream"]); + FORBID_DUPLICATE_TYPES = new Set(["webTransform", "duplex"]); + TYPE_TO_MESSAGE = { + generator: "a generator", + asyncGenerator: "an async generator", + fileUrl: "a file URL", + filePath: "a file path string", + fileNumber: "a file descriptor number", + webStream: "a web stream", + nodeStream: "a Node.js stream", + webTransform: "a web TransformStream", + duplex: "a Duplex stream", + native: "any value", + iterable: "an iterable", + asyncIterable: "an async iterable", + string: "a string", + uint8Array: "a Uint8Array" + }; +}); + +// node_modules/execa/lib/transform/object-mode.js +var getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === "output" ? getOutputObjectModes(objectMode, index, newTransforms) : getInputObjectModes(objectMode, index, newTransforms), getOutputObjectModes = (objectMode, index, newTransforms) => { + const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode; + const readableObjectMode = objectMode ?? writableObjectMode; + return { writableObjectMode, readableObjectMode }; +}, getInputObjectModes = (objectMode, index, newTransforms) => { + const writableObjectMode = index === 0 ? objectMode === true : newTransforms[index - 1].value.readableObjectMode; + const readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode); + return { writableObjectMode, readableObjectMode }; +}, getFdObjectMode = (stdioItems, direction) => { + const lastTransform = stdioItems.findLast(({ type }) => TRANSFORM_TYPES.has(type)); + if (lastTransform === undefined) { + return false; + } + return direction === "input" ? lastTransform.value.writableObjectMode : lastTransform.value.readableObjectMode; +}; +var init_object_mode = __esm(() => { + init_type(); +}); + +// node_modules/execa/lib/transform/normalize.js +var normalizeTransforms = (stdioItems, optionName, direction, options) => [ + ...stdioItems.filter(({ type }) => !TRANSFORM_TYPES.has(type)), + ...getTransforms(stdioItems, optionName, direction, options) +], getTransforms = (stdioItems, optionName, direction, { encoding }) => { + const transforms = stdioItems.filter(({ type }) => TRANSFORM_TYPES.has(type)); + const newTransforms = Array.from({ length: transforms.length }); + for (const [index, stdioItem] of Object.entries(transforms)) { + newTransforms[index] = normalizeTransform({ + stdioItem, + index: Number(index), + newTransforms, + optionName, + direction, + encoding + }); + } + return sortTransforms(newTransforms, direction); +}, normalizeTransform = ({ stdioItem, stdioItem: { type }, index, newTransforms, optionName, direction, encoding }) => { + if (type === "duplex") { + return normalizeDuplex({ stdioItem, optionName }); + } + if (type === "webTransform") { + return normalizeTransformStream({ + stdioItem, + index, + newTransforms, + direction + }); + } + return normalizeGenerator({ + stdioItem, + index, + newTransforms, + direction, + encoding + }); +}, normalizeDuplex = ({ + stdioItem, + stdioItem: { + value: { + transform, + transform: { writableObjectMode, readableObjectMode }, + objectMode = readableObjectMode + } + }, + optionName +}) => { + if (objectMode && !readableObjectMode) { + throw new TypeError(`The \`${optionName}.objectMode\` option can only be \`true\` if \`new Duplex({objectMode: true})\` is used.`); + } + if (!objectMode && readableObjectMode) { + throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`); + } + return { + ...stdioItem, + value: { transform, writableObjectMode, readableObjectMode } + }; +}, normalizeTransformStream = ({ stdioItem, stdioItem: { value }, index, newTransforms, direction }) => { + const { transform, objectMode } = isPlainObject2(value) ? value : { transform: value }; + const { writableObjectMode, readableObjectMode } = getTransformObjectModes(objectMode, index, newTransforms, direction); + return { + ...stdioItem, + value: { transform, writableObjectMode, readableObjectMode } + }; +}, normalizeGenerator = ({ stdioItem, stdioItem: { value }, index, newTransforms, direction, encoding }) => { + const { + transform, + final, + binary: binaryOption = false, + preserveNewlines = false, + objectMode + } = isPlainObject2(value) ? value : { transform: value }; + const binary = binaryOption || BINARY_ENCODINGS.has(encoding); + const { writableObjectMode, readableObjectMode } = getTransformObjectModes(objectMode, index, newTransforms, direction); + return { + ...stdioItem, + value: { + transform, + final, + binary, + preserveNewlines, + writableObjectMode, + readableObjectMode + } + }; +}, sortTransforms = (newTransforms, direction) => direction === "input" ? newTransforms.reverse() : newTransforms; +var init_normalize = __esm(() => { + init_encoding_option(); + init_type(); + init_object_mode(); +}); + +// node_modules/execa/lib/stdio/direction.js +import process8 from "node:process"; +var getStreamDirection = (stdioItems, fdNumber, optionName) => { + const directions = stdioItems.map((stdioItem) => getStdioItemDirection(stdioItem, fdNumber)); + if (directions.includes("input") && directions.includes("output")) { + throw new TypeError(`The \`${optionName}\` option must not be an array of both readable and writable values.`); + } + return directions.find(Boolean) ?? DEFAULT_DIRECTION; +}, getStdioItemDirection = ({ type, value }, fdNumber) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value), KNOWN_DIRECTIONS, anyDirection = () => { + return; +}, alwaysInput = () => "input", guessStreamDirection, getStandardStreamDirection = (value) => { + if ([0, process8.stdin].includes(value)) { + return "input"; + } + if ([1, 2, process8.stdout, process8.stderr].includes(value)) { + return "output"; + } +}, DEFAULT_DIRECTION = "output"; +var init_direction = __esm(() => { + init_type(); + KNOWN_DIRECTIONS = ["input", "output", "output"]; + guessStreamDirection = { + generator: anyDirection, + asyncGenerator: anyDirection, + fileUrl: anyDirection, + filePath: anyDirection, + iterable: alwaysInput, + asyncIterable: alwaysInput, + uint8Array: alwaysInput, + webStream: (value) => isWritableStream2(value) ? "output" : "input", + nodeStream(value) { + if (!isReadableStream(value, { checkOpen: false })) { + return "output"; + } + return isWritableStream(value, { checkOpen: false }) ? undefined : "input"; + }, + webTransform: anyDirection, + duplex: anyDirection, + native(value) { + const standardStreamDirection = getStandardStreamDirection(value); + if (standardStreamDirection !== undefined) { + return standardStreamDirection; + } + if (isStream(value, { checkOpen: false })) { + return guessStreamDirection.nodeStream(value); + } + } + }; +}); + +// node_modules/execa/lib/ipc/array.js +var normalizeIpcStdioArray = (stdioArray, ipc) => ipc && !stdioArray.includes("ipc") ? [...stdioArray, "ipc"] : stdioArray; + +// node_modules/execa/lib/stdio/stdio-option.js +var normalizeStdioOption = ({ stdio, ipc, buffer, ...options }, verboseInfo, isSync) => { + const stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue2(stdioOption, fdNumber)); + return isSync ? normalizeStdioSync(stdioArray, buffer, verboseInfo) : normalizeIpcStdioArray(stdioArray, ipc); +}, getStdioArray = (stdio, options) => { + if (stdio === undefined) { + return STANDARD_STREAMS_ALIASES.map((alias) => options[alias]); + } + if (hasAlias(options)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${STANDARD_STREAMS_ALIASES.map((alias) => `\`${alias}\``).join(", ")}`); + } + if (typeof stdio === "string") { + return [stdio, stdio, stdio]; + } + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length); + return Array.from({ length }, (_, fdNumber) => stdio[fdNumber]); +}, hasAlias = (options) => STANDARD_STREAMS_ALIASES.some((alias) => options[alias] !== undefined), addDefaultValue2 = (stdioOption, fdNumber) => { + if (Array.isArray(stdioOption)) { + return stdioOption.map((item) => addDefaultValue2(item, fdNumber)); + } + if (stdioOption === null || stdioOption === undefined) { + return fdNumber >= STANDARD_STREAMS_ALIASES.length ? "ignore" : "pipe"; + } + return stdioOption; +}, normalizeStdioSync = (stdioArray, buffer, verboseInfo) => stdioArray.map((stdioOption, fdNumber) => !buffer[fdNumber] && fdNumber !== 0 && !isFullVerbose(verboseInfo, fdNumber) && isOutputPipeOnly(stdioOption) ? "ignore" : stdioOption), isOutputPipeOnly = (stdioOption) => stdioOption === "pipe" || Array.isArray(stdioOption) && stdioOption.every((item) => item === "pipe"); +var init_stdio_option = __esm(() => { + init_standard_stream(); + init_values(); +}); + +// node_modules/execa/lib/stdio/native.js +import { readFileSync } from "node:fs"; +import tty2 from "node:tty"; +var handleNativeStream = ({ stdioItem, stdioItem: { type }, isStdioArray, fdNumber, direction, isSync }) => { + if (!isStdioArray || type !== "native") { + return stdioItem; + } + return isSync ? handleNativeStreamSync({ stdioItem, fdNumber, direction }) : handleNativeStreamAsync({ stdioItem, fdNumber }); +}, handleNativeStreamSync = ({ stdioItem, stdioItem: { value, optionName }, fdNumber, direction }) => { + const targetFd = getTargetFd({ + value, + optionName, + fdNumber, + direction + }); + if (targetFd !== undefined) { + return targetFd; + } + if (isStream(value, { checkOpen: false })) { + throw new TypeError(`The \`${optionName}: Stream\` option cannot both be an array and include a stream with synchronous methods.`); + } + return stdioItem; +}, getTargetFd = ({ value, optionName, fdNumber, direction }) => { + const targetFdNumber = getTargetFdNumber(value, fdNumber); + if (targetFdNumber === undefined) { + return; + } + if (direction === "output") { + return { type: "fileNumber", value: targetFdNumber, optionName }; + } + if (tty2.isatty(targetFdNumber)) { + throw new TypeError(`The \`${optionName}: ${serializeOptionValue(value)}\` option is invalid: it cannot be a TTY with synchronous methods.`); + } + return { type: "uint8Array", value: bufferToUint8Array(readFileSync(targetFdNumber)), optionName }; +}, getTargetFdNumber = (value, fdNumber) => { + if (value === "inherit") { + return fdNumber; + } + if (typeof value === "number") { + return value; + } + const standardStreamIndex = STANDARD_STREAMS.indexOf(value); + if (standardStreamIndex !== -1) { + return standardStreamIndex; + } +}, handleNativeStreamAsync = ({ stdioItem, stdioItem: { value, optionName }, fdNumber }) => { + if (value === "inherit") { + return { type: "nodeStream", value: getStandardStream(fdNumber, value, optionName), optionName }; + } + if (typeof value === "number") { + return { type: "nodeStream", value: getStandardStream(value, value, optionName), optionName }; + } + if (isStream(value, { checkOpen: false })) { + return { type: "nodeStream", value, optionName }; + } + return stdioItem; +}, getStandardStream = (fdNumber, value, optionName) => { + const standardStream = STANDARD_STREAMS[fdNumber]; + if (standardStream === undefined) { + throw new TypeError(`The \`${optionName}: ${value}\` option is invalid: no such standard stream.`); + } + return standardStream; +}; +var init_native = __esm(() => { + init_standard_stream(); + init_uint_array(); + init_fd_options(); +}); + +// node_modules/execa/lib/stdio/input-option.js +var handleInputOptions = ({ input, inputFile }, fdNumber) => fdNumber === 0 ? [ + ...handleInputOption(input), + ...handleInputFileOption(inputFile) +] : [], handleInputOption = (input) => input === undefined ? [] : [{ + type: getInputType(input), + value: input, + optionName: "input" +}], getInputType = (input) => { + if (isReadableStream(input, { checkOpen: false })) { + return "nodeStream"; + } + if (typeof input === "string") { + return "string"; + } + if (isUint8Array(input)) { + return "uint8Array"; + } + throw new Error("The `input` option must be a string, a Uint8Array or a Node.js Readable stream."); +}, handleInputFileOption = (inputFile) => inputFile === undefined ? [] : [{ + ...getInputFileType(inputFile), + optionName: "inputFile" +}], getInputFileType = (inputFile) => { + if (isUrl(inputFile)) { + return { type: "fileUrl", value: inputFile }; + } + if (isFilePathString(inputFile)) { + return { type: "filePath", value: { file: inputFile } }; + } + throw new Error("The `inputFile` option must be a file path string or a file URL."); +}; +var init_input_option = __esm(() => { + init_uint_array(); + init_type(); +}); + +// node_modules/execa/lib/stdio/duplicate.js +var filterDuplicates = (stdioItems) => stdioItems.filter((stdioItemOne, indexOne) => stdioItems.every((stdioItemTwo, indexTwo) => stdioItemOne.value !== stdioItemTwo.value || indexOne >= indexTwo || stdioItemOne.type === "generator" || stdioItemOne.type === "asyncGenerator")), getDuplicateStream = ({ stdioItem: { type, value, optionName }, direction, fileDescriptors, isSync }) => { + const otherStdioItems = getOtherStdioItems(fileDescriptors, type); + if (otherStdioItems.length === 0) { + return; + } + if (isSync) { + validateDuplicateStreamSync({ + otherStdioItems, + type, + value, + optionName, + direction + }); + return; + } + if (SPECIAL_DUPLICATE_TYPES.has(type)) { + return getDuplicateStreamInstance({ + otherStdioItems, + type, + value, + optionName, + direction + }); + } + if (FORBID_DUPLICATE_TYPES.has(type)) { + validateDuplicateTransform({ + otherStdioItems, + type, + value, + optionName + }); + } +}, getOtherStdioItems = (fileDescriptors, type) => fileDescriptors.flatMap(({ direction, stdioItems }) => stdioItems.filter((stdioItem) => stdioItem.type === type).map((stdioItem) => ({ ...stdioItem, direction }))), validateDuplicateStreamSync = ({ otherStdioItems, type, value, optionName, direction }) => { + if (SPECIAL_DUPLICATE_TYPES_SYNC.has(type)) { + getDuplicateStreamInstance({ + otherStdioItems, + type, + value, + optionName, + direction + }); + } +}, getDuplicateStreamInstance = ({ otherStdioItems, type, value, optionName, direction }) => { + const duplicateStdioItems = otherStdioItems.filter((stdioItem) => hasSameValue(stdioItem, value)); + if (duplicateStdioItems.length === 0) { + return; + } + const differentStdioItem = duplicateStdioItems.find((stdioItem) => stdioItem.direction !== direction); + throwOnDuplicateStream(differentStdioItem, optionName, type); + return direction === "output" ? duplicateStdioItems[0].stream : undefined; +}, hasSameValue = ({ type, value }, secondValue) => { + if (type === "filePath") { + return value.file === secondValue.file; + } + if (type === "fileUrl") { + return value.href === secondValue.href; + } + return value === secondValue; +}, validateDuplicateTransform = ({ otherStdioItems, type, value, optionName }) => { + const duplicateStdioItem = otherStdioItems.find(({ value: { transform } }) => transform === value.transform); + throwOnDuplicateStream(duplicateStdioItem, optionName, type); +}, throwOnDuplicateStream = (stdioItem, optionName, type) => { + if (stdioItem !== undefined) { + throw new TypeError(`The \`${stdioItem.optionName}\` and \`${optionName}\` options must not target ${TYPE_TO_MESSAGE[type]} that is the same.`); + } +}; +var init_duplicate = __esm(() => { + init_type(); +}); + +// node_modules/execa/lib/stdio/handle.js +var handleStdio = (addProperties, options, verboseInfo, isSync) => { + const stdio = normalizeStdioOption(options, verboseInfo, isSync); + const initialFileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({ + stdioOption, + fdNumber, + options, + isSync + })); + const fileDescriptors = getFinalFileDescriptors({ + initialFileDescriptors, + addProperties, + options, + isSync + }); + options.stdio = fileDescriptors.map(({ stdioItems }) => forwardStdio(stdioItems)); + return fileDescriptors; +}, getFileDescriptor = ({ stdioOption, fdNumber, options, isSync }) => { + const optionName = getStreamName(fdNumber); + const { stdioItems: initialStdioItems, isStdioArray } = initializeStdioItems({ + stdioOption, + fdNumber, + options, + optionName + }); + const direction = getStreamDirection(initialStdioItems, fdNumber, optionName); + const stdioItems = initialStdioItems.map((stdioItem) => handleNativeStream({ + stdioItem, + isStdioArray, + fdNumber, + direction, + isSync + })); + const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options); + const objectMode = getFdObjectMode(normalizedStdioItems, direction); + validateFileObjectMode(normalizedStdioItems, objectMode); + return { direction, objectMode, stdioItems: normalizedStdioItems }; +}, initializeStdioItems = ({ stdioOption, fdNumber, options, optionName }) => { + const values = Array.isArray(stdioOption) ? stdioOption : [stdioOption]; + const initialStdioItems = [ + ...values.map((value) => initializeStdioItem(value, optionName)), + ...handleInputOptions(options, fdNumber) + ]; + const stdioItems = filterDuplicates(initialStdioItems); + const isStdioArray = stdioItems.length > 1; + validateStdioArray(stdioItems, isStdioArray, optionName); + validateStreams(stdioItems); + return { stdioItems, isStdioArray }; +}, initializeStdioItem = (value, optionName) => ({ + type: getStdioItemType(value, optionName), + value, + optionName +}), validateStdioArray = (stdioItems, isStdioArray, optionName) => { + if (stdioItems.length === 0) { + throw new TypeError(`The \`${optionName}\` option must not be an empty array.`); + } + if (!isStdioArray) { + return; + } + for (const { value, optionName: optionName2 } of stdioItems) { + if (INVALID_STDIO_ARRAY_OPTIONS.has(value)) { + throw new Error(`The \`${optionName2}\` option must not include \`${value}\`.`); + } + } +}, INVALID_STDIO_ARRAY_OPTIONS, validateStreams = (stdioItems) => { + for (const stdioItem of stdioItems) { + validateFileStdio(stdioItem); + } +}, validateFileStdio = ({ type, value, optionName }) => { + if (isRegularUrl(value)) { + throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme. +For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`); + } + if (isUnknownStdioString(type, value)) { + throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`); + } +}, validateFileObjectMode = (stdioItems, objectMode) => { + if (!objectMode) { + return; + } + const fileStdioItem = stdioItems.find(({ type }) => FILE_TYPES.has(type)); + if (fileStdioItem !== undefined) { + throw new TypeError(`The \`${fileStdioItem.optionName}\` option cannot use both files and transforms in objectMode.`); + } +}, getFinalFileDescriptors = ({ initialFileDescriptors, addProperties, options, isSync }) => { + const fileDescriptors = []; + try { + for (const fileDescriptor of initialFileDescriptors) { + fileDescriptors.push(getFinalFileDescriptor({ + fileDescriptor, + fileDescriptors, + addProperties, + options, + isSync + })); + } + return fileDescriptors; + } catch (error) { + cleanupCustomStreams(fileDescriptors); + throw error; + } +}, getFinalFileDescriptor = ({ + fileDescriptor: { direction, objectMode, stdioItems }, + fileDescriptors, + addProperties, + options, + isSync +}) => { + const finalStdioItems = stdioItems.map((stdioItem) => addStreamProperties({ + stdioItem, + addProperties, + direction, + options, + fileDescriptors, + isSync + })); + return { direction, objectMode, stdioItems: finalStdioItems }; +}, addStreamProperties = ({ stdioItem, addProperties, direction, options, fileDescriptors, isSync }) => { + const duplicateStream = getDuplicateStream({ + stdioItem, + direction, + fileDescriptors, + isSync + }); + if (duplicateStream !== undefined) { + return { ...stdioItem, stream: duplicateStream }; + } + return { + ...stdioItem, + ...addProperties[direction][stdioItem.type](stdioItem, options) + }; +}, cleanupCustomStreams = (fileDescriptors) => { + for (const { stdioItems } of fileDescriptors) { + for (const { stream } of stdioItems) { + if (stream !== undefined && !isStandardStream(stream)) { + stream.destroy(); + } + } + } +}, forwardStdio = (stdioItems) => { + if (stdioItems.length > 1) { + return stdioItems.some(({ value: value2 }) => value2 === "overlapped") ? "overlapped" : "pipe"; + } + const [{ type, value }] = stdioItems; + return type === "native" ? value : "pipe"; +}; +var init_handle = __esm(() => { + init_standard_stream(); + init_normalize(); + init_object_mode(); + init_type(); + init_direction(); + init_stdio_option(); + init_native(); + init_input_option(); + init_duplicate(); + INVALID_STDIO_ARRAY_OPTIONS = new Set(["ignore", "ipc"]); +}); + +// node_modules/execa/lib/stdio/handle-sync.js +import { readFileSync as readFileSync2 } from "node:fs"; +var handleStdioSync = (options, verboseInfo) => handleStdio(addPropertiesSync, options, verboseInfo, true), forbiddenIfSync = ({ type, optionName }) => { + throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]); +}, forbiddenNativeIfSync = ({ optionName, value }) => { + if (value === "ipc" || value === "overlapped") { + throwInvalidSyncValue(optionName, `"${value}"`); + } + return {}; +}, throwInvalidSyncValue = (optionName, value) => { + throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`); +}, addProperties, addPropertiesSync; +var init_handle_sync = __esm(() => { + init_uint_array(); + init_handle(); + init_type(); + addProperties = { + generator() {}, + asyncGenerator: forbiddenIfSync, + webStream: forbiddenIfSync, + nodeStream: forbiddenIfSync, + webTransform: forbiddenIfSync, + duplex: forbiddenIfSync, + asyncIterable: forbiddenIfSync, + native: forbiddenNativeIfSync + }; + addPropertiesSync = { + input: { + ...addProperties, + fileUrl: ({ value }) => ({ contents: [bufferToUint8Array(readFileSync2(value))] }), + filePath: ({ value: { file } }) => ({ contents: [bufferToUint8Array(readFileSync2(file))] }), + fileNumber: forbiddenIfSync, + iterable: ({ value }) => ({ contents: [...value] }), + string: ({ value }) => ({ contents: [value] }), + uint8Array: ({ value }) => ({ contents: [value] }) + }, + output: { + ...addProperties, + fileUrl: ({ value }) => ({ path: value }), + filePath: ({ value: { file, append } }) => ({ path: file, append }), + fileNumber: ({ value }) => ({ path: value }), + iterable: forbiddenIfSync, + string: forbiddenIfSync, + uint8Array: forbiddenIfSync + } + }; +}); + +// node_modules/execa/lib/io/strip-newline.js +var stripNewline = (value, { stripFinalNewline: stripFinalNewline2 }, fdNumber) => getStripFinalNewline(stripFinalNewline2, fdNumber) && value !== undefined && !Array.isArray(value) ? stripFinalNewline(value) : value, getStripFinalNewline = (stripFinalNewline2, fdNumber) => fdNumber === "all" ? stripFinalNewline2[1] || stripFinalNewline2[2] : stripFinalNewline2[fdNumber]; +var init_strip_newline = __esm(() => { + init_strip_final_newline(); +}); + +// node_modules/execa/lib/transform/split.js +var getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped ? undefined : initializeSplitLines(preserveNewlines, state), splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode ? chunk.flatMap((item) => splitLinesItemSync(item, preserveNewlines)) : splitLinesItemSync(chunk, preserveNewlines), splitLinesItemSync = (chunk, preserveNewlines) => { + const { transform, final } = initializeSplitLines(preserveNewlines, {}); + return [...transform(chunk), ...final()]; +}, initializeSplitLines = (preserveNewlines, state) => { + state.previousChunks = ""; + return { + transform: splitGenerator.bind(undefined, state, preserveNewlines), + final: linesFinal.bind(undefined, state) + }; +}, splitGenerator = function* (state, preserveNewlines, chunk) { + if (typeof chunk !== "string") { + yield chunk; + return; + } + let { previousChunks } = state; + let start = -1; + for (let end = 0;end < chunk.length; end += 1) { + if (chunk[end] === ` +`) { + const newlineLength = getNewlineLength(chunk, end, preserveNewlines, state); + let line = chunk.slice(start + 1, end + 1 - newlineLength); + if (previousChunks.length > 0) { + line = concatString(previousChunks, line); + previousChunks = ""; + } + yield line; + start = end; + } + } + if (start !== chunk.length - 1) { + previousChunks = concatString(previousChunks, chunk.slice(start + 1)); + } + state.previousChunks = previousChunks; +}, getNewlineLength = (chunk, end, preserveNewlines, state) => { + if (preserveNewlines) { + return 0; + } + state.isWindowsNewline = end !== 0 && chunk[end - 1] === "\r"; + return state.isWindowsNewline ? 2 : 1; +}, linesFinal = function* ({ previousChunks }) { + if (previousChunks.length > 0) { + yield previousChunks; + } +}, getAppendNewlineGenerator = ({ binary, preserveNewlines, readableObjectMode, state }) => binary || preserveNewlines || readableObjectMode ? undefined : { transform: appendNewlineGenerator.bind(undefined, state) }, appendNewlineGenerator = function* ({ isWindowsNewline = false }, chunk) { + const { unixNewline, windowsNewline, LF: LF3, concatBytes } = typeof chunk === "string" ? linesStringInfo : linesUint8ArrayInfo; + if (chunk.at(-1) === LF3) { + yield chunk; + return; + } + const newline = isWindowsNewline ? windowsNewline : unixNewline; + yield concatBytes(chunk, newline); +}, concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`, linesStringInfo, concatUint8Array = (firstChunk, secondChunk) => { + const chunk = new Uint8Array(firstChunk.length + secondChunk.length); + chunk.set(firstChunk, 0); + chunk.set(secondChunk, firstChunk.length); + return chunk; +}, linesUint8ArrayInfo; +var init_split = __esm(() => { + linesStringInfo = { + windowsNewline: `\r +`, + unixNewline: ` +`, + LF: ` +`, + concatBytes: concatString + }; + linesUint8ArrayInfo = { + windowsNewline: new Uint8Array([13, 10]), + unixNewline: new Uint8Array([10]), + LF: 10, + concatBytes: concatUint8Array + }; +}); + +// node_modules/execa/lib/transform/validate.js +import { Buffer as Buffer4 } from "node:buffer"; +var getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode ? undefined : validateStringTransformInput.bind(undefined, optionName), validateStringTransformInput = function* (optionName, chunk) { + if (typeof chunk !== "string" && !isUint8Array(chunk) && !Buffer4.isBuffer(chunk)) { + throw new TypeError(`The \`${optionName}\` option's transform must use "objectMode: true" to receive as input: ${typeof chunk}.`); + } + yield chunk; +}, getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode ? validateObjectTransformReturn.bind(undefined, optionName) : validateStringTransformReturn.bind(undefined, optionName), validateObjectTransformReturn = function* (optionName, chunk) { + validateEmptyReturn(optionName, chunk); + yield chunk; +}, validateStringTransformReturn = function* (optionName, chunk) { + validateEmptyReturn(optionName, chunk); + if (typeof chunk !== "string" && !isUint8Array(chunk)) { + throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeof chunk}.`); + } + yield chunk; +}, validateEmptyReturn = (optionName, chunk) => { + if (chunk === null || chunk === undefined) { + throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`. +Instead, \`yield\` should either be called with a value, or not be called at all. For example: + if (condition) { yield value; }`); + } +}; +var init_validate = __esm(() => { + init_uint_array(); +}); + +// node_modules/execa/lib/transform/encoding-transform.js +import { Buffer as Buffer5 } from "node:buffer"; +import { StringDecoder as StringDecoder2 } from "node:string_decoder"; +var getEncodingTransformGenerator = (binary, encoding, skipped) => { + if (skipped) { + return; + } + if (binary) { + return { transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder) }; + } + const stringDecoder = new StringDecoder2(encoding); + return { + transform: encodingStringGenerator.bind(undefined, stringDecoder), + final: encodingStringFinal.bind(undefined, stringDecoder) + }; +}, encodingUint8ArrayGenerator = function* (textEncoder3, chunk) { + if (Buffer5.isBuffer(chunk)) { + yield bufferToUint8Array(chunk); + } else if (typeof chunk === "string") { + yield textEncoder3.encode(chunk); + } else { + yield chunk; + } +}, encodingStringGenerator = function* (stringDecoder, chunk) { + yield isUint8Array(chunk) ? stringDecoder.write(chunk) : chunk; +}, encodingStringFinal = function* (stringDecoder) { + const lastChunk = stringDecoder.end(); + if (lastChunk !== "") { + yield lastChunk; + } +}; +var init_encoding_transform = __esm(() => { + init_uint_array(); +}); + +// node_modules/execa/lib/transform/run-async.js +import { callbackify } from "node:util"; +var pushChunks, transformChunk = async function* (chunk, generators, index) { + if (index === generators.length) { + yield chunk; + return; + } + const { transform = identityGenerator } = generators[index]; + for await (const transformedChunk of transform(chunk)) { + yield* transformChunk(transformedChunk, generators, index + 1); + } +}, finalChunks = async function* (generators) { + for (const [index, { final }] of Object.entries(generators)) { + yield* generatorFinalChunks(final, Number(index), generators); + } +}, generatorFinalChunks = async function* (final, index, generators) { + if (final === undefined) { + return; + } + for await (const finalChunk of final()) { + yield* transformChunk(finalChunk, generators, index + 1); + } +}, destroyTransform, identityGenerator = function* (chunk) { + yield chunk; +}; +var init_run_async = __esm(() => { + pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => { + state.currentIterable = getChunks(...getChunksArguments); + try { + for await (const chunk of state.currentIterable) { + transformStream.push(chunk); + } + } finally { + delete state.currentIterable; + } + }); + destroyTransform = callbackify(async ({ currentIterable }, error) => { + if (currentIterable !== undefined) { + await (error ? currentIterable.throw(error) : currentIterable.return()); + return; + } + if (error) { + throw error; + } + }); +}); + +// node_modules/execa/lib/transform/run-sync.js +var pushChunksSync = (getChunksSync, getChunksArguments, transformStream, done) => { + try { + for (const chunk of getChunksSync(...getChunksArguments)) { + transformStream.push(chunk); + } + done(); + } catch (error) { + done(error); + } +}, runTransformSync = (generators, chunks) => [ + ...chunks.flatMap((chunk) => [...transformChunkSync(chunk, generators, 0)]), + ...finalChunksSync(generators) +], transformChunkSync = function* (chunk, generators, index) { + if (index === generators.length) { + yield chunk; + return; + } + const { transform = identityGenerator2 } = generators[index]; + for (const transformedChunk of transform(chunk)) { + yield* transformChunkSync(transformedChunk, generators, index + 1); + } +}, finalChunksSync = function* (generators) { + for (const [index, { final }] of Object.entries(generators)) { + yield* generatorFinalChunksSync(final, Number(index), generators); + } +}, generatorFinalChunksSync = function* (final, index, generators) { + if (final === undefined) { + return; + } + for (const finalChunk of final()) { + yield* transformChunkSync(finalChunk, generators, index + 1); + } +}, identityGenerator2 = function* (chunk) { + yield chunk; +}; + +// node_modules/execa/lib/transform/generator.js +import { Transform, getDefaultHighWaterMark } from "node:stream"; +var generatorToStream = ({ + value, + value: { transform, final, writableObjectMode, readableObjectMode }, + optionName +}, { encoding }) => { + const state = {}; + const generators = addInternalGenerators(value, encoding, optionName); + const transformAsync = isAsyncGenerator(transform); + const finalAsync = isAsyncGenerator(final); + const transformMethod = transformAsync ? pushChunks.bind(undefined, transformChunk, state) : pushChunksSync.bind(undefined, transformChunkSync); + const finalMethod = transformAsync || finalAsync ? pushChunks.bind(undefined, finalChunks, state) : pushChunksSync.bind(undefined, finalChunksSync); + const destroyMethod = transformAsync || finalAsync ? destroyTransform.bind(undefined, state) : undefined; + const stream = new Transform({ + writableObjectMode, + writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode), + readableObjectMode, + readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode), + transform(chunk, encoding2, done) { + transformMethod([chunk, generators, 0], this, done); + }, + flush(done) { + finalMethod([generators], this, done); + }, + destroy: destroyMethod + }); + return { stream }; +}, runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => { + const generators = stdioItems.filter(({ type }) => type === "generator"); + const reversedGenerators = isInput ? generators.reverse() : generators; + for (const { value, optionName } of reversedGenerators) { + const generators2 = addInternalGenerators(value, encoding, optionName); + chunks = runTransformSync(generators2, chunks); + } + return chunks; +}, addInternalGenerators = ({ transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines }, encoding, optionName) => { + const state = {}; + return [ + { transform: getValidateTransformInput(writableObjectMode, optionName) }, + getEncodingTransformGenerator(binary, encoding, writableObjectMode), + getSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state), + { transform, final }, + { transform: getValidateTransformReturn(readableObjectMode, optionName) }, + getAppendNewlineGenerator({ + binary, + preserveNewlines, + readableObjectMode, + state + }) + ].filter(Boolean); +}; +var init_generator = __esm(() => { + init_type(); + init_split(); + init_validate(); + init_encoding_transform(); + init_run_async(); +}); + +// node_modules/execa/lib/io/input-sync.js +var addInputOptionsSync = (fileDescriptors, options) => { + for (const fdNumber of getInputFdNumbers(fileDescriptors)) { + addInputOptionSync(fileDescriptors, fdNumber, options); + } +}, getInputFdNumbers = (fileDescriptors) => new Set(Object.entries(fileDescriptors).filter(([, { direction }]) => direction === "input").map(([fdNumber]) => Number(fdNumber))), addInputOptionSync = (fileDescriptors, fdNumber, options) => { + const { stdioItems } = fileDescriptors[fdNumber]; + const allStdioItems = stdioItems.filter(({ contents }) => contents !== undefined); + if (allStdioItems.length === 0) { + return; + } + if (fdNumber !== 0) { + const [{ type, optionName }] = allStdioItems; + throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`); + } + const allContents = allStdioItems.map(({ contents }) => contents); + const transformedContents = allContents.map((contents) => applySingleInputGeneratorsSync(contents, stdioItems)); + options.input = joinToUint8Array(transformedContents); +}, applySingleInputGeneratorsSync = (contents, stdioItems) => { + const newContents = runGeneratorsSync(contents, stdioItems, "utf8", true); + validateSerializable(newContents); + return joinToUint8Array(newContents); +}, validateSerializable = (newContents) => { + const invalidItem = newContents.find((item) => typeof item !== "string" && !isUint8Array(item)); + if (invalidItem !== undefined) { + throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`); + } +}; +var init_input_sync = __esm(() => { + init_generator(); + init_uint_array(); + init_type(); +}); + +// node_modules/execa/lib/verbose/output.js +var shouldLogOutput = ({ stdioItems, encoding, verboseInfo, fdNumber }) => fdNumber !== "all" && isFullVerbose(verboseInfo, fdNumber) && !BINARY_ENCODINGS.has(encoding) && fdUsesVerbose(fdNumber) && (stdioItems.some(({ type, value }) => type === "native" && PIPED_STDIO_VALUES.has(value)) || stdioItems.every(({ type }) => TRANSFORM_TYPES.has(type))), fdUsesVerbose = (fdNumber) => fdNumber === 1 || fdNumber === 2, PIPED_STDIO_VALUES, logLines = async (linesIterable, stream, fdNumber, verboseInfo) => { + for await (const line of linesIterable) { + if (!isPipingStream(stream)) { + logLine(line, fdNumber, verboseInfo); + } + } +}, logLinesSync = (linesArray, fdNumber, verboseInfo) => { + for (const line of linesArray) { + logLine(line, fdNumber, verboseInfo); + } +}, isPipingStream = (stream) => stream._readableState.pipes.length > 0, logLine = (line, fdNumber, verboseInfo) => { + const verboseMessage = serializeVerboseMessage(line); + verboseLog({ + type: "output", + verboseMessage, + fdNumber, + verboseInfo + }); +}; +var init_output = __esm(() => { + init_encoding_option(); + init_type(); + init_log(); + init_values(); + PIPED_STDIO_VALUES = new Set(["pipe", "overlapped"]); +}); + +// node_modules/execa/lib/io/output-sync.js +import { writeFileSync, appendFileSync } from "node:fs"; +var transformOutputSync = ({ fileDescriptors, syncResult: { output }, options, isMaxBuffer, verboseInfo }) => { + if (output === null) { + return { output: Array.from({ length: 3 }) }; + } + const state = {}; + const outputFiles = new Set([]); + const transformedOutput = output.map((result, fdNumber) => transformOutputResultSync({ + result, + fileDescriptors, + fdNumber, + state, + outputFiles, + isMaxBuffer, + verboseInfo + }, options)); + return { output: transformedOutput, ...state }; +}, transformOutputResultSync = ({ result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo }, { buffer, encoding, lines, stripFinalNewline: stripFinalNewline2, maxBuffer }) => { + if (result === null) { + return; + } + const truncatedResult = truncateMaxBufferSync(result, isMaxBuffer, maxBuffer); + const uint8ArrayResult = bufferToUint8Array(truncatedResult); + const { stdioItems, objectMode } = fileDescriptors[fdNumber]; + const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state); + const { serializedResult, finalResult = serializedResult } = serializeChunks({ + chunks, + objectMode, + encoding, + lines, + stripFinalNewline: stripFinalNewline2, + fdNumber + }); + logOutputSync({ + serializedResult, + fdNumber, + state, + verboseInfo, + encoding, + stdioItems, + objectMode + }); + const returnedResult = buffer[fdNumber] ? finalResult : undefined; + try { + if (state.error === undefined) { + writeToFiles(serializedResult, stdioItems, outputFiles); + } + return returnedResult; + } catch (error) { + state.error = error; + return returnedResult; + } +}, runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => { + try { + return runGeneratorsSync(chunks, stdioItems, encoding, false); + } catch (error) { + state.error = error; + return chunks; + } +}, serializeChunks = ({ chunks, objectMode, encoding, lines, stripFinalNewline: stripFinalNewline2, fdNumber }) => { + if (objectMode) { + return { serializedResult: chunks }; + } + if (encoding === "buffer") { + return { serializedResult: joinToUint8Array(chunks) }; + } + const serializedResult = joinToString(chunks, encoding); + if (lines[fdNumber]) { + return { serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline2[fdNumber], objectMode) }; + } + return { serializedResult }; +}, logOutputSync = ({ serializedResult, fdNumber, state, verboseInfo, encoding, stdioItems, objectMode }) => { + if (!shouldLogOutput({ + stdioItems, + encoding, + verboseInfo, + fdNumber + })) { + return; + } + const linesArray = splitLinesSync(serializedResult, false, objectMode); + try { + logLinesSync(linesArray, fdNumber, verboseInfo); + } catch (error) { + state.error ??= error; + } +}, writeToFiles = (serializedResult, stdioItems, outputFiles) => { + for (const { path: path7, append } of stdioItems.filter(({ type }) => FILE_TYPES.has(type))) { + const pathString = typeof path7 === "string" ? path7 : path7.toString(); + if (append || outputFiles.has(pathString)) { + appendFileSync(path7, serializedResult); + } else { + outputFiles.add(pathString); + writeFileSync(path7, serializedResult); + } + } +}; +var init_output_sync = __esm(() => { + init_output(); + init_generator(); + init_split(); + init_uint_array(); + init_type(); + init_max_buffer(); +}); + +// node_modules/execa/lib/resolve/all-sync.js +var getAllSync = ([, stdout, stderr], options) => { + if (!options.all) { + return; + } + if (stdout === undefined) { + return stderr; + } + if (stderr === undefined) { + return stdout; + } + if (Array.isArray(stdout)) { + return Array.isArray(stderr) ? [...stdout, ...stderr] : [...stdout, stripNewline(stderr, options, "all")]; + } + if (Array.isArray(stderr)) { + return [stripNewline(stdout, options, "all"), ...stderr]; + } + if (isUint8Array(stdout) && isUint8Array(stderr)) { + return concatUint8Arrays([stdout, stderr]); + } + return `${stdout}${stderr}`; +}; +var init_all_sync = __esm(() => { + init_uint_array(); + init_strip_newline(); +}); + +// node_modules/execa/lib/resolve/exit-async.js +import { once as once4 } from "node:events"; +var waitForExit = async (subprocess, context3) => { + const [exitCode, signal] = await waitForExitOrError(subprocess); + context3.isForcefullyTerminated ??= false; + return [exitCode, signal]; +}, waitForExitOrError = async (subprocess) => { + const [spawnPayload, exitPayload] = await Promise.allSettled([ + once4(subprocess, "spawn"), + once4(subprocess, "exit") + ]); + if (spawnPayload.status === "rejected") { + return []; + } + return exitPayload.status === "rejected" ? waitForSubprocessExit(subprocess) : exitPayload.value; +}, waitForSubprocessExit = async (subprocess) => { + try { + return await once4(subprocess, "exit"); + } catch { + return waitForSubprocessExit(subprocess); + } +}, waitForSuccessfulExit = async (exitPromise) => { + const [exitCode, signal] = await exitPromise; + if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) { + throw new DiscardedError; + } + return [exitCode, signal]; +}, isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined, isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null; +var init_exit_async = __esm(() => { + init_final_error(); +}); + +// node_modules/execa/lib/resolve/exit-sync.js +var getExitResultSync = ({ error, status: exitCode, signal, output }, { maxBuffer }) => { + const resultError = getResultError(error, exitCode, signal); + const timedOut = resultError?.code === "ETIMEDOUT"; + const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer); + return { + resultError, + exitCode, + signal, + timedOut, + isMaxBuffer + }; +}, getResultError = (error, exitCode, signal) => { + if (error !== undefined) { + return error; + } + return isFailedExit(exitCode, signal) ? new DiscardedError : undefined; +}; +var init_exit_sync = __esm(() => { + init_final_error(); + init_max_buffer(); + init_exit_async(); +}); + +// node_modules/execa/lib/methods/main-sync.js +import { spawnSync } from "node:child_process"; +var execaCoreSync = (rawFile, rawArguments, rawOptions) => { + const { file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors } = handleSyncArguments(rawFile, rawArguments, rawOptions); + const result = spawnSubprocessSync({ + file, + commandArguments, + options, + command, + escapedCommand, + verboseInfo, + fileDescriptors, + startTime + }); + return handleResult(result, verboseInfo, options); +}, handleSyncArguments = (rawFile, rawArguments, rawOptions) => { + const { command, escapedCommand, startTime, verboseInfo } = handleCommand(rawFile, rawArguments, rawOptions); + const syncOptions = normalizeSyncOptions(rawOptions); + const { file, commandArguments, options } = normalizeOptions(rawFile, rawArguments, syncOptions); + validateSyncOptions(options); + const fileDescriptors = handleStdioSync(options, verboseInfo); + return { + file, + commandArguments, + command, + escapedCommand, + startTime, + verboseInfo, + options, + fileDescriptors + }; +}, normalizeSyncOptions = (options) => options.node && !options.ipc ? { ...options, ipc: false } : options, validateSyncOptions = ({ ipc, ipcInput, detached, cancelSignal }) => { + if (ipcInput) { + throwInvalidSyncOption("ipcInput"); + } + if (ipc) { + throwInvalidSyncOption("ipc: true"); + } + if (detached) { + throwInvalidSyncOption("detached: true"); + } + if (cancelSignal) { + throwInvalidSyncOption("cancelSignal"); + } +}, throwInvalidSyncOption = (value) => { + throw new TypeError(`The "${value}" option cannot be used with synchronous methods.`); +}, spawnSubprocessSync = ({ file, commandArguments, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime }) => { + const syncResult = runSubprocessSync({ + file, + commandArguments, + options, + command, + escapedCommand, + fileDescriptors, + startTime + }); + if (syncResult.failed) { + return syncResult; + } + const { resultError, exitCode, signal, timedOut, isMaxBuffer } = getExitResultSync(syncResult, options); + const { output, error = resultError } = transformOutputSync({ + fileDescriptors, + syncResult, + options, + isMaxBuffer, + verboseInfo + }); + const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber)); + const all = stripNewline(getAllSync(output, options), options, "all"); + return getSyncResult({ + error, + exitCode, + signal, + timedOut, + isMaxBuffer, + stdio, + all, + options, + command, + escapedCommand, + startTime + }); +}, runSubprocessSync = ({ file, commandArguments, options, command, escapedCommand, fileDescriptors, startTime }) => { + try { + addInputOptionsSync(fileDescriptors, options); + const normalizedOptions = normalizeSpawnSyncOptions(options); + return spawnSync(...concatenateShell(file, commandArguments, normalizedOptions)); + } catch (error) { + return makeEarlyError({ + error, + command, + escapedCommand, + fileDescriptors, + options, + startTime, + isSync: true + }); + } +}, normalizeSpawnSyncOptions = ({ encoding, maxBuffer, ...options }) => ({ ...options, encoding: "buffer", maxBuffer: getMaxBufferSync(maxBuffer) }), getSyncResult = ({ error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime }) => error === undefined ? makeSuccessResult({ + command, + escapedCommand, + stdio, + all, + ipcOutput: [], + options, + startTime +}) : makeError({ + error, + command, + escapedCommand, + timedOut, + isCanceled: false, + isGracefullyCanceled: false, + isMaxBuffer, + isForcefullyTerminated: false, + exitCode, + signal, + stdio, + all, + ipcOutput: [], + options, + startTime, + isSync: true +}); +var init_main_sync = __esm(() => { + init_command(); + init_options(); + init_result(); + init_reject(); + init_handle_sync(); + init_strip_newline(); + init_input_sync(); + init_output_sync(); + init_max_buffer(); + init_all_sync(); + init_exit_sync(); +}); + +// node_modules/execa/lib/ipc/get-one.js +import { once as once5, on as on2 } from "node:events"; +var getOneMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true, filter } = {}) => { + validateIpcMethod({ + methodName: "getOneMessage", + isSubprocess, + ipc, + isConnected: isConnected(anyProcess) + }); + return getOneMessageAsync({ + anyProcess, + channel, + isSubprocess, + filter, + reference + }); +}, getOneMessageAsync = async ({ anyProcess, channel, isSubprocess, filter, reference }) => { + addReference(channel, reference); + const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess); + const controller = new AbortController; + try { + return await Promise.race([ + getMessage(ipcEmitter, filter, controller), + throwOnDisconnect2(ipcEmitter, isSubprocess, controller), + throwOnStrictError(ipcEmitter, isSubprocess, controller) + ]); + } catch (error) { + disconnect(anyProcess); + throw error; + } finally { + controller.abort(); + removeReference(channel, reference); + } +}, getMessage = async (ipcEmitter, filter, { signal }) => { + if (filter === undefined) { + const [message] = await once5(ipcEmitter, "message", { signal }); + return message; + } + for await (const [message] of on2(ipcEmitter, "message", { signal })) { + if (filter(message)) { + return message; + } + } +}, throwOnDisconnect2 = async (ipcEmitter, isSubprocess, { signal }) => { + await once5(ipcEmitter, "disconnect", { signal }); + throwOnEarlyDisconnect(isSubprocess); +}, throwOnStrictError = async (ipcEmitter, isSubprocess, { signal }) => { + const [error] = await once5(ipcEmitter, "strict:error", { signal }); + throw getStrictResponseError(error, isSubprocess); +}; +var init_get_one = __esm(() => { + init_validation(); + init_forward(); +}); + +// node_modules/execa/lib/ipc/get-each.js +import { once as once6, on as on3 } from "node:events"; +var getEachMessage = ({ anyProcess, channel, isSubprocess, ipc }, { reference = true } = {}) => loopOnMessages({ + anyProcess, + channel, + isSubprocess, + ipc, + shouldAwait: !isSubprocess, + reference +}), loopOnMessages = ({ anyProcess, channel, isSubprocess, ipc, shouldAwait, reference }) => { + validateIpcMethod({ + methodName: "getEachMessage", + isSubprocess, + ipc, + isConnected: isConnected(anyProcess) + }); + addReference(channel, reference); + const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess); + const controller = new AbortController; + const state = {}; + stopOnDisconnect(anyProcess, ipcEmitter, controller); + abortOnStrictError({ + ipcEmitter, + isSubprocess, + controller, + state + }); + return iterateOnMessages({ + anyProcess, + channel, + ipcEmitter, + isSubprocess, + shouldAwait, + controller, + state, + reference + }); +}, stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => { + try { + await once6(ipcEmitter, "disconnect", { signal: controller.signal }); + controller.abort(); + } catch {} +}, abortOnStrictError = async ({ ipcEmitter, isSubprocess, controller, state }) => { + try { + const [error] = await once6(ipcEmitter, "strict:error", { signal: controller.signal }); + state.error = getStrictResponseError(error, isSubprocess); + controller.abort(); + } catch {} +}, iterateOnMessages = async function* ({ anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference }) { + try { + for await (const [message] of on3(ipcEmitter, "message", { signal: controller.signal })) { + throwIfStrictError(state); + yield message; + } + } catch { + throwIfStrictError(state); + } finally { + controller.abort(); + removeReference(channel, reference); + if (!isSubprocess) { + disconnect(anyProcess); + } + if (shouldAwait) { + await anyProcess; + } + } +}, throwIfStrictError = ({ error }) => { + if (error) { + throw error; + } +}; +var init_get_each = __esm(() => { + init_validation(); + init_forward(); +}); + +// node_modules/execa/lib/ipc/methods.js +import process9 from "node:process"; +var addIpcMethods = (subprocess, { ipc }) => { + Object.assign(subprocess, getIpcMethods(subprocess, false, ipc)); +}, getIpcExport = () => { + const anyProcess = process9; + const isSubprocess = true; + const ipc = process9.channel !== undefined; + return { + ...getIpcMethods(anyProcess, isSubprocess, ipc), + getCancelSignal: getCancelSignal.bind(undefined, { + anyProcess, + channel: anyProcess.channel, + isSubprocess, + ipc + }) + }; +}, getIpcMethods = (anyProcess, isSubprocess, ipc) => ({ + sendMessage: sendMessage.bind(undefined, { + anyProcess, + channel: anyProcess.channel, + isSubprocess, + ipc + }), + getOneMessage: getOneMessage.bind(undefined, { + anyProcess, + channel: anyProcess.channel, + isSubprocess, + ipc + }), + getEachMessage: getEachMessage.bind(undefined, { + anyProcess, + channel: anyProcess.channel, + isSubprocess, + ipc + }) +}); +var init_methods = __esm(() => { + init_send(); + init_get_one(); + init_get_each(); + init_graceful(); +}); + +// node_modules/execa/lib/return/early-error.js +import { ChildProcess as ChildProcess2 } from "node:child_process"; +import { + PassThrough as PassThrough3, + Readable, + Writable, + Duplex +} from "node:stream"; +var handleEarlyError = ({ error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo }) => { + cleanupCustomStreams(fileDescriptors); + const subprocess = new ChildProcess2; + createDummyStreams(subprocess, fileDescriptors); + Object.assign(subprocess, { readable, writable, duplex }); + const earlyError = makeEarlyError({ + error, + command, + escapedCommand, + fileDescriptors, + options, + startTime, + isSync: false + }); + const promise = handleDummyPromise(earlyError, verboseInfo, options); + return { subprocess, promise }; +}, createDummyStreams = (subprocess, fileDescriptors) => { + const stdin = createDummyStream(); + const stdout = createDummyStream(); + const stderr = createDummyStream(); + const extraStdio = Array.from({ length: fileDescriptors.length - 3 }, createDummyStream); + const all = createDummyStream(); + const stdio = [stdin, stdout, stderr, ...extraStdio]; + Object.assign(subprocess, { + stdin, + stdout, + stderr, + all, + stdio + }); +}, createDummyStream = () => { + const stream = new PassThrough3; + stream.end(); + return stream; +}, readable = () => new Readable({ read() {} }), writable = () => new Writable({ write() {} }), duplex = () => new Duplex({ read() {}, write() {} }), handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options); +var init_early_error = __esm(() => { + init_handle(); + init_result(); + init_reject(); +}); + +// node_modules/execa/lib/stdio/handle-async.js +import { createReadStream as createReadStream2, createWriteStream } from "node:fs"; +import { Buffer as Buffer6 } from "node:buffer"; +import { Readable as Readable2, Writable as Writable2, Duplex as Duplex2 } from "node:stream"; +var handleStdioAsync = (options, verboseInfo) => handleStdio(addPropertiesAsync, options, verboseInfo, false), forbiddenIfAsync = ({ type, optionName }) => { + throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`); +}, addProperties2, addPropertiesAsync; +var init_handle_async = __esm(() => { + init_generator(); + init_handle(); + init_type(); + addProperties2 = { + fileNumber: forbiddenIfAsync, + generator: generatorToStream, + asyncGenerator: generatorToStream, + nodeStream: ({ value }) => ({ stream: value }), + webTransform({ value: { transform, writableObjectMode, readableObjectMode } }) { + const objectMode = writableObjectMode || readableObjectMode; + const stream = Duplex2.fromWeb(transform, { objectMode }); + return { stream }; + }, + duplex: ({ value: { transform } }) => ({ stream: transform }), + native() {} + }; + addPropertiesAsync = { + input: { + ...addProperties2, + fileUrl: ({ value }) => ({ stream: createReadStream2(value) }), + filePath: ({ value: { file } }) => ({ stream: createReadStream2(file) }), + webStream: ({ value }) => ({ stream: Readable2.fromWeb(value) }), + iterable: ({ value }) => ({ stream: Readable2.from(value) }), + asyncIterable: ({ value }) => ({ stream: Readable2.from(value) }), + string: ({ value }) => ({ stream: Readable2.from(value) }), + uint8Array: ({ value }) => ({ stream: Readable2.from(Buffer6.from(value)) }) + }, + output: { + ...addProperties2, + fileUrl: ({ value }) => ({ stream: createWriteStream(value) }), + filePath: ({ value: { file, append } }) => ({ stream: createWriteStream(file, append ? { flags: "a" } : {}) }), + webStream: ({ value }) => ({ stream: Writable2.fromWeb(value) }), + iterable: forbiddenIfAsync, + asyncIterable: forbiddenIfAsync, + string: forbiddenIfAsync, + uint8Array: forbiddenIfAsync + } + }; +}); + +// node_modules/@sindresorhus/merge-streams/index.js +import { on as on4, once as once7 } from "node:events"; +import { PassThrough as PassThroughStream, getDefaultHighWaterMark as getDefaultHighWaterMark2 } from "node:stream"; +import { finished as finished2 } from "node:stream/promises"; +function mergeStreams(streams) { + if (!Array.isArray(streams)) { + throw new TypeError(`Expected an array, got \`${typeof streams}\`.`); + } + for (const stream of streams) { + validateStream(stream); + } + const objectMode = streams.some(({ readableObjectMode }) => readableObjectMode); + const highWaterMark = getHighWaterMark(streams, objectMode); + const passThroughStream = new MergedStream({ + objectMode, + writableHighWaterMark: highWaterMark, + readableHighWaterMark: highWaterMark + }); + for (const stream of streams) { + passThroughStream.add(stream); + } + return passThroughStream; +} +var getHighWaterMark = (streams, objectMode) => { + if (streams.length === 0) { + return getDefaultHighWaterMark2(objectMode); + } + const highWaterMarks = streams.filter(({ readableObjectMode }) => readableObjectMode === objectMode).map(({ readableHighWaterMark }) => readableHighWaterMark); + return Math.max(...highWaterMarks); +}, MergedStream, onMergedStreamFinished = async (passThroughStream, streams, unpipeEvent) => { + updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_COUNT); + const controller = new AbortController; + try { + await Promise.race([ + onMergedStreamEnd(passThroughStream, controller), + onInputStreamsUnpipe(passThroughStream, streams, unpipeEvent, controller) + ]); + } finally { + controller.abort(); + updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_COUNT); + } +}, onMergedStreamEnd = async (passThroughStream, { signal }) => { + try { + await finished2(passThroughStream, { signal, cleanup: true }); + } catch (error) { + errorOrAbortStream(passThroughStream, error); + throw error; + } +}, onInputStreamsUnpipe = async (passThroughStream, streams, unpipeEvent, { signal }) => { + for await (const [unpipedStream] of on4(passThroughStream, "unpipe", { signal })) { + if (streams.has(unpipedStream)) { + unpipedStream.emit(unpipeEvent); + } + } +}, validateStream = (stream) => { + if (typeof stream?.pipe !== "function") { + throw new TypeError(`Expected a readable stream, got: \`${typeof stream}\`.`); + } +}, endWhenStreamsDone = async ({ passThroughStream, stream, streams, ended, aborted, onFinished, unpipeEvent }) => { + updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_PER_STREAM); + const controller = new AbortController; + try { + await Promise.race([ + afterMergedStreamFinished(onFinished, stream, controller), + onInputStreamEnd({ + passThroughStream, + stream, + streams, + ended, + aborted, + controller + }), + onInputStreamUnpipe({ + stream, + streams, + ended, + aborted, + unpipeEvent, + controller + }) + ]); + } finally { + controller.abort(); + updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_PER_STREAM); + } + if (streams.size > 0 && streams.size === ended.size + aborted.size) { + if (ended.size === 0 && aborted.size > 0) { + abortStream(passThroughStream); + } else { + endStream(passThroughStream); + } + } +}, afterMergedStreamFinished = async (onFinished, stream, { signal }) => { + try { + await onFinished; + if (!signal.aborted) { + abortStream(stream); + } + } catch (error) { + if (!signal.aborted) { + errorOrAbortStream(stream, error); + } + } +}, onInputStreamEnd = async ({ passThroughStream, stream, streams, ended, aborted, controller: { signal } }) => { + try { + await finished2(stream, { + signal, + cleanup: true, + readable: true, + writable: false + }); + if (streams.has(stream)) { + ended.add(stream); + } + } catch (error) { + if (signal.aborted || !streams.has(stream)) { + return; + } + if (isAbortError(error)) { + aborted.add(stream); + } else { + errorStream(passThroughStream, error); + } + } +}, onInputStreamUnpipe = async ({ stream, streams, ended, aborted, unpipeEvent, controller: { signal } }) => { + await once7(stream, unpipeEvent, { signal }); + if (!stream.readable) { + return once7(signal, "abort", { signal }); + } + streams.delete(stream); + ended.delete(stream); + aborted.delete(stream); +}, endStream = (stream) => { + if (stream.writable) { + stream.end(); + } +}, errorOrAbortStream = (stream, error) => { + if (isAbortError(error)) { + abortStream(stream); + } else { + errorStream(stream, error); + } +}, isAbortError = (error) => error?.code === "ERR_STREAM_PREMATURE_CLOSE", abortStream = (stream) => { + if (stream.readable || stream.writable) { + stream.destroy(); + } +}, errorStream = (stream, error) => { + if (!stream.destroyed) { + stream.once("error", noop3); + stream.destroy(error); + } +}, noop3 = () => {}, updateMaxListeners = (passThroughStream, increment2) => { + const maxListeners = passThroughStream.getMaxListeners(); + if (maxListeners !== 0 && maxListeners !== Number.POSITIVE_INFINITY) { + passThroughStream.setMaxListeners(maxListeners + increment2); + } +}, PASSTHROUGH_LISTENERS_COUNT = 2, PASSTHROUGH_LISTENERS_PER_STREAM = 1; +var init_merge_streams = __esm(() => { + MergedStream = class MergedStream extends PassThroughStream { + #streams = new Set([]); + #ended = new Set([]); + #aborted = new Set([]); + #onFinished; + #unpipeEvent = Symbol("unpipe"); + #streamPromises = new WeakMap; + add(stream) { + validateStream(stream); + if (this.#streams.has(stream)) { + return; + } + this.#streams.add(stream); + this.#onFinished ??= onMergedStreamFinished(this, this.#streams, this.#unpipeEvent); + const streamPromise = endWhenStreamsDone({ + passThroughStream: this, + stream, + streams: this.#streams, + ended: this.#ended, + aborted: this.#aborted, + onFinished: this.#onFinished, + unpipeEvent: this.#unpipeEvent + }); + this.#streamPromises.set(stream, streamPromise); + stream.pipe(this, { end: false }); + } + async remove(stream) { + validateStream(stream); + if (!this.#streams.has(stream)) { + return false; + } + const streamPromise = this.#streamPromises.get(stream); + if (streamPromise === undefined) { + return false; + } + this.#streamPromises.delete(stream); + stream.unpipe(this); + await streamPromise; + return true; + } + }; +}); + +// node_modules/execa/lib/io/pipeline.js +import { finished as finished3 } from "node:stream/promises"; +var pipeStreams = (source, destination) => { + source.pipe(destination); + onSourceFinish(source, destination); + onDestinationFinish(source, destination); +}, onSourceFinish = async (source, destination) => { + if (isStandardStream(source) || isStandardStream(destination)) { + return; + } + try { + await finished3(source, { cleanup: true, readable: true, writable: false }); + } catch {} + endDestinationStream(destination); +}, endDestinationStream = (destination) => { + if (destination.writable) { + destination.end(); + } +}, onDestinationFinish = async (source, destination) => { + if (isStandardStream(source) || isStandardStream(destination)) { + return; + } + try { + await finished3(destination, { cleanup: true, readable: false, writable: true }); + } catch {} + abortSourceStream(source); +}, abortSourceStream = (source) => { + if (source.readable) { + source.destroy(); + } +}; +var init_pipeline = __esm(() => { + init_standard_stream(); +}); + +// node_modules/execa/lib/io/output-async.js +var pipeOutputAsync = (subprocess, fileDescriptors, controller) => { + const pipeGroups = new Map; + for (const [fdNumber, { stdioItems, direction }] of Object.entries(fileDescriptors)) { + for (const { stream } of stdioItems.filter(({ type }) => TRANSFORM_TYPES.has(type))) { + pipeTransform(subprocess, stream, direction, fdNumber); + } + for (const { stream } of stdioItems.filter(({ type }) => !TRANSFORM_TYPES.has(type))) { + pipeStdioItem({ + subprocess, + stream, + direction, + fdNumber, + pipeGroups, + controller + }); + } + } + for (const [outputStream, inputStreams] of pipeGroups.entries()) { + const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams); + pipeStreams(inputStream, outputStream); + } +}, pipeTransform = (subprocess, stream, direction, fdNumber) => { + if (direction === "output") { + pipeStreams(subprocess.stdio[fdNumber], stream); + } else { + pipeStreams(stream, subprocess.stdio[fdNumber]); + } + const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber]; + if (streamProperty !== undefined) { + subprocess[streamProperty] = stream; + } + subprocess.stdio[fdNumber] = stream; +}, SUBPROCESS_STREAM_PROPERTIES, pipeStdioItem = ({ subprocess, stream, direction, fdNumber, pipeGroups, controller }) => { + if (stream === undefined) { + return; + } + setStandardStreamMaxListeners(stream, controller); + const [inputStream, outputStream] = direction === "output" ? [stream, subprocess.stdio[fdNumber]] : [subprocess.stdio[fdNumber], stream]; + const outputStreams = pipeGroups.get(inputStream) ?? []; + pipeGroups.set(inputStream, [...outputStreams, outputStream]); +}, setStandardStreamMaxListeners = (stream, { signal }) => { + if (isStandardStream(stream)) { + incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal); + } +}, MAX_LISTENERS_INCREMENT = 2; +var init_output_async = __esm(() => { + init_merge_streams(); + init_standard_stream(); + init_max_listeners(); + init_type(); + init_pipeline(); + SUBPROCESS_STREAM_PROPERTIES = ["stdin", "stdout", "stderr"]; +}); + +// node_modules/signal-exit/dist/mjs/signals.js +var signals; +var init_signals2 = __esm(() => { + signals = []; + signals.push("SIGHUP", "SIGINT", "SIGTERM"); + if (process.platform !== "win32") { + signals.push("SIGALRM", "SIGABRT", "SIGVTALRM", "SIGXCPU", "SIGXFSZ", "SIGUSR2", "SIGTRAP", "SIGSYS", "SIGQUIT", "SIGIOT"); + } + if (process.platform === "linux") { + signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT"); + } +}); + +// node_modules/signal-exit/dist/mjs/index.js +class Emitter { + emitted = { + afterExit: false, + exit: false + }; + listeners = { + afterExit: [], + exit: [] + }; + count = 0; + id = Math.random(); + constructor() { + if (global2[kExitEmitter]) { + return global2[kExitEmitter]; + } + ObjectDefineProperty(global2, kExitEmitter, { + value: this, + writable: false, + enumerable: false, + configurable: false + }); + } + on(ev, fn) { + this.listeners[ev].push(fn); + } + removeListener(ev, fn) { + const list = this.listeners[ev]; + const i3 = list.indexOf(fn); + if (i3 === -1) { + return; + } + if (i3 === 0 && list.length === 1) { + list.length = 0; + } else { + list.splice(i3, 1); + } + } + emit(ev, code, signal) { + if (this.emitted[ev]) { + return false; + } + this.emitted[ev] = true; + let ret = false; + for (const fn of this.listeners[ev]) { + ret = fn(code, signal) === true || ret; + } + if (ev === "exit") { + ret = this.emit("afterExit", code, signal) || ret; + } + return ret; + } +} + +class SignalExitBase { +} +var processOk = (process10) => !!process10 && typeof process10 === "object" && typeof process10.removeListener === "function" && typeof process10.emit === "function" && typeof process10.reallyExit === "function" && typeof process10.listeners === "function" && typeof process10.kill === "function" && typeof process10.pid === "number" && typeof process10.on === "function", kExitEmitter, global2, ObjectDefineProperty, signalExitWrap = (handler) => { + return { + onExit(cb, opts) { + return handler.onExit(cb, opts); + }, + load() { + return handler.load(); + }, + unload() { + return handler.unload(); + } + }; +}, SignalExitFallback, SignalExit, process10, onExit, load, unload; +var init_mjs = __esm(() => { + init_signals2(); + kExitEmitter = Symbol.for("signal-exit emitter"); + global2 = globalThis; + ObjectDefineProperty = Object.defineProperty.bind(Object); + SignalExitFallback = class SignalExitFallback extends SignalExitBase { + onExit() { + return () => {}; + } + load() {} + unload() {} + }; + SignalExit = class SignalExit extends SignalExitBase { + #hupSig = process10.platform === "win32" ? "SIGINT" : "SIGHUP"; + #emitter = new Emitter; + #process; + #originalProcessEmit; + #originalProcessReallyExit; + #sigListeners = {}; + #loaded = false; + constructor(process10) { + super(); + this.#process = process10; + this.#sigListeners = {}; + for (const sig of signals) { + this.#sigListeners[sig] = () => { + const listeners = this.#process.listeners(sig); + let { count: count2 } = this.#emitter; + const p = process10; + if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") { + count2 += p.__signal_exit_emitter__.count; + } + if (listeners.length === count2) { + this.unload(); + const ret = this.#emitter.emit("exit", null, sig); + const s2 = sig === "SIGHUP" ? this.#hupSig : sig; + if (!ret) + process10.kill(process10.pid, s2); + } + }; + } + this.#originalProcessReallyExit = process10.reallyExit; + this.#originalProcessEmit = process10.emit; + } + onExit(cb, opts) { + if (!processOk(this.#process)) { + return () => {}; + } + if (this.#loaded === false) { + this.load(); + } + const ev = opts?.alwaysLast ? "afterExit" : "exit"; + this.#emitter.on(ev, cb); + return () => { + this.#emitter.removeListener(ev, cb); + if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) { + this.unload(); + } + }; + } + load() { + if (this.#loaded) { + return; + } + this.#loaded = true; + this.#emitter.count += 1; + for (const sig of signals) { + try { + const fn = this.#sigListeners[sig]; + if (fn) + this.#process.on(sig, fn); + } catch (_) {} + } + this.#process.emit = (ev, ...a2) => { + return this.#processEmit(ev, ...a2); + }; + this.#process.reallyExit = (code) => { + return this.#processReallyExit(code); + }; + } + unload() { + if (!this.#loaded) { + return; + } + this.#loaded = false; + signals.forEach((sig) => { + const listener = this.#sigListeners[sig]; + if (!listener) { + throw new Error("Listener not defined for signal: " + sig); + } + try { + this.#process.removeListener(sig, listener); + } catch (_) {} + }); + this.#process.emit = this.#originalProcessEmit; + this.#process.reallyExit = this.#originalProcessReallyExit; + this.#emitter.count -= 1; + } + #processReallyExit(code) { + if (!processOk(this.#process)) { + return 0; + } + this.#process.exitCode = code || 0; + this.#emitter.emit("exit", this.#process.exitCode, null); + return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode); + } + #processEmit(ev, ...args) { + const og = this.#originalProcessEmit; + if (ev === "exit" && processOk(this.#process)) { + if (typeof args[0] === "number") { + this.#process.exitCode = args[0]; + } + const ret = og.call(this.#process, ev, ...args); + this.#emitter.emit("exit", this.#process.exitCode, null); + return ret; + } else { + return og.call(this.#process, ev, ...args); + } + } + }; + process10 = globalThis.process; + ({ + onExit, + load, + unload + } = signalExitWrap(processOk(process10) ? new SignalExit(process10) : new SignalExitFallback)); +}); + +// node_modules/execa/lib/terminate/cleanup.js +import { addAbortListener as addAbortListener2 } from "node:events"; +var cleanupOnExit = (subprocess, { cleanup, detached }, { signal }) => { + if (!cleanup || detached) { + return; + } + const removeExitHandler = onExit(() => { + subprocess.kill(); + }); + addAbortListener2(signal, () => { + removeExitHandler(); + }); +}; +var init_cleanup = __esm(() => { + init_mjs(); +}); + +// node_modules/execa/lib/pipe/pipe-arguments.js +var normalizePipeArguments = ({ source, sourcePromise, boundOptions, createNested }, ...pipeArguments) => { + const startTime = getStartTime(); + const { + destination, + destinationStream, + destinationError, + from, + unpipeSignal + } = getDestinationStream(boundOptions, createNested, pipeArguments); + const { sourceStream, sourceError } = getSourceStream(source, from); + const { options: sourceOptions, fileDescriptors } = SUBPROCESS_OPTIONS.get(source); + return { + sourcePromise, + sourceStream, + sourceOptions, + sourceError, + destination, + destinationStream, + destinationError, + unpipeSignal, + fileDescriptors, + startTime + }; +}, getDestinationStream = (boundOptions, createNested, pipeArguments) => { + try { + const { + destination, + pipeOptions: { from, to, unpipeSignal } = {} + } = getDestination(boundOptions, createNested, ...pipeArguments); + const destinationStream = getToStream(destination, to); + return { + destination, + destinationStream, + from, + unpipeSignal + }; + } catch (error) { + return { destinationError: error }; + } +}, getDestination = (boundOptions, createNested, firstArgument, ...pipeArguments) => { + if (Array.isArray(firstArgument)) { + const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...pipeArguments); + return { destination, pipeOptions: boundOptions }; + } + if (typeof firstArgument === "string" || firstArgument instanceof URL || isDenoExecPath(firstArgument)) { + if (Object.keys(boundOptions).length > 0) { + throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).'); + } + const [rawFile, rawArguments, rawOptions] = normalizeParameters(firstArgument, ...pipeArguments); + const destination = createNested(mapDestinationArguments)(rawFile, rawArguments, rawOptions); + return { destination, pipeOptions: rawOptions }; + } + if (SUBPROCESS_OPTIONS.has(firstArgument)) { + if (Object.keys(boundOptions).length > 0) { + throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`)."); + } + return { destination: firstArgument, pipeOptions: pipeArguments[0] }; + } + throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`); +}, mapDestinationArguments = ({ options }) => ({ options: { ...options, stdin: "pipe", piped: true } }), getSourceStream = (source, from) => { + try { + const sourceStream = getFromStream(source, from); + return { sourceStream }; + } catch (error) { + return { sourceError: error }; + } +}; +var init_pipe_arguments = __esm(() => { + init_parameters(); + init_duration(); + init_fd_options(); + init_file_url(); +}); + +// node_modules/execa/lib/pipe/throw.js +var handlePipeArgumentsError = ({ + sourceStream, + sourceError, + destinationStream, + destinationError, + fileDescriptors, + sourceOptions, + startTime +}) => { + const error = getPipeArgumentsError({ + sourceStream, + sourceError, + destinationStream, + destinationError + }); + if (error !== undefined) { + throw createNonCommandError({ + error, + fileDescriptors, + sourceOptions, + startTime + }); + } +}, getPipeArgumentsError = ({ sourceStream, sourceError, destinationStream, destinationError }) => { + if (sourceError !== undefined && destinationError !== undefined) { + return destinationError; + } + if (destinationError !== undefined) { + abortSourceStream(sourceStream); + return destinationError; + } + if (sourceError !== undefined) { + endDestinationStream(destinationStream); + return sourceError; + } +}, createNonCommandError = ({ error, fileDescriptors, sourceOptions, startTime }) => makeEarlyError({ + error, + command: PIPE_COMMAND_MESSAGE, + escapedCommand: PIPE_COMMAND_MESSAGE, + fileDescriptors, + options: sourceOptions, + startTime, + isSync: false +}), PIPE_COMMAND_MESSAGE = "source.pipe(destination)"; +var init_throw = __esm(() => { + init_result(); + init_pipeline(); +}); + +// node_modules/execa/lib/pipe/sequence.js +var waitForBothSubprocesses = async (subprocessPromises) => { + const [ + { status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason }, + { status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason } + ] = await subprocessPromises; + if (!destinationResult.pipedFrom.includes(sourceResult)) { + destinationResult.pipedFrom.push(sourceResult); + } + if (destinationStatus === "rejected") { + throw destinationResult; + } + if (sourceStatus === "rejected") { + throw sourceResult; + } + return destinationResult; +}; + +// node_modules/execa/lib/pipe/streaming.js +import { finished as finished4 } from "node:stream/promises"; +var pipeSubprocessStream = (sourceStream, destinationStream, maxListenersController) => { + const mergedStream = MERGED_STREAMS.has(destinationStream) ? pipeMoreSubprocessStream(sourceStream, destinationStream) : pipeFirstSubprocessStream(sourceStream, destinationStream); + incrementMaxListeners(sourceStream, SOURCE_LISTENERS_PER_PIPE, maxListenersController.signal); + incrementMaxListeners(destinationStream, DESTINATION_LISTENERS_PER_PIPE, maxListenersController.signal); + cleanupMergedStreamsMap(destinationStream); + return mergedStream; +}, pipeFirstSubprocessStream = (sourceStream, destinationStream) => { + const mergedStream = mergeStreams([sourceStream]); + pipeStreams(mergedStream, destinationStream); + MERGED_STREAMS.set(destinationStream, mergedStream); + return mergedStream; +}, pipeMoreSubprocessStream = (sourceStream, destinationStream) => { + const mergedStream = MERGED_STREAMS.get(destinationStream); + mergedStream.add(sourceStream); + return mergedStream; +}, cleanupMergedStreamsMap = async (destinationStream) => { + try { + await finished4(destinationStream, { cleanup: true, readable: false, writable: true }); + } catch {} + MERGED_STREAMS.delete(destinationStream); +}, MERGED_STREAMS, SOURCE_LISTENERS_PER_PIPE = 2, DESTINATION_LISTENERS_PER_PIPE = 1; +var init_streaming = __esm(() => { + init_merge_streams(); + init_max_listeners(); + init_pipeline(); + MERGED_STREAMS = new WeakMap; +}); + +// node_modules/execa/lib/pipe/abort.js +import { aborted } from "node:util"; +var unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === undefined ? [] : [unpipeOnSignalAbort(unpipeSignal, unpipeContext)], unpipeOnSignalAbort = async (unpipeSignal, { sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime }) => { + await aborted(unpipeSignal, sourceStream); + await mergedStream.remove(sourceStream); + const error = new Error("Pipe canceled by `unpipeSignal` option."); + throw createNonCommandError({ + error, + fileDescriptors, + sourceOptions, + startTime + }); +}; +var init_abort = __esm(() => { + init_throw(); +}); + +// node_modules/execa/lib/pipe/setup.js +var pipeToSubprocess = (sourceInfo, ...pipeArguments) => { + if (isPlainObject2(pipeArguments[0])) { + return pipeToSubprocess.bind(undefined, { + ...sourceInfo, + boundOptions: { ...sourceInfo.boundOptions, ...pipeArguments[0] } + }); + } + const { destination, ...normalizedInfo } = normalizePipeArguments(sourceInfo, ...pipeArguments); + const promise = handlePipePromise({ ...normalizedInfo, destination }); + promise.pipe = pipeToSubprocess.bind(undefined, { + ...sourceInfo, + source: destination, + sourcePromise: promise, + boundOptions: {} + }); + return promise; +}, handlePipePromise = async ({ + sourcePromise, + sourceStream, + sourceOptions, + sourceError, + destination, + destinationStream, + destinationError, + unpipeSignal, + fileDescriptors, + startTime +}) => { + const subprocessPromises = getSubprocessPromises(sourcePromise, destination); + handlePipeArgumentsError({ + sourceStream, + sourceError, + destinationStream, + destinationError, + fileDescriptors, + sourceOptions, + startTime + }); + const maxListenersController = new AbortController; + try { + const mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController); + return await Promise.race([ + waitForBothSubprocesses(subprocessPromises), + ...unpipeOnAbort(unpipeSignal, { + sourceStream, + mergedStream, + sourceOptions, + fileDescriptors, + startTime + }) + ]); + } finally { + maxListenersController.abort(); + } +}, getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]); +var init_setup = __esm(() => { + init_pipe_arguments(); + init_throw(); + init_streaming(); + init_abort(); +}); + +// node_modules/execa/lib/io/iterate.js +import { on as on5 } from "node:events"; +import { getDefaultHighWaterMark as getDefaultHighWaterMark3 } from "node:stream"; +var iterateOnSubprocessStream = ({ subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines }) => { + const controller = new AbortController; + stopReadingOnExit(subprocess, controller); + return iterateOnStream({ + stream: subprocessStdout, + controller, + binary, + shouldEncode: !subprocessStdout.readableObjectMode && shouldEncode, + encoding, + shouldSplit: !subprocessStdout.readableObjectMode, + preserveNewlines + }); +}, stopReadingOnExit = async (subprocess, controller) => { + try { + await subprocess; + } catch {} finally { + controller.abort(); + } +}, iterateForResult = ({ stream, onStreamEnd, lines, encoding, stripFinalNewline: stripFinalNewline2, allMixed }) => { + const controller = new AbortController; + stopReadingOnStreamEnd(onStreamEnd, controller, stream); + const objectMode = stream.readableObjectMode && !allMixed; + return iterateOnStream({ + stream, + controller, + binary: encoding === "buffer", + shouldEncode: !objectMode, + encoding, + shouldSplit: !objectMode && lines, + preserveNewlines: !stripFinalNewline2 + }); +}, stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => { + try { + await onStreamEnd; + } catch { + stream.destroy(); + } finally { + controller.abort(); + } +}, iterateOnStream = ({ stream, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) => { + const onStdoutChunk = on5(stream, "data", { + signal: controller.signal, + highWaterMark: HIGH_WATER_MARK, + highWatermark: HIGH_WATER_MARK + }); + return iterateOnData({ + onStdoutChunk, + controller, + binary, + shouldEncode, + encoding, + shouldSplit, + preserveNewlines + }); +}, DEFAULT_OBJECT_HIGH_WATER_MARK, HIGH_WATER_MARK, iterateOnData = async function* ({ onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) { + const generators = getGenerators({ + binary, + shouldEncode, + encoding, + shouldSplit, + preserveNewlines + }); + try { + for await (const [chunk] of onStdoutChunk) { + yield* transformChunkSync(chunk, generators, 0); + } + } catch (error) { + if (!controller.signal.aborted) { + throw error; + } + } finally { + yield* finalChunksSync(generators); + } +}, getGenerators = ({ binary, shouldEncode, encoding, shouldSplit, preserveNewlines }) => [ + getEncodingTransformGenerator(binary, encoding, !shouldEncode), + getSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {}) +].filter(Boolean); +var init_iterate = __esm(() => { + init_encoding_transform(); + init_split(); + DEFAULT_OBJECT_HIGH_WATER_MARK = getDefaultHighWaterMark3(true); + HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK; +}); + +// node_modules/execa/lib/io/contents.js +import { setImmediate as setImmediate2 } from "node:timers/promises"; +var getStreamOutput = async ({ stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => { + const logPromise = logOutputAsync({ + stream, + onStreamEnd, + fdNumber, + encoding, + allMixed, + verboseInfo, + streamInfo + }); + if (!buffer) { + await Promise.all([resumeStream(stream), logPromise]); + return; + } + const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline2, fdNumber); + const iterable = iterateForResult({ + stream, + onStreamEnd, + lines, + encoding, + stripFinalNewline: stripFinalNewlineValue, + allMixed + }); + const [output] = await Promise.all([ + getStreamContents2({ + stream, + iterable, + fdNumber, + encoding, + maxBuffer, + lines + }), + logPromise + ]); + return output; +}, logOutputAsync = async ({ stream, onStreamEnd, fdNumber, encoding, allMixed, verboseInfo, streamInfo: { fileDescriptors } }) => { + if (!shouldLogOutput({ + stdioItems: fileDescriptors[fdNumber]?.stdioItems, + encoding, + verboseInfo, + fdNumber + })) { + return; + } + const linesIterable = iterateForResult({ + stream, + onStreamEnd, + lines: true, + encoding, + stripFinalNewline: true, + allMixed + }); + await logLines(linesIterable, stream, fdNumber, verboseInfo); +}, resumeStream = async (stream) => { + await setImmediate2(); + if (stream.readableFlowing === null) { + stream.resume(); + } +}, getStreamContents2 = async ({ stream, stream: { readableObjectMode }, iterable, fdNumber, encoding, maxBuffer, lines }) => { + try { + if (readableObjectMode || lines) { + return await getStreamAsArray(iterable, { maxBuffer }); + } + if (encoding === "buffer") { + return new Uint8Array(await getStreamAsArrayBuffer(iterable, { maxBuffer })); + } + return await getStreamAsString(iterable, { maxBuffer }); + } catch (error) { + return handleBufferedData(handleMaxBuffer({ + error, + stream, + readableObjectMode, + lines, + encoding, + fdNumber + })); + } +}, getBufferedData = async (streamPromise) => { + try { + return await streamPromise; + } catch (error) { + return handleBufferedData(error); + } +}, handleBufferedData = ({ bufferedData }) => isArrayBuffer(bufferedData) ? new Uint8Array(bufferedData) : bufferedData; +var init_contents2 = __esm(() => { + init_source(); + init_uint_array(); + init_output(); + init_iterate(); + init_max_buffer(); + init_strip_newline(); +}); + +// node_modules/execa/lib/resolve/wait-stream.js +import { finished as finished5 } from "node:stream/promises"; +var waitForStream = async (stream, fdNumber, streamInfo, { isSameDirection, stopOnExit = false } = {}) => { + const state = handleStdinDestroy(stream, streamInfo); + const abortController = new AbortController; + try { + await Promise.race([ + ...stopOnExit ? [streamInfo.exitPromise] : [], + finished5(stream, { cleanup: true, signal: abortController.signal }) + ]); + } catch (error) { + if (!state.stdinCleanedUp) { + handleStreamError(error, fdNumber, streamInfo, isSameDirection); + } + } finally { + abortController.abort(); + } +}, handleStdinDestroy = (stream, { originalStreams: [originalStdin], subprocess }) => { + const state = { stdinCleanedUp: false }; + if (stream === originalStdin) { + spyOnStdinDestroy(stream, subprocess, state); + } + return state; +}, spyOnStdinDestroy = (subprocessStdin, subprocess, state) => { + const { _destroy } = subprocessStdin; + subprocessStdin._destroy = (...destroyArguments) => { + setStdinCleanedUp(subprocess, state); + _destroy.call(subprocessStdin, ...destroyArguments); + }; +}, setStdinCleanedUp = ({ exitCode, signalCode }, state) => { + if (exitCode !== null || signalCode !== null) { + state.stdinCleanedUp = true; + } +}, handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => { + if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) { + throw error; + } +}, shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => { + if (streamInfo.propagating) { + return isStreamEpipe(error) || isStreamAbort(error); + } + streamInfo.propagating = true; + return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection ? isStreamEpipe(error) : isStreamAbort(error); +}, isInputFileDescriptor = ({ fileDescriptors }, fdNumber) => fdNumber !== "all" && fileDescriptors[fdNumber].direction === "input", isStreamAbort = (error) => error?.code === "ERR_STREAM_PREMATURE_CLOSE", isStreamEpipe = (error) => error?.code === "EPIPE"; +var init_wait_stream = () => {}; + +// node_modules/execa/lib/resolve/stdio.js +var waitForStdioStreams = ({ subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({ + stream, + fdNumber, + encoding, + buffer: buffer[fdNumber], + maxBuffer: maxBuffer[fdNumber], + lines: lines[fdNumber], + allMixed: false, + stripFinalNewline: stripFinalNewline2, + verboseInfo, + streamInfo +})), waitForSubprocessStream = async ({ stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => { + if (!stream) { + return; + } + const onStreamEnd = waitForStream(stream, fdNumber, streamInfo); + if (isInputFileDescriptor(streamInfo, fdNumber)) { + await onStreamEnd; + return; + } + const [output] = await Promise.all([ + getStreamOutput({ + stream, + onStreamEnd, + fdNumber, + encoding, + buffer, + maxBuffer, + lines, + allMixed, + stripFinalNewline: stripFinalNewline2, + verboseInfo, + streamInfo + }), + onStreamEnd + ]); + return output; +}; +var init_stdio = __esm(() => { + init_contents2(); + init_wait_stream(); +}); + +// node_modules/execa/lib/resolve/all-async.js +var makeAllStream = ({ stdout, stderr }, { all }) => all && (stdout || stderr) ? mergeStreams([stdout, stderr].filter(Boolean)) : undefined, waitForAllStream = ({ subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline: stripFinalNewline2, verboseInfo, streamInfo }) => waitForSubprocessStream({ + ...getAllStream(subprocess, buffer), + fdNumber: "all", + encoding, + maxBuffer: maxBuffer[1] + maxBuffer[2], + lines: lines[1] || lines[2], + allMixed: getAllMixed(subprocess), + stripFinalNewline: stripFinalNewline2, + verboseInfo, + streamInfo +}), getAllStream = ({ stdout, stderr, all }, [, bufferStdout, bufferStderr]) => { + const buffer = bufferStdout || bufferStderr; + if (!buffer) { + return { stream: all, buffer }; + } + if (!bufferStdout) { + return { stream: stderr, buffer }; + } + if (!bufferStderr) { + return { stream: stdout, buffer }; + } + return { stream: all, buffer }; +}, getAllMixed = ({ all, stdout, stderr }) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode; +var init_all_async = __esm(() => { + init_merge_streams(); + init_stdio(); +}); + +// node_modules/execa/lib/verbose/ipc.js +var shouldLogIpc = (verboseInfo) => isFullVerbose(verboseInfo, "ipc"), logIpcOutput = (message, verboseInfo) => { + const verboseMessage = serializeVerboseMessage(message); + verboseLog({ + type: "ipc", + verboseMessage, + fdNumber: "ipc", + verboseInfo + }); +}; +var init_ipc = __esm(() => { + init_log(); + init_values(); +}); + +// node_modules/execa/lib/ipc/buffer-messages.js +var waitForIpcOutput = async ({ + subprocess, + buffer: bufferArray, + maxBuffer: maxBufferArray, + ipc, + ipcOutput, + verboseInfo +}) => { + if (!ipc) { + return ipcOutput; + } + const isVerbose2 = shouldLogIpc(verboseInfo); + const buffer = getFdSpecificValue(bufferArray, "ipc"); + const maxBuffer = getFdSpecificValue(maxBufferArray, "ipc"); + for await (const message of loopOnMessages({ + anyProcess: subprocess, + channel: subprocess.channel, + isSubprocess: false, + ipc, + shouldAwait: false, + reference: true + })) { + if (buffer) { + checkIpcMaxBuffer(subprocess, ipcOutput, maxBuffer); + ipcOutput.push(message); + } + if (isVerbose2) { + logIpcOutput(message, verboseInfo); + } + } + return ipcOutput; +}, getBufferedIpcOutput = async (ipcOutputPromise, ipcOutput) => { + await Promise.allSettled([ipcOutputPromise]); + return ipcOutput; +}; +var init_buffer_messages = __esm(() => { + init_max_buffer(); + init_ipc(); + init_specific(); + init_get_each(); +}); + +// node_modules/execa/lib/resolve/wait-subprocess.js +import { once as once8 } from "node:events"; +var waitForSubprocessResult = async ({ + subprocess, + options: { + encoding, + buffer, + maxBuffer, + lines, + timeoutDuration: timeout, + cancelSignal, + gracefulCancel, + forceKillAfterDelay, + stripFinalNewline: stripFinalNewline2, + ipc, + ipcInput + }, + context: context3, + verboseInfo, + fileDescriptors, + originalStreams, + onInternalError, + controller +}) => { + const exitPromise = waitForExit(subprocess, context3); + const streamInfo = { + originalStreams, + fileDescriptors, + subprocess, + exitPromise, + propagating: false + }; + const stdioPromises = waitForStdioStreams({ + subprocess, + encoding, + buffer, + maxBuffer, + lines, + stripFinalNewline: stripFinalNewline2, + verboseInfo, + streamInfo + }); + const allPromise = waitForAllStream({ + subprocess, + encoding, + buffer, + maxBuffer, + lines, + stripFinalNewline: stripFinalNewline2, + verboseInfo, + streamInfo + }); + const ipcOutput = []; + const ipcOutputPromise = waitForIpcOutput({ + subprocess, + buffer, + maxBuffer, + ipc, + ipcOutput, + verboseInfo + }); + const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo); + const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo); + try { + return await Promise.race([ + Promise.all([ + {}, + waitForSuccessfulExit(exitPromise), + Promise.all(stdioPromises), + allPromise, + ipcOutputPromise, + sendIpcInput(subprocess, ipcInput), + ...originalPromises, + ...customStreamsEndPromises + ]), + onInternalError, + throwOnSubprocessError(subprocess, controller), + ...throwOnTimeout(subprocess, timeout, context3, controller), + ...throwOnCancel({ + subprocess, + cancelSignal, + gracefulCancel, + context: context3, + controller + }), + ...throwOnGracefulCancel({ + subprocess, + cancelSignal, + gracefulCancel, + forceKillAfterDelay, + context: context3, + controller + }) + ]); + } catch (error) { + context3.terminationReason ??= "other"; + return Promise.all([ + { error }, + exitPromise, + Promise.all(stdioPromises.map((stdioPromise) => getBufferedData(stdioPromise))), + getBufferedData(allPromise), + getBufferedIpcOutput(ipcOutputPromise, ipcOutput), + Promise.allSettled(originalPromises), + Promise.allSettled(customStreamsEndPromises) + ]); + } +}, waitForOriginalStreams = (originalStreams, subprocess, streamInfo) => originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber] ? undefined : waitForStream(stream, fdNumber, streamInfo)), waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({ stdioItems }, fdNumber) => stdioItems.filter(({ value, stream = value }) => isStream(stream, { checkOpen: false }) && !isStandardStream(stream)).map(({ type, value, stream = value }) => waitForStream(stream, fdNumber, streamInfo, { + isSameDirection: TRANSFORM_TYPES.has(type), + stopOnExit: type === "native" +}))), throwOnSubprocessError = async (subprocess, { signal }) => { + const [error] = await once8(subprocess, "error", { signal }); + throw error; +}; +var init_wait_subprocess = __esm(() => { + init_timeout(); + init_cancel(); + init_graceful2(); + init_standard_stream(); + init_type(); + init_contents2(); + init_buffer_messages(); + init_ipc_input(); + init_all_async(); + init_stdio(); + init_exit_async(); + init_wait_stream(); +}); + +// node_modules/execa/lib/convert/concurrent.js +var initializeConcurrentStreams = () => ({ + readableDestroy: new WeakMap, + writableFinal: new WeakMap, + writableDestroy: new WeakMap +}), addConcurrentStream = (concurrentStreams, stream, waitName) => { + const weakMap = concurrentStreams[waitName]; + if (!weakMap.has(stream)) { + weakMap.set(stream, []); + } + const promises = weakMap.get(stream); + const promise = createDeferred(); + promises.push(promise); + const resolve = promise.resolve.bind(promise); + return { resolve, promises }; +}, waitForConcurrentStreams = async ({ resolve, promises }, subprocess) => { + resolve(); + const [isSubprocessExit] = await Promise.race([ + Promise.allSettled([true, subprocess]), + Promise.all([false, ...promises]) + ]); + return !isSubprocessExit; +}; +var init_concurrent = () => {}; + +// node_modules/execa/lib/convert/shared.js +import { finished as finished6 } from "node:stream/promises"; +var safeWaitForSubprocessStdin = async (subprocessStdin) => { + if (subprocessStdin === undefined) { + return; + } + try { + await waitForSubprocessStdin(subprocessStdin); + } catch {} +}, safeWaitForSubprocessStdout = async (subprocessStdout) => { + if (subprocessStdout === undefined) { + return; + } + try { + await waitForSubprocessStdout(subprocessStdout); + } catch {} +}, waitForSubprocessStdin = async (subprocessStdin) => { + await finished6(subprocessStdin, { cleanup: true, readable: false, writable: true }); +}, waitForSubprocessStdout = async (subprocessStdout) => { + await finished6(subprocessStdout, { cleanup: true, readable: true, writable: false }); +}, waitForSubprocess = async (subprocess, error) => { + await subprocess; + if (error) { + throw error; + } +}, destroyOtherStream = (stream, isOpen, error) => { + if (error && !isStreamAbort(error)) { + stream.destroy(error); + } else if (isOpen) { + stream.destroy(); + } +}; +var init_shared = __esm(() => { + init_wait_stream(); +}); + +// node_modules/execa/lib/convert/readable.js +import { Readable as Readable3 } from "node:stream"; +import { callbackify as callbackify2 } from "node:util"; +var createReadable = ({ subprocess, concurrentStreams, encoding }, { from, binary: binaryOption = true, preserveNewlines = true } = {}) => { + const binary = binaryOption || BINARY_ENCODINGS.has(encoding); + const { subprocessStdout, waitReadableDestroy } = getSubprocessStdout(subprocess, from, concurrentStreams); + const { readableEncoding, readableObjectMode, readableHighWaterMark } = getReadableOptions(subprocessStdout, binary); + const { read, onStdoutDataDone } = getReadableMethods({ + subprocessStdout, + subprocess, + binary, + encoding, + preserveNewlines + }); + const readable2 = new Readable3({ + read, + destroy: callbackify2(onReadableDestroy.bind(undefined, { subprocessStdout, subprocess, waitReadableDestroy })), + highWaterMark: readableHighWaterMark, + objectMode: readableObjectMode, + encoding: readableEncoding + }); + onStdoutFinished({ + subprocessStdout, + onStdoutDataDone, + readable: readable2, + subprocess + }); + return readable2; +}, getSubprocessStdout = (subprocess, from, concurrentStreams) => { + const subprocessStdout = getFromStream(subprocess, from); + const waitReadableDestroy = addConcurrentStream(concurrentStreams, subprocessStdout, "readableDestroy"); + return { subprocessStdout, waitReadableDestroy }; +}, getReadableOptions = ({ readableEncoding, readableObjectMode, readableHighWaterMark }, binary) => binary ? { readableEncoding, readableObjectMode, readableHighWaterMark } : { readableEncoding, readableObjectMode: true, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK }, getReadableMethods = ({ subprocessStdout, subprocess, binary, encoding, preserveNewlines }) => { + const onStdoutDataDone = createDeferred(); + const onStdoutData = iterateOnSubprocessStream({ + subprocessStdout, + subprocess, + binary, + shouldEncode: !binary, + encoding, + preserveNewlines + }); + return { + read() { + onRead(this, onStdoutData, onStdoutDataDone); + }, + onStdoutDataDone + }; +}, onRead = async (readable2, onStdoutData, onStdoutDataDone) => { + try { + const { value, done } = await onStdoutData.next(); + if (done) { + onStdoutDataDone.resolve(); + } else { + readable2.push(value); + } + } catch {} +}, onStdoutFinished = async ({ subprocessStdout, onStdoutDataDone, readable: readable2, subprocess, subprocessStdin }) => { + try { + await waitForSubprocessStdout(subprocessStdout); + await subprocess; + await safeWaitForSubprocessStdin(subprocessStdin); + await onStdoutDataDone; + if (readable2.readable) { + readable2.push(null); + } + } catch (error) { + await safeWaitForSubprocessStdin(subprocessStdin); + destroyOtherReadable(readable2, error); + } +}, onReadableDestroy = async ({ subprocessStdout, subprocess, waitReadableDestroy }, error) => { + if (await waitForConcurrentStreams(waitReadableDestroy, subprocess)) { + destroyOtherReadable(subprocessStdout, error); + await waitForSubprocess(subprocess, error); + } +}, destroyOtherReadable = (stream, error) => { + destroyOtherStream(stream, stream.readable, error); +}; +var init_readable = __esm(() => { + init_encoding_option(); + init_fd_options(); + init_iterate(); + init_concurrent(); + init_shared(); +}); + +// node_modules/execa/lib/convert/writable.js +import { Writable as Writable3 } from "node:stream"; +import { callbackify as callbackify3 } from "node:util"; +var createWritable = ({ subprocess, concurrentStreams }, { to } = {}) => { + const { subprocessStdin, waitWritableFinal, waitWritableDestroy } = getSubprocessStdin(subprocess, to, concurrentStreams); + const writable2 = new Writable3({ + ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal), + destroy: callbackify3(onWritableDestroy.bind(undefined, { + subprocessStdin, + subprocess, + waitWritableFinal, + waitWritableDestroy + })), + highWaterMark: subprocessStdin.writableHighWaterMark, + objectMode: subprocessStdin.writableObjectMode + }); + onStdinFinished(subprocessStdin, writable2); + return writable2; +}, getSubprocessStdin = (subprocess, to, concurrentStreams) => { + const subprocessStdin = getToStream(subprocess, to); + const waitWritableFinal = addConcurrentStream(concurrentStreams, subprocessStdin, "writableFinal"); + const waitWritableDestroy = addConcurrentStream(concurrentStreams, subprocessStdin, "writableDestroy"); + return { subprocessStdin, waitWritableFinal, waitWritableDestroy }; +}, getWritableMethods = (subprocessStdin, subprocess, waitWritableFinal) => ({ + write: onWrite.bind(undefined, subprocessStdin), + final: callbackify3(onWritableFinal.bind(undefined, subprocessStdin, subprocess, waitWritableFinal)) +}), onWrite = (subprocessStdin, chunk, encoding, done) => { + if (subprocessStdin.write(chunk, encoding)) { + done(); + } else { + subprocessStdin.once("drain", done); + } +}, onWritableFinal = async (subprocessStdin, subprocess, waitWritableFinal) => { + if (await waitForConcurrentStreams(waitWritableFinal, subprocess)) { + if (subprocessStdin.writable) { + subprocessStdin.end(); + } + await subprocess; + } +}, onStdinFinished = async (subprocessStdin, writable2, subprocessStdout) => { + try { + await waitForSubprocessStdin(subprocessStdin); + if (writable2.writable) { + writable2.end(); + } + } catch (error) { + await safeWaitForSubprocessStdout(subprocessStdout); + destroyOtherWritable(writable2, error); + } +}, onWritableDestroy = async ({ subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy }, error) => { + await waitForConcurrentStreams(waitWritableFinal, subprocess); + if (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) { + destroyOtherWritable(subprocessStdin, error); + await waitForSubprocess(subprocess, error); + } +}, destroyOtherWritable = (stream, error) => { + destroyOtherStream(stream, stream.writable, error); +}; +var init_writable = __esm(() => { + init_fd_options(); + init_concurrent(); + init_shared(); +}); + +// node_modules/execa/lib/convert/duplex.js +import { Duplex as Duplex3 } from "node:stream"; +import { callbackify as callbackify4 } from "node:util"; +var createDuplex = ({ subprocess, concurrentStreams, encoding }, { from, to, binary: binaryOption = true, preserveNewlines = true } = {}) => { + const binary = binaryOption || BINARY_ENCODINGS.has(encoding); + const { subprocessStdout, waitReadableDestroy } = getSubprocessStdout(subprocess, from, concurrentStreams); + const { subprocessStdin, waitWritableFinal, waitWritableDestroy } = getSubprocessStdin(subprocess, to, concurrentStreams); + const { readableEncoding, readableObjectMode, readableHighWaterMark } = getReadableOptions(subprocessStdout, binary); + const { read, onStdoutDataDone } = getReadableMethods({ + subprocessStdout, + subprocess, + binary, + encoding, + preserveNewlines + }); + const duplex2 = new Duplex3({ + read, + ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal), + destroy: callbackify4(onDuplexDestroy.bind(undefined, { + subprocessStdout, + subprocessStdin, + subprocess, + waitReadableDestroy, + waitWritableFinal, + waitWritableDestroy + })), + readableHighWaterMark, + writableHighWaterMark: subprocessStdin.writableHighWaterMark, + readableObjectMode, + writableObjectMode: subprocessStdin.writableObjectMode, + encoding: readableEncoding + }); + onStdoutFinished({ + subprocessStdout, + onStdoutDataDone, + readable: duplex2, + subprocess, + subprocessStdin + }); + onStdinFinished(subprocessStdin, duplex2, subprocessStdout); + return duplex2; +}, onDuplexDestroy = async ({ subprocessStdout, subprocessStdin, subprocess, waitReadableDestroy, waitWritableFinal, waitWritableDestroy }, error) => { + await Promise.all([ + onReadableDestroy({ subprocessStdout, subprocess, waitReadableDestroy }, error), + onWritableDestroy({ + subprocessStdin, + subprocess, + waitWritableFinal, + waitWritableDestroy + }, error) + ]); +}; +var init_duplex = __esm(() => { + init_encoding_option(); + init_readable(); + init_writable(); +}); + +// node_modules/execa/lib/convert/iterable.js +var createIterable = (subprocess, encoding, { + from, + binary: binaryOption = false, + preserveNewlines = false +} = {}) => { + const binary = binaryOption || BINARY_ENCODINGS.has(encoding); + const subprocessStdout = getFromStream(subprocess, from); + const onStdoutData = iterateOnSubprocessStream({ + subprocessStdout, + subprocess, + binary, + shouldEncode: true, + encoding, + preserveNewlines + }); + return iterateOnStdoutData(onStdoutData, subprocessStdout, subprocess); +}, iterateOnStdoutData = async function* (onStdoutData, subprocessStdout, subprocess) { + try { + yield* onStdoutData; + } finally { + if (subprocessStdout.readable) { + subprocessStdout.destroy(); + } + await subprocess; + } +}; +var init_iterable = __esm(() => { + init_encoding_option(); + init_fd_options(); + init_iterate(); +}); + +// node_modules/execa/lib/convert/add.js +var addConvertedStreams = (subprocess, { encoding }) => { + const concurrentStreams = initializeConcurrentStreams(); + subprocess.readable = createReadable.bind(undefined, { subprocess, concurrentStreams, encoding }); + subprocess.writable = createWritable.bind(undefined, { subprocess, concurrentStreams }); + subprocess.duplex = createDuplex.bind(undefined, { subprocess, concurrentStreams, encoding }); + subprocess.iterable = createIterable.bind(undefined, subprocess, encoding); + subprocess[Symbol.asyncIterator] = createIterable.bind(undefined, subprocess, encoding, {}); +}; +var init_add = __esm(() => { + init_concurrent(); + init_readable(); + init_writable(); + init_duplex(); + init_iterable(); +}); + +// node_modules/execa/lib/methods/promise.js +var mergePromise = (subprocess, promise) => { + for (const [property, descriptor] of descriptors) { + const value = descriptor.value.bind(promise); + Reflect.defineProperty(subprocess, property, { ...descriptor, value }); + } +}, nativePromisePrototype, descriptors; +var init_promise = __esm(() => { + nativePromisePrototype = (async () => {})().constructor.prototype; + descriptors = ["then", "catch", "finally"].map((property) => [ + property, + Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property) + ]); +}); + +// node_modules/execa/lib/methods/main-async.js +import { setMaxListeners } from "node:events"; +import { spawn } from "node:child_process"; +var execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => { + const { file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors } = handleAsyncArguments(rawFile, rawArguments, rawOptions); + const { subprocess, promise } = spawnSubprocessAsync({ + file, + commandArguments, + options, + startTime, + verboseInfo, + command, + escapedCommand, + fileDescriptors + }); + subprocess.pipe = pipeToSubprocess.bind(undefined, { + source: subprocess, + sourcePromise: promise, + boundOptions: {}, + createNested + }); + mergePromise(subprocess, promise); + SUBPROCESS_OPTIONS.set(subprocess, { options, fileDescriptors }); + return subprocess; +}, handleAsyncArguments = (rawFile, rawArguments, rawOptions) => { + const { command, escapedCommand, startTime, verboseInfo } = handleCommand(rawFile, rawArguments, rawOptions); + const { file, commandArguments, options: normalizedOptions } = normalizeOptions(rawFile, rawArguments, rawOptions); + const options = handleAsyncOptions(normalizedOptions); + const fileDescriptors = handleStdioAsync(options, verboseInfo); + return { + file, + commandArguments, + command, + escapedCommand, + startTime, + verboseInfo, + options, + fileDescriptors + }; +}, handleAsyncOptions = ({ timeout, signal, ...options }) => { + if (signal !== undefined) { + throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.'); + } + return { ...options, timeoutDuration: timeout }; +}, spawnSubprocessAsync = ({ file, commandArguments, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors }) => { + let subprocess; + try { + subprocess = spawn(...concatenateShell(file, commandArguments, options)); + } catch (error) { + return handleEarlyError({ + error, + command, + escapedCommand, + fileDescriptors, + options, + startTime, + verboseInfo + }); + } + const controller = new AbortController; + setMaxListeners(Number.POSITIVE_INFINITY, controller.signal); + const originalStreams = [...subprocess.stdio]; + pipeOutputAsync(subprocess, fileDescriptors, controller); + cleanupOnExit(subprocess, options, controller); + const context3 = {}; + const onInternalError = createDeferred(); + subprocess.kill = subprocessKill.bind(undefined, { + kill: subprocess.kill.bind(subprocess), + options, + onInternalError, + context: context3, + controller + }); + subprocess.all = makeAllStream(subprocess, options); + addConvertedStreams(subprocess, options); + addIpcMethods(subprocess, options); + const promise = handlePromise({ + subprocess, + options, + startTime, + verboseInfo, + fileDescriptors, + originalStreams, + command, + escapedCommand, + context: context3, + onInternalError, + controller + }); + return { subprocess, promise }; +}, handlePromise = async ({ subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context: context3, onInternalError, controller }) => { + const [ + errorInfo, + [exitCode, signal], + stdioResults, + allResult, + ipcOutput + ] = await waitForSubprocessResult({ + subprocess, + options, + context: context3, + verboseInfo, + fileDescriptors, + originalStreams, + onInternalError, + controller + }); + controller.abort(); + onInternalError.resolve(); + const stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber)); + const all = stripNewline(allResult, options, "all"); + const result = getAsyncResult({ + errorInfo, + exitCode, + signal, + stdio, + all, + ipcOutput, + context: context3, + options, + command, + escapedCommand, + startTime + }); + return handleResult(result, verboseInfo, options); +}, getAsyncResult = ({ errorInfo, exitCode, signal, stdio, all, ipcOutput, context: context3, options, command, escapedCommand, startTime }) => ("error" in errorInfo) ? makeError({ + error: errorInfo.error, + command, + escapedCommand, + timedOut: context3.terminationReason === "timeout", + isCanceled: context3.terminationReason === "cancel" || context3.terminationReason === "gracefulCancel", + isGracefullyCanceled: context3.terminationReason === "gracefulCancel", + isMaxBuffer: errorInfo.error instanceof MaxBufferError, + isForcefullyTerminated: context3.isForcefullyTerminated, + exitCode, + signal, + stdio, + all, + ipcOutput, + options, + startTime, + isSync: false +}) : makeSuccessResult({ + command, + escapedCommand, + stdio, + all, + ipcOutput, + options, + startTime +}); +var init_main_async = __esm(() => { + init_source(); + init_command(); + init_options(); + init_fd_options(); + init_methods(); + init_result(); + init_reject(); + init_early_error(); + init_handle_async(); + init_strip_newline(); + init_output_async(); + init_kill(); + init_cleanup(); + init_setup(); + init_all_async(); + init_wait_subprocess(); + init_add(); + init_promise(); +}); + +// node_modules/execa/lib/methods/bind.js +var mergeOptions = (boundOptions, options) => { + const newOptions = Object.fromEntries(Object.entries(options).map(([optionName, optionValue]) => [ + optionName, + mergeOption(optionName, boundOptions[optionName], optionValue) + ])); + return { ...boundOptions, ...newOptions }; +}, mergeOption = (optionName, boundOptionValue, optionValue) => { + if (DEEP_OPTIONS.has(optionName) && isPlainObject2(boundOptionValue) && isPlainObject2(optionValue)) { + return { ...boundOptionValue, ...optionValue }; + } + return optionValue; +}, DEEP_OPTIONS; +var init_bind = __esm(() => { + init_specific(); + DEEP_OPTIONS = new Set(["env", ...FD_SPECIFIC_OPTIONS]); +}); + +// node_modules/execa/lib/methods/create.js +var createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => { + const createNested = (mapArguments2, boundOptions2, setBoundExeca2) => createExeca(mapArguments2, boundOptions2, deepOptions, setBoundExeca2); + const boundExeca = (...execaArguments) => callBoundExeca({ + mapArguments, + deepOptions, + boundOptions, + setBoundExeca, + createNested + }, ...execaArguments); + if (setBoundExeca !== undefined) { + setBoundExeca(boundExeca, createNested, boundOptions); + } + return boundExeca; +}, callBoundExeca = ({ mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested }, firstArgument, ...nextArguments) => { + if (isPlainObject2(firstArgument)) { + return createNested(mapArguments, mergeOptions(boundOptions, firstArgument), setBoundExeca); + } + const { file, commandArguments, options, isSync } = parseArguments({ + mapArguments, + firstArgument, + nextArguments, + deepOptions, + boundOptions + }); + return isSync ? execaCoreSync(file, commandArguments, options) : execaCoreAsync(file, commandArguments, options, createNested); +}, parseArguments = ({ mapArguments, firstArgument, nextArguments, deepOptions, boundOptions }) => { + const callArguments = isTemplateString(firstArgument) ? parseTemplates(firstArgument, nextArguments) : [firstArgument, ...nextArguments]; + const [initialFile, initialArguments, initialOptions] = normalizeParameters(...callArguments); + const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), initialOptions); + const { + file = initialFile, + commandArguments = initialArguments, + options = mergedOptions, + isSync = false + } = mapArguments({ file: initialFile, commandArguments: initialArguments, options: mergedOptions }); + return { + file, + commandArguments, + options, + isSync + }; +}; +var init_create = __esm(() => { + init_parameters(); + init_template(); + init_main_sync(); + init_main_async(); + init_bind(); +}); + +// node_modules/execa/lib/methods/command.js +var mapCommandAsync = ({ file, commandArguments }) => parseCommand(file, commandArguments), mapCommandSync = ({ file, commandArguments }) => ({ ...parseCommand(file, commandArguments), isSync: true }), parseCommand = (command, unusedArguments) => { + if (unusedArguments.length > 0) { + throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArguments}.`); + } + const [file, ...commandArguments] = parseCommandString(command); + return { file, commandArguments }; +}, parseCommandString = (command) => { + if (typeof command !== "string") { + throw new TypeError(`The command must be a string: ${String(command)}.`); + } + const trimmedCommand = command.trim(); + if (trimmedCommand === "") { + return []; + } + const tokens = []; + for (const token of trimmedCommand.split(SPACES_REGEXP)) { + const previousToken = tokens.at(-1); + if (previousToken && previousToken.endsWith("\\")) { + tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; + } else { + tokens.push(token); + } + } + return tokens; +}, SPACES_REGEXP; +var init_command2 = __esm(() => { + SPACES_REGEXP = / +/g; +}); + +// node_modules/execa/lib/methods/script.js +var setScriptSync = (boundExeca, createNested, boundOptions) => { + boundExeca.sync = createNested(mapScriptSync, boundOptions); + boundExeca.s = boundExeca.sync; +}, mapScriptAsync = ({ options }) => getScriptOptions(options), mapScriptSync = ({ options }) => ({ ...getScriptOptions(options), isSync: true }), getScriptOptions = (options) => ({ options: { ...getScriptStdinOption(options), ...options } }), getScriptStdinOption = ({ input, inputFile, stdio }) => input === undefined && inputFile === undefined && stdio === undefined ? { stdin: "inherit" } : {}, deepScriptOptions; +var init_script = __esm(() => { + deepScriptOptions = { preferLocal: true }; +}); + +// node_modules/execa/index.js +var execa, execaSync, execaCommand, execaCommandSync, execaNode, $, sendMessage2, getOneMessage2, getEachMessage2, getCancelSignal2; +var init_execa = __esm(() => { + init_create(); + init_command2(); + init_node2(); + init_script(); + init_methods(); + execa = createExeca(() => ({})); + execaSync = createExeca(() => ({ isSync: true })); + execaCommand = createExeca(mapCommandAsync); + execaCommandSync = createExeca(mapCommandSync); + execaNode = createExeca(mapNode); + $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync); + ({ + sendMessage: sendMessage2, + getOneMessage: getOneMessage2, + getEachMessage: getEachMessage2, + getCancelSignal: getCancelSignal2 + } = getIpcExport()); +}); + +// node_modules/tar/dist/esm/index.min.js +import Qr from "events"; +import I from "fs"; +import { EventEmitter as Di } from "node:events"; +import Cs from "node:stream"; +import { StringDecoder as Hr } from "node:string_decoder"; +import cr from "node:path"; +import Kt from "node:fs"; +import { dirname as Fn, parse as kn } from "path"; +import { EventEmitter as Dn } from "events"; +import zi from "assert"; +import { Buffer as Ot } from "buffer"; +import * as Ps from "zlib"; +import en from "zlib"; +import { posix as Zt } from "node:path"; +import { basename as _n } from "node:path"; +import ui from "fs"; +import X from "fs"; +import js from "path"; +import { win32 as Pn } from "node:path"; +import ar from "path"; +import Br from "node:fs"; +import co from "node:assert"; +import { randomBytes as Mr } from "node:crypto"; +import m2 from "node:fs"; +import R from "node:path"; +import pr from "fs"; +import wi from "node:fs"; +import we from "node:path"; +import k from "node:fs"; +import ro from "node:fs/promises"; +import Si from "node:path"; +import { join as xr } from "node:path"; +import v from "node:fs"; +import Pr from "node:path"; +function Zn(s4, t2, e2) { + let i3 = t2, r2 = t2 ? t2.next : s4.head, n2 = new me(e2, i3, r2, s4); + return n2.next === undefined && (s4.tail = n2), n2.prev === undefined && (s4.head = n2), s4.length++, n2; +} +function Yn(s4, t2) { + s4.tail = new me(t2, s4.tail, undefined, s4), s4.head || (s4.head = s4.tail), s4.length++; +} +function Kn(s4, t2) { + s4.head = new me(t2, undefined, s4.head, s4), s4.tail || (s4.tail = s4.head), s4.length++; +} +var zr, Ur = (s2, t2) => { + for (var e2 in t2) + zr(s2, e2, { get: t2[e2], enumerable: true }); +}, Ds, Wr = (s2) => !!s2 && typeof s2 == "object" && (s2 instanceof A2 || s2 instanceof Cs || Gr(s2) || Zr(s2)), Gr = (s2) => !!s2 && typeof s2 == "object" && s2 instanceof Di && typeof s2.pipe == "function" && s2.pipe !== Cs.Writable.prototype.pipe, Zr = (s2) => !!s2 && typeof s2 == "object" && s2 instanceof Di && typeof s2.write == "function" && typeof s2.end == "function", Q, J, nt, De, qt, Ne, Ns, Ae, As, z, Mt, g, Qt, Bt, b, N, _, bi, Ie, L, w, _i, Oi, Is, Ti, Z2, xi, Ce, Jt, Rt, C, jt = (s2) => Promise.resolve().then(s2), Yr = (s2) => s2(), Kr = (s2) => s2 === "end" || s2 === "finish" || s2 === "prefinish", Vr = (s2) => s2 instanceof ArrayBuffer || !!s2 && typeof s2 == "object" && s2.constructor && s2.constructor.name === "ArrayBuffer" && s2.byteLength >= 0, $r = (s2) => !Buffer.isBuffer(s2) && ArrayBuffer.isView(s2), Fe = class { + src; + dest; + opts; + ondrain; + constructor(t2, e2, i3) { + this.src = t2, this.dest = e2, this.opts = i3, this.ondrain = () => t2[Bt](), this.dest.on("drain", this.ondrain); + } + unpipe() { + this.dest.removeListener("drain", this.ondrain); + } + proxyErrors(t2) {} + end() { + this.unpipe(), this.opts.end && this.dest.end(); + } +}, Li, Xr = (s2) => !!s2.objectMode, qr = (s2) => !s2.objectMode && !!s2.encoding && s2.encoding !== "buffer", A2, Jr, ht, H, te, u2, Ni, tt, Ai, ki, vi, ie, ke, Ut, Ht, Ii, Pt, at, U, ot, Y, zt, Ci, j, ee, Fi, ve, gt, Me, bt, _t, Be, et, Wt, jr, Fs = (s2) => !!s2.sync && !!s2.file, ks = (s2) => !s2.sync && !!s2.file, vs = (s2) => !!s2.sync && !s2.file, Ms = (s2) => !s2.sync && !s2.file, Bs = (s2) => !!s2.file, tn = (s2) => { + let t2 = jr.get(s2); + return t2 || s2; +}, se = (s2 = {}) => { + if (!s2) + return {}; + let t2 = {}; + for (let [e2, i3] of Object.entries(s2)) { + let r2 = tn(e2); + t2[r2] = i3; + } + return t2.chmod === undefined && t2.noChmod === false && (t2.chmod = true), delete t2.noChmod, t2; +}, K = (s2, t2, e2, i3, r2) => Object.assign((n2 = [], o2, h3) => { + Array.isArray(n2) && (o2 = n2, n2 = {}), typeof o2 == "function" && (h3 = o2, o2 = undefined), o2 = o2 ? Array.from(o2) : []; + let a2 = se(n2); + if (r2?.(a2, o2), Fs(a2)) { + if (typeof h3 == "function") + throw new TypeError("callback not supported for sync tar functions"); + return s2(a2, o2); + } else if (ks(a2)) { + let l = t2(a2, o2); + return h3 ? l.then(() => h3(), h3) : l; + } else if (vs(a2)) { + if (typeof h3 == "function") + throw new TypeError("callback not supported for sync tar functions"); + return e2(a2, o2); + } else if (Ms(a2)) { + if (typeof h3 == "function") + throw new TypeError("callback only supported with file option"); + return i3(a2, o2); + } + throw new Error("impossible options??"); +}, { syncFile: s2, asyncFile: t2, syncNoFile: e2, asyncNoFile: i3, validate: r2 }), sn, M, rn, zs, nn = (s2) => s2, Bi, Tt, Gt, Pi, re, Pe, ze, Ue, He, We, Ge, Ze, Ye, Ke, Us = (s2, t2) => { + if (Number.isSafeInteger(s2)) + s2 < 0 ? an(s2, t2) : hn(s2, t2); + else + throw Error("cannot encode number outside of javascript safe integer range"); + return t2; +}, hn = (s2, t2) => { + t2[0] = 128; + for (var e2 = t2.length;e2 > 1; e2--) + t2[e2 - 1] = s2 & 255, s2 = Math.floor(s2 / 256); +}, an = (s2, t2) => { + t2[0] = 255; + var e2 = false; + s2 = s2 * -1; + for (var i3 = t2.length;i3 > 1; i3--) { + var r2 = s2 & 255; + s2 = Math.floor(s2 / 256), e2 ? t2[i3 - 1] = Ws(r2) : r2 === 0 ? t2[i3 - 1] = 0 : (e2 = true, t2[i3 - 1] = Gs(r2)); + } +}, Hs = (s2) => { + let t2 = s2[0], e2 = t2 === 128 ? cn(s2.subarray(1, s2.length)) : t2 === 255 ? ln(s2) : null; + if (e2 === null) + throw Error("invalid base256 encoding"); + if (!Number.isSafeInteger(e2)) + throw Error("parsed number outside of javascript safe integer range"); + return e2; +}, ln = (s2) => { + for (var t2 = s2.length, e2 = 0, i3 = false, r2 = t2 - 1;r2 > -1; r2--) { + var n2 = Number(s2[r2]), o2; + i3 ? o2 = Ws(n2) : n2 === 0 ? o2 = n2 : (i3 = true, o2 = Gs(n2)), o2 !== 0 && (e2 -= o2 * Math.pow(256, t2 - r2 - 1)); + } + return e2; +}, cn = (s2) => { + for (var t2 = s2.length, e2 = 0, i3 = t2 - 1;i3 > -1; i3--) { + var r2 = Number(s2[i3]); + r2 !== 0 && (e2 += r2 * Math.pow(256, t2 - i3 - 1)); + } + return e2; +}, Ws = (s2) => (255 ^ s2) & 255, Gs = (s2) => (255 ^ s2) + 1 & 255, Hi, ne = (s2) => oe.has(s2), dn = (s2) => Ve.has(s2), Ui, oe, Ve, mn = (s2) => s2 === undefined || s2 < 0 ? undefined : s2, F2 = class { + cksumValid = false; + needPax = false; + nullBlock = false; + block; + path; + mode; + uid; + gid; + size; + cksum; + #t = "Unsupported"; + linkpath; + uname; + gname; + devmaj = 0; + devmin = 0; + atime; + ctime; + mtime; + charset; + comment; + constructor(t2, e2 = 0, i3, r2) { + Buffer.isBuffer(t2) ? this.decode(t2, e2 || 0, i3, r2) : t2 && this.#i(t2); + } + decode(t2, e2, i3, r2) { + if (e2 || (e2 = 0), !t2 || !(t2.length >= e2 + 512)) + throw new Error("need 512 bytes for header"); + let n2 = xt(t2, e2 + 156, 1), o2 = Ui.has(n2), h3 = o2 ? i3 : undefined, a2 = o2 ? r2 : undefined; + if (this.path = h3?.path ?? xt(t2, e2, 100), this.mode = h3?.mode ?? a2?.mode ?? lt(t2, e2 + 100, 8), this.uid = h3?.uid ?? a2?.uid ?? lt(t2, e2 + 108, 8), this.gid = h3?.gid ?? a2?.gid ?? lt(t2, e2 + 116, 8), this.size = mn(h3?.size ?? a2?.size ?? lt(t2, e2 + 124, 12)), this.mtime = h3?.mtime ?? a2?.mtime ?? Wi(t2, e2 + 136, 12), this.cksum = lt(t2, e2 + 148, 12), a2 && this.#i(a2, true), h3 && this.#i(h3), ne(n2) && (this.#t = n2 || "0"), this.#t === "0" && this.path.slice(-1) === "/" && (this.#t = "5"), this.#t === "5" && (this.size = 0), this.linkpath = xt(t2, e2 + 157, 100), t2.subarray(e2 + 257, e2 + 265).toString() === "ustar\x0000") + if (this.uname = h3?.uname ?? a2?.uname ?? xt(t2, e2 + 265, 32), this.gname = h3?.gname ?? a2?.gname ?? xt(t2, e2 + 297, 32), this.devmaj = h3?.devmaj ?? a2?.devmaj ?? lt(t2, e2 + 329, 8) ?? 0, this.devmin = h3?.devmin ?? a2?.devmin ?? lt(t2, e2 + 337, 8) ?? 0, t2[e2 + 475] !== 0) { + let c3 = xt(t2, e2 + 345, 155); + this.path = c3 + "/" + this.path; + } else { + let c3 = xt(t2, e2 + 345, 130); + c3 && (this.path = c3 + "/" + this.path), this.atime = i3?.atime ?? r2?.atime ?? Wi(t2, e2 + 476, 12), this.ctime = i3?.ctime ?? r2?.ctime ?? Wi(t2, e2 + 488, 12); + } + let l = 256; + for (let c3 = e2;c3 < e2 + 148; c3++) + l += t2[c3]; + for (let c3 = e2 + 156;c3 < e2 + 512; c3++) + l += t2[c3]; + this.cksumValid = l === this.cksum, this.cksum === undefined && l === 256 && (this.nullBlock = true); + } + #i(t2, e2 = false) { + Object.assign(this, Object.fromEntries(Object.entries(t2).filter(([i3, r2]) => !(r2 == null || i3 === "size" && Number(r2) < 0 || i3 === "path" && e2 || i3 === "linkpath" && e2 || i3 === "global")))); + } + encode(t2, e2 = 0) { + if (t2 || (t2 = this.block = Buffer.alloc(512)), this.#t === "Unsupported" && (this.#t = "0"), !(t2.length >= e2 + 512)) + throw new Error("need 512 bytes for header"); + let i3 = this.ctime || this.atime ? 130 : 155, r2 = un(this.path || "", i3), n2 = r2[0], o2 = r2[1]; + this.needPax = !!r2[2], this.needPax = Lt(t2, e2, 100, n2) || this.needPax, this.needPax = ct(t2, e2 + 100, 8, this.mode) || this.needPax, this.needPax = ct(t2, e2 + 108, 8, this.uid) || this.needPax, this.needPax = ct(t2, e2 + 116, 8, this.gid) || this.needPax, this.needPax = ct(t2, e2 + 124, 12, this.size) || this.needPax, this.needPax = Gi(t2, e2 + 136, 12, this.mtime) || this.needPax, t2[e2 + 156] = Number(this.#t.codePointAt(0)), this.needPax = Lt(t2, e2 + 157, 100, this.linkpath) || this.needPax, t2.write("ustar\x0000", e2 + 257, 8), this.needPax = Lt(t2, e2 + 265, 32, this.uname) || this.needPax, this.needPax = Lt(t2, e2 + 297, 32, this.gname) || this.needPax, this.needPax = ct(t2, e2 + 329, 8, this.devmaj) || this.needPax, this.needPax = ct(t2, e2 + 337, 8, this.devmin) || this.needPax, this.needPax = Lt(t2, e2 + 345, i3, o2) || this.needPax, t2[e2 + 475] !== 0 ? this.needPax = Lt(t2, e2 + 345, 155, o2) || this.needPax : (this.needPax = Lt(t2, e2 + 345, 130, o2) || this.needPax, this.needPax = Gi(t2, e2 + 476, 12, this.atime) || this.needPax, this.needPax = Gi(t2, e2 + 488, 12, this.ctime) || this.needPax); + let h3 = 256; + for (let a2 = e2;a2 < e2 + 148; a2++) + h3 += t2[a2]; + for (let a2 = e2 + 156;a2 < e2 + 512; a2++) + h3 += t2[a2]; + return this.cksum = h3, ct(t2, e2 + 148, 8, this.cksum), this.cksumValid = true, this.needPax; + } + get type() { + return this.#t === "Unsupported" ? this.#t : oe.get(this.#t); + } + get typeKey() { + return this.#t; + } + set type(t2) { + let e2 = String(Ve.get(t2)); + if (ne(e2) || e2 === "Unsupported") + this.#t = e2; + else if (ne(t2)) + this.#t = t2; + else + throw new TypeError("invalid entry type: " + t2); + } +}, un = (s2, t2) => { + let i3 = s2, r2 = "", n2, o2 = Zt.parse(s2).root || "."; + if (Buffer.byteLength(i3) < 100) + n2 = [i3, r2, false]; + else { + r2 = Zt.dirname(i3), i3 = Zt.basename(i3); + do + Buffer.byteLength(i3) <= 100 && Buffer.byteLength(r2) <= t2 ? n2 = [i3, r2, false] : Buffer.byteLength(i3) > 100 && Buffer.byteLength(r2) <= t2 ? n2 = [i3.slice(0, 99), r2, true] : (i3 = Zt.join(Zt.basename(r2), i3), r2 = Zt.dirname(r2)); + while (r2 !== o2 && n2 === undefined); + n2 || (n2 = [s2.slice(0, 99), "", true]); + } + return n2; +}, xt = (s2, t2, e2) => s2.subarray(t2, t2 + e2).toString("utf8").replace(/\0.*/, ""), Wi = (s2, t2, e2) => pn(lt(s2, t2, e2)), pn = (s2) => s2 === undefined ? undefined : new Date(s2 * 1000), lt = (s2, t2, e2) => Number(s2[t2]) & 128 ? Hs(s2.subarray(t2, t2 + e2)) : wn(s2, t2, e2), En = (s2) => isNaN(s2) ? undefined : s2, wn = (s2, t2, e2) => En(parseInt(s2.subarray(t2, t2 + e2).toString("utf8").replace(/\0.*$/, "").trim(), 8)), Sn, ct = (s2, t2, e2, i3) => i3 === undefined ? false : i3 > Sn[e2] || i3 < 0 ? (Us(i3, s2.subarray(t2, t2 + e2)), true) : (yn(s2, t2, e2, i3), false), yn = (s2, t2, e2, i3) => s2.write(Rn(i3, e2), t2, e2, "ascii"), Rn = (s2, t2) => gn(Math.floor(s2).toString(8), t2), gn = (s2, t2) => (s2.length === t2 - 1 ? s2 : new Array(t2 - s2.length - 1).join("0") + s2 + " ") + "\x00", Gi = (s2, t2, e2, i3) => i3 === undefined ? false : ct(s2, t2, e2, i3.getTime() / 1000), bn, Lt = (s2, t2, e2, i3) => i3 === undefined ? false : (s2.write(i3 + bn, t2, e2, "utf8"), i3.length !== Buffer.byteLength(i3) || i3.length > e2), ft = class s2 { + atime; + mtime; + ctime; + charset; + comment; + gid; + uid; + gname; + uname; + linkpath; + dev; + ino; + nlink; + path; + size; + mode; + global; + constructor(t2, e2 = false) { + this.atime = t2.atime, this.charset = t2.charset, this.comment = t2.comment, this.ctime = t2.ctime, this.dev = t2.dev, this.gid = t2.gid, this.global = e2, this.gname = t2.gname, this.ino = t2.ino, this.linkpath = t2.linkpath, this.mtime = t2.mtime, this.nlink = t2.nlink, this.path = t2.path, this.size = t2.size, this.uid = t2.uid, this.uname = t2.uname; + } + encode() { + let t2 = this.encodeBody(); + if (t2 === "") + return Buffer.allocUnsafe(0); + let e2 = Buffer.byteLength(t2), i3 = 512 * Math.ceil(1 + e2 / 512), r2 = Buffer.allocUnsafe(i3); + for (let n2 = 0;n2 < 512; n2++) + r2[n2] = 0; + new F2({ path: ("PaxHeader/" + _n(this.path ?? "")).slice(0, 99), mode: this.mode || 420, uid: this.uid, gid: this.gid, size: e2, mtime: this.mtime, type: this.global ? "GlobalExtendedHeader" : "ExtendedHeader", linkpath: "", uname: this.uname || "", gname: this.gname || "", devmaj: 0, devmin: 0, atime: this.atime, ctime: this.ctime }).encode(r2), r2.write(t2, 512, e2, "utf8"); + for (let n2 = e2 + 512;n2 < r2.length; n2++) + r2[n2] = 0; + return r2; + } + encodeBody() { + return this.encodeField("path") + this.encodeField("ctime") + this.encodeField("atime") + this.encodeField("dev") + this.encodeField("ino") + this.encodeField("nlink") + this.encodeField("charset") + this.encodeField("comment") + this.encodeField("gid") + this.encodeField("gname") + this.encodeField("linkpath") + this.encodeField("mtime") + this.encodeField("size") + this.encodeField("uid") + this.encodeField("uname"); + } + encodeField(t2) { + if (this[t2] === undefined) + return ""; + let e2 = this[t2], i3 = e2 instanceof Date ? e2.getTime() / 1000 : e2, r2 = " " + (t2 === "dev" || t2 === "ino" || t2 === "nlink" ? "SCHILY." : "") + t2 + "=" + i3 + ` +`, n2 = Buffer.byteLength(r2), o2 = Math.floor(Math.log(n2) / Math.log(10)) + 1; + return n2 + o2 >= Math.pow(10, o2) && (o2 += 1), o2 + n2 + r2; + } + static parse(t2, e2, i3 = false) { + return new s2(On(Tn(t2), e2), i3); + } +}, On = (s3, t2) => t2 ? Object.assign({}, t2, s3) : s3, Tn = (s3) => s3.replace(/\n$/, "").split(` +`).reduce(xn, Object.create(null)), xn = (s3, t2) => { + let e2 = parseInt(t2, 10); + if (e2 !== Buffer.byteLength(t2) + 1) + return s3; + t2 = t2.slice((e2 + " ").length); + let i3 = t2.split("="), r2 = i3.shift(); + if (!r2) + return s3; + let n2 = r2.replace(/^SCHILY\.(dev|ino|nlink)/, "$1"), o2 = i3.join("=").replace(/\0.*/, ""); + switch (n2) { + case "path": + case "linkpath": + case "type": + case "charset": + case "comment": + case "gname": + case "uname": + s3[n2] = o2; + break; + case "ctime": + case "atime": + case "mtime": + s3[n2] = new Date(Number(o2) * 1000); + break; + case "size": + let h3 = +o2; + h3 >= 0 && (s3[n2] = h3); + break; + case "gid": + case "uid": + case "dev": + case "ino": + case "nlink": + case "mode": + s3[n2] = +o2; + break; + } + return s3; +}, Ln, f3, $e, Dt = (s3, t2, e2, i3 = {}) => { + s3.file && (i3.file = s3.file), s3.cwd && (i3.cwd = s3.cwd), i3.code = e2 instanceof Error && e2.code || t2, i3.tarCode = t2, !s3.strict && i3.recoverable !== false ? (e2 instanceof Error && (i3 = Object.assign(e2, i3), e2 = e2.message), s3.emit("warn", t2, e2, i3)) : e2 instanceof Error ? s3.emit("error", Object.assign(e2, i3)) : s3.emit("error", Object.assign(new Error(`${t2}: ${e2}`), i3)); +}, Nn, Xi, qi, An, B, Nt, it, Zi, Zs, V, he, dt, Ys, p, st, mt, Yi, At, y, Xe, qe, Ki, Ks, Vs, ae, Vi, Qe, Yt, $2, Je, It, je, ti, $s, In = 1000, le, $i, Xs, Cn = () => true, rt, ut = (s3) => { + let t2 = s3.length - 1, e2 = -1; + for (;t2 > -1 && s3.charAt(t2) === "/"; ) + e2 = t2, t2--; + return e2 === -1 ? s3 : s3.slice(0, e2); +}, vn = (s3) => { + let t2 = s3.onReadEntry; + s3.onReadEntry = t2 ? (e2) => { + t2(e2), e2.resume(); + } : (e2) => e2.resume(); +}, Qi = (s3, t2) => { + let e2 = new Map(t2.map((n2) => [ut(n2), true])), i3 = s3.filter, r2 = (n2, o2 = "") => { + let h3 = o2 || kn(n2).root || ".", a2; + if (n2 === h3) + a2 = false; + else { + let l = e2.get(n2); + a2 = l !== undefined ? l : r2(Fn(n2), h3); + } + return e2.set(n2, a2), a2; + }; + s3.filter = i3 ? (n2, o2) => i3(n2, o2) && r2(ut(n2)) : (n2) => r2(ut(n2)); +}, Mn = (s3) => { + let t2 = new rt(s3), e2 = s3.file, i3; + try { + i3 = Kt.openSync(e2, "r"); + let r2 = Kt.fstatSync(i3), n2 = s3.maxReadSize || 16 * 1024 * 1024; + if (r2.size < n2) { + let o2 = Buffer.allocUnsafe(r2.size), h3 = Kt.readSync(i3, o2, 0, r2.size, 0); + t2.end(h3 === o2.byteLength ? o2 : o2.subarray(0, h3)); + } else { + let o2 = 0, h3 = Buffer.allocUnsafe(n2); + for (;o2 < r2.size; ) { + let a2 = Kt.readSync(i3, h3, 0, n2, o2); + if (a2 === 0) + break; + o2 += a2, t2.write(h3.subarray(0, a2)); + } + t2.end(); + } + } finally { + if (typeof i3 == "number") + try { + Kt.closeSync(i3); + } catch {} + } +}, Bn = (s3, t2) => { + let e2 = new rt(s3), i3 = s3.maxReadSize || 16 * 1024 * 1024, r2 = s3.file; + return new Promise((o2, h3) => { + e2.on("error", h3), e2.on("end", o2), Kt.stat(r2, (a2, l) => { + if (a2) + h3(a2); + else { + let c3 = new _t(r2, { readSize: i3, size: l.size }); + c3.on("error", h3), c3.pipe(e2); + } + }); + }); +}, Ct, Ji = (s3, t2, e2) => (s3 &= 4095, e2 && (s3 = (s3 | 384) & -19), t2 && (s3 & 256 && (s3 |= 64), s3 & 32 && (s3 |= 8), s3 & 4 && (s3 |= 1)), s3), zn, qs, ce = (s3) => { + let t2 = "", e2 = qs(s3); + for (;zn(s3) || e2.root; ) { + let i3 = s3.charAt(0) === "/" && s3.slice(0, 4) !== "//?/" ? "/" : e2.root; + s3 = s3.slice(i3.length), t2 += i3, e2 = qs(s3); + } + return [t2, s3]; +}, ei, ji, Un, Hn, ts = (s3) => ei.reduce((t2, e2) => t2.split(e2).join(Un.get(e2)), s3), Qs = (s3) => ji.reduce((t2, e2) => t2.split(e2).join(Hn.get(e2)), s3), rr = (s3, t2) => t2 ? (s3 = f3(s3).replace(/^\.(\/|$)/, ""), ut(t2) + "/" + s3) : f3(s3), Wn, tr, er, ir, is, sr, fe, ii, ss, si, rs, ns, os2, hs, pt, ri, as, es, q, de, ni, oi, Gn = (s3) => s3.isFile() ? "File" : s3.isDirectory() ? "Directory" : s3.isSymbolicLink() ? "SymbolicLink" : "Unsupported", hi, me = class { + list; + next; + prev; + value; + constructor(t2, e2, i3, r2) { + this.list = r2, this.value = t2, e2 ? (e2.next = this, this.prev = e2) : this.prev = undefined, i3 ? (i3.prev = this, this.next = i3) : this.next = undefined; + } +}, pi = class { + path; + absolute; + entry; + stat; + readdir; + pending = false; + pendingLink = false; + ignore = false; + piped = false; + constructor(t2, e2) { + this.path = t2 || "./", this.absolute = e2; + } +}, nr, li, ue, W, pe, Et, Ft, Ee, ai, G, ls, ci, or, ds, ms, fi, di, hr, cs, mi, lr, fs2, wt, kt, Vn = (s4, t2) => { + let e2 = new kt(s4), i3 = new Wt(s4.file, { mode: s4.mode || 438 }); + e2.pipe(i3), fr(e2, t2); +}, $n = (s4, t2) => { + let e2 = new wt(s4), i3 = new et(s4.file, { mode: s4.mode || 438 }); + e2.pipe(i3); + let r2 = new Promise((n2, o2) => { + i3.on("error", o2), i3.on("close", n2), e2.on("error", o2); + }); + return dr(e2, t2).catch((n2) => e2.emit("error", n2)), r2; +}, fr = (s4, t2) => { + t2.forEach((e2) => { + e2.charAt(0) === "@" ? Ct({ file: cr.resolve(s4.cwd, e2.slice(1)), sync: true, noResume: true, onReadEntry: (i3) => s4.add(i3) }) : s4.add(e2); + }), s4.end(); +}, dr = async (s4, t2) => { + for (let e2 of t2) + e2.charAt(0) === "@" ? await Ct({ file: cr.resolve(String(s4.cwd), e2.slice(1)), noResume: true, onReadEntry: (i3) => { + s4.add(i3); + } }) : s4.add(e2); + s4.end(); +}, Xn = (s4, t2) => { + let e2 = new kt(s4); + return fr(e2, t2), e2; +}, qn = (s4, t2) => { + let e2 = new wt(s4); + return dr(e2, t2).catch((i3) => e2.emit("error", i3)), e2; +}, Qn, Jn, Er, wr, mr, Sr, yr, Rr, jn, to, eo, ur, us, ps = (s4, t2, e2) => { + try { + return wi.lchownSync(s4, t2, e2); + } catch (i3) { + if (i3?.code !== "ENOENT") + throw i3; + } +}, Ei = (s4, t2, e2, i3) => { + wi.lchown(s4, t2, e2, (r2) => { + i3(r2 && r2?.code !== "ENOENT" ? r2 : null); + }); +}, io = (s4, t2, e2, i3, r2) => { + if (t2.isDirectory()) + Es(we.resolve(s4, t2.name), e2, i3, (n2) => { + if (n2) + return r2(n2); + let o2 = we.resolve(s4, t2.name); + Ei(o2, e2, i3, r2); + }); + else { + let n2 = we.resolve(s4, t2.name); + Ei(n2, e2, i3, r2); + } +}, Es = (s4, t2, e2, i3) => { + wi.readdir(s4, { withFileTypes: true }, (r2, n2) => { + if (r2) { + if (r2.code === "ENOENT") + return i3(); + if (r2.code !== "ENOTDIR" && r2.code !== "ENOTSUP") + return i3(r2); + } + if (r2 || !n2.length) + return Ei(s4, t2, e2, i3); + let o2 = n2.length, h3 = null, a2 = (l) => { + if (!h3) { + if (l) + return i3(h3 = l); + if (--o2 === 0) + return Ei(s4, t2, e2, i3); + } + }; + for (let l of n2) + io(s4, l, t2, e2, a2); + }); +}, so = (s4, t2, e2, i3) => { + t2.isDirectory() && ws(we.resolve(s4, t2.name), e2, i3), ps(we.resolve(s4, t2.name), e2, i3); +}, ws = (s4, t2, e2) => { + let i3; + try { + i3 = wi.readdirSync(s4, { withFileTypes: true }); + } catch (r2) { + let n2 = r2; + if (n2?.code === "ENOENT") + return; + if (n2?.code === "ENOTDIR" || n2?.code === "ENOTSUP") + return ps(s4, t2, e2); + throw n2; + } + for (let r2 of i3) + so(s4, r2, t2, e2); + return ps(s4, t2, e2); +}, Se, St, no = (s4, t2) => { + k.stat(s4, (e2, i3) => { + (e2 || !i3.isDirectory()) && (e2 = new Se(s4, e2?.code || "ENOTDIR")), t2(e2); + }); +}, gr = (s4, t2, e2) => { + s4 = f3(s4); + let i3 = t2.umask ?? 18, r2 = t2.mode | 448, n2 = (r2 & i3) !== 0, o2 = t2.uid, h3 = t2.gid, a2 = typeof o2 == "number" && typeof h3 == "number" && (o2 !== t2.processUid || h3 !== t2.processGid), l = t2.preserve, c3 = t2.unlink, d = f3(t2.cwd), S2 = (E, x2) => { + E ? e2(E) : x2 && a2 ? Es(x2, o2, h3, (Le) => S2(Le)) : n2 ? k.chmod(s4, r2, e2) : e2(); + }; + if (s4 === d) + return no(s4, S2); + if (l) + return ro.mkdir(s4, { mode: r2, recursive: true }).then((E) => S2(null, E ?? undefined), S2); + let D = f3(Si.relative(d, s4)).split("/"); + Ss(d, D, r2, c3, d, undefined, S2); +}, Ss = (s4, t2, e2, i3, r2, n2, o2) => { + if (t2.length === 0) + return o2(null, n2); + let h3 = t2.shift(), a2 = f3(Si.resolve(s4 + "/" + h3)); + k.mkdir(a2, e2, br(a2, t2, e2, i3, r2, n2, o2)); +}, br = (s4, t2, e2, i3, r2, n2, o2) => (h3) => { + h3 ? k.lstat(s4, (a2, l) => { + if (a2) + a2.path = a2.path && f3(a2.path), o2(a2); + else if (l.isDirectory()) + Ss(s4, t2, e2, i3, r2, n2, o2); + else if (i3) + k.unlink(s4, (c3) => { + if (c3) + return o2(c3); + k.mkdir(s4, e2, br(s4, t2, e2, i3, r2, n2, o2)); + }); + else { + if (l.isSymbolicLink()) + return o2(new St(s4, s4 + "/" + t2.join("/"))); + o2(h3); + } + }) : (n2 = n2 || s4, Ss(s4, t2, e2, i3, r2, n2, o2)); +}, oo = (s4) => { + let t2 = false, e2; + try { + t2 = k.statSync(s4).isDirectory(); + } catch (i3) { + e2 = i3?.code; + } finally { + if (!t2) + throw new Se(s4, e2 ?? "ENOTDIR"); + } +}, _r = (s4, t2) => { + s4 = f3(s4); + let e2 = t2.umask ?? 18, i3 = t2.mode | 448, r2 = (i3 & e2) !== 0, n2 = t2.uid, o2 = t2.gid, h3 = typeof n2 == "number" && typeof o2 == "number" && (n2 !== t2.processUid || o2 !== t2.processGid), a2 = t2.preserve, l = t2.unlink, c3 = f3(t2.cwd), d = (E) => { + E && h3 && ws(E, n2, o2), r2 && k.chmodSync(s4, i3); + }; + if (s4 === c3) + return oo(c3), d(); + if (a2) + return d(k.mkdirSync(s4, { mode: i3, recursive: true }) ?? undefined); + let T = f3(Si.relative(c3, s4)).split("/"), D; + for (let E = T.shift(), x2 = c3;E && (x2 += "/" + E); E = T.shift()) { + x2 = f3(Si.resolve(x2)); + try { + k.mkdirSync(x2, i3), D = D || x2; + } catch { + let Le = k.lstatSync(x2); + if (Le.isDirectory()) + continue; + if (l) { + k.unlinkSync(x2), k.mkdirSync(x2, i3), D = D || x2; + continue; + } else if (Le.isSymbolicLink()) + return new St(x2, x2 + "/" + T.join("/")); + } + } + return d(D); +}, ys, Or = 1e4, Vt, Tr = (s4) => { + Vt.has(s4) ? Vt.delete(s4) : ys[s4] = s4.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"), Vt.add(s4); + let t2 = ys[s4], e2 = Vt.size - Or; + if (e2 > Or / 10) { + for (let i3 of Vt) + if (Vt.delete(i3), delete ys[i3], --e2 <= 0) + break; + } + return t2; +}, ho, ao, lo = (s4) => s4.split("/").slice(0, -1).reduce((e2, i3) => { + let r2 = e2.at(-1); + return r2 !== undefined && (i3 = xr(r2, i3)), e2.push(i3 || "/"), e2; +}, []), yi = class { + #t = new Map; + #i = new Map; + #s = new Set; + reserve(t2, e2) { + t2 = ao ? ["win32 parallelization disabled"] : t2.map((r2) => ut(xr(Tr(r2)))); + let i3 = new Set(t2.map((r2) => lo(r2)).reduce((r2, n2) => r2.concat(n2))); + this.#i.set(e2, { dirs: i3, paths: t2 }); + for (let r2 of t2) { + let n2 = this.#t.get(r2); + n2 ? n2.push(e2) : this.#t.set(r2, [e2]); + } + for (let r2 of i3) { + let n2 = this.#t.get(r2); + if (!n2) + this.#t.set(r2, [new Set([e2])]); + else { + let o2 = n2.at(-1); + o2 instanceof Set ? o2.add(e2) : n2.push(new Set([e2])); + } + } + return this.#r(e2); + } + #n(t2) { + let e2 = this.#i.get(t2); + if (!e2) + throw new Error("function does not have any path reservations"); + return { paths: e2.paths.map((i3) => this.#t.get(i3)), dirs: [...e2.dirs].map((i3) => this.#t.get(i3)) }; + } + check(t2) { + let { paths: e2, dirs: i3 } = this.#n(t2); + return e2.every((r2) => r2 && r2[0] === t2) && i3.every((r2) => r2 && r2[0] instanceof Set && r2[0].has(t2)); + } + #r(t2) { + return this.#s.has(t2) || !this.check(t2) ? false : (this.#s.add(t2), t2(() => this.#e(t2)), true); + } + #e(t2) { + if (!this.#s.has(t2)) + return false; + let e2 = this.#i.get(t2); + if (!e2) + throw new Error("invalid reservation"); + let { paths: i3, dirs: r2 } = e2, n2 = new Set; + for (let o2 of i3) { + let h3 = this.#t.get(o2); + if (!h3 || h3?.[0] !== t2) + continue; + let a2 = h3[1]; + if (!a2) { + this.#t.delete(o2); + continue; + } + if (h3.shift(), typeof a2 == "function") + n2.add(a2); + else + for (let l of a2) + n2.add(l); + } + for (let o2 of r2) { + let h3 = this.#t.get(o2), a2 = h3?.[0]; + if (!(!h3 || !(a2 instanceof Set))) + if (a2.size === 1 && h3.length === 1) { + this.#t.delete(o2); + continue; + } else if (a2.size === 1) { + h3.shift(); + let l = h3[0]; + typeof l == "function" && n2.add(l); + } else + a2.delete(t2); + } + return this.#s.delete(t2), n2.forEach((o2) => this.#r(o2)), true; + } +}, Lr = () => process.umask(), Dr, _s, Nr, Os, P, Ts, xs, gi, Ar, Ir, Re, Cr, Fr, Rs, yt, O, Ri, kr, $t, gs, bs, Ls, ge, be, _e, Oe, fo, Te, mo = 1024, uo = (s4, t2) => { + if (!Te) + return m2.unlink(s4, t2); + let e2 = s4 + ".DELETE." + Mr(16).toString("hex"); + m2.rename(s4, e2, (i3) => { + if (i3) + return t2(i3); + m2.unlink(e2, t2); + }); +}, po = (s4) => { + if (!Te) + return m2.unlinkSync(s4); + let t2 = s4 + ".DELETE." + Mr(16).toString("hex"); + m2.renameSync(s4, t2), m2.unlinkSync(t2); +}, vr = (s4, t2, e2) => s4 !== undefined && s4 === s4 >>> 0 ? s4 : t2 !== undefined && t2 === t2 >>> 0 ? t2 : e2, Xt, ye = (s4) => { + try { + return [null, s4()]; + } catch (t2) { + return [t2, null]; + } +}, xe, Eo = (s4) => { + let t2 = new xe(s4), e2 = s4.file, i3 = Br.statSync(e2), r2 = s4.maxReadSize || 16 * 1024 * 1024; + new Be(e2, { readSize: r2, size: i3.size }).pipe(t2); +}, wo = (s4, t2) => { + let e2 = new Xt(s4), i3 = s4.maxReadSize || 16 * 1024 * 1024, r2 = s4.file; + return new Promise((o2, h3) => { + e2.on("error", h3), e2.on("close", o2), Br.stat(r2, (a2, l) => { + if (a2) + h3(a2); + else { + let c3 = new _t(r2, { readSize: i3, size: l.size }); + c3.on("error", h3), c3.pipe(e2); + } + }); + }); +}, So, yo = (s4, t2) => { + let e2 = new kt(s4), i3 = true, r2, n2; + try { + try { + r2 = v.openSync(s4.file, "r+"); + } catch (a2) { + if (a2?.code === "ENOENT") + r2 = v.openSync(s4.file, "w+"); + else + throw a2; + } + let o2 = v.fstatSync(r2), h3 = Buffer.alloc(512); + t: + for (n2 = 0;n2 < o2.size; n2 += 512) { + for (let c3 = 0, d = 0;c3 < 512; c3 += d) { + if (d = v.readSync(r2, h3, c3, h3.length - c3, n2 + c3), n2 === 0 && h3[0] === 31 && h3[1] === 139) + throw new Error("cannot append to compressed archives"); + if (!d) + break t; + } + let a2 = new F2(h3); + if (!a2.cksumValid) + break; + let l = 512 * Math.ceil((a2.size || 0) / 512); + if (n2 + l + 512 > o2.size) + break; + n2 += l, s4.mtimeCache && a2.mtime && s4.mtimeCache.set(String(a2.path), a2.mtime); + } + i3 = false, Ro(s4, e2, n2, r2, t2); + } finally { + if (i3) + try { + v.closeSync(r2); + } catch {} + } +}, Ro = (s4, t2, e2, i3, r2) => { + let n2 = new Wt(s4.file, { fd: i3, start: e2 }); + t2.pipe(n2), bo(t2, r2); +}, go = (s4, t2) => { + t2 = Array.from(t2); + let e2 = new wt(s4), i3 = (n2, o2, h3) => { + let a2 = (T, D) => { + T ? v.close(n2, (E) => h3(T)) : h3(null, D); + }, l = 0; + if (o2 === 0) + return a2(null, 0); + let c3 = 0, d = Buffer.alloc(512), S2 = (T, D) => { + if (T || D === undefined) + return a2(T); + if (c3 += D, c3 < 512 && D) + return v.read(n2, d, c3, d.length - c3, l + c3, S2); + if (l === 0 && d[0] === 31 && d[1] === 139) + return a2(new Error("cannot append to compressed archives")); + if (c3 < 512) + return a2(null, l); + let E = new F2(d); + if (!E.cksumValid) + return a2(null, l); + let x2 = 512 * Math.ceil((E.size ?? 0) / 512); + if (l + x2 + 512 > o2 || (l += x2 + 512, l >= o2)) + return a2(null, l); + s4.mtimeCache && E.mtime && s4.mtimeCache.set(String(E.path), E.mtime), c3 = 0, v.read(n2, d, 0, 512, l, S2); + }; + v.read(n2, d, 0, 512, l, S2); + }; + return new Promise((n2, o2) => { + e2.on("error", o2); + let h3 = "r+", a2 = (l, c3) => { + if (l && l.code === "ENOENT" && h3 === "r+") + return h3 = "w+", v.open(s4.file, h3, a2); + if (l || !c3) + return o2(l); + v.fstat(c3, (d, S2) => { + if (d) + return v.close(c3, () => o2(d)); + i3(c3, S2.size, (T, D) => { + if (T) + return o2(T); + let E = new et(s4.file, { fd: c3, start: D }); + e2.pipe(E), E.on("error", o2), E.on("close", n2), _o(e2, t2); + }); + }); + }; + v.open(s4.file, h3, a2); + }); +}, bo = (s4, t2) => { + t2.forEach((e2) => { + e2.charAt(0) === "@" ? Ct({ file: Pr.resolve(s4.cwd, e2.slice(1)), sync: true, noResume: true, onReadEntry: (i3) => s4.add(i3) }) : s4.add(e2); + }), s4.end(); +}, _o = async (s4, t2) => { + for (let e2 of t2) + e2.charAt(0) === "@" ? await Ct({ file: Pr.resolve(String(s4.cwd), e2.slice(1)), noResume: true, onReadEntry: (i3) => s4.add(i3) }) : s4.add(e2); + s4.end(); +}, vt, Oo, To = (s4) => { + let t2 = s4.filter; + s4.mtimeCache || (s4.mtimeCache = new Map), s4.filter = t2 ? (e2, i3) => t2(e2, i3) && !((s4.mtimeCache?.get(e2) ?? i3.mtime ?? 0) > (i3.mtime ?? 0)) : (e2, i3) => !((s4.mtimeCache?.get(e2) ?? i3.mtime ?? 0) > (i3.mtime ?? 0)); +}; +var init_index_min = __esm(() => { + zr = Object.defineProperty; + Ds = typeof process == "object" && process ? process : { stdout: null, stderr: null }; + Q = Symbol("EOF"); + J = Symbol("maybeEmitEnd"); + nt = Symbol("emittedEnd"); + De = Symbol("emittingEnd"); + qt = Symbol("emittedError"); + Ne = Symbol("closed"); + Ns = Symbol("read"); + Ae = Symbol("flush"); + As = Symbol("flushChunk"); + z = Symbol("encoding"); + Mt = Symbol("decoder"); + g = Symbol("flowing"); + Qt = Symbol("paused"); + Bt = Symbol("resume"); + b = Symbol("buffer"); + N = Symbol("pipes"); + _ = Symbol("bufferLength"); + bi = Symbol("bufferPush"); + Ie = Symbol("bufferShift"); + L = Symbol("objectMode"); + w = Symbol("destroyed"); + _i = Symbol("error"); + Oi = Symbol("emitData"); + Is = Symbol("emitEnd"); + Ti = Symbol("emitEnd2"); + Z2 = Symbol("async"); + xi = Symbol("abort"); + Ce = Symbol("aborted"); + Jt = Symbol("signal"); + Rt = Symbol("dataListeners"); + C = Symbol("discarded"); + Li = class extends Fe { + unpipe() { + this.src.removeListener("error", this.proxyErrors), super.unpipe(); + } + constructor(t2, e2, i3) { + super(t2, e2, i3), this.proxyErrors = (r2) => this.dest.emit("error", r2), t2.on("error", this.proxyErrors); + } + }; + A2 = class extends Di { + [g] = false; + [Qt] = false; + [N] = []; + [b] = []; + [L]; + [z]; + [Z2]; + [Mt]; + [Q] = false; + [nt] = false; + [De] = false; + [Ne] = false; + [qt] = null; + [_] = 0; + [w] = false; + [Jt]; + [Ce] = false; + [Rt] = 0; + [C] = false; + writable = true; + readable = true; + constructor(...t2) { + let e2 = t2[0] || {}; + if (super(), e2.objectMode && typeof e2.encoding == "string") + throw new TypeError("Encoding and objectMode may not be used together"); + Xr(e2) ? (this[L] = true, this[z] = null) : qr(e2) ? (this[z] = e2.encoding, this[L] = false) : (this[L] = false, this[z] = null), this[Z2] = !!e2.async, this[Mt] = this[z] ? new Hr(this[z]) : null, e2 && e2.debugExposeBuffer === true && Object.defineProperty(this, "buffer", { get: () => this[b] }), e2 && e2.debugExposePipes === true && Object.defineProperty(this, "pipes", { get: () => this[N] }); + let { signal: i3 } = e2; + i3 && (this[Jt] = i3, i3.aborted ? this[xi]() : i3.addEventListener("abort", () => this[xi]())); + } + get bufferLength() { + return this[_]; + } + get encoding() { + return this[z]; + } + set encoding(t2) { + throw new Error("Encoding must be set at instantiation time"); + } + setEncoding(t2) { + throw new Error("Encoding must be set at instantiation time"); + } + get objectMode() { + return this[L]; + } + set objectMode(t2) { + throw new Error("objectMode must be set at instantiation time"); + } + get async() { + return this[Z2]; + } + set async(t2) { + this[Z2] = this[Z2] || !!t2; + } + [xi]() { + this[Ce] = true, this.emit("abort", this[Jt]?.reason), this.destroy(this[Jt]?.reason); + } + get aborted() { + return this[Ce]; + } + set aborted(t2) {} + write(t2, e2, i3) { + if (this[Ce]) + return false; + if (this[Q]) + throw new Error("write after end"); + if (this[w]) + return this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" })), true; + typeof e2 == "function" && (i3 = e2, e2 = "utf8"), e2 || (e2 = "utf8"); + let r2 = this[Z2] ? jt : Yr; + if (!this[L] && !Buffer.isBuffer(t2)) { + if ($r(t2)) + t2 = Buffer.from(t2.buffer, t2.byteOffset, t2.byteLength); + else if (Vr(t2)) + t2 = Buffer.from(t2); + else if (typeof t2 != "string") + throw new Error("Non-contiguous data written to non-objectMode stream"); + } + return this[L] ? (this[g] && this[_] !== 0 && this[Ae](true), this[g] ? this.emit("data", t2) : this[bi](t2), this[_] !== 0 && this.emit("readable"), i3 && r2(i3), this[g]) : t2.length ? (typeof t2 == "string" && !(e2 === this[z] && !this[Mt]?.lastNeed) && (t2 = Buffer.from(t2, e2)), Buffer.isBuffer(t2) && this[z] && (t2 = this[Mt].write(t2)), this[g] && this[_] !== 0 && this[Ae](true), this[g] ? this.emit("data", t2) : this[bi](t2), this[_] !== 0 && this.emit("readable"), i3 && r2(i3), this[g]) : (this[_] !== 0 && this.emit("readable"), i3 && r2(i3), this[g]); + } + read(t2) { + if (this[w]) + return null; + if (this[C] = false, this[_] === 0 || t2 === 0 || t2 && t2 > this[_]) + return this[J](), null; + this[L] && (t2 = null), this[b].length > 1 && !this[L] && (this[b] = [this[z] ? this[b].join("") : Buffer.concat(this[b], this[_])]); + let e2 = this[Ns](t2 || null, this[b][0]); + return this[J](), e2; + } + [Ns](t2, e2) { + if (this[L]) + this[Ie](); + else { + let i3 = e2; + t2 === i3.length || t2 === null ? this[Ie]() : typeof i3 == "string" ? (this[b][0] = i3.slice(t2), e2 = i3.slice(0, t2), this[_] -= t2) : (this[b][0] = i3.subarray(t2), e2 = i3.subarray(0, t2), this[_] -= t2); + } + return this.emit("data", e2), !this[b].length && !this[Q] && this.emit("drain"), e2; + } + end(t2, e2, i3) { + return typeof t2 == "function" && (i3 = t2, t2 = undefined), typeof e2 == "function" && (i3 = e2, e2 = "utf8"), t2 !== undefined && this.write(t2, e2), i3 && this.once("end", i3), this[Q] = true, this.writable = false, (this[g] || !this[Qt]) && this[J](), this; + } + [Bt]() { + this[w] || (!this[Rt] && !this[N].length && (this[C] = true), this[Qt] = false, this[g] = true, this.emit("resume"), this[b].length ? this[Ae]() : this[Q] ? this[J]() : this.emit("drain")); + } + resume() { + return this[Bt](); + } + pause() { + this[g] = false, this[Qt] = true, this[C] = false; + } + get destroyed() { + return this[w]; + } + get flowing() { + return this[g]; + } + get paused() { + return this[Qt]; + } + [bi](t2) { + this[L] ? this[_] += 1 : this[_] += t2.length, this[b].push(t2); + } + [Ie]() { + return this[L] ? this[_] -= 1 : this[_] -= this[b][0].length, this[b].shift(); + } + [Ae](t2 = false) { + do + ; + while (this[As](this[Ie]()) && this[b].length); + !t2 && !this[b].length && !this[Q] && this.emit("drain"); + } + [As](t2) { + return this.emit("data", t2), this[g]; + } + pipe(t2, e2) { + if (this[w]) + return t2; + this[C] = false; + let i3 = this[nt]; + return e2 = e2 || {}, t2 === Ds.stdout || t2 === Ds.stderr ? e2.end = false : e2.end = e2.end !== false, e2.proxyErrors = !!e2.proxyErrors, i3 ? e2.end && t2.end() : (this[N].push(e2.proxyErrors ? new Li(this, t2, e2) : new Fe(this, t2, e2)), this[Z2] ? jt(() => this[Bt]()) : this[Bt]()), t2; + } + unpipe(t2) { + let e2 = this[N].find((i3) => i3.dest === t2); + e2 && (this[N].length === 1 ? (this[g] && this[Rt] === 0 && (this[g] = false), this[N] = []) : this[N].splice(this[N].indexOf(e2), 1), e2.unpipe()); + } + addListener(t2, e2) { + return this.on(t2, e2); + } + on(t2, e2) { + let i3 = super.on(t2, e2); + if (t2 === "data") + this[C] = false, this[Rt]++, !this[N].length && !this[g] && this[Bt](); + else if (t2 === "readable" && this[_] !== 0) + super.emit("readable"); + else if (Kr(t2) && this[nt]) + super.emit(t2), this.removeAllListeners(t2); + else if (t2 === "error" && this[qt]) { + let r2 = e2; + this[Z2] ? jt(() => r2.call(this, this[qt])) : r2.call(this, this[qt]); + } + return i3; + } + removeListener(t2, e2) { + return this.off(t2, e2); + } + off(t2, e2) { + let i3 = super.off(t2, e2); + return t2 === "data" && (this[Rt] = this.listeners("data").length, this[Rt] === 0 && !this[C] && !this[N].length && (this[g] = false)), i3; + } + removeAllListeners(t2) { + let e2 = super.removeAllListeners(t2); + return (t2 === "data" || t2 === undefined) && (this[Rt] = 0, !this[C] && !this[N].length && (this[g] = false)), e2; + } + get emittedEnd() { + return this[nt]; + } + [J]() { + !this[De] && !this[nt] && !this[w] && this[b].length === 0 && this[Q] && (this[De] = true, this.emit("end"), this.emit("prefinish"), this.emit("finish"), this[Ne] && this.emit("close"), this[De] = false); + } + emit(t2, ...e2) { + let i3 = e2[0]; + if (t2 !== "error" && t2 !== "close" && t2 !== w && this[w]) + return false; + if (t2 === "data") + return !this[L] && !i3 ? false : this[Z2] ? (jt(() => this[Oi](i3)), true) : this[Oi](i3); + if (t2 === "end") + return this[Is](); + if (t2 === "close") { + if (this[Ne] = true, !this[nt] && !this[w]) + return false; + let n2 = super.emit("close"); + return this.removeAllListeners("close"), n2; + } else if (t2 === "error") { + this[qt] = i3, super.emit(_i, i3); + let n2 = !this[Jt] || this.listeners("error").length ? super.emit("error", i3) : false; + return this[J](), n2; + } else if (t2 === "resume") { + let n2 = super.emit("resume"); + return this[J](), n2; + } else if (t2 === "finish" || t2 === "prefinish") { + let n2 = super.emit(t2); + return this.removeAllListeners(t2), n2; + } + let r2 = super.emit(t2, ...e2); + return this[J](), r2; + } + [Oi](t2) { + for (let i3 of this[N]) + i3.dest.write(t2) === false && this.pause(); + let e2 = this[C] ? false : super.emit("data", t2); + return this[J](), e2; + } + [Is]() { + return this[nt] ? false : (this[nt] = true, this.readable = false, this[Z2] ? (jt(() => this[Ti]()), true) : this[Ti]()); + } + [Ti]() { + if (this[Mt]) { + let e2 = this[Mt].end(); + if (e2) { + for (let i3 of this[N]) + i3.dest.write(e2); + this[C] || super.emit("data", e2); + } + } + for (let e2 of this[N]) + e2.end(); + let t2 = super.emit("end"); + return this.removeAllListeners("end"), t2; + } + async collect() { + let t2 = Object.assign([], { dataLength: 0 }); + this[L] || (t2.dataLength = 0); + let e2 = this.promise(); + return this.on("data", (i3) => { + t2.push(i3), this[L] || (t2.dataLength += i3.length); + }), await e2, t2; + } + async concat() { + if (this[L]) + throw new Error("cannot concat in objectMode"); + let t2 = await this.collect(); + return this[z] ? t2.join("") : Buffer.concat(t2, t2.dataLength); + } + async promise() { + return new Promise((t2, e2) => { + this.on(w, () => e2(new Error("stream destroyed"))), this.on("error", (i3) => e2(i3)), this.on("end", () => t2()); + }); + } + [Symbol.asyncIterator]() { + this[C] = false; + let t2 = false, e2 = async () => (this.pause(), t2 = true, { value: undefined, done: true }); + return { next: () => { + if (t2) + return e2(); + let r2 = this.read(); + if (r2 !== null) + return Promise.resolve({ done: false, value: r2 }); + if (this[Q]) + return e2(); + let n2, o2, h3 = (d) => { + this.off("data", a2), this.off("end", l), this.off(w, c3), e2(), o2(d); + }, a2 = (d) => { + this.off("error", h3), this.off("end", l), this.off(w, c3), this.pause(), n2({ value: d, done: !!this[Q] }); + }, l = () => { + this.off("error", h3), this.off("data", a2), this.off(w, c3), e2(), n2({ done: true, value: undefined }); + }, c3 = () => h3(new Error("stream destroyed")); + return new Promise((d, S2) => { + o2 = S2, n2 = d, this.once(w, c3), this.once("error", h3), this.once("end", l), this.once("data", a2); + }); + }, throw: e2, return: e2, [Symbol.asyncIterator]() { + return this; + }, [Symbol.asyncDispose]: async () => {} }; + } + [Symbol.iterator]() { + this[C] = false; + let t2 = false, e2 = () => (this.pause(), this.off(_i, e2), this.off(w, e2), this.off("end", e2), t2 = true, { done: true, value: undefined }), i3 = () => { + if (t2) + return e2(); + let r2 = this.read(); + return r2 === null ? e2() : { done: false, value: r2 }; + }; + return this.once("end", e2), this.once(_i, e2), this.once(w, e2), { next: i3, throw: e2, return: e2, [Symbol.iterator]() { + return this; + }, [Symbol.dispose]: () => {} }; + } + destroy(t2) { + if (this[w]) + return t2 ? this.emit("error", t2) : this.emit(w), this; + this[w] = true, this[C] = true, this[b].length = 0, this[_] = 0; + let e2 = this; + return typeof e2.close == "function" && !this[Ne] && e2.close(), t2 ? this.emit("error", t2) : this.emit(w), this; + } + static get isStream() { + return Wr; + } + }; + Jr = I.writev; + ht = Symbol("_autoClose"); + H = Symbol("_close"); + te = Symbol("_ended"); + u2 = Symbol("_fd"); + Ni = Symbol("_finished"); + tt = Symbol("_flags"); + Ai = Symbol("_flush"); + ki = Symbol("_handleChunk"); + vi = Symbol("_makeBuf"); + ie = Symbol("_mode"); + ke = Symbol("_needDrain"); + Ut = Symbol("_onerror"); + Ht = Symbol("_onopen"); + Ii = Symbol("_onread"); + Pt = Symbol("_onwrite"); + at = Symbol("_open"); + U = Symbol("_path"); + ot = Symbol("_pos"); + Y = Symbol("_queue"); + zt = Symbol("_read"); + Ci = Symbol("_readSize"); + j = Symbol("_reading"); + ee = Symbol("_remain"); + Fi = Symbol("_size"); + ve = Symbol("_write"); + gt = Symbol("_writing"); + Me = Symbol("_defaultFlag"); + bt = Symbol("_errored"); + _t = class extends A2 { + [bt] = false; + [u2]; + [U]; + [Ci]; + [j] = false; + [Fi]; + [ee]; + [ht]; + constructor(t2, e2) { + if (e2 = e2 || {}, super(e2), this.readable = true, this.writable = false, typeof t2 != "string") + throw new TypeError("path must be a string"); + this[bt] = false, this[u2] = typeof e2.fd == "number" ? e2.fd : undefined, this[U] = t2, this[Ci] = e2.readSize || 16 * 1024 * 1024, this[j] = false, this[Fi] = typeof e2.size == "number" ? e2.size : 1 / 0, this[ee] = this[Fi], this[ht] = typeof e2.autoClose == "boolean" ? e2.autoClose : true, typeof this[u2] == "number" ? this[zt]() : this[at](); + } + get fd() { + return this[u2]; + } + get path() { + return this[U]; + } + write() { + throw new TypeError("this is a readable stream"); + } + end() { + throw new TypeError("this is a readable stream"); + } + [at]() { + I.open(this[U], "r", (t2, e2) => this[Ht](t2, e2)); + } + [Ht](t2, e2) { + t2 ? this[Ut](t2) : (this[u2] = e2, this.emit("open", e2), this[zt]()); + } + [vi]() { + return Buffer.allocUnsafe(Math.min(this[Ci], this[ee])); + } + [zt]() { + if (!this[j]) { + this[j] = true; + let t2 = this[vi](); + if (t2.length === 0) + return process.nextTick(() => this[Ii](null, 0, t2)); + I.read(this[u2], t2, 0, t2.length, null, (e2, i3, r2) => this[Ii](e2, i3, r2)); + } + } + [Ii](t2, e2, i3) { + this[j] = false, t2 ? this[Ut](t2) : this[ki](e2, i3) && this[zt](); + } + [H]() { + if (this[ht] && typeof this[u2] == "number") { + let t2 = this[u2]; + this[u2] = undefined, I.close(t2, (e2) => e2 ? this.emit("error", e2) : this.emit("close")); + } + } + [Ut](t2) { + this[j] = true, this[H](), this.emit("error", t2); + } + [ki](t2, e2) { + let i3 = false; + return this[ee] -= t2, t2 > 0 && (i3 = super.write(t2 < e2.length ? e2.subarray(0, t2) : e2)), (t2 === 0 || this[ee] <= 0) && (i3 = false, this[H](), super.end()), i3; + } + emit(t2, ...e2) { + switch (t2) { + case "prefinish": + case "finish": + return false; + case "drain": + return typeof this[u2] == "number" && this[zt](), false; + case "error": + return this[bt] ? false : (this[bt] = true, super.emit(t2, ...e2)); + default: + return super.emit(t2, ...e2); + } + } + }; + Be = class extends _t { + [at]() { + let t2 = true; + try { + this[Ht](null, I.openSync(this[U], "r")), t2 = false; + } finally { + t2 && this[H](); + } + } + [zt]() { + let t2 = true; + try { + if (!this[j]) { + this[j] = true; + do { + let e2 = this[vi](), i3 = e2.length === 0 ? 0 : I.readSync(this[u2], e2, 0, e2.length, null); + if (!this[ki](i3, e2)) + break; + } while (true); + this[j] = false; + } + t2 = false; + } finally { + t2 && this[H](); + } + } + [H]() { + if (this[ht] && typeof this[u2] == "number") { + let t2 = this[u2]; + this[u2] = undefined, I.closeSync(t2), this.emit("close"); + } + } + }; + et = class extends Qr { + readable = false; + writable = true; + [bt] = false; + [gt] = false; + [te] = false; + [Y] = []; + [ke] = false; + [U]; + [ie]; + [ht]; + [u2]; + [Me]; + [tt]; + [Ni] = false; + [ot]; + constructor(t2, e2) { + e2 = e2 || {}, super(e2), this[U] = t2, this[u2] = typeof e2.fd == "number" ? e2.fd : undefined, this[ie] = e2.mode === undefined ? 438 : e2.mode, this[ot] = typeof e2.start == "number" ? e2.start : undefined, this[ht] = typeof e2.autoClose == "boolean" ? e2.autoClose : true; + let i3 = this[ot] !== undefined ? "r+" : "w"; + this[Me] = e2.flags === undefined, this[tt] = e2.flags === undefined ? i3 : e2.flags, this[u2] === undefined && this[at](); + } + emit(t2, ...e2) { + if (t2 === "error") { + if (this[bt]) + return false; + this[bt] = true; + } + return super.emit(t2, ...e2); + } + get fd() { + return this[u2]; + } + get path() { + return this[U]; + } + [Ut](t2) { + this[H](), this[gt] = true, this.emit("error", t2); + } + [at]() { + I.open(this[U], this[tt], this[ie], (t2, e2) => this[Ht](t2, e2)); + } + [Ht](t2, e2) { + this[Me] && this[tt] === "r+" && t2 && t2.code === "ENOENT" ? (this[tt] = "w", this[at]()) : t2 ? this[Ut](t2) : (this[u2] = e2, this.emit("open", e2), this[gt] || this[Ai]()); + } + end(t2, e2) { + return t2 && this.write(t2, e2), this[te] = true, !this[gt] && !this[Y].length && typeof this[u2] == "number" && this[Pt](null, 0), this; + } + write(t2, e2) { + return typeof t2 == "string" && (t2 = Buffer.from(t2, e2)), this[te] ? (this.emit("error", new Error("write() after end()")), false) : this[u2] === undefined || this[gt] || this[Y].length ? (this[Y].push(t2), this[ke] = true, false) : (this[gt] = true, this[ve](t2), true); + } + [ve](t2) { + I.write(this[u2], t2, 0, t2.length, this[ot], (e2, i3) => this[Pt](e2, i3)); + } + [Pt](t2, e2) { + t2 ? this[Ut](t2) : (this[ot] !== undefined && typeof e2 == "number" && (this[ot] += e2), this[Y].length ? this[Ai]() : (this[gt] = false, this[te] && !this[Ni] ? (this[Ni] = true, this[H](), this.emit("finish")) : this[ke] && (this[ke] = false, this.emit("drain")))); + } + [Ai]() { + if (this[Y].length === 0) + this[te] && this[Pt](null, 0); + else if (this[Y].length === 1) + this[ve](this[Y].pop()); + else { + let t2 = this[Y]; + this[Y] = [], Jr(this[u2], t2, this[ot], (e2, i3) => this[Pt](e2, i3)); + } + } + [H]() { + if (this[ht] && typeof this[u2] == "number") { + let t2 = this[u2]; + this[u2] = undefined, I.close(t2, (e2) => e2 ? this.emit("error", e2) : this.emit("close")); + } + } + }; + Wt = class extends et { + [at]() { + let t2; + if (this[Me] && this[tt] === "r+") + try { + t2 = I.openSync(this[U], this[tt], this[ie]); + } catch (e2) { + if (e2?.code === "ENOENT") + return this[tt] = "w", this[at](); + throw e2; + } + else + t2 = I.openSync(this[U], this[tt], this[ie]); + this[Ht](null, t2); + } + [H]() { + if (this[ht] && typeof this[u2] == "number") { + let t2 = this[u2]; + this[u2] = undefined, I.closeSync(t2), this.emit("close"); + } + } + [ve](t2) { + let e2 = true; + try { + this[Pt](null, I.writeSync(this[u2], t2, 0, t2.length, this[ot])), e2 = false; + } finally { + if (e2) + try { + this[H](); + } catch {} + } + } + }; + jr = new Map([["C", "cwd"], ["f", "file"], ["z", "gzip"], ["P", "preservePaths"], ["U", "unlink"], ["strip-components", "strip"], ["stripComponents", "strip"], ["keep-newer", "newer"], ["keepNewer", "newer"], ["keep-newer-files", "newer"], ["keepNewerFiles", "newer"], ["k", "keep"], ["keep-existing", "keep"], ["keepExisting", "keep"], ["m", "noMtime"], ["no-mtime", "noMtime"], ["p", "preserveOwner"], ["L", "follow"], ["h", "follow"], ["onentry", "onReadEntry"]]); + sn = en.constants || { ZLIB_VERNUM: 4736 }; + M = Object.freeze(Object.assign(Object.create(null), { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, Z_VERSION_ERROR: -6, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, DEFLATE: 1, INFLATE: 2, GZIP: 3, GUNZIP: 4, DEFLATERAW: 5, INFLATERAW: 6, UNZIP: 7, BROTLI_DECODE: 8, BROTLI_ENCODE: 9, Z_MIN_WINDOWBITS: 8, Z_MAX_WINDOWBITS: 15, Z_DEFAULT_WINDOWBITS: 15, Z_MIN_CHUNK: 64, Z_MAX_CHUNK: 1 / 0, Z_DEFAULT_CHUNK: 16384, Z_MIN_MEMLEVEL: 1, Z_MAX_MEMLEVEL: 9, Z_DEFAULT_MEMLEVEL: 8, Z_MIN_LEVEL: -1, Z_MAX_LEVEL: 9, Z_DEFAULT_LEVEL: -1, BROTLI_OPERATION_PROCESS: 0, BROTLI_OPERATION_FLUSH: 1, BROTLI_OPERATION_FINISH: 2, BROTLI_OPERATION_EMIT_METADATA: 3, BROTLI_MODE_GENERIC: 0, BROTLI_MODE_TEXT: 1, BROTLI_MODE_FONT: 2, BROTLI_DEFAULT_MODE: 0, BROTLI_MIN_QUALITY: 0, BROTLI_MAX_QUALITY: 11, BROTLI_DEFAULT_QUALITY: 11, BROTLI_MIN_WINDOW_BITS: 10, BROTLI_MAX_WINDOW_BITS: 24, BROTLI_LARGE_MAX_WINDOW_BITS: 30, BROTLI_DEFAULT_WINDOW: 22, BROTLI_MIN_INPUT_BLOCK_BITS: 16, BROTLI_MAX_INPUT_BLOCK_BITS: 24, BROTLI_PARAM_MODE: 0, BROTLI_PARAM_QUALITY: 1, BROTLI_PARAM_LGWIN: 2, BROTLI_PARAM_LGBLOCK: 3, BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4, BROTLI_PARAM_SIZE_HINT: 5, BROTLI_PARAM_LARGE_WINDOW: 6, BROTLI_PARAM_NPOSTFIX: 7, BROTLI_PARAM_NDIRECT: 8, BROTLI_DECODER_RESULT_ERROR: 0, BROTLI_DECODER_RESULT_SUCCESS: 1, BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0, BROTLI_DECODER_PARAM_LARGE_WINDOW: 1, BROTLI_DECODER_NO_ERROR: 0, BROTLI_DECODER_SUCCESS: 1, BROTLI_DECODER_NEEDS_MORE_INPUT: 2, BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1, BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2, BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4, BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5, BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6, BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7, BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9, BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10, BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11, BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12, BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13, BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14, BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15, BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16, BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19, BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21, BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22, BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26, BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27, BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30, BROTLI_DECODER_ERROR_UNREACHABLE: -31 }, sn)); + rn = Ot.concat; + zs = Object.getOwnPropertyDescriptor(Ot, "concat"); + Bi = zs?.writable === true || zs?.set !== undefined ? (s2) => { + Ot.concat = s2 ? nn : rn; + } : (s2) => {}; + Tt = Symbol("_superWrite"); + Gt = class extends Error { + code; + errno; + constructor(t2, e2) { + super("zlib: " + t2.message, { cause: t2 }), this.code = t2.code, this.errno = t2.errno, this.code || (this.code = "ZLIB_ERROR"), this.message = "zlib: " + t2.message, Error.captureStackTrace(this, e2 ?? this.constructor); + } + get name() { + return "ZlibError"; + } + }; + Pi = Symbol("flushFlag"); + re = class extends A2 { + #t = false; + #i = false; + #s; + #n; + #r; + #e; + #o; + get sawError() { + return this.#t; + } + get handle() { + return this.#e; + } + get flushFlag() { + return this.#s; + } + constructor(t2, e2) { + if (!t2 || typeof t2 != "object") + throw new TypeError("invalid options for ZlibBase constructor"); + if (super(t2), this.#s = t2.flush ?? 0, this.#n = t2.finishFlush ?? 0, this.#r = t2.fullFlushFlag ?? 0, typeof Ps[e2] != "function") + throw new TypeError("Compression method not supported: " + e2); + try { + this.#e = new Ps[e2](t2); + } catch (i3) { + throw new Gt(i3, this.constructor); + } + this.#o = (i3) => { + this.#t || (this.#t = true, this.close(), this.emit("error", i3)); + }, this.#e?.on("error", (i3) => this.#o(new Gt(i3))), this.once("end", () => this.close); + } + close() { + this.#e && (this.#e.close(), this.#e = undefined, this.emit("close")); + } + reset() { + if (!this.#t) + return zi(this.#e, "zlib binding closed"), this.#e.reset?.(); + } + flush(t2) { + this.ended || (typeof t2 != "number" && (t2 = this.#r), this.write(Object.assign(Ot.alloc(0), { [Pi]: t2 }))); + } + end(t2, e2, i3) { + return typeof t2 == "function" && (i3 = t2, e2 = undefined, t2 = undefined), typeof e2 == "function" && (i3 = e2, e2 = undefined), t2 && (e2 ? this.write(t2, e2) : this.write(t2)), this.flush(this.#n), this.#i = true, super.end(i3); + } + get ended() { + return this.#i; + } + [Tt](t2) { + return super.write(t2); + } + write(t2, e2, i3) { + if (typeof e2 == "function" && (i3 = e2, e2 = "utf8"), typeof t2 == "string" && (t2 = Ot.from(t2, e2)), this.#t) + return; + zi(this.#e, "zlib binding closed"); + let r2 = this.#e._handle, n2 = r2.close; + r2.close = () => {}; + let o2 = this.#e.close; + this.#e.close = () => {}, Bi(true); + let h3; + try { + let l = typeof t2[Pi] == "number" ? t2[Pi] : this.#s; + h3 = this.#e._processChunk(t2, l), Bi(false); + } catch (l) { + Bi(false), this.#o(new Gt(l, this.write)); + } finally { + this.#e && (this.#e._handle = r2, r2.close = n2, this.#e.close = o2, this.#e.removeAllListeners("error")); + } + this.#e && this.#e.on("error", (l) => this.#o(new Gt(l, this.write))); + let a2; + if (h3) + if (Array.isArray(h3) && h3.length > 0) { + let l = h3[0]; + a2 = this[Tt](Ot.from(l)); + for (let c3 = 1;c3 < h3.length; c3++) + a2 = this[Tt](h3[c3]); + } else + a2 = this[Tt](Ot.from(h3)); + return i3 && i3(), a2; + } + }; + Pe = class extends re { + #t; + #i; + constructor(t2, e2) { + t2 = t2 || {}, t2.flush = t2.flush || M.Z_NO_FLUSH, t2.finishFlush = t2.finishFlush || M.Z_FINISH, t2.fullFlushFlag = M.Z_FULL_FLUSH, super(t2, e2), this.#t = t2.level, this.#i = t2.strategy; + } + params(t2, e2) { + if (!this.sawError) { + if (!this.handle) + throw new Error("cannot switch params when binding is closed"); + if (!this.handle.params) + throw new Error("not supported in this implementation"); + if (this.#t !== t2 || this.#i !== e2) { + this.flush(M.Z_SYNC_FLUSH), zi(this.handle, "zlib binding closed"); + let i3 = this.handle.flush; + this.handle.flush = (r2, n2) => { + typeof r2 == "function" && (n2 = r2, r2 = this.flushFlag), this.flush(r2), n2?.(); + }; + try { + this.handle.params(t2, e2); + } finally { + this.handle.flush = i3; + } + this.handle && (this.#t = t2, this.#i = e2); + } + } + } + }; + ze = class extends Pe { + #t; + constructor(t2) { + super(t2, "Gzip"), this.#t = t2 && !!t2.portable; + } + [Tt](t2) { + return this.#t ? (this.#t = false, t2[9] = 255, super[Tt](t2)) : super[Tt](t2); + } + }; + Ue = class extends Pe { + constructor(t2) { + super(t2, "Unzip"); + } + }; + He = class extends re { + constructor(t2, e2) { + t2 = t2 || {}, t2.flush = t2.flush || M.BROTLI_OPERATION_PROCESS, t2.finishFlush = t2.finishFlush || M.BROTLI_OPERATION_FINISH, t2.fullFlushFlag = M.BROTLI_OPERATION_FLUSH, super(t2, e2); + } + }; + We = class extends He { + constructor(t2) { + super(t2, "BrotliCompress"); + } + }; + Ge = class extends He { + constructor(t2) { + super(t2, "BrotliDecompress"); + } + }; + Ze = class extends re { + constructor(t2, e2) { + t2 = t2 || {}, t2.flush = t2.flush || M.ZSTD_e_continue, t2.finishFlush = t2.finishFlush || M.ZSTD_e_end, t2.fullFlushFlag = M.ZSTD_e_flush, super(t2, e2); + } + }; + Ye = class extends Ze { + constructor(t2) { + super(t2, "ZstdCompress"); + } + }; + Ke = class extends Ze { + constructor(t2) { + super(t2, "ZstdDecompress"); + } + }; + Hi = {}; + Ur(Hi, { code: () => Ve, isCode: () => ne, isName: () => dn, name: () => oe, normalFsTypes: () => Ui }); + Ui = new Set(["0", "", "1", "2", "3", "4", "5", "6", "7", "D"]); + oe = new Map([["0", "File"], ["", "OldFile"], ["1", "Link"], ["2", "SymbolicLink"], ["3", "CharacterDevice"], ["4", "BlockDevice"], ["5", "Directory"], ["6", "FIFO"], ["7", "ContiguousFile"], ["g", "GlobalExtendedHeader"], ["x", "ExtendedHeader"], ["A", "SolarisACL"], ["D", "GNUDumpDir"], ["I", "Inode"], ["K", "NextFileHasLongLinkpath"], ["L", "NextFileHasLongPath"], ["M", "ContinuationFile"], ["N", "OldGnuLongPath"], ["S", "SparseFile"], ["V", "TapeVolumeHeader"], ["X", "OldExtendedHeader"]]); + Ve = new Map(Array.from(oe).map((s2) => [s2[1], s2[0]])); + Sn = { 12: 8589934591, 8: 2097151 }; + bn = new Array(156).join("\x00"); + Ln = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; + f3 = Ln !== "win32" ? (s3) => String(s3) : (s3) => String(s3).replaceAll(/\\/g, "/"); + $e = class extends A2 { + extended; + globalExtended; + header; + startBlockSize; + blockRemain; + remain; + type; + meta = false; + ignore = false; + path; + mode; + uid; + gid; + uname; + gname; + size = 0; + mtime; + atime; + ctime; + linkpath; + dev; + ino; + nlink; + invalid = false; + absolute; + unsupported = false; + constructor(t2, e2, i3) { + switch (super({}), this.pause(), this.extended = e2, this.globalExtended = i3, this.header = t2, this.remain = t2.size ?? 0, this.startBlockSize = 512 * Math.ceil(this.remain / 512), this.blockRemain = this.startBlockSize, this.type = t2.type, this.type) { + case "File": + case "OldFile": + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + case "ContiguousFile": + case "GNUDumpDir": + break; + case "NextFileHasLongLinkpath": + case "NextFileHasLongPath": + case "OldGnuLongPath": + case "GlobalExtendedHeader": + case "ExtendedHeader": + case "OldExtendedHeader": + this.meta = true; + break; + default: + this.ignore = true; + } + if (!t2.path) + throw new Error("no path provided for tar.ReadEntry"); + this.path = f3(t2.path), this.mode = t2.mode, this.mode && (this.mode = this.mode & 4095), this.uid = t2.uid, this.gid = t2.gid, this.uname = t2.uname, this.gname = t2.gname, this.size = this.remain, this.mtime = t2.mtime, this.atime = t2.atime, this.ctime = t2.ctime, this.linkpath = t2.linkpath ? f3(t2.linkpath) : undefined, this.uname = t2.uname, this.gname = t2.gname, e2 && this.#t(e2), i3 && this.#t(i3, true); + } + write(t2) { + let e2 = t2.length; + if (e2 > this.blockRemain) + throw new Error("writing more to entry than is appropriate"); + let i3 = this.remain, r2 = this.blockRemain; + return this.remain = Math.max(0, i3 - e2), this.blockRemain = Math.max(0, r2 - e2), this.ignore ? true : i3 >= e2 ? super.write(t2) : super.write(t2.subarray(0, i3)); + } + #t(t2, e2 = false) { + t2.path && (t2.path = f3(t2.path)), t2.linkpath && (t2.linkpath = f3(t2.linkpath)), Object.assign(this, Object.fromEntries(Object.entries(t2).filter(([i3, r2]) => !(r2 == null || i3 === "path" && e2)))); + } + }; + Nn = 1024 * 1024; + Xi = Buffer.from([31, 139]); + qi = Buffer.from([40, 181, 47, 253]); + An = Math.max(Xi.length, qi.length); + B = Symbol("state"); + Nt = Symbol("writeEntry"); + it = Symbol("readEntry"); + Zi = Symbol("nextEntry"); + Zs = Symbol("processEntry"); + V = Symbol("extendedHeader"); + he = Symbol("globalExtendedHeader"); + dt = Symbol("meta"); + Ys = Symbol("emitMeta"); + p = Symbol("buffer"); + st = Symbol("queue"); + mt = Symbol("ended"); + Yi = Symbol("emittedEnd"); + At = Symbol("emit"); + y = Symbol("unzip"); + Xe = Symbol("consumeChunk"); + qe = Symbol("consumeChunkSub"); + Ki = Symbol("consumeBody"); + Ks = Symbol("consumeMeta"); + Vs = Symbol("consumeHeader"); + ae = Symbol("consuming"); + Vi = Symbol("bufferConcat"); + Qe = Symbol("maybeEnd"); + Yt = Symbol("writing"); + $2 = Symbol("aborted"); + Je = Symbol("onDone"); + It = Symbol("sawValidEntry"); + je = Symbol("sawNullBlock"); + ti = Symbol("sawEOF"); + $s = Symbol("closeStream"); + le = Symbol("compressedBytesRead"); + $i = Symbol("decompressedBytesRead"); + Xs = Symbol("checkDecompressionRatio"); + rt = class extends Dn { + file; + strict; + maxMetaEntrySize; + filter; + brotli; + zstd; + maxDecompressionRatio; + writable = true; + readable = false; + [st] = []; + [p]; + [it]; + [Nt]; + [B] = "begin"; + [dt] = ""; + [V]; + [he]; + [mt] = false; + [y]; + [$2] = false; + [It]; + [je] = false; + [ti] = false; + [Yt] = false; + [ae] = false; + [Yi] = false; + [le] = 0; + [$i] = 0; + constructor(t2 = {}) { + super(), this.file = t2.file || "", this.on(Je, () => { + (this[B] === "begin" || this[It] === false) && this.warn("TAR_BAD_ARCHIVE", "Unrecognized archive format"); + }), t2.ondone ? this.on(Je, t2.ondone) : this.on(Je, () => { + this.emit("prefinish"), this.emit("finish"), this.emit("end"); + }), this.strict = !!t2.strict, this.maxDecompressionRatio = typeof t2.maxDecompressionRatio == "number" ? t2.maxDecompressionRatio : In, this.maxMetaEntrySize = t2.maxMetaEntrySize || Nn, this.filter = typeof t2.filter == "function" ? t2.filter : Cn; + let e2 = t2.file && (t2.file.endsWith(".tar.br") || t2.file.endsWith(".tbr")); + this.brotli = !(t2.gzip || t2.zstd) && t2.brotli !== undefined ? t2.brotli : e2 ? undefined : false; + let i3 = t2.file && (t2.file.endsWith(".tar.zst") || t2.file.endsWith(".tzst")); + this.zstd = !(t2.gzip || t2.brotli) && t2.zstd !== undefined ? t2.zstd : i3 ? true : undefined, this.on("end", () => this[$s]()), typeof t2.onwarn == "function" && this.on("warn", t2.onwarn), typeof t2.onReadEntry == "function" && this.on("entry", t2.onReadEntry); + } + warn(t2, e2, i3 = {}) { + Dt(this, t2, e2, i3); + } + [Vs](t2, e2) { + this[It] === undefined && (this[It] = false); + let i3; + try { + i3 = new F2(t2, e2, this[V], this[he]); + } catch (r2) { + return this.warn("TAR_ENTRY_INVALID", r2); + } + if (i3.nullBlock) + this[je] ? (this[ti] = true, this[B] === "begin" && (this[B] = "header"), this[At]("eof")) : (this[je] = true, this[At]("nullBlock")); + else if (this[je] = false, !i3.cksumValid) + this.warn("TAR_ENTRY_INVALID", "checksum failure", { header: i3 }); + else if (!i3.path) + this.warn("TAR_ENTRY_INVALID", "path is required", { header: i3 }); + else { + let r2 = i3.type; + if (/^(Symbolic)?Link$/.test(r2) && !i3.linkpath) + this.warn("TAR_ENTRY_INVALID", "linkpath required", { header: i3 }); + else if (!/^(Symbolic)?Link$/.test(r2) && !/^(Global)?ExtendedHeader$/.test(r2) && i3.linkpath) + this.warn("TAR_ENTRY_INVALID", "linkpath forbidden", { header: i3 }); + else { + let n2 = this[Nt] = new $e(i3, this[V], this[he]); + if (!this[It]) + if (n2.remain) { + let o2 = () => { + n2.invalid || (this[It] = true); + }; + n2.on("end", o2); + } else + this[It] = true; + n2.meta ? n2.size > this.maxMetaEntrySize ? (n2.ignore = true, this[At]("ignoredEntry", n2), this[B] = "ignore", n2.resume()) : n2.size > 0 && (this[dt] = "", n2.on("data", (o2) => this[dt] += o2), this[B] = "meta") : (this[V] = undefined, n2.ignore = n2.ignore || !this.filter(n2.path, n2), n2.ignore ? (this[At]("ignoredEntry", n2), this[B] = n2.remain ? "ignore" : "header", n2.resume()) : (n2.remain ? this[B] = "body" : (this[B] = "header", n2.end()), this[it] ? this[st].push(n2) : (this[st].push(n2), this[Zi]()))); + } + } + } + [$s]() { + queueMicrotask(() => this.emit("close")); + } + [Zs](t2) { + let e2 = true; + if (!t2) + this[it] = undefined, e2 = false; + else if (Array.isArray(t2)) { + let [i3, ...r2] = t2; + this.emit(i3, ...r2); + } else + this[it] = t2, this.emit("entry", t2), t2.emittedEnd || (t2.on("end", () => this[Zi]()), e2 = false); + return e2; + } + [Zi]() { + do + ; + while (this[Zs](this[st].shift())); + if (this[st].length === 0) { + let t2 = this[it]; + !t2 || t2.flowing || t2.size === t2.remain ? this[Yt] || this.emit("drain") : t2.once("drain", () => this.emit("drain")); + } + } + [Ki](t2, e2) { + let i3 = this[Nt]; + if (!i3) + throw new Error("attempt to consume body without entry??"); + let r2 = i3.blockRemain ?? 0, n2 = r2 >= t2.length && e2 === 0 ? t2 : t2.subarray(e2, e2 + r2); + return i3.write(n2), i3.blockRemain || (this[B] = "header", this[Nt] = undefined, i3.end()), n2.length; + } + [Ks](t2, e2) { + let i3 = this[Nt], r2 = this[Ki](t2, e2); + return !this[Nt] && i3 && this[Ys](i3), r2; + } + [At](t2, e2, i3) { + this[st].length === 0 && !this[it] ? this.emit(t2, e2, i3) : this[st].push([t2, e2, i3]); + } + [Ys](t2) { + switch (this[At]("meta", this[dt]), t2.type) { + case "ExtendedHeader": + case "OldExtendedHeader": + this[V] = ft.parse(this[dt], this[V], false); + break; + case "GlobalExtendedHeader": + this[he] = ft.parse(this[dt], this[he], true); + break; + case "NextFileHasLongPath": + case "OldGnuLongPath": { + let e2 = this[V] ?? Object.create(null); + this[V] = e2, e2.path = this[dt].replace(/\0.*/, ""); + break; + } + case "NextFileHasLongLinkpath": { + let e2 = this[V] || Object.create(null); + this[V] = e2, e2.linkpath = this[dt].replace(/\0.*/, ""); + break; + } + default: + throw new Error("unknown meta: " + t2.type); + } + } + abort(t2) { + this[$2] || (this[$2] = true, this.emit("abort", t2), this.warn("TAR_ABORT", t2, { recoverable: false })); + } + [Xs](t2) { + this[$i] += t2.length; + let e2 = this[$i] / this[le]; + return e2 > this.maxDecompressionRatio ? (this.abort(new Error(`max decompression ratio exceeded: ${e2.toFixed(2)} > ${this.maxDecompressionRatio}`)), false) : true; + } + write(t2, e2, i3) { + if (typeof e2 == "function" && (i3 = e2, e2 = undefined), typeof t2 == "string" && (t2 = Buffer.from(t2, typeof e2 == "string" ? e2 : "utf8")), this[$2]) + return i3?.(), false; + if ((this[y] === undefined || this.brotli === undefined && this[y] === false) && t2) { + if (this[p] && (t2 = Buffer.concat([this[p], t2]), this[p] = undefined), t2.length < An) + return this[p] = t2, i3?.(), true; + for (let a2 = 0;this[y] === undefined && a2 < Xi.length; a2++) + t2[a2] !== Xi[a2] && (this[y] = false); + let o2 = false; + if (this[y] === false && this.zstd !== false) { + o2 = true; + for (let a2 = 0;a2 < qi.length; a2++) + if (t2[a2] !== qi[a2]) { + o2 = false; + break; + } + } + let h3 = this.brotli === undefined && !o2; + if (this[y] === false && h3) + if (t2.length < 512) + if (this[mt]) + this.brotli = true; + else + return this[p] = t2, i3?.(), true; + else + try { + new F2(t2.subarray(0, 512)), this.brotli = false; + } catch { + this.brotli = true; + } + if (this[y] === undefined || this[y] === false && (this.brotli || o2)) { + let a2 = this[mt]; + this[mt] = false, this[y] = this[y] === undefined ? new Ue({}) : o2 ? new Ke({}) : new Ge({}), this[y].on("data", (c3) => { + this[Xs](c3) && this[Xe](c3); + }), this[y].on("error", (c3) => { + this[$2] || this.abort(c3); + }), this[y].on("end", () => { + this[mt] = true, this[Xe](); + }), this[Yt] = true, this[le] += t2.length; + let l = !!this[y][a2 ? "end" : "write"](t2); + return this[Yt] = false, i3?.(), l; + } + } + this[Yt] = true, this[y] ? (this[le] += t2.length, this[y].write(t2)) : this[Xe](t2), this[Yt] = false; + let n2 = this[st].length > 0 ? false : this[it] ? this[it].flowing : true; + return !n2 && this[st].length === 0 && this[it]?.once("drain", () => this.emit("drain")), i3?.(), n2; + } + [Vi](t2) { + t2 && !this[$2] && (this[p] = this[p] ? Buffer.concat([this[p], t2]) : t2); + } + [Qe]() { + if (this[mt] && !this[Yi] && !this[$2] && !this[ae]) { + this[Yi] = true; + let t2 = this[Nt]; + if (t2?.blockRemain) { + let e2 = this[p] ? this[p].length : 0; + this.warn("TAR_BAD_ARCHIVE", `Truncated input (needed ${t2.blockRemain} more bytes, only ${e2} available)`, { entry: t2 }), this[p] && t2.write(this[p]), t2.end(); + } + this[At](Je); + } + } + [Xe](t2) { + if (this[ae] && t2) + this[Vi](t2); + else if (!t2 && !this[p]) + this[Qe](); + else if (t2) { + if (this[ae] = true, this[p]) { + this[Vi](t2); + let e2 = this[p]; + this[p] = undefined, this[qe](e2); + } else + this[qe](t2); + for (;this[p] && this[p]?.length >= 512 && !this[$2] && !this[ti]; ) { + let e2 = this[p]; + this[p] = undefined, this[qe](e2); + } + this[ae] = false; + } + (!this[p] || this[mt]) && this[Qe](); + } + [qe](t2) { + let e2 = 0, i3 = t2.length; + for (;e2 + 512 <= i3 && !this[$2] && !this[ti]; ) + switch (this[B]) { + case "begin": + case "header": + this[Vs](t2, e2), e2 += 512; + break; + case "ignore": + case "body": + e2 += this[Ki](t2, e2); + break; + case "meta": + e2 += this[Ks](t2, e2); + break; + default: + throw new Error("invalid state: " + this[B]); + } + e2 < i3 && (this[p] = this[p] ? Buffer.concat([t2.subarray(e2), this[p]]) : t2.subarray(e2)); + } + end(t2, e2, i3) { + return typeof t2 == "function" && (i3 = t2, e2 = undefined, t2 = undefined), typeof e2 == "function" && (i3 = e2, e2 = undefined), typeof t2 == "string" && (t2 = Buffer.from(t2, e2)), i3 && this.once("finish", i3), this[$2] || (this[y] ? (t2 && (this[le] += t2.length, this[y].write(t2)), this[y].end()) : (this[mt] = true, (this.brotli === undefined || this.zstd === undefined) && (t2 = t2 || Buffer.alloc(0)), t2 && this.write(t2), this[Qe]())), this; + } + }; + Ct = K(Mn, Bn, (s3) => new rt(s3), (s3) => new rt(s3), (s3, t2) => { + t2?.length && Qi(s3, t2), s3.noResume || vn(s3); + }); + ({ isAbsolute: zn, parse: qs } = Pn); + ei = ["|", "<", ">", "?", ":"]; + ji = ei.map((s3) => String.fromCodePoint(61440 + Number(s3.codePointAt(0)))); + Un = new Map(ei.map((s3, t2) => [s3, ji[t2]])); + Hn = new Map(ji.map((s3, t2) => [s3, ei[t2]])); + Wn = 16 * 1024 * 1024; + tr = Symbol("process"); + er = Symbol("file"); + ir = Symbol("directory"); + is = Symbol("symlink"); + sr = Symbol("hardlink"); + fe = Symbol("header"); + ii = Symbol("read"); + ss = Symbol("lstat"); + si = Symbol("onlstat"); + rs = Symbol("onread"); + ns = Symbol("onreadlink"); + os2 = Symbol("openfile"); + hs = Symbol("onopenfile"); + pt = Symbol("close"); + ri = Symbol("mode"); + as = Symbol("awaitDrain"); + es = Symbol("ondrain"); + q = Symbol("prefix"); + de = class extends A2 { + path; + portable; + myuid = process.getuid && process.getuid() || 0; + myuser = process.env.USER || ""; + maxReadSize; + linkCache; + statCache; + preservePaths; + cwd; + strict; + mtime; + noPax; + noMtime; + prefix; + fd; + blockLen = 0; + blockRemain = 0; + buf; + pos = 0; + remain = 0; + length = 0; + offset = 0; + win32; + absolute; + header; + type; + linkpath; + stat; + onWriteEntry; + #t = false; + constructor(t2, e2 = {}) { + let i3 = se(e2); + super(), this.path = f3(t2), this.portable = !!i3.portable, this.maxReadSize = i3.maxReadSize || Wn, this.linkCache = i3.linkCache || new Map, this.statCache = i3.statCache || new Map, this.preservePaths = !!i3.preservePaths, this.cwd = f3(i3.cwd || process.cwd()), this.strict = !!i3.strict, this.noPax = !!i3.noPax, this.noMtime = !!i3.noMtime, this.mtime = i3.mtime, this.prefix = i3.prefix ? f3(i3.prefix) : undefined, this.onWriteEntry = i3.onWriteEntry, typeof i3.onwarn == "function" && this.on("warn", i3.onwarn); + let r2 = false; + if (!this.preservePaths) { + let [o2, h3] = ce(this.path); + o2 && typeof h3 == "string" && (this.path = h3, r2 = o2); + } + this.win32 = !!i3.win32 || process.platform === "win32", this.win32 && (this.path = Qs(this.path.replaceAll(/\\/g, "/")), t2 = t2.replaceAll(/\\/g, "/")), this.absolute = f3(i3.absolute || js.resolve(this.cwd, t2)), this.path === "" && (this.path = "./"), r2 && this.warn("TAR_ENTRY_INFO", `stripping ${r2} from absolute path`, { entry: this, path: r2 + this.path }); + let n2 = this.statCache.get(this.absolute); + n2 ? this[si](n2) : this[ss](); + } + warn(t2, e2, i3 = {}) { + return Dt(this, t2, e2, i3); + } + emit(t2, ...e2) { + return t2 === "error" && (this.#t = true), super.emit(t2, ...e2); + } + [ss]() { + X.lstat(this.absolute, (t2, e2) => { + if (t2) + return this.emit("error", t2); + this[si](e2); + }); + } + [si](t2) { + this.statCache.set(this.absolute, t2), this.stat = t2, t2.isFile() || (t2.size = 0), this.type = Gn(t2), this.emit("stat", t2), this[tr](); + } + [tr]() { + switch (this.type) { + case "File": + return this[er](); + case "Directory": + return this[ir](); + case "SymbolicLink": + return this[is](); + default: + return this.end(); + } + } + [ri](t2) { + return Ji(t2, this.type === "Directory", this.portable); + } + [q](t2) { + return rr(t2, this.prefix); + } + [fe]() { + if (!this.stat) + throw new Error("cannot write header before stat"); + this.type === "Directory" && this.portable && (this.noMtime = true), this.onWriteEntry?.(this), this.header = new F2({ path: this[q](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[q](this.linkpath) : this.linkpath, mode: this[ri](this.stat.mode), uid: this.portable ? undefined : this.stat.uid, gid: this.portable ? undefined : this.stat.gid, size: this.stat.size, mtime: this.noMtime ? undefined : this.mtime || this.stat.mtime, type: this.type === "Unsupported" ? undefined : this.type, uname: this.portable ? undefined : this.stat.uid === this.myuid ? this.myuser : "", atime: this.portable ? undefined : this.stat.atime, ctime: this.portable ? undefined : this.stat.ctime }), this.header.encode() && !this.noPax && super.write(new ft({ atime: this.portable ? undefined : this.header.atime, ctime: this.portable ? undefined : this.header.ctime, gid: this.portable ? undefined : this.header.gid, mtime: this.noMtime ? undefined : this.mtime || this.header.mtime, path: this[q](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[q](this.linkpath) : this.linkpath, size: this.header.size, uid: this.portable ? undefined : this.header.uid, uname: this.portable ? undefined : this.header.uname, dev: this.portable ? undefined : this.stat.dev, ino: this.portable ? undefined : this.stat.ino, nlink: this.portable ? undefined : this.stat.nlink }).encode()); + let t2 = this.header?.block; + if (!t2) + throw new Error("failed to encode header"); + super.write(t2); + } + [ir]() { + if (!this.stat) + throw new Error("cannot create directory entry without stat"); + this.path.slice(-1) !== "/" && (this.path += "/"), this.stat.size = 0, this[fe](), this.end(); + } + [is]() { + X.readlink(this.absolute, (t2, e2) => { + if (t2) + return this.emit("error", t2); + this[ns](e2); + }); + } + [ns](t2) { + this.linkpath = f3(t2), this[fe](), this.end(); + } + [sr](t2) { + if (!this.stat) + throw new Error("cannot create link entry without stat"); + this.type = "Link", this.linkpath = f3(js.relative(this.cwd, t2)), this.stat.size = 0, this[fe](), this.end(); + } + [er]() { + if (!this.stat) + throw new Error("cannot create file entry without stat"); + if (this.stat.nlink > 1) { + let t2 = `${this.stat.dev}:${this.stat.ino}`, e2 = this.linkCache.get(t2); + if (e2?.indexOf(this.cwd) === 0) + return this[sr](e2); + this.linkCache.set(t2, this.absolute); + } + if (this[fe](), this.stat.size === 0) + return this.end(); + this[os2](); + } + [os2]() { + X.open(this.absolute, "r", (t2, e2) => { + if (t2) + return this.emit("error", t2); + this[hs](e2); + }); + } + [hs](t2) { + if (this.fd = t2, this.#t) + return this[pt](); + if (!this.stat) + throw new Error("should stat before calling onopenfile"); + this.blockLen = 512 * Math.ceil(this.stat.size / 512), this.blockRemain = this.blockLen; + let e2 = Math.min(this.blockLen, this.maxReadSize); + this.buf = Buffer.allocUnsafe(e2), this.offset = 0, this.pos = 0, this.remain = this.stat.size, this.length = this.buf.length, this[ii](); + } + [ii]() { + let { fd: t2, buf: e2, offset: i3, length: r2, pos: n2 } = this; + if (t2 === undefined || e2 === undefined) + throw new Error("cannot read file without first opening"); + X.read(t2, e2, i3, r2, n2, (o2, h3) => { + if (o2) + return this[pt](() => this.emit("error", o2)); + this[rs](h3); + }); + } + [pt](t2 = () => {}) { + this.fd !== undefined && X.close(this.fd, t2); + } + [rs](t2) { + if (t2 <= 0 && this.remain > 0) { + let r2 = Object.assign(new Error("encountered unexpected EOF"), { path: this.absolute, syscall: "read", code: "EOF" }); + return this[pt](() => this.emit("error", r2)); + } + if (t2 > this.remain) { + let r2 = Object.assign(new Error("did not encounter expected EOF"), { path: this.absolute, syscall: "read", code: "EOF" }); + return this[pt](() => this.emit("error", r2)); + } + if (!this.buf) + throw new Error("should have created buffer prior to reading"); + if (t2 === this.remain) + for (let r2 = t2;r2 < this.length && t2 < this.blockRemain; r2++) + this.buf[r2 + this.offset] = 0, t2++, this.remain++; + let e2 = this.offset === 0 && t2 === this.buf.length ? this.buf : this.buf.subarray(this.offset, this.offset + t2); + this.write(e2) ? this[es]() : this[as](() => this[es]()); + } + [as](t2) { + this.once("drain", t2); + } + write(t2, e2, i3) { + if (typeof e2 == "function" && (i3 = e2, e2 = undefined), typeof t2 == "string" && (t2 = Buffer.from(t2, typeof e2 == "string" ? e2 : "utf8")), this.blockRemain < t2.length) { + let r2 = Object.assign(new Error("writing more data than expected"), { path: this.absolute }); + return this.emit("error", r2); + } + return this.remain -= t2.length, this.blockRemain -= t2.length, this.pos += t2.length, this.offset += t2.length, super.write(t2, null, i3); + } + [es]() { + if (!this.remain) + return this.blockRemain && super.write(Buffer.alloc(this.blockRemain)), this[pt]((t2) => t2 ? this.emit("error", t2) : this.end()); + if (!this.buf) + throw new Error("buffer lost somehow in ONDRAIN"); + this.offset >= this.length && (this.buf = Buffer.allocUnsafe(Math.min(this.blockRemain, this.buf.length)), this.offset = 0), this.length = this.buf.length - this.offset, this[ii](); + } + }; + ni = class extends de { + sync = true; + [ss]() { + this[si](X.lstatSync(this.absolute)); + } + [is]() { + this[ns](X.readlinkSync(this.absolute)); + } + [os2]() { + this[hs](X.openSync(this.absolute, "r")); + } + [ii]() { + let t2 = true; + try { + let { fd: e2, buf: i3, offset: r2, length: n2, pos: o2 } = this; + if (e2 === undefined || i3 === undefined) + throw new Error("fd and buf must be set in READ method"); + let h3 = X.readSync(e2, i3, r2, n2, o2); + this[rs](h3), t2 = false; + } finally { + if (t2) + try { + this[pt](() => {}); + } catch {} + } + } + [as](t2) { + t2(); + } + [pt](t2 = () => {}) { + this.fd !== undefined && X.closeSync(this.fd), t2(); + } + }; + oi = class extends A2 { + blockLen = 0; + blockRemain = 0; + buf = 0; + pos = 0; + remain = 0; + length = 0; + preservePaths; + portable; + strict; + noPax; + noMtime; + readEntry; + type; + prefix; + path; + mode; + uid; + gid; + uname; + gname; + header; + mtime; + atime; + ctime; + linkpath; + size; + onWriteEntry; + warn(t2, e2, i3 = {}) { + return Dt(this, t2, e2, i3); + } + constructor(t2, e2 = {}) { + let i3 = se(e2); + super(), this.preservePaths = !!i3.preservePaths, this.portable = !!i3.portable, this.strict = !!i3.strict, this.noPax = !!i3.noPax, this.noMtime = !!i3.noMtime, this.onWriteEntry = i3.onWriteEntry, this.readEntry = t2; + let { type: r2 } = t2; + if (r2 === "Unsupported") + throw new Error("writing entry that should be ignored"); + this.type = r2, this.type === "Directory" && this.portable && (this.noMtime = true), this.prefix = i3.prefix, this.path = f3(t2.path), this.mode = t2.mode !== undefined ? this[ri](t2.mode) : undefined, this.uid = this.portable ? undefined : t2.uid, this.gid = this.portable ? undefined : t2.gid, this.uname = this.portable ? undefined : t2.uname, this.gname = this.portable ? undefined : t2.gname, this.size = t2.size, this.mtime = this.noMtime ? undefined : i3.mtime || t2.mtime, this.atime = this.portable ? undefined : t2.atime, this.ctime = this.portable ? undefined : t2.ctime, this.linkpath = t2.linkpath !== undefined ? f3(t2.linkpath) : undefined, typeof i3.onwarn == "function" && this.on("warn", i3.onwarn); + let n2 = false; + if (!this.preservePaths) { + let [h3, a2] = ce(this.path); + h3 && typeof a2 == "string" && (this.path = a2, n2 = h3); + } + this.remain = t2.size, this.blockRemain = t2.startBlockSize, this.onWriteEntry?.(this), this.header = new F2({ path: this[q](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[q](this.linkpath) : this.linkpath, mode: this.mode, uid: this.portable ? undefined : this.uid, gid: this.portable ? undefined : this.gid, size: this.size, mtime: this.noMtime ? undefined : this.mtime, type: this.type, uname: this.portable ? undefined : this.uname, atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime }), n2 && this.warn("TAR_ENTRY_INFO", `stripping ${n2} from absolute path`, { entry: this, path: n2 + this.path }), this.header.encode() && !this.noPax && super.write(new ft({ atime: this.portable ? undefined : this.atime, ctime: this.portable ? undefined : this.ctime, gid: this.portable ? undefined : this.gid, mtime: this.noMtime ? undefined : this.mtime, path: this[q](this.path), linkpath: this.type === "Link" && this.linkpath !== undefined ? this[q](this.linkpath) : this.linkpath, size: this.size, uid: this.portable ? undefined : this.uid, uname: this.portable ? undefined : this.uname, dev: this.portable ? undefined : this.readEntry.dev, ino: this.portable ? undefined : this.readEntry.ino, nlink: this.portable ? undefined : this.readEntry.nlink }).encode()); + let o2 = this.header?.block; + if (!o2) + throw new Error("failed to encode header"); + super.write(o2), t2.pipe(this); + } + [q](t2) { + return rr(t2, this.prefix); + } + [ri](t2) { + return Ji(t2, this.type === "Directory", this.portable); + } + write(t2, e2, i3) { + typeof e2 == "function" && (i3 = e2, e2 = undefined), typeof t2 == "string" && (t2 = Buffer.from(t2, typeof e2 == "string" ? e2 : "utf8")); + let r2 = t2.length; + if (r2 > this.blockRemain) + throw new Error("writing more to entry than is appropriate"); + return this.blockRemain -= r2, super.write(t2, i3); + } + end(t2, e2, i3) { + return this.blockRemain && super.write(Buffer.alloc(this.blockRemain)), typeof t2 == "function" && (i3 = t2, e2 = undefined, t2 = undefined), typeof e2 == "function" && (i3 = e2, e2 = undefined), typeof t2 == "string" && (t2 = Buffer.from(t2, e2 ?? "utf8")), i3 && this.once("finish", i3), t2 ? super.end(t2, i3) : super.end(i3), this; + } + }; + hi = class s3 { + tail; + head; + length = 0; + static create(t2 = []) { + return new s3(t2); + } + constructor(t2 = []) { + for (let e2 of t2) + this.push(e2); + } + *[Symbol.iterator]() { + for (let t2 = this.head;t2; t2 = t2.next) + yield t2.value; + } + removeNode(t2) { + if (t2.list !== this) + throw new Error("removing node which does not belong to this list"); + let { next: e2, prev: i3 } = t2; + return e2 && (e2.prev = i3), i3 && (i3.next = e2), t2 === this.head && (this.head = e2), t2 === this.tail && (this.tail = i3), this.length--, t2.next = undefined, t2.prev = undefined, t2.list = undefined, e2; + } + unshiftNode(t2) { + if (t2 === this.head) + return; + t2.list && t2.list.removeNode(t2); + let e2 = this.head; + t2.list = this, t2.next = e2, e2 && (e2.prev = t2), this.head = t2, this.tail || (this.tail = t2), this.length++; + } + pushNode(t2) { + if (t2 === this.tail) + return; + t2.list && t2.list.removeNode(t2); + let e2 = this.tail; + t2.list = this, t2.prev = e2, e2 && (e2.next = t2), this.tail = t2, this.head || (this.head = t2), this.length++; + } + push(...t2) { + for (let e2 = 0, i3 = t2.length;e2 < i3; e2++) + Yn(this, t2[e2]); + return this.length; + } + unshift(...t2) { + for (var e2 = 0, i3 = t2.length;e2 < i3; e2++) + Kn(this, t2[e2]); + return this.length; + } + pop() { + if (!this.tail) + return; + let t2 = this.tail.value, e2 = this.tail; + return this.tail = this.tail.prev, this.tail ? this.tail.next = undefined : this.head = undefined, e2.list = undefined, this.length--, t2; + } + shift() { + if (!this.head) + return; + let t2 = this.head.value, e2 = this.head; + return this.head = this.head.next, this.head ? this.head.prev = undefined : this.tail = undefined, e2.list = undefined, this.length--, t2; + } + forEach(t2, e2) { + e2 = e2 || this; + for (let i3 = this.head, r2 = 0;i3; r2++) + t2.call(e2, i3.value, r2, this), i3 = i3.next; + } + forEachReverse(t2, e2) { + e2 = e2 || this; + for (let i3 = this.tail, r2 = this.length - 1;i3; r2--) + t2.call(e2, i3.value, r2, this), i3 = i3.prev; + } + get(t2) { + let e2 = 0, i3 = this.head; + for (;i3 && e2 < t2; e2++) + i3 = i3.next; + if (e2 === t2 && i3) + return i3.value; + } + getReverse(t2) { + let e2 = 0, i3 = this.tail; + for (;i3 && e2 < t2; e2++) + i3 = i3.prev; + if (e2 === t2 && i3) + return i3.value; + } + map(t2, e2) { + e2 = e2 || this; + let i3 = new s3; + for (let r2 = this.head;r2; ) + i3.push(t2.call(e2, r2.value, this)), r2 = r2.next; + return i3; + } + mapReverse(t2, e2) { + e2 = e2 || this; + var i3 = new s3; + for (let r2 = this.tail;r2; ) + i3.push(t2.call(e2, r2.value, this)), r2 = r2.prev; + return i3; + } + reduce(t2, e2) { + let i3, r2 = this.head; + if (arguments.length > 1) + i3 = e2; + else if (this.head) + r2 = this.head.next, i3 = this.head.value; + else + throw new TypeError("Reduce of empty list with no initial value"); + for (var n2 = 0;r2; n2++) + i3 = t2(i3, r2.value, n2), r2 = r2.next; + return i3; + } + reduceReverse(t2, e2) { + let i3, r2 = this.tail; + if (arguments.length > 1) + i3 = e2; + else if (this.tail) + r2 = this.tail.prev, i3 = this.tail.value; + else + throw new TypeError("Reduce of empty list with no initial value"); + for (let n2 = this.length - 1;r2; n2--) + i3 = t2(i3, r2.value, n2), r2 = r2.prev; + return i3; + } + toArray() { + let t2 = new Array(this.length); + for (let e2 = 0, i3 = this.head;i3; e2++) + t2[e2] = i3.value, i3 = i3.next; + return t2; + } + toArrayReverse() { + let t2 = new Array(this.length); + for (let e2 = 0, i3 = this.tail;i3; e2++) + t2[e2] = i3.value, i3 = i3.prev; + return t2; + } + slice(t2 = 0, e2 = this.length) { + e2 < 0 && (e2 += this.length), t2 < 0 && (t2 += this.length); + let i3 = new s3; + if (e2 < t2 || e2 < 0) + return i3; + t2 < 0 && (t2 = 0), e2 > this.length && (e2 = this.length); + let r2 = this.head, n2 = 0; + for (n2 = 0;r2 && n2 < t2; n2++) + r2 = r2.next; + for (;r2 && n2 < e2; n2++, r2 = r2.next) + i3.push(r2.value); + return i3; + } + sliceReverse(t2 = 0, e2 = this.length) { + e2 < 0 && (e2 += this.length), t2 < 0 && (t2 += this.length); + let i3 = new s3; + if (e2 < t2 || e2 < 0) + return i3; + t2 < 0 && (t2 = 0), e2 > this.length && (e2 = this.length); + let r2 = this.length, n2 = this.tail; + for (;n2 && r2 > e2; r2--) + n2 = n2.prev; + for (;n2 && r2 > t2; r2--, n2 = n2.prev) + i3.push(n2.value); + return i3; + } + splice(t2, e2 = 0, ...i3) { + t2 > this.length && (t2 = this.length - 1), t2 < 0 && (t2 = this.length + t2); + let r2 = this.head; + for (let o2 = 0;r2 && o2 < t2; o2++) + r2 = r2.next; + let n2 = []; + for (let o2 = 0;r2 && o2 < e2; o2++) + n2.push(r2.value), r2 = this.removeNode(r2); + r2 ? r2 !== this.tail && (r2 = r2.prev) : r2 = this.tail; + for (let o2 of i3) + r2 = Zn(this, r2, o2); + return n2; + } + reverse() { + let t2 = this.head, e2 = this.tail; + for (let i3 = t2;i3; i3 = i3.prev) { + let r2 = i3.prev; + i3.prev = i3.next, i3.next = r2; + } + return this.head = e2, this.tail = t2, this; + } + }; + nr = Buffer.alloc(1024); + li = Symbol("onStat"); + ue = Symbol("ended"); + W = Symbol("queue"); + pe = Symbol("pendingLinks"); + Et = Symbol("current"); + Ft = Symbol("process"); + Ee = Symbol("processing"); + ai = Symbol("processJob"); + G = Symbol("jobs"); + ls = Symbol("jobDone"); + ci = Symbol("addFSEntry"); + or = Symbol("addTarEntry"); + ds = Symbol("stat"); + ms = Symbol("readdir"); + fi = Symbol("onreaddir"); + di = Symbol("pipe"); + hr = Symbol("entry"); + cs = Symbol("entryOpt"); + mi = Symbol("writeEntryClass"); + lr = Symbol("write"); + fs2 = Symbol("ondrain"); + wt = class extends A2 { + sync = false; + opt; + cwd; + maxReadSize; + preservePaths; + strict; + noPax; + prefix; + linkCache; + statCache; + file; + portable; + zip; + readdirCache; + noDirRecurse; + follow; + noMtime; + mtime; + filter; + jobs; + [mi]; + onWriteEntry; + [W]; + [pe] = new Map; + [G] = 0; + [Ee] = false; + [ue] = false; + constructor(t2 = {}) { + if (super(), this.opt = t2, this.file = t2.file || "", this.cwd = t2.cwd || process.cwd(), this.maxReadSize = t2.maxReadSize, this.preservePaths = !!t2.preservePaths, this.strict = !!t2.strict, this.noPax = !!t2.noPax, this.prefix = f3(t2.prefix || ""), this.linkCache = t2.linkCache || new Map, this.statCache = t2.statCache || new Map, this.readdirCache = t2.readdirCache || new Map, this.onWriteEntry = t2.onWriteEntry, this[mi] = de, typeof t2.onwarn == "function" && this.on("warn", t2.onwarn), this.portable = !!t2.portable, t2.gzip || t2.brotli || t2.zstd) { + if ((t2.gzip ? 1 : 0) + (t2.brotli ? 1 : 0) + (t2.zstd ? 1 : 0) > 1) + throw new TypeError("gzip, brotli, zstd are mutually exclusive"); + if (t2.gzip && (typeof t2.gzip != "object" && (t2.gzip = {}), this.portable && (t2.gzip.portable = true), this.zip = new ze(t2.gzip)), t2.brotli && (typeof t2.brotli != "object" && (t2.brotli = {}), this.zip = new We(t2.brotli)), t2.zstd && (typeof t2.zstd != "object" && (t2.zstd = {}), this.zip = new Ye(t2.zstd)), !this.zip) + throw new Error("impossible"); + let e2 = this.zip; + e2.on("data", (i3) => super.write(i3)), e2.on("end", () => super.end()), e2.on("drain", () => this[fs2]()), this.on("resume", () => e2.resume()); + } else + this.on("drain", this[fs2]); + this.noDirRecurse = !!t2.noDirRecurse, this.follow = !!t2.follow, this.noMtime = !!t2.noMtime, t2.mtime && (this.mtime = t2.mtime), this.filter = typeof t2.filter == "function" ? t2.filter : () => true, this[W] = new hi, this[G] = 0, this.jobs = Number(t2.jobs) || 4, this[Ee] = false, this[ue] = false; + } + [lr](t2) { + return super.write(t2); + } + add(t2) { + return this.write(t2), this; + } + end(t2, e2, i3) { + return typeof t2 == "function" && (i3 = t2, t2 = undefined), typeof e2 == "function" && (i3 = e2, e2 = undefined), t2 && this.add(t2), this[ue] = true, this[Ft](), i3 && i3(), this; + } + write(t2) { + if (this[ue]) + throw new Error("write after end"); + return typeof t2 == "string" ? this[ci](t2) : this[or](t2), this.flowing; + } + [or](t2) { + let e2 = f3(ar.resolve(this.cwd, t2.path)); + if (!this.filter(t2.path, t2)) + t2.resume(); + else { + let i3 = new pi(t2.path, e2); + i3.entry = new oi(t2, this[cs](i3)), i3.entry.on("end", () => this[ls](i3)), this[G] += 1, this[W].push(i3); + } + this[Ft](); + } + [ci](t2) { + let e2 = f3(ar.resolve(this.cwd, t2)); + this[W].push(new pi(t2, e2)), this[Ft](); + } + [ds](t2) { + t2.pending = true, this[G] += 1; + let e2 = this.follow ? "stat" : "lstat"; + ui[e2](t2.absolute, (i3, r2) => { + t2.pending = false, this[G] -= 1, i3 ? this.emit("error", i3) : this[li](t2, r2); + }); + } + [li](t2, e2) { + if (this.statCache.set(t2.absolute, e2), t2.stat = e2, !this.filter(t2.path, e2)) + t2.ignore = true; + else if (e2.isFile() && e2.nlink > 1 && !this.linkCache.get(`${e2.dev}:${e2.ino}`) && !this.sync) + if (t2 === this[Et]) + this[ai](t2); + else { + let i3 = `${e2.dev}:${e2.ino}`, r2 = this[pe].get(i3); + r2 ? r2.push(t2) : this[pe].set(i3, [t2]), t2.pendingLink = true, t2.pending = true; + } + this[Ft](); + } + [ms](t2) { + t2.pending = true, this[G] += 1, ui.readdir(t2.absolute, (e2, i3) => { + if (t2.pending = false, this[G] -= 1, e2) + return this.emit("error", e2); + this[fi](t2, i3); + }); + } + [fi](t2, e2) { + this.readdirCache.set(t2.absolute, e2), t2.readdir = e2, this[Ft](); + } + [Ft]() { + if (!this[Ee]) { + this[Ee] = true; + for (let t2 = this[W].head;t2 && this[G] < this.jobs; t2 = t2.next) + if (this[ai](t2.value), t2.value.ignore) { + let e2 = t2.next; + this[W].removeNode(t2), t2.next = e2; + } + this[Ee] = false, this[ue] && this[W].length === 0 && this[G] === 0 && (this.zip ? this.zip.end(nr) : (super.write(nr), super.end())); + } + } + get [Et]() { + return this[W] && this[W].head && this[W].head.value; + } + [ls](t2) { + this[W].shift(), this[G] -= 1; + let { stat: e2 } = t2; + if (e2 && e2.isFile() && e2.nlink > 1) { + let i3 = `${e2.dev}:${e2.ino}`, r2 = this[pe].get(i3); + if (r2) { + this[pe].delete(i3); + for (let n2 of r2) + n2.pending = false, this[ai](n2); + } + } + this[Ft](); + } + [ai](t2) { + if (t2.pending && t2.pendingLink && t2 === this[Et] && (t2.pending = false, t2.pendingLink = false), !t2.pending) { + if (t2.entry) { + t2 === this[Et] && !t2.piped && this[di](t2); + return; + } + if (!t2.stat) { + let e2 = this.statCache.get(t2.absolute); + e2 ? this[li](t2, e2) : this[ds](t2); + } + if (t2.stat && !t2.ignore) { + if (!this.noDirRecurse && t2.stat.isDirectory() && !t2.readdir) { + let e2 = this.readdirCache.get(t2.absolute); + if (e2 ? this[fi](t2, e2) : this[ms](t2), !t2.readdir) + return; + } + if (t2.entry = this[hr](t2), !t2.entry) { + t2.ignore = true; + return; + } + t2 === this[Et] && !t2.piped && this[di](t2); + } + } + } + [cs](t2) { + return { onwarn: (e2, i3, r2) => this.warn(e2, i3, r2), noPax: this.noPax, cwd: this.cwd, absolute: t2.absolute, preservePaths: this.preservePaths, maxReadSize: this.maxReadSize, strict: this.strict, portable: this.portable, linkCache: this.linkCache, statCache: this.statCache, noMtime: this.noMtime, mtime: this.mtime, prefix: this.prefix, onWriteEntry: this.onWriteEntry }; + } + [hr](t2) { + this[G] += 1; + try { + return new this[mi](t2.path, this[cs](t2)).on("end", () => this[ls](t2)).on("error", (i3) => this.emit("error", i3)); + } catch (e2) { + this.emit("error", e2); + } + } + [fs2]() { + this[Et] && this[Et].entry && this[Et].entry.resume(); + } + [di](t2) { + t2.piped = true, t2.readdir && t2.readdir.forEach((r2) => { + let n2 = t2.path, o2 = n2 === "./" ? "" : n2.replace(/\/*$/, "/"); + this[ci](o2 + r2); + }); + let e2 = t2.entry, i3 = this.zip; + if (!e2) + throw new Error("cannot pipe without source"); + i3 ? e2.on("data", (r2) => { + i3.write(r2) || e2.pause(); + }) : e2.on("data", (r2) => { + super.write(r2) || e2.pause(); + }); + } + pause() { + return this.zip && this.zip.pause(), super.pause(); + } + warn(t2, e2, i3 = {}) { + Dt(this, t2, e2, i3); + } + }; + kt = class extends wt { + sync = true; + constructor(t2) { + super(t2), this[mi] = ni; + } + pause() {} + resume() {} + [ds](t2) { + let e2 = this.follow ? "statSync" : "lstatSync"; + this[li](t2, ui[e2](t2.absolute)); + } + [ms](t2) { + this[fi](t2, ui.readdirSync(t2.absolute)); + } + [di](t2) { + let e2 = t2.entry, i3 = this.zip; + if (t2.readdir && t2.readdir.forEach((r2) => { + let n2 = t2.path, o2 = n2 === "./" ? "" : n2.replace(/\/*$/, "/"); + this[ci](o2 + r2); + }), !e2) + throw new Error("Cannot pipe without source"); + i3 ? e2.on("data", (r2) => { + i3.write(r2); + }) : e2.on("data", (r2) => { + super[lr](r2); + }); + } + }; + Qn = K(Vn, $n, Xn, qn, (s4, t2) => { + if (!t2?.length) + throw new TypeError("no paths specified to add to archive"); + }); + Jn = process.env.__FAKE_PLATFORM__ || process.platform; + Er = Jn === "win32"; + ({ O_CREAT: wr, O_NOFOLLOW: mr, O_TRUNC: Sr, O_WRONLY: yr } = pr.constants); + Rr = Number(process.env.__FAKE_FS_O_FILENAME__) || pr.constants.UV_FS_O_FILEMAP || 0; + jn = Er && !!Rr; + to = 512 * 1024; + eo = Rr | Sr | wr | yr; + ur = !Er && typeof mr == "number" ? mr | Sr | wr | yr : null; + us = ur !== null ? () => ur : jn ? (s4) => s4 < to ? eo : "w" : () => "w"; + Se = class extends Error { + path; + code; + syscall = "chdir"; + constructor(t2, e2) { + super(`${e2}: Cannot cd into '${t2}'`), this.path = t2, this.code = e2; + } + get name() { + return "CwdError"; + } + }; + St = class extends Error { + path; + symlink; + syscall = "symlink"; + code = "TAR_SYMLINK_ERROR"; + constructor(t2, e2) { + super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"), this.symlink = t2, this.path = e2; + } + get name() { + return "SymlinkError"; + } + }; + ys = Object.create(null); + Vt = new Set; + ho = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; + ao = ho === "win32"; + Dr = Symbol("onEntry"); + _s = Symbol("checkFs"); + Nr = Symbol("checkFs2"); + Os = Symbol("isReusable"); + P = Symbol("makeFs"); + Ts = Symbol("file"); + xs = Symbol("directory"); + gi = Symbol("link"); + Ar = Symbol("symlink"); + Ir = Symbol("hardlink"); + Re = Symbol("ensureNoSymlink"); + Cr = Symbol("unsupported"); + Fr = Symbol("checkPath"); + Rs = Symbol("stripAbsolutePath"); + yt = Symbol("mkdir"); + O = Symbol("onError"); + Ri = Symbol("pending"); + kr = Symbol("pend"); + $t = Symbol("unpend"); + gs = Symbol("ended"); + bs = Symbol("maybeClose"); + Ls = Symbol("skip"); + ge = Symbol("doChown"); + be = Symbol("uid"); + _e = Symbol("gid"); + Oe = Symbol("checkedCwd"); + fo = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform; + Te = fo === "win32"; + Xt = class extends rt { + [gs] = false; + [Oe] = false; + [Ri] = 0; + reservations = new yi; + transform; + writable = true; + readable = false; + uid; + gid; + setOwner; + preserveOwner; + processGid; + processUid; + maxDepth; + forceChown; + win32; + newer; + keep; + noMtime; + preservePaths; + unlink; + cwd; + strip; + processUmask; + umask; + dmode; + fmode; + chmod; + constructor(t2 = {}) { + if (t2.ondone = () => { + this[gs] = true, this[bs](); + }, super(t2), this.transform = t2.transform, this.chmod = !!t2.chmod, typeof t2.uid == "number" || typeof t2.gid == "number") { + if (typeof t2.uid != "number" || typeof t2.gid != "number") + throw new TypeError("cannot set owner without number uid and gid"); + if (t2.preserveOwner) + throw new TypeError("cannot preserve owner in archive and also set owner explicitly"); + this.uid = t2.uid, this.gid = t2.gid, this.setOwner = true; + } else + this.uid = undefined, this.gid = undefined, this.setOwner = false; + this.preserveOwner = t2.preserveOwner === undefined && typeof t2.uid != "number" ? process.getuid?.() === 0 : !!t2.preserveOwner, this.processUid = (this.preserveOwner || this.setOwner) && process.getuid ? process.getuid() : undefined, this.processGid = (this.preserveOwner || this.setOwner) && process.getgid ? process.getgid() : undefined, this.maxDepth = typeof t2.maxDepth == "number" ? t2.maxDepth : mo, this.forceChown = t2.forceChown === true, this.win32 = !!t2.win32 || Te, this.newer = !!t2.newer, this.keep = !!t2.keep, this.noMtime = !!t2.noMtime, this.preservePaths = !!t2.preservePaths, this.unlink = !!t2.unlink, this.cwd = f3(R.resolve(t2.cwd || process.cwd())), this.strip = Number(t2.strip) || 0, this.processUmask = this.chmod ? typeof t2.processUmask == "number" ? t2.processUmask : Lr() : 0, this.umask = typeof t2.umask == "number" ? t2.umask : this.processUmask, this.dmode = t2.dmode || 511 & ~this.umask, this.fmode = t2.fmode || 438 & ~this.umask, this.on("entry", (e2) => this[Dr](e2)); + } + warn(t2, e2, i3 = {}) { + return (t2 === "TAR_BAD_ARCHIVE" || t2 === "TAR_ABORT") && (i3.recoverable = false), super.warn(t2, e2, i3); + } + [bs]() { + this[gs] && this[Ri] === 0 && (this.emit("prefinish"), this.emit("finish"), this.emit("end")); + } + [Rs](t2, e2) { + let i3 = t2[e2], { type: r2 } = t2; + if (!i3 || this.preservePaths) + return true; + let [n2, o2] = ce(i3), h3 = o2.replaceAll(/\\/g, "/").split("/"); + if (h3.includes("..") || Te && /^[a-z]:\.\.$/i.test(h3[0] ?? "")) { + if (e2 === "path" || r2 === "Link") + return this.warn("TAR_ENTRY_ERROR", `${e2} contains '..'`, { entry: t2, [e2]: i3 }), false; + let a2 = R.posix.dirname(t2.path), l = R.posix.normalize(R.posix.join(a2, h3.join("/"))); + if (l.startsWith("../") || l === "..") + return this.warn("TAR_ENTRY_ERROR", `${e2} escapes extraction directory`, { entry: t2, [e2]: i3 }), false; + } + return n2 && (t2[e2] = String(o2), this.warn("TAR_ENTRY_INFO", `stripping ${n2} from absolute ${e2}`, { entry: t2, [e2]: i3 })), true; + } + [Fr](t2) { + let e2 = f3(t2.path), i3 = e2.split("/"); + if (this.strip) { + if (i3.length < this.strip) + return false; + if (t2.type === "Link") { + let r2 = f3(String(t2.linkpath)).split("/"); + if (r2.length >= this.strip) + t2.linkpath = r2.slice(this.strip).join("/"); + else + return false; + } + i3.splice(0, this.strip), t2.path = i3.join("/"); + } + if (isFinite(this.maxDepth) && i3.length > this.maxDepth) + return this.warn("TAR_ENTRY_ERROR", "path excessively deep", { entry: t2, path: e2, depth: i3.length, maxDepth: this.maxDepth }), false; + if (!this[Rs](t2, "path") || !this[Rs](t2, "linkpath")) + return false; + if (t2.absolute = R.isAbsolute(t2.path) ? f3(R.resolve(t2.path)) : f3(R.resolve(this.cwd, t2.path)), !this.preservePaths && typeof t2.absolute == "string" && t2.absolute.indexOf(this.cwd + "/") !== 0 && t2.absolute !== this.cwd) + return this.warn("TAR_ENTRY_ERROR", "path escaped extraction target", { entry: t2, path: f3(t2.path), resolvedPath: t2.absolute, cwd: this.cwd }), false; + if (t2.absolute === this.cwd && t2.type !== "Directory" && t2.type !== "GNUDumpDir") + return false; + if (this.win32) { + let { root: r2 } = R.win32.parse(String(t2.absolute)); + t2.absolute = r2 + ts(String(t2.absolute).slice(r2.length)); + let { root: n2 } = R.win32.parse(t2.path); + t2.path = n2 + ts(t2.path.slice(n2.length)); + } + return true; + } + [Dr](t2) { + if (!this[Fr](t2)) + return t2.resume(); + switch (co.equal(typeof t2.absolute, "string"), t2.type) { + case "Directory": + case "GNUDumpDir": + t2.mode && (t2.mode = t2.mode | 448); + case "File": + case "OldFile": + case "ContiguousFile": + case "Link": + case "SymbolicLink": + return this[_s](t2); + default: + return this[Cr](t2); + } + } + [O](t2, e2) { + t2.name === "CwdError" ? this.emit("error", t2) : (this.warn("TAR_ENTRY_ERROR", t2, { entry: e2 }), this[$t](), e2.resume()); + } + [yt](t2, e2, i3) { + gr(f3(t2), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cwd: this.cwd, mode: e2 }, i3); + } + [ge](t2) { + return this.forceChown || this.preserveOwner && (typeof t2.uid == "number" && t2.uid !== this.processUid || typeof t2.gid == "number" && t2.gid !== this.processGid) || typeof this.uid == "number" && this.uid !== this.processUid || typeof this.gid == "number" && this.gid !== this.processGid; + } + [be](t2) { + return vr(this.uid, t2.uid, this.processUid); + } + [_e](t2) { + return vr(this.gid, t2.gid, this.processGid); + } + [Ts](t2, e2) { + let i3 = typeof t2.mode == "number" ? t2.mode & 4095 : this.fmode, r2 = new et(String(t2.absolute), { flags: us(t2.size), mode: i3, autoClose: false }); + r2.on("error", (a2) => { + r2.fd && m2.close(r2.fd, () => {}), r2.write = () => true, this[O](a2, t2), e2(); + }); + let n2 = 1, o2 = (a2) => { + if (a2) { + r2.fd && m2.close(r2.fd, () => {}), this[O](a2, t2), e2(); + return; + } + --n2 === 0 && r2.fd !== undefined && m2.close(r2.fd, (l) => { + l ? this[O](l, t2) : this[$t](), e2(); + }); + }; + r2.on("finish", () => { + let a2 = String(t2.absolute), l = r2.fd; + if (typeof l == "number" && t2.mtime && !this.noMtime) { + n2++; + let c3 = t2.atime || new Date, d = t2.mtime; + m2.futimes(l, c3, d, (S2) => S2 ? m2.utimes(a2, c3, d, (T) => o2(T && S2)) : o2()); + } + if (typeof l == "number" && this[ge](t2)) { + n2++; + let c3 = this[be](t2), d = this[_e](t2); + typeof c3 == "number" && typeof d == "number" && m2.fchown(l, c3, d, (S2) => S2 ? m2.chown(a2, c3, d, (T) => o2(T && S2)) : o2()); + } + o2(); + }); + let h3 = this.transform && this.transform(t2) || t2; + h3 !== t2 && (h3.on("error", (a2) => { + this[O](a2, t2), e2(); + }), t2.pipe(h3)), h3.pipe(r2); + } + [xs](t2, e2) { + let i3 = typeof t2.mode == "number" ? t2.mode & 4095 : this.dmode; + this[yt](String(t2.absolute), i3, (r2) => { + if (r2) { + this[O](r2, t2), e2(); + return; + } + let n2 = 1, o2 = () => { + --n2 === 0 && (e2(), this[$t](), t2.resume()); + }; + t2.mtime && !this.noMtime && (n2++, m2.utimes(String(t2.absolute), t2.atime || new Date, t2.mtime, o2)), this[ge](t2) && (n2++, m2.chown(String(t2.absolute), Number(this[be](t2)), Number(this[_e](t2)), o2)), o2(); + }); + } + [Cr](t2) { + t2.unsupported = true, this.warn("TAR_ENTRY_UNSUPPORTED", `unsupported entry type: ${t2.type}`, { entry: t2 }), t2.resume(); + } + [Ar](t2, e2) { + let i3 = f3(R.relative(this.cwd, R.resolve(R.dirname(String(t2.absolute)), String(t2.linkpath)))).split("/"); + this[Re](t2, this.cwd, i3, () => this[gi](t2, String(t2.linkpath), "symlink", e2), (r2) => { + this[O](r2, t2), e2(); + }); + } + [Ir](t2, e2) { + let i3 = f3(R.resolve(this.cwd, String(t2.linkpath))), r2 = f3(String(t2.linkpath)).split("/"); + this[Re](t2, this.cwd, r2, () => this[gi](t2, i3, "link", e2), (n2) => { + this[O](n2, t2), e2(); + }); + } + [Re](t2, e2, i3, r2, n2) { + let o2 = i3.shift(); + if (this.preservePaths || o2 === undefined) + return r2(); + let h3 = R.resolve(e2, o2); + m2.lstat(h3, (a2, l) => { + if (a2) + return r2(); + if (l?.isSymbolicLink()) + return n2(new St(h3, R.resolve(h3, i3.join("/")))); + this[Re](t2, h3, i3, r2, n2); + }); + } + [kr]() { + this[Ri]++; + } + [$t]() { + this[Ri]--, this[bs](); + } + [Ls](t2) { + this[$t](), t2.resume(); + } + [Os](t2, e2) { + return t2.type === "File" && !this.unlink && e2.isFile() && e2.nlink <= 1 && !Te; + } + [_s](t2) { + this[kr](); + let e2 = [t2.path]; + t2.linkpath && e2.push(t2.linkpath), this.reservations.reserve(e2, (i3) => this[Nr](t2, i3)); + } + [Nr](t2, e2) { + let i3 = (h3) => { + e2(h3); + }, r2 = () => { + this[yt](this.cwd, this.dmode, (h3) => { + if (h3) { + this[O](h3, t2), i3(); + return; + } + this[Oe] = true, n2(); + }); + }, n2 = () => { + if (t2.absolute !== this.cwd) { + let h3 = f3(R.dirname(String(t2.absolute))); + if (h3 !== this.cwd) + return this[yt](h3, this.dmode, (a2) => { + if (a2) { + this[O](a2, t2), i3(); + return; + } + o2(); + }); + } + o2(); + }, o2 = () => { + m2.lstat(String(t2.absolute), (h3, a2) => { + if (a2 && (this.keep || this.newer && a2.mtime > (t2.mtime ?? a2.mtime))) { + this[Ls](t2), i3(); + return; + } + if (h3 || this[Os](t2, a2)) + return this[P](null, t2, i3); + if (a2.isDirectory()) { + if (t2.type === "Directory") { + let l = this.chmod && t2.mode && (a2.mode & 4095) !== t2.mode, c3 = (d) => this[P](d ?? null, t2, i3); + return l ? m2.chmod(String(t2.absolute), Number(t2.mode), c3) : c3(); + } + if (t2.absolute !== this.cwd) + return m2.rmdir(String(t2.absolute), (l) => this[P](l ?? null, t2, i3)); + } + if (t2.absolute === this.cwd) + return this[P](null, t2, i3); + uo(String(t2.absolute), (l) => this[P](l ?? null, t2, i3)); + }); + }; + this[Oe] ? n2() : r2(); + } + [P](t2, e2, i3) { + if (t2) { + this[O](t2, e2), i3(); + return; + } + switch (e2.type) { + case "File": + case "OldFile": + case "ContiguousFile": + return this[Ts](e2, i3); + case "Link": + return this[Ir](e2, i3); + case "SymbolicLink": + return this[Ar](e2, i3); + case "Directory": + case "GNUDumpDir": + return this[xs](e2, i3); + } + } + [gi](t2, e2, i3, r2) { + m2[i3](e2, String(t2.absolute), (n2) => { + n2 ? this[O](n2, t2) : (this[$t](), t2.resume()), r2(); + }); + } + }; + xe = class extends Xt { + sync = true; + [P](t2, e2) { + return super[P](t2, e2, () => {}); + } + [_s](t2) { + if (!this[Oe]) { + let n2 = this[yt](this.cwd, this.dmode); + if (n2) + return this[O](n2, t2); + this[Oe] = true; + } + if (t2.absolute !== this.cwd) { + let n2 = f3(R.dirname(String(t2.absolute))); + if (n2 !== this.cwd) { + let o2 = this[yt](n2, this.dmode); + if (o2) + return this[O](o2, t2); + } + } + let [e2, i3] = ye(() => m2.lstatSync(String(t2.absolute))); + if (i3 && (this.keep || this.newer && i3.mtime > (t2.mtime ?? i3.mtime))) + return this[Ls](t2); + if (e2 || this[Os](t2, i3)) + return this[P](null, t2); + if (i3.isDirectory()) { + if (t2.type === "Directory") { + let o2 = this.chmod && t2.mode && (i3.mode & 4095) !== t2.mode, [h3] = o2 ? ye(() => { + m2.chmodSync(String(t2.absolute), Number(t2.mode)); + }) : []; + return this[P](h3, t2); + } + let [n2] = ye(() => m2.rmdirSync(String(t2.absolute))); + this[P](n2, t2); + } + let [r2] = t2.absolute === this.cwd ? [] : ye(() => po(String(t2.absolute))); + this[P](r2, t2); + } + [Ts](t2, e2) { + let i3 = typeof t2.mode == "number" ? t2.mode & 4095 : this.fmode, r2 = (h3) => { + let a2; + try { + m2.closeSync(n2); + } catch (l) { + a2 = l; + } + (h3 || a2) && this[O](h3 || a2, t2), e2(); + }, n2; + try { + n2 = m2.openSync(String(t2.absolute), us(t2.size), i3); + } catch (h3) { + return r2(h3); + } + let o2 = this.transform && this.transform(t2) || t2; + o2 !== t2 && (o2.on("error", (h3) => this[O](h3, t2)), t2.pipe(o2)), o2.on("data", (h3) => { + try { + m2.writeSync(n2, h3, 0, h3.length); + } catch (a2) { + r2(a2); + } + }), o2.on("end", () => { + let h3 = null; + if (t2.mtime && !this.noMtime) { + let a2 = t2.atime || new Date, l = t2.mtime; + try { + m2.futimesSync(n2, a2, l); + } catch (c3) { + try { + m2.utimesSync(String(t2.absolute), a2, l); + } catch { + h3 = c3; + } + } + } + if (this[ge](t2)) { + let a2 = this[be](t2), l = this[_e](t2); + try { + m2.fchownSync(n2, Number(a2), Number(l)); + } catch (c3) { + try { + m2.chownSync(String(t2.absolute), Number(a2), Number(l)); + } catch { + h3 = h3 || c3; + } + } + } + r2(h3); + }); + } + [xs](t2, e2) { + let i3 = typeof t2.mode == "number" ? t2.mode & 4095 : this.dmode, r2 = this[yt](String(t2.absolute), i3); + if (r2) { + this[O](r2, t2), e2(); + return; + } + if (t2.mtime && !this.noMtime) + try { + m2.utimesSync(String(t2.absolute), t2.atime || new Date, t2.mtime); + } catch {} + if (this[ge](t2)) + try { + m2.chownSync(String(t2.absolute), Number(this[be](t2)), Number(this[_e](t2))); + } catch {} + e2(), t2.resume(); + } + [yt](t2, e2) { + try { + return _r(f3(t2), { uid: this.uid, gid: this.gid, processUid: this.processUid, processGid: this.processGid, umask: this.processUmask, preserve: this.preservePaths, unlink: this.unlink, cwd: this.cwd, mode: e2 }); + } catch (i3) { + return i3; + } + } + [Re](t2, e2, i3, r2, n2) { + if (this.preservePaths || i3.length === 0) + return r2(); + let o2 = e2; + for (let h3 of i3) { + o2 = R.resolve(o2, h3); + let [a2, l] = ye(() => m2.lstatSync(o2)); + if (a2) + return r2(); + if (l.isSymbolicLink()) + return n2(new St(o2, R.resolve(e2, i3.join("/")))); + } + r2(); + } + [gi](t2, e2, i3, r2) { + let n2 = `${i3}Sync`; + try { + m2[n2](e2, String(t2.absolute)), r2(), t2.resume(); + } catch (o2) { + return this[O](o2, t2); + } + } + }; + So = K(Eo, wo, (s4) => new xe(s4), (s4) => new Xt(s4), (s4, t2) => { + t2?.length && Qi(s4, t2); + }); + vt = K(yo, go, () => { + throw new TypeError("file is required"); + }, () => { + throw new TypeError("file is required"); + }, (s4, t2) => { + if (!Bs(s4)) + throw new TypeError("file is required"); + if (s4.gzip || s4.brotli || s4.zstd || s4.file.endsWith(".br") || s4.file.endsWith(".tbr")) + throw new TypeError("cannot append to compressed archives"); + if (!t2?.length) + throw new TypeError("no paths specified to add/replace"); + }); + Oo = K(vt.syncFile, vt.asyncFile, vt.syncNoFile, vt.asyncNoFile, (s4, t2 = []) => { + vt.validate?.(s4, t2), To(s4); + }); +}); + +// src/provisioning/bin.ts +import * as crypto2 from "crypto"; +import * as fs3 from "fs"; +import * as os3 from "os"; +import * as path7 from "path"; +import * as process11 from "process"; +import readline from "readline"; +import { fileURLToPath as fileURLToPath3 } from "url"; + +class Bin { + _subProcess; + binPath; + cliVersion; + cacheDir = envPaths("dagger", { suffix: "" }).cache; + DAGGER_CLI_BIN_PREFIX = "dagger"; + constructor(binPath, cliVersion) { + this.binPath = binPath; + this.cliVersion = cliVersion; + } + Addr() { + return "http://dagger"; + } + get subProcess() { + return this._subProcess; + } + async Connect(opts) { + let downloadError; + if (!this.binPath) { + try { + this.binPath = await this.downloadCLI(opts.LogOutput); + } catch (e2) { + downloadError = e2 instanceof Error ? e2 : new Error(String(e2)); + this.binPath = this.fallbackToLocalCLI(downloadError, opts.LogOutput); + } + } + try { + return await this.runEngineSession(this.binPath, opts); + } catch (e2) { + if (downloadError) { + const sessionError = e2 instanceof Error ? e2 : new Error(String(e2)); + throw new AggregateError([downloadError, sessionError], `${downloadError.message} +failed to use CLI from PATH "${this.binPath}": ${sessionError.message}`, { cause: e2 }); + } + throw e2; + } + } + async downloadCLI(logOutput) { + if (!this.cliVersion) { + throw new Error("cliVersion is not set"); + } + const binPath = this.buildBinPath(); + this.createCacheDir(); + const tmpBinDownloadDir = fs3.mkdtempSync(path7.join(this.cacheDir, `temp-${this.getRandomId()}`)); + const tmpBinPath = this.buildOsExePath(tmpBinDownloadDir, this.DAGGER_CLI_BIN_PREFIX); + try { + const expectedChecksum = await this.expectedChecksum(); + if (logOutput) { + logOutput.write("Downloading CLI... "); + } + const actualChecksum = await this.extractArchive(tmpBinDownloadDir, this.normalizedOS()); + if (actualChecksum !== expectedChecksum) { + throw new Error(`checksum mismatch: expected ${expectedChecksum}, got ${actualChecksum}`); + } + fs3.chmodSync(tmpBinPath, 448); + fs3.renameSync(tmpBinPath, binPath); + fs3.rmSync(tmpBinDownloadDir, { recursive: true }); + if (logOutput) { + logOutput.write(`OK! +`); + } + } catch (e2) { + fs3.rmSync(tmpBinDownloadDir, { recursive: true }); + throw new InitEngineSessionBinaryError(`failed to download dagger cli binary: ${e2}`, { + cause: e2 + }); + } + try { + const files2 = fs3.readdirSync(this.cacheDir); + files2.forEach((file) => { + const filePath = path7.join(this.cacheDir, file); + if (filePath === binPath || !file.startsWith(this.DAGGER_CLI_BIN_PREFIX)) { + return; + } + fs3.unlinkSync(filePath); + }); + } catch { + console.error("could not clean up temporary binary files"); + } + return binPath; + } + fallbackToLocalCLI(downloadError, logOutput) { + if (!this.hasCLIReleaseUnavailableError(downloadError)) { + throw downloadError; + } + let binPath; + try { + binPath = this.findDaggerCLI(); + } catch (e2) { + const pathError = e2 instanceof Error ? e2 : new Error(String(e2)); + throw new AggregateError([downloadError, pathError], `${downloadError.message} +dagger CLI not found in PATH: ${pathError.message}`, { cause: e2 }); + } + const warningOutput = logOutput ?? process11.stderr; + warningOutput.write(`CLI version ${this.cliVersion} is unavailable; using ${binPath} from PATH (version compatibility is not guaranteed). +`); + return binPath; + } + hasCLIReleaseUnavailableError(error) { + const seen = new Set; + let current = error; + while (current && !seen.has(current)) { + if (current instanceof CLIReleaseUnavailableError) { + return true; + } + seen.add(current); + current = current.cause instanceof Error ? current.cause : undefined; + } + return false; + } + findDaggerCLI() { + const pathEnv = process11.env.PATH; + if (!pathEnv) { + throw new Error("PATH is not set"); + } + const platform3 = this.normalizedOS(); + const pathImplementation = platform3 === "windows" ? path7.win32 : path7.posix; + for (const candidate of this.daggerCLIPathCandidates(platform3, pathEnv, process11.env.PATHEXT)) { + try { + fs3.accessSync(candidate, fs3.constants.X_OK); + if (!fs3.statSync(candidate).isFile()) { + continue; + } + } catch { + continue; + } + if (!pathImplementation.isAbsolute(candidate)) { + throw new Error(`cannot run dagger executable found relative to the current directory: ${candidate}`); + } + return candidate; + } + throw new Error("dagger executable was not found"); + } + daggerCLIPathCandidates(platform3, pathEnv, pathExt) { + const windows2 = platform3 === "windows"; + const pathImplementation = windows2 ? path7.win32 : path7.posix; + const extensions = windows2 ? this.windowsExecutableExtensions(pathExt) : [""]; + const candidates = []; + for (let directory of pathEnv.split(pathImplementation.delimiter)) { + if (windows2) { + if (directory === "") { + continue; + } + directory = directory.replace(/^"(.*)"$/, "$1"); + } else if (directory === "") { + directory = "."; + } + for (const extension of extensions) { + candidates.push(pathImplementation.join(directory, `${this.DAGGER_CLI_BIN_PREFIX}${extension}`)); + } + } + return candidates; + } + windowsExecutableExtensions(pathExt) { + const value = pathExt || ".COM;.EXE;.BAT;.CMD"; + return value.toLowerCase().split(";").filter((extension) => extension !== "").map((extension) => extension.startsWith(".") ? extension : `.${extension}`); + } + getSDKVersion() { + const currentFileUrl = import.meta.url; + const currentFilePath = fileURLToPath3(currentFileUrl); + let currentPath = path7.dirname(currentFilePath); + while (currentPath !== path7.parse(currentPath).root) { + const packageJsonPath = path7.join(currentPath, "package.json"); + if (fs3.existsSync(packageJsonPath)) { + try { + const packageJsonContent = fs3.readFileSync(packageJsonPath, "utf8"); + const packageJson = JSON.parse(packageJsonContent); + return packageJson.version; + } catch { + return "n/a"; + } + } else { + currentPath = path7.join(currentPath, ".."); + } + } + } + async runEngineSession(binPath, opts) { + const args = ["session"]; + const sdkVersion = this.getSDKVersion(); + const flagsAndValues = [ + { flag: "--workdir", value: opts.Workdir }, + { flag: "--project", value: opts.Project }, + { flag: "--label", value: "dagger.io/sdk.name:nodejs" }, + { flag: "--label", value: `dagger.io/sdk.version:${sdkVersion}` } + ]; + flagsAndValues.forEach((pair) => { + if (pair.value) { + args.push(pair.flag, pair.value); + } + }); + if (opts.LoadWorkspaceModules) { + args.push("--load-workspace-modules"); + } + if (opts.LogOutput) { + opts.LogOutput.write("Creating new Engine session... "); + } + this._subProcess = execa(binPath, args, { + stdio: "pipe", + reject: true, + cleanup: true, + forceKillAfterDelay: 300000 + }); + if (opts.LogOutput) { + this._subProcess.stderr?.pipe(opts.LogOutput); + } + const stdoutReader = readline.createInterface({ + input: this._subProcess?.stdout + }); + const timeOutDuration = 300000; + if (opts.LogOutput) { + opts.LogOutput.write(`OK! +Establishing connection to Engine... `); + } + const connectParams = await Promise.race([ + this.readConnectParams(stdoutReader), + new Promise((_2, reject) => { + setTimeout(() => { + reject(new EngineSessionConnectionTimeoutError("Engine connection timeout", { + timeOutDuration + })); + }, timeOutDuration).unref(); + }) + ]); + if (opts.LogOutput) { + opts.LogOutput.write(`OK! +`); + } + return createGQLClient(connectParams.port, connectParams.session_token); + } + async readConnectParams(stdoutReader) { + for await (const line of stdoutReader) { + const connectParams = JSON.parse(line); + if (connectParams.port && connectParams.session_token) { + return connectParams; + } + throw new EngineSessionConnectParamsParseError(`invalid connect params: ${line}`, { + parsedLine: line + }); + } + try { + await this.subProcess; + } catch { + this.subProcess?.catch((e2) => { + throw new EngineSessionError(e2.stderr); + }); + } + } + async Close() { + if (this.subProcess?.pid) { + this.subProcess.kill("SIGTERM"); + } + } + createCacheDir() { + fs3.mkdirSync(this.cacheDir, { mode: 448, recursive: true }); + } + buildBinPath() { + return this.buildOsExePath(this.cacheDir, `${this.DAGGER_CLI_BIN_PREFIX}-${this.cliVersion}`); + } + buildOsExePath(destinationDir, filename) { + const binPath = path7.join(destinationDir, filename); + switch (this.normalizedOS()) { + case "windows": + return `${binPath}.exe`; + default: + return binPath; + } + } + normalizedArch() { + switch (os3.arch()) { + case "x64": + return "amd64"; + default: + return os3.arch(); + } + } + normalizedOS() { + switch (os3.platform()) { + case "win32": + return "windows"; + default: + return os3.platform(); + } + } + cliArchiveName() { + if (OVERRIDE_CLI_URL && OVERRIDE_CLI_URL != "") { + return path7.basename(new URL(OVERRIDE_CLI_URL).pathname); + } + let ext = "tar.gz"; + if (this.normalizedOS() === "windows") { + ext = "zip"; + } + return `dagger_v${this.cliVersion}_${this.normalizedOS()}_${this.normalizedArch()}.${ext}`; + } + cliArchiveURL() { + if (OVERRIDE_CLI_URL && OVERRIDE_CLI_URL != "") { + return OVERRIDE_CLI_URL; + } + return `https://${CLI_HOST}/dagger/releases/${this.cliVersion}/${this.cliArchiveName()}`; + } + cliChecksumURL() { + if (OVERRIDE_CHECKSUMS_URL && OVERRIDE_CHECKSUMS_URL != "") { + return OVERRIDE_CHECKSUMS_URL; + } + return `https://${CLI_HOST}/dagger/releases/${this.cliVersion}/checksums.txt`; + } + async checksumMap() { + const checksums = await fetch2(this.cliChecksumURL()); + if (!checksums.ok) { + const message = `failed to download checksums.txt from ${this.cliChecksumURL()}: ${checksums.status} ${checksums.statusText}`; + if (this.isCLIReleaseUnavailable(checksums.status)) { + throw new CLIReleaseUnavailableError(message); + } + throw new Error(message); + } + const checksumsText = await checksums.text(); + const checksumMap = new Map; + for (const line of checksumsText.split(` +`)) { + const [checksum, filename] = line.split(/\s+/); + checksumMap.set(filename, checksum); + } + return checksumMap; + } + isCLIReleaseUnavailable(status) { + return status === 403 || status === 404; + } + async expectedChecksum() { + const checksumMap = await this.checksumMap(); + const expectedChecksum = checksumMap.get(this.cliArchiveName()); + if (!expectedChecksum) { + throw new Error(`failed to find checksum for ${this.cliArchiveName()} in checksums.txt`); + } + return expectedChecksum; + } + async extractArchive(destDir, os4) { + const archiveResp = await fetch2(this.cliArchiveURL()); + if (!archiveResp.ok) { + throw new Error(`failed to download dagger cli archive from ${this.cliArchiveURL()}`); + } + if (!archiveResp.body) { + throw new Error("archive response body is null"); + } + const archivePath = path7.join(destDir, os4 === "windows" ? "dagger.zip" : "dagger.tar.gz"); + const archiveFile = fs3.createWriteStream(archivePath); + await new Promise((resolve, reject) => { + archiveResp.body?.pipe(archiveFile); + archiveResp.body?.on("error", reject); + archiveFile.on("finish", () => resolve(undefined)); + }); + const actualChecksum = crypto2.createHash("sha256").update(fs3.readFileSync(archivePath)).digest("hex"); + if (os4 === "windows") { + const zip2 = new import_adm_zip.default(archivePath); + zip2.extractEntryTo("dagger.exe", destDir, false, true); + } else { + So({ + cwd: destDir, + file: archivePath, + sync: true + }); + } + return actualChecksum; + } + getRandomId() { + return process11.hrtime.bigint().toString(); + } +} +var import_adm_zip, OVERRIDE_CLI_URL = "", OVERRIDE_CHECKSUMS_URL = "", CLI_HOST = "dl.dagger.io", CLIReleaseUnavailableError; +var init_bin = __esm(() => { + init_env_paths(); + init_execa(); + init_src(); + init_index_min(); + init_errors(); + init_client(); + import_adm_zip = __toESM(require_adm_zip(), 1); + CLIReleaseUnavailableError = class CLIReleaseUnavailableError extends Error { + constructor(message) { + super(message); + this.name = "CLIReleaseUnavailableError"; + } + }; +}); + +// src/provisioning/default.ts +var CLI_VERSION = "1.0.0-beta.9"; + +// src/provisioning/index.ts +var exports_provisioning = {}; +__export(exports_provisioning, { + withEngineSession: () => withEngineSession +}); +async function withEngineSession(connectOpts, cb) { + const cliBin = process.env["_EXPERIMENTAL_DAGGER_CLI_BIN"]; + const engineConn = new Bin(cliBin, CLI_VERSION); + const gqlClient = await engineConn.Connect(connectOpts); + try { + const res = await cb(gqlClient); + return res; + } finally { + await engineConn.Close(); + } +} +var init_provisioning = __esm(() => { + init_bin(); +}); + +// node_modules/reflect-metadata/Reflect.js +var require_Reflect = __commonJS(() => { + /*! ***************************************************************************** + Copyright (C) Microsoft. All rights reserved. + 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 + + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED + WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, + MERCHANTABLITY OR NON-INFRINGEMENT. + + See the Apache Version 2.0 License for specific language governing permissions + and limitations under the License. + ***************************************************************************** */ + var Reflect2; + (function(Reflect3) { + (function(factory) { + var root = typeof globalThis === "object" ? globalThis : typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : sloppyModeThis(); + var exporter = makeExporter(Reflect3); + if (typeof root.Reflect !== "undefined") { + exporter = makeExporter(root.Reflect, exporter); + } + factory(exporter, root); + if (typeof root.Reflect === "undefined") { + root.Reflect = Reflect3; + } + function makeExporter(target, previous) { + return function(key, value) { + Object.defineProperty(target, key, { configurable: true, writable: true, value }); + if (previous) + previous(key, value); + }; + } + function functionThis() { + try { + return Function("return this;")(); + } catch (_2) {} + } + function indirectEvalThis() { + try { + return (undefined, eval)("(function() { return this; })()"); + } catch (_2) {} + } + function sloppyModeThis() { + return functionThis() || indirectEvalThis(); + } + })(function(exporter, root) { + var hasOwn = Object.prototype.hasOwnProperty; + var supportsSymbol = typeof Symbol === "function"; + var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive"; + var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator"; + var supportsCreate = typeof Object.create === "function"; + var supportsProto = { __proto__: [] } instanceof Array; + var downLevel = !supportsCreate && !supportsProto; + var HashMap = { + create: supportsCreate ? function() { + return MakeDictionary(Object.create(null)); + } : supportsProto ? function() { + return MakeDictionary({ __proto__: null }); + } : function() { + return MakeDictionary({}); + }, + has: downLevel ? function(map, key) { + return hasOwn.call(map, key); + } : function(map, key) { + return key in map; + }, + get: downLevel ? function(map, key) { + return hasOwn.call(map, key) ? map[key] : undefined; + } : function(map, key) { + return map[key]; + } + }; + var functionPrototype = Object.getPrototypeOf(Function); + var _Map = typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill(); + var _Set = typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill(); + var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill(); + var registrySymbol = supportsSymbol ? Symbol.for("@reflect-metadata:registry") : undefined; + var metadataRegistry = GetOrCreateMetadataRegistry(); + var metadataProvider = CreateMetadataProvider(metadataRegistry); + function decorate(decorators, target, propertyKey, attributes) { + if (!IsUndefined(propertyKey)) { + if (!IsArray(decorators)) + throw new TypeError; + if (!IsObject(target)) + throw new TypeError; + if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) + throw new TypeError; + if (IsNull(attributes)) + attributes = undefined; + propertyKey = ToPropertyKey(propertyKey); + return DecorateProperty(decorators, target, propertyKey, attributes); + } else { + if (!IsArray(decorators)) + throw new TypeError; + if (!IsConstructor(target)) + throw new TypeError; + return DecorateConstructor(decorators, target); + } + } + exporter("decorate", decorate); + function metadata(metadataKey, metadataValue) { + function decorator(target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) + throw new TypeError; + OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); + } + return decorator; + } + exporter("metadata", metadata); + function defineMetadata(metadataKey, metadataValue, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey); + } + exporter("defineMetadata", defineMetadata); + function hasMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryHasMetadata(metadataKey, target, propertyKey); + } + exporter("hasMetadata", hasMetadata); + function hasOwnMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey); + } + exporter("hasOwnMetadata", hasOwnMetadata); + function getMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryGetMetadata(metadataKey, target, propertyKey); + } + exporter("getMetadata", getMetadata); + function getOwnMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey); + } + exporter("getOwnMetadata", getOwnMetadata); + function getMetadataKeys(target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryMetadataKeys(target, propertyKey); + } + exporter("getMetadataKeys", getMetadataKeys); + function getOwnMetadataKeys(target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + return OrdinaryOwnMetadataKeys(target, propertyKey); + } + exporter("getOwnMetadataKeys", getOwnMetadataKeys); + function deleteMetadata(metadataKey, target, propertyKey) { + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + if (!IsObject(target)) + throw new TypeError; + if (!IsUndefined(propertyKey)) + propertyKey = ToPropertyKey(propertyKey); + var provider = GetMetadataProvider(target, propertyKey, false); + if (IsUndefined(provider)) + return false; + return provider.OrdinaryDeleteMetadata(metadataKey, target, propertyKey); + } + exporter("deleteMetadata", deleteMetadata); + function DecorateConstructor(decorators, target) { + for (var i3 = decorators.length - 1;i3 >= 0; --i3) { + var decorator = decorators[i3]; + var decorated = decorator(target); + if (!IsUndefined(decorated) && !IsNull(decorated)) { + if (!IsConstructor(decorated)) + throw new TypeError; + target = decorated; + } + } + return target; + } + function DecorateProperty(decorators, target, propertyKey, descriptor) { + for (var i3 = decorators.length - 1;i3 >= 0; --i3) { + var decorator = decorators[i3]; + var decorated = decorator(target, propertyKey, descriptor); + if (!IsUndefined(decorated) && !IsNull(decorated)) { + if (!IsObject(decorated)) + throw new TypeError; + descriptor = decorated; + } + } + return descriptor; + } + function OrdinaryHasMetadata(MetadataKey, O2, P2) { + var hasOwn2 = OrdinaryHasOwnMetadata(MetadataKey, O2, P2); + if (hasOwn2) + return true; + var parent = OrdinaryGetPrototypeOf(O2); + if (!IsNull(parent)) + return OrdinaryHasMetadata(MetadataKey, parent, P2); + return false; + } + function OrdinaryHasOwnMetadata(MetadataKey, O2, P2) { + var provider = GetMetadataProvider(O2, P2, false); + if (IsUndefined(provider)) + return false; + return ToBoolean(provider.OrdinaryHasOwnMetadata(MetadataKey, O2, P2)); + } + function OrdinaryGetMetadata(MetadataKey, O2, P2) { + var hasOwn2 = OrdinaryHasOwnMetadata(MetadataKey, O2, P2); + if (hasOwn2) + return OrdinaryGetOwnMetadata(MetadataKey, O2, P2); + var parent = OrdinaryGetPrototypeOf(O2); + if (!IsNull(parent)) + return OrdinaryGetMetadata(MetadataKey, parent, P2); + return; + } + function OrdinaryGetOwnMetadata(MetadataKey, O2, P2) { + var provider = GetMetadataProvider(O2, P2, false); + if (IsUndefined(provider)) + return; + return provider.OrdinaryGetOwnMetadata(MetadataKey, O2, P2); + } + function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O2, P2) { + var provider = GetMetadataProvider(O2, P2, true); + provider.OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O2, P2); + } + function OrdinaryMetadataKeys(O2, P2) { + var ownKeys = OrdinaryOwnMetadataKeys(O2, P2); + var parent = OrdinaryGetPrototypeOf(O2); + if (parent === null) + return ownKeys; + var parentKeys = OrdinaryMetadataKeys(parent, P2); + if (parentKeys.length <= 0) + return ownKeys; + if (ownKeys.length <= 0) + return parentKeys; + var set = new _Set; + var keys = []; + for (var _i2 = 0, ownKeys_1 = ownKeys;_i2 < ownKeys_1.length; _i2++) { + var key = ownKeys_1[_i2]; + var hasKey = set.has(key); + if (!hasKey) { + set.add(key); + keys.push(key); + } + } + for (var _a = 0, parentKeys_1 = parentKeys;_a < parentKeys_1.length; _a++) { + var key = parentKeys_1[_a]; + var hasKey = set.has(key); + if (!hasKey) { + set.add(key); + keys.push(key); + } + } + return keys; + } + function OrdinaryOwnMetadataKeys(O2, P2) { + var provider = GetMetadataProvider(O2, P2, false); + if (!provider) { + return []; + } + return provider.OrdinaryOwnMetadataKeys(O2, P2); + } + function Type(x2) { + if (x2 === null) + return 1; + switch (typeof x2) { + case "undefined": + return 0; + case "boolean": + return 2; + case "string": + return 3; + case "symbol": + return 4; + case "number": + return 5; + case "object": + return x2 === null ? 1 : 6; + default: + return 6; + } + } + function IsUndefined(x2) { + return x2 === undefined; + } + function IsNull(x2) { + return x2 === null; + } + function IsSymbol(x2) { + return typeof x2 === "symbol"; + } + function IsObject(x2) { + return typeof x2 === "object" ? x2 !== null : typeof x2 === "function"; + } + function ToPrimitive(input, PreferredType) { + switch (Type(input)) { + case 0: + return input; + case 1: + return input; + case 2: + return input; + case 3: + return input; + case 4: + return input; + case 5: + return input; + } + var hint = PreferredType === 3 ? "string" : PreferredType === 5 ? "number" : "default"; + var exoticToPrim = GetMethod(input, toPrimitiveSymbol); + if (exoticToPrim !== undefined) { + var result = exoticToPrim.call(input, hint); + if (IsObject(result)) + throw new TypeError; + return result; + } + return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint); + } + function OrdinaryToPrimitive(O2, hint) { + if (hint === "string") { + var toString_1 = O2.toString; + if (IsCallable(toString_1)) { + var result = toString_1.call(O2); + if (!IsObject(result)) + return result; + } + var valueOf = O2.valueOf; + if (IsCallable(valueOf)) { + var result = valueOf.call(O2); + if (!IsObject(result)) + return result; + } + } else { + var valueOf = O2.valueOf; + if (IsCallable(valueOf)) { + var result = valueOf.call(O2); + if (!IsObject(result)) + return result; + } + var toString_2 = O2.toString; + if (IsCallable(toString_2)) { + var result = toString_2.call(O2); + if (!IsObject(result)) + return result; + } + } + throw new TypeError; + } + function ToBoolean(argument) { + return !!argument; + } + function ToString(argument) { + return "" + argument; + } + function ToPropertyKey(argument) { + var key = ToPrimitive(argument, 3); + if (IsSymbol(key)) + return key; + return ToString(key); + } + function IsArray(argument) { + return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]"; + } + function IsCallable(argument) { + return typeof argument === "function"; + } + function IsConstructor(argument) { + return typeof argument === "function"; + } + function IsPropertyKey(argument) { + switch (Type(argument)) { + case 3: + return true; + case 4: + return true; + default: + return false; + } + } + function SameValueZero(x2, y2) { + return x2 === y2 || x2 !== x2 && y2 !== y2; + } + function GetMethod(V2, P2) { + var func = V2[P2]; + if (func === undefined || func === null) + return; + if (!IsCallable(func)) + throw new TypeError; + return func; + } + function GetIterator(obj) { + var method = GetMethod(obj, iteratorSymbol); + if (!IsCallable(method)) + throw new TypeError; + var iterator = method.call(obj); + if (!IsObject(iterator)) + throw new TypeError; + return iterator; + } + function IteratorValue(iterResult) { + return iterResult.value; + } + function IteratorStep(iterator) { + var result = iterator.next(); + return result.done ? false : result; + } + function IteratorClose(iterator) { + var f4 = iterator["return"]; + if (f4) + f4.call(iterator); + } + function OrdinaryGetPrototypeOf(O2) { + var proto = Object.getPrototypeOf(O2); + if (typeof O2 !== "function" || O2 === functionPrototype) + return proto; + if (proto !== functionPrototype) + return proto; + var prototype = O2.prototype; + var prototypeProto = prototype && Object.getPrototypeOf(prototype); + if (prototypeProto == null || prototypeProto === Object.prototype) + return proto; + var constructor = prototypeProto.constructor; + if (typeof constructor !== "function") + return proto; + if (constructor === O2) + return proto; + return constructor; + } + function CreateMetadataRegistry() { + var fallback; + if (!IsUndefined(registrySymbol) && typeof root.Reflect !== "undefined" && !(registrySymbol in root.Reflect) && typeof root.Reflect.defineMetadata === "function") { + fallback = CreateFallbackProvider(root.Reflect); + } + var first; + var second; + var rest; + var targetProviderMap = new _WeakMap; + var registry = { + registerProvider, + getProvider, + setProvider + }; + return registry; + function registerProvider(provider) { + if (!Object.isExtensible(registry)) { + throw new Error("Cannot add provider to a frozen registry."); + } + switch (true) { + case fallback === provider: + break; + case IsUndefined(first): + first = provider; + break; + case first === provider: + break; + case IsUndefined(second): + second = provider; + break; + case second === provider: + break; + default: + if (rest === undefined) + rest = new _Set; + rest.add(provider); + break; + } + } + function getProviderNoCache(O2, P2) { + if (!IsUndefined(first)) { + if (first.isProviderFor(O2, P2)) + return first; + if (!IsUndefined(second)) { + if (second.isProviderFor(O2, P2)) + return first; + if (!IsUndefined(rest)) { + var iterator = GetIterator(rest); + while (true) { + var next = IteratorStep(iterator); + if (!next) { + return; + } + var provider = IteratorValue(next); + if (provider.isProviderFor(O2, P2)) { + IteratorClose(iterator); + return provider; + } + } + } + } + } + if (!IsUndefined(fallback) && fallback.isProviderFor(O2, P2)) { + return fallback; + } + return; + } + function getProvider(O2, P2) { + var providerMap = targetProviderMap.get(O2); + var provider; + if (!IsUndefined(providerMap)) { + provider = providerMap.get(P2); + } + if (!IsUndefined(provider)) { + return provider; + } + provider = getProviderNoCache(O2, P2); + if (!IsUndefined(provider)) { + if (IsUndefined(providerMap)) { + providerMap = new _Map; + targetProviderMap.set(O2, providerMap); + } + providerMap.set(P2, provider); + } + return provider; + } + function hasProvider(provider) { + if (IsUndefined(provider)) + throw new TypeError; + return first === provider || second === provider || !IsUndefined(rest) && rest.has(provider); + } + function setProvider(O2, P2, provider) { + if (!hasProvider(provider)) { + throw new Error("Metadata provider not registered."); + } + var existingProvider = getProvider(O2, P2); + if (existingProvider !== provider) { + if (!IsUndefined(existingProvider)) { + return false; + } + var providerMap = targetProviderMap.get(O2); + if (IsUndefined(providerMap)) { + providerMap = new _Map; + targetProviderMap.set(O2, providerMap); + } + providerMap.set(P2, provider); + } + return true; + } + } + function GetOrCreateMetadataRegistry() { + var metadataRegistry2; + if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) { + metadataRegistry2 = root.Reflect[registrySymbol]; + } + if (IsUndefined(metadataRegistry2)) { + metadataRegistry2 = CreateMetadataRegistry(); + } + if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) { + Object.defineProperty(root.Reflect, registrySymbol, { + enumerable: false, + configurable: false, + writable: false, + value: metadataRegistry2 + }); + } + return metadataRegistry2; + } + function CreateMetadataProvider(registry) { + var metadata2 = new _WeakMap; + var provider = { + isProviderFor: function(O2, P2) { + var targetMetadata = metadata2.get(O2); + if (IsUndefined(targetMetadata)) + return false; + return targetMetadata.has(P2); + }, + OrdinaryDefineOwnMetadata: OrdinaryDefineOwnMetadata2, + OrdinaryHasOwnMetadata: OrdinaryHasOwnMetadata2, + OrdinaryGetOwnMetadata: OrdinaryGetOwnMetadata2, + OrdinaryOwnMetadataKeys: OrdinaryOwnMetadataKeys2, + OrdinaryDeleteMetadata + }; + metadataRegistry.registerProvider(provider); + return provider; + function GetOrCreateMetadataMap(O2, P2, Create) { + var targetMetadata = metadata2.get(O2); + var createdTargetMetadata = false; + if (IsUndefined(targetMetadata)) { + if (!Create) + return; + targetMetadata = new _Map; + metadata2.set(O2, targetMetadata); + createdTargetMetadata = true; + } + var metadataMap = targetMetadata.get(P2); + if (IsUndefined(metadataMap)) { + if (!Create) + return; + metadataMap = new _Map; + targetMetadata.set(P2, metadataMap); + if (!registry.setProvider(O2, P2, provider)) { + targetMetadata.delete(P2); + if (createdTargetMetadata) { + metadata2.delete(O2); + } + throw new Error("Wrong provider for target."); + } + } + return metadataMap; + } + function OrdinaryHasOwnMetadata2(MetadataKey, O2, P2) { + var metadataMap = GetOrCreateMetadataMap(O2, P2, false); + if (IsUndefined(metadataMap)) + return false; + return ToBoolean(metadataMap.has(MetadataKey)); + } + function OrdinaryGetOwnMetadata2(MetadataKey, O2, P2) { + var metadataMap = GetOrCreateMetadataMap(O2, P2, false); + if (IsUndefined(metadataMap)) + return; + return metadataMap.get(MetadataKey); + } + function OrdinaryDefineOwnMetadata2(MetadataKey, MetadataValue, O2, P2) { + var metadataMap = GetOrCreateMetadataMap(O2, P2, true); + metadataMap.set(MetadataKey, MetadataValue); + } + function OrdinaryOwnMetadataKeys2(O2, P2) { + var keys = []; + var metadataMap = GetOrCreateMetadataMap(O2, P2, false); + if (IsUndefined(metadataMap)) + return keys; + var keysObj = metadataMap.keys(); + var iterator = GetIterator(keysObj); + var k2 = 0; + while (true) { + var next = IteratorStep(iterator); + if (!next) { + keys.length = k2; + return keys; + } + var nextValue = IteratorValue(next); + try { + keys[k2] = nextValue; + } catch (e2) { + try { + IteratorClose(iterator); + } finally { + throw e2; + } + } + k2++; + } + } + function OrdinaryDeleteMetadata(MetadataKey, O2, P2) { + var metadataMap = GetOrCreateMetadataMap(O2, P2, false); + if (IsUndefined(metadataMap)) + return false; + if (!metadataMap.delete(MetadataKey)) + return false; + if (metadataMap.size === 0) { + var targetMetadata = metadata2.get(O2); + if (!IsUndefined(targetMetadata)) { + targetMetadata.delete(P2); + if (targetMetadata.size === 0) { + metadata2.delete(targetMetadata); + } + } + } + return true; + } + } + function CreateFallbackProvider(reflect) { + var { defineMetadata: defineMetadata2, hasOwnMetadata: hasOwnMetadata2, getOwnMetadata: getOwnMetadata2, getOwnMetadataKeys: getOwnMetadataKeys2, deleteMetadata: deleteMetadata2 } = reflect; + var metadataOwner = new _WeakMap; + var provider = { + isProviderFor: function(O2, P2) { + var metadataPropertySet = metadataOwner.get(O2); + if (!IsUndefined(metadataPropertySet) && metadataPropertySet.has(P2)) { + return true; + } + if (getOwnMetadataKeys2(O2, P2).length) { + if (IsUndefined(metadataPropertySet)) { + metadataPropertySet = new _Set; + metadataOwner.set(O2, metadataPropertySet); + } + metadataPropertySet.add(P2); + return true; + } + return false; + }, + OrdinaryDefineOwnMetadata: defineMetadata2, + OrdinaryHasOwnMetadata: hasOwnMetadata2, + OrdinaryGetOwnMetadata: getOwnMetadata2, + OrdinaryOwnMetadataKeys: getOwnMetadataKeys2, + OrdinaryDeleteMetadata: deleteMetadata2 + }; + return provider; + } + function GetMetadataProvider(O2, P2, Create) { + var registeredProvider = metadataRegistry.getProvider(O2, P2); + if (!IsUndefined(registeredProvider)) { + return registeredProvider; + } + if (Create) { + if (metadataRegistry.setProvider(O2, P2, metadataProvider)) { + return metadataProvider; + } + throw new Error("Illegal state."); + } + return; + } + function CreateMapPolyfill() { + var cacheSentinel = {}; + var arraySentinel = []; + var MapIterator = function() { + function MapIterator2(keys, values, selector) { + this._index = 0; + this._keys = keys; + this._values = values; + this._selector = selector; + } + MapIterator2.prototype["@@iterator"] = function() { + return this; + }; + MapIterator2.prototype[iteratorSymbol] = function() { + return this; + }; + MapIterator2.prototype.next = function() { + var index = this._index; + if (index >= 0 && index < this._keys.length) { + var result = this._selector(this._keys[index], this._values[index]); + if (index + 1 >= this._keys.length) { + this._index = -1; + this._keys = arraySentinel; + this._values = arraySentinel; + } else { + this._index++; + } + return { value: result, done: false }; + } + return { value: undefined, done: true }; + }; + MapIterator2.prototype.throw = function(error) { + if (this._index >= 0) { + this._index = -1; + this._keys = arraySentinel; + this._values = arraySentinel; + } + throw error; + }; + MapIterator2.prototype.return = function(value) { + if (this._index >= 0) { + this._index = -1; + this._keys = arraySentinel; + this._values = arraySentinel; + } + return { value, done: true }; + }; + return MapIterator2; + }(); + var Map2 = function() { + function Map3() { + this._keys = []; + this._values = []; + this._cacheKey = cacheSentinel; + this._cacheIndex = -2; + } + Object.defineProperty(Map3.prototype, "size", { + get: function() { + return this._keys.length; + }, + enumerable: true, + configurable: true + }); + Map3.prototype.has = function(key) { + return this._find(key, false) >= 0; + }; + Map3.prototype.get = function(key) { + var index = this._find(key, false); + return index >= 0 ? this._values[index] : undefined; + }; + Map3.prototype.set = function(key, value) { + var index = this._find(key, true); + this._values[index] = value; + return this; + }; + Map3.prototype.delete = function(key) { + var index = this._find(key, false); + if (index >= 0) { + var size = this._keys.length; + for (var i3 = index + 1;i3 < size; i3++) { + this._keys[i3 - 1] = this._keys[i3]; + this._values[i3 - 1] = this._values[i3]; + } + this._keys.length--; + this._values.length--; + if (SameValueZero(key, this._cacheKey)) { + this._cacheKey = cacheSentinel; + this._cacheIndex = -2; + } + return true; + } + return false; + }; + Map3.prototype.clear = function() { + this._keys.length = 0; + this._values.length = 0; + this._cacheKey = cacheSentinel; + this._cacheIndex = -2; + }; + Map3.prototype.keys = function() { + return new MapIterator(this._keys, this._values, getKey); + }; + Map3.prototype.values = function() { + return new MapIterator(this._keys, this._values, getValue); + }; + Map3.prototype.entries = function() { + return new MapIterator(this._keys, this._values, getEntry); + }; + Map3.prototype["@@iterator"] = function() { + return this.entries(); + }; + Map3.prototype[iteratorSymbol] = function() { + return this.entries(); + }; + Map3.prototype._find = function(key, insert) { + if (!SameValueZero(this._cacheKey, key)) { + this._cacheIndex = -1; + for (var i3 = 0;i3 < this._keys.length; i3++) { + if (SameValueZero(this._keys[i3], key)) { + this._cacheIndex = i3; + break; + } + } + } + if (this._cacheIndex < 0 && insert) { + this._cacheIndex = this._keys.length; + this._keys.push(key); + this._values.push(undefined); + } + return this._cacheIndex; + }; + return Map3; + }(); + return Map2; + function getKey(key, _2) { + return key; + } + function getValue(_2, value) { + return value; + } + function getEntry(key, value) { + return [key, value]; + } + } + function CreateSetPolyfill() { + var Set2 = function() { + function Set3() { + this._map = new _Map; + } + Object.defineProperty(Set3.prototype, "size", { + get: function() { + return this._map.size; + }, + enumerable: true, + configurable: true + }); + Set3.prototype.has = function(value) { + return this._map.has(value); + }; + Set3.prototype.add = function(value) { + return this._map.set(value, value), this; + }; + Set3.prototype.delete = function(value) { + return this._map.delete(value); + }; + Set3.prototype.clear = function() { + this._map.clear(); + }; + Set3.prototype.keys = function() { + return this._map.keys(); + }; + Set3.prototype.values = function() { + return this._map.keys(); + }; + Set3.prototype.entries = function() { + return this._map.entries(); + }; + Set3.prototype["@@iterator"] = function() { + return this.keys(); + }; + Set3.prototype[iteratorSymbol] = function() { + return this.keys(); + }; + return Set3; + }(); + return Set2; + } + function CreateWeakMapPolyfill() { + var UUID_SIZE = 16; + var keys = HashMap.create(); + var rootKey = CreateUniqueKey(); + return function() { + function WeakMap2() { + this._key = CreateUniqueKey(); + } + WeakMap2.prototype.has = function(target) { + var table = GetOrCreateWeakMapTable(target, false); + return table !== undefined ? HashMap.has(table, this._key) : false; + }; + WeakMap2.prototype.get = function(target) { + var table = GetOrCreateWeakMapTable(target, false); + return table !== undefined ? HashMap.get(table, this._key) : undefined; + }; + WeakMap2.prototype.set = function(target, value) { + var table = GetOrCreateWeakMapTable(target, true); + table[this._key] = value; + return this; + }; + WeakMap2.prototype.delete = function(target) { + var table = GetOrCreateWeakMapTable(target, false); + return table !== undefined ? delete table[this._key] : false; + }; + WeakMap2.prototype.clear = function() { + this._key = CreateUniqueKey(); + }; + return WeakMap2; + }(); + function CreateUniqueKey() { + var key; + do + key = "@@WeakMap@@" + CreateUUID(); + while (HashMap.has(keys, key)); + keys[key] = true; + return key; + } + function GetOrCreateWeakMapTable(target, create) { + if (!hasOwn.call(target, rootKey)) { + if (!create) + return; + Object.defineProperty(target, rootKey, { value: HashMap.create() }); + } + return target[rootKey]; + } + function FillRandomBytes(buffer, size) { + for (var i3 = 0;i3 < size; ++i3) + buffer[i3] = Math.random() * 255 | 0; + return buffer; + } + function GenRandomBytes(size) { + if (typeof Uint8Array === "function") { + var array = new Uint8Array(size); + if (typeof crypto !== "undefined") { + crypto.getRandomValues(array); + } else if (typeof msCrypto !== "undefined") { + msCrypto.getRandomValues(array); + } else { + FillRandomBytes(array, size); + } + return array; + } + return FillRandomBytes(new Array(size), size); + } + function CreateUUID() { + var data = GenRandomBytes(UUID_SIZE); + data[6] = data[6] & 79 | 64; + data[8] = data[8] & 191 | 128; + var result = ""; + for (var offset = 0;offset < UUID_SIZE; ++offset) { + var byte = data[offset]; + if (offset === 4 || offset === 6 || offset === 8) + result += "-"; + if (byte < 16) + result += "0"; + result += byte.toString(16).toLowerCase(); + } + return result; + } + } + function MakeDictionary(obj) { + obj.__ = undefined; + delete obj.__; + return obj; + } + }); + })(Reflect2 || (Reflect2 = {})); +}); + +// src/index.ts +init_main(); + +// src/telemetry/telemetry.ts +var opentelemetry2 = __toESM(require_src(), 1); + +// src/telemetry/init.ts +var import_core = __toESM(require_src3(), 1); +var import_exporter_trace_otlp_proto = __toESM(require_src9(), 1); +var import_sdk_node = __toESM(require_src33(), 1); +var import_sdk_trace_base2 = __toESM(require_src12(), 1); + +// src/telemetry/live_processor.ts +var import_sdk_trace_base = __toESM(require_src12(), 1); + +class LiveProcessor extends import_sdk_trace_base.BatchSpanProcessor { + onStart(_span, _parentContext) { + this.onEnd(_span); + } +} + +// src/telemetry/init.ts +var SERVICE_NAME = "dagger-typescript-sdk"; +function otelConfigured() { + return Object.keys(process.env).some((key) => key.startsWith("OTEL_")); +} +var NEARLY_IMMEDIATE = 100; + +class DaggerOtelConfigurator { + is_configured = false; + sdk; + initialize() { + if (this.is_configured) { + return; + } + this.configure(); + this.is_configured = true; + } + configure() { + if (!otelConfigured()) { + return; + } + if (import_core.getBooleanFromEnv("OTEL_SDK_DISABLED") ?? true) { + return; + } + this.setupEnv(); + const exporter = new import_exporter_trace_otlp_proto.OTLPTraceExporter; + let processor; + if (process.env.OTEL_EXPORTER_OTLP_TRACES_LIVE !== undefined) { + processor = new LiveProcessor(exporter, { + scheduledDelayMillis: NEARLY_IMMEDIATE + }); + } else { + processor = new import_sdk_trace_base2.BatchSpanProcessor(exporter, { + scheduledDelayMillis: NEARLY_IMMEDIATE + }); + } + this.sdk = new import_sdk_node.NodeSDK({ + serviceName: SERVICE_NAME, + spanProcessors: [processor] + }); + this.sdk.start(); + } + async close() { + if (this.sdk) { + await this.sdk.shutdown(); + } + } + setupEnv() { + Object.entries(process.env).forEach(([key, value]) => { + if (key.startsWith("OTEL_") && key.endsWith("_ENDPOINT") && value?.startsWith("http://")) { + const insecure = key.replace(/_ENDPOINT$/, "_INSECURE"); + if (process.env[insecure] === undefined) { + process.env[insecure] = "true"; + } + } + }); + } +} + +// src/telemetry/tracer.ts +var opentelemetry = __toESM(require_src(), 1); + +class Tracer { + tracer; + constructor(name) { + this.tracer = opentelemetry.trace.getTracer(name); + } + startSpan(name, attributes) { + return this.tracer.startSpan(name, { attributes }); + } + async startActiveSpan(name, fn, attributes) { + return this.tracer.startActiveSpan(name, { attributes }, async (span) => { + try { + return await fn(span); + } catch (e) { + if (e instanceof Error) { + span.recordException(e); + span.setStatus({ + code: opentelemetry.SpanStatusCode.ERROR, + message: e.message + }); + } + throw e; + } finally { + span.end(); + } + }); + } +} + +// src/telemetry/telemetry.ts +var DAGGER_TRACER_NAME = "dagger.io/sdk.typescript"; +var configurator = new DaggerOtelConfigurator; +function initialize() { + configurator.initialize(); +} +async function close() { + await configurator.close(); +} +function getTracer(name = DAGGER_TRACER_NAME) { + initialize(); + return new Tracer(name); +} +function getContext() { + const ctx = opentelemetry2.context.active(); + const spanCtx = opentelemetry2.trace.getSpanContext(ctx); + if (spanCtx && opentelemetry2.trace.isSpanContextValid(spanCtx)) { + return ctx; + } + const parentID = process.env.TRACEPARENT; + if (parentID) { + return opentelemetry2.propagation.extract(ctx, { + traceparent: parentID + }); + } + return ctx; +} +// src/api/client.gen.ts +var exports_client_gen = {}; +__export(exports_client_gen, { + dag: () => dag, + _SyncerClient: () => _SyncerClient, + _NodeClient: () => _NodeClient, + _ExportableClient: () => _ExportableClient, + WorkspaceSDK: () => WorkspaceSDK, + WorkspaceModuleSetting: () => WorkspaceModuleSetting, + WorkspaceModule: () => WorkspaceModule, + WorkspaceMigrationStep: () => WorkspaceMigrationStep, + WorkspaceMigration: () => WorkspaceMigration, + WorkspaceGit: () => WorkspaceGit, + Workspace: () => Workspace, + Volume: () => Volume, + UpGroup: () => UpGroup, + Up: () => Up, + TypeDefKindValueToName: () => TypeDefKindValueToName, + TypeDefKindNameToValue: () => TypeDefKindNameToValue, + TypeDefKind: () => TypeDefKind, + TypeDef: () => TypeDef, + Terminal: () => Terminal, + Stat: () => Stat, + SourceMap: () => SourceMap, + Socket: () => Socket, + Service: () => Service, + Secret: () => Secret, + SearchSubmatch: () => SearchSubmatch, + SearchResult: () => SearchResult, + Schema: () => Schema, + ScalarTypeDef: () => ScalarTypeDef, + SDKConfig: () => SDKConfig, + ReturnTypeValueToName: () => ReturnTypeValueToName, + ReturnTypeNameToValue: () => ReturnTypeNameToValue, + ReturnType: () => ReturnType, + RemoteGitMirror: () => RemoteGitMirror, + RegistryProtocolValueToName: () => RegistryProtocolValueToName, + RegistryProtocolNameToValue: () => RegistryProtocolNameToValue, + RegistryProtocol: () => RegistryProtocol, + Port: () => Port, + ObjectTypeDef: () => ObjectTypeDef, + NetworkProtocolValueToName: () => NetworkProtocolValueToName, + NetworkProtocolNameToValue: () => NetworkProtocolNameToValue, + NetworkProtocol: () => NetworkProtocol, + Module_: () => Module_, + ModuleSourceKindValueToName: () => ModuleSourceKindValueToName, + ModuleSourceKindNameToValue: () => ModuleSourceKindNameToValue, + ModuleSourceKind: () => ModuleSourceKind, + ModuleSourceExperimentalFeatureValueToName: () => ModuleSourceExperimentalFeatureValueToName, + ModuleSourceExperimentalFeatureNameToValue: () => ModuleSourceExperimentalFeatureNameToValue, + ModuleSourceExperimentalFeature: () => ModuleSourceExperimentalFeature, + ModuleSource: () => ModuleSource, + ModuleConfigClient: () => ModuleConfigClient, + ListTypeDef: () => ListTypeDef, + Label: () => Label, + LLMTokenUsage: () => LLMTokenUsage, + LLMMessageRoleValueToName: () => LLMMessageRoleValueToName, + LLMMessageRoleNameToValue: () => LLMMessageRoleNameToValue, + LLMMessageRole: () => LLMMessageRole, + LLMMessage: () => LLMMessage, + LLMContentBlockKindValueToName: () => LLMContentBlockKindValueToName, + LLMContentBlockKindNameToValue: () => LLMContentBlockKindNameToValue, + LLMContentBlockKind: () => LLMContentBlockKind, + LLMContentBlock: () => LLMContentBlock, + LLM: () => LLM, + JSONValue: () => JSONValue, + InterfaceTypeDef: () => InterfaceTypeDef, + InputTypeDef: () => InputTypeDef, + ImageMediaTypesValueToName: () => ImageMediaTypesValueToName, + ImageMediaTypesNameToValue: () => ImageMediaTypesNameToValue, + ImageMediaTypes: () => ImageMediaTypes, + ImageLayerCompressionValueToName: () => ImageLayerCompressionValueToName, + ImageLayerCompressionNameToValue: () => ImageLayerCompressionNameToValue, + ImageLayerCompression: () => ImageLayerCompression, + Host: () => Host, + HealthcheckConfig: () => HealthcheckConfig, + HTTPState: () => HTTPState, + GitRepository: () => GitRepository, + GitRef: () => GitRef, + GeneratorGroup: () => GeneratorGroup, + Generator: () => Generator, + GeneratedCode: () => GeneratedCode, + Function_: () => Function_, + FunctionCallArgValue: () => FunctionCallArgValue, + FunctionCall: () => FunctionCall, + FunctionCachePolicyValueToName: () => FunctionCachePolicyValueToName, + FunctionCachePolicyNameToValue: () => FunctionCachePolicyNameToValue, + FunctionCachePolicy: () => FunctionCachePolicy, + FunctionArg: () => FunctionArg, + FileTypeValueToName: () => FileTypeValueToName, + FileTypeNameToValue: () => FileTypeNameToValue, + FileType: () => FileType, + File: () => File, + FieldTypeDef: () => FieldTypeDef, + ExistsTypeValueToName: () => ExistsTypeValueToName, + ExistsTypeNameToValue: () => ExistsTypeNameToValue, + ExistsType: () => ExistsType, + ErrorValue: () => ErrorValue, + Error: () => Error2, + EnvVariable: () => EnvVariable, + EnvFile: () => EnvFile, + Env: () => Env, + EnumValueTypeDef: () => EnumValueTypeDef, + EnumTypeDef: () => EnumTypeDef, + EngineCacheEntrySet: () => EngineCacheEntrySet, + EngineCacheEntry: () => EngineCacheEntry, + EngineCache: () => EngineCache, + Engine: () => Engine, + Directory: () => Directory, + DiffStatKindValueToName: () => DiffStatKindValueToName, + DiffStatKindNameToValue: () => DiffStatKindNameToValue, + DiffStatKind: () => DiffStatKind, + DiffStat: () => DiffStat, + CurrentModuleAsSDKModule: () => CurrentModuleAsSDKModule, + CurrentModuleAsSDKClient: () => CurrentModuleAsSDKClient, + CurrentModuleAsSDK: () => CurrentModuleAsSDK, + CurrentModule: () => CurrentModule, + Container: () => Container, + Cloud: () => Cloud, + ClientFilesyncMirror: () => ClientFilesyncMirror, + Client: () => Client, + CheckGroup: () => CheckGroup, + Check: () => Check, + ChangesetsMergeConflictValueToName: () => ChangesetsMergeConflictValueToName, + ChangesetsMergeConflictNameToValue: () => ChangesetsMergeConflictNameToValue, + ChangesetsMergeConflict: () => ChangesetsMergeConflict, + ChangesetMergeConflictValueToName: () => ChangesetMergeConflictValueToName, + ChangesetMergeConflictNameToValue: () => ChangesetMergeConflictNameToValue, + ChangesetMergeConflict: () => ChangesetMergeConflict, + Changeset: () => Changeset, + CacheVolume: () => CacheVolume, + CacheSharingModeValueToName: () => CacheSharingModeValueToName, + CacheSharingModeNameToValue: () => CacheSharingModeNameToValue, + CacheSharingMode: () => CacheSharingMode, + Binding: () => Binding, + BaseClient: () => BaseClient, + Address: () => Address +}); + +// src/common/graphql/compute_query.ts +init_main(); +init_errors(); +function buildArgs(args) { + const metadata = args.__metadata || {}; + const formatValue = (key, value) => { + if (metadata[key]?.is_enum) { + return JSON.stringify(metadata[key].value_to_name?.(value)).replace(/['"]+/g, ""); + } + return JSON.stringify(value).replace(/\{"[a-zA-Z]+":|,"[a-zA-Z]+":/gi, (str) => { + return str.replace(/"/g, ""); + }); + }; + if (args === undefined || args === null) { + return ""; + } + const formattedArgs = Object.entries(args).reduce((acc, [key, value]) => { + if (key === "__metadata") { + return acc; + } + if (value !== undefined && value !== null) { + acc.push(`${key}: ${formatValue(key, value)}`); + } + return acc; + }, []); + if (formattedArgs.length === 0) { + return ""; + } + return `(${formattedArgs})`; +} +async function computeNestedQuery(query, client) { + const isQueryTree = (value) => value["_ctx"] !== undefined; + const isArrayQueryTree = (value) => value.every((v) => v instanceof Object && isQueryTree(v)); + const computeQueryTree = async (value) => { + for (const op of value["_ctx"]["_queryTree"]) { + await computeNestedQuery([op], client); + } + return buildQuery([ + ...value["_ctx"]["_queryTree"], + { + operation: "id" + } + ]); + }; + const queryToExec = query.filter((q) => !!q.args); + for (const q of queryToExec) { + await Promise.all(Object.entries(q.args).map(async ([key, value]) => { + if (value instanceof Object && isQueryTree(value)) { + const getQueryTree = await computeQueryTree(value); + q.args[key] = await compute(getQueryTree, client); + } + if (Array.isArray(value) && isArrayQueryTree(value)) { + const tmp = q.args[key]; + for (let i = 0;i < value.length; i++) { + const getQueryTree = await computeQueryTree(value[i]); + tmp[i] = await compute(getQueryTree, client); + } + q.args[key] = tmp; + } + })); + } +} +function buildQuery(q) { + const query = q.reduce((acc, { operation, args, inlineType }, i) => { + const qLen = q.length; + const isLast = qLen - 1 === i; + acc += ` ${operation} ${args ? `${buildArgs(args)}` : ""}`; + if (!isLast) { + acc += " {"; + if (inlineType) { + acc += ` ... on ${inlineType} {`; + } + } else { + let closes = ""; + for (let j = i - 1;j >= 0; j--) { + if (q[j].inlineType) { + closes += " }"; + } + closes += " }"; + } + acc += closes; + } + return acc; + }, ""); + return `{${query} }`; +} +async function computeQuery(q, client) { + await computeNestedQuery(q, client); + const query = buildQuery(q); + return await compute(query, client); +} +function queryFlatten(response) { + if (!(response instanceof Object) || Array.isArray(response)) { + return response; + } + const keys = Object.keys(response); + if (keys.length != 1) { + throw new TooManyNestedObjectsError("Too many nested objects inside graphql response", { + response + }); + } + const nestedKey = keys[0]; + return queryFlatten(response[nestedKey]); +} +async function compute(query, client) { + let computeQuery2; + try { + computeQuery2 = await client.request(gql` + ${query} + `); + } catch (e) { + if (e instanceof ClientError) { + const msg = e.response.errors?.[0]?.message ?? `API Error`; + const ext = e.response.errors?.[0]?.extensions; + if (ext?._type === "EXEC_ERROR") { + throw new ExecError(msg, { + cmd: ext.cmd ?? [], + exitCode: ext.exitCode ?? -1, + stdout: ext.stdout ?? "", + stderr: ext.stderr ?? "", + extensions: ext + }); + } + throw new GraphQLRequestError(msg, { + error: e, + cause: e + }); + } + if (e.errno === "ECONNREFUSED") { + throw new NotAwaitedRequestError("Encountered an error while requesting data via graphql through a synchronous call. Make sure the function called is awaited.", { cause: e }); + } + throw new UnknownDaggerError("Encountered an unknown error while requesting data via graphql", { + cause: e + }); + } + return queryFlatten(computeQuery2); +} + +// src/common/graphql/connection.ts +class Connection { + _gqlClient; + constructor(_gqlClient) { + this._gqlClient = _gqlClient; + } + resetClient() { + this._gqlClient = undefined; + } + setGQLClient(gqlClient) { + this._gqlClient = gqlClient; + } + getGQLClient() { + if (!this._gqlClient) { + throw new Error("GraphQL client is not set"); + } + return this._gqlClient; + } +} +var globalConnection = new Connection; + +// src/common/context.ts +class Context { + _queryTree; + _connection; + constructor(_queryTree = [], _connection = globalConnection) { + this._queryTree = _queryTree; + this._connection = _connection; + } + getGQLClient() { + return this._connection.getGQLClient(); + } + copy() { + return new Context([], this._connection); + } + select(operation, args) { + return new Context([...this._queryTree, { operation, args }], this._connection); + } + selectNode(id, typeName) { + return new Context([ + ...this._queryTree, + { operation: "node", args: { id }, inlineType: typeName } + ], this._connection); + } + execute() { + return computeQuery(this._queryTree, this._connection.getGQLClient()); + } +} + +class BaseClient { + _ctx; + constructor(_ctx = new Context) { + this._ctx = _ctx; + } +} + +// src/api/client.gen.ts +var CacheSharingMode; +((CacheSharingMode2) => { + CacheSharingMode2["Locked"] = "LOCKED"; + CacheSharingMode2["Private"] = "PRIVATE"; + CacheSharingMode2["Shared"] = "SHARED"; +})(CacheSharingMode ||= {}); +function CacheSharingModeValueToName(value) { + switch (value) { + case "LOCKED" /* Locked */: + return "LOCKED"; + case "PRIVATE" /* Private */: + return "PRIVATE"; + case "SHARED" /* Shared */: + return "SHARED"; + default: + return value; + } +} +function CacheSharingModeNameToValue(name) { + switch (name) { + case "LOCKED": + return "LOCKED" /* Locked */; + case "PRIVATE": + return "PRIVATE" /* Private */; + case "SHARED": + return "SHARED" /* Shared */; + default: + return name; + } +} +var ChangesetMergeConflict; +((ChangesetMergeConflict2) => { + ChangesetMergeConflict2["Fail"] = "FAIL"; + ChangesetMergeConflict2["FailEarly"] = "FAIL_EARLY"; + ChangesetMergeConflict2["LeaveConflictMarkers"] = "LEAVE_CONFLICT_MARKERS"; + ChangesetMergeConflict2["PreferOurs"] = "PREFER_OURS"; + ChangesetMergeConflict2["PreferTheirs"] = "PREFER_THEIRS"; +})(ChangesetMergeConflict ||= {}); +function ChangesetMergeConflictValueToName(value) { + switch (value) { + case "FAIL" /* Fail */: + return "FAIL"; + case "FAIL_EARLY" /* FailEarly */: + return "FAIL_EARLY"; + case "LEAVE_CONFLICT_MARKERS" /* LeaveConflictMarkers */: + return "LEAVE_CONFLICT_MARKERS"; + case "PREFER_OURS" /* PreferOurs */: + return "PREFER_OURS"; + case "PREFER_THEIRS" /* PreferTheirs */: + return "PREFER_THEIRS"; + default: + return value; + } +} +function ChangesetMergeConflictNameToValue(name) { + switch (name) { + case "FAIL": + return "FAIL" /* Fail */; + case "FAIL_EARLY": + return "FAIL_EARLY" /* FailEarly */; + case "LEAVE_CONFLICT_MARKERS": + return "LEAVE_CONFLICT_MARKERS" /* LeaveConflictMarkers */; + case "PREFER_OURS": + return "PREFER_OURS" /* PreferOurs */; + case "PREFER_THEIRS": + return "PREFER_THEIRS" /* PreferTheirs */; + default: + return name; + } +} +var ChangesetsMergeConflict; +((ChangesetsMergeConflict2) => { + ChangesetsMergeConflict2["Fail"] = "FAIL"; + ChangesetsMergeConflict2["FailEarly"] = "FAIL_EARLY"; +})(ChangesetsMergeConflict ||= {}); +function ChangesetsMergeConflictValueToName(value) { + switch (value) { + case "FAIL" /* Fail */: + return "FAIL"; + case "FAIL_EARLY" /* FailEarly */: + return "FAIL_EARLY"; + default: + return value; + } +} +function ChangesetsMergeConflictNameToValue(name) { + switch (name) { + case "FAIL": + return "FAIL" /* Fail */; + case "FAIL_EARLY": + return "FAIL_EARLY" /* FailEarly */; + default: + return name; + } +} +var DiffStatKind; +((DiffStatKind2) => { + DiffStatKind2["Added"] = "ADDED"; + DiffStatKind2["Modified"] = "MODIFIED"; + DiffStatKind2["Removed"] = "REMOVED"; + DiffStatKind2["Renamed"] = "RENAMED"; +})(DiffStatKind ||= {}); +function DiffStatKindValueToName(value) { + switch (value) { + case "ADDED" /* Added */: + return "ADDED"; + case "MODIFIED" /* Modified */: + return "MODIFIED"; + case "REMOVED" /* Removed */: + return "REMOVED"; + case "RENAMED" /* Renamed */: + return "RENAMED"; + default: + return value; + } +} +function DiffStatKindNameToValue(name) { + switch (name) { + case "ADDED": + return "ADDED" /* Added */; + case "MODIFIED": + return "MODIFIED" /* Modified */; + case "REMOVED": + return "REMOVED" /* Removed */; + case "RENAMED": + return "RENAMED" /* Renamed */; + default: + return name; + } +} +var ExistsType; +((ExistsType2) => { + ExistsType2["DirectoryType"] = "DIRECTORY_TYPE"; + ExistsType2["RegularType"] = "REGULAR_TYPE"; + ExistsType2["SymlinkType"] = "SYMLINK_TYPE"; +})(ExistsType ||= {}); +function ExistsTypeValueToName(value) { + switch (value) { + case "DIRECTORY_TYPE" /* DirectoryType */: + return "DIRECTORY_TYPE"; + case "REGULAR_TYPE" /* RegularType */: + return "REGULAR_TYPE"; + case "SYMLINK_TYPE" /* SymlinkType */: + return "SYMLINK_TYPE"; + default: + return value; + } +} +function ExistsTypeNameToValue(name) { + switch (name) { + case "DIRECTORY_TYPE": + return "DIRECTORY_TYPE" /* DirectoryType */; + case "REGULAR_TYPE": + return "REGULAR_TYPE" /* RegularType */; + case "SYMLINK_TYPE": + return "SYMLINK_TYPE" /* SymlinkType */; + default: + return name; + } +} +var FileType; +((FileType2) => { + FileType2["Directory"] = "DIRECTORY"; + FileType2["DirectoryType"] = "DIRECTORY"; + FileType2["Regular"] = "REGULAR"; + FileType2["RegularType"] = "REGULAR"; + FileType2["Symlink"] = "SYMLINK"; + FileType2["SymlinkType"] = "SYMLINK"; + FileType2["Unknown"] = "UNKNOWN"; +})(FileType ||= {}); +function FileTypeValueToName(value) { + switch (value) { + case "DIRECTORY" /* Directory */: + return "DIRECTORY"; + case "REGULAR" /* Regular */: + return "REGULAR"; + case "SYMLINK" /* Symlink */: + return "SYMLINK"; + case "UNKNOWN" /* Unknown */: + return "UNKNOWN"; + default: + return value; + } +} +function FileTypeNameToValue(name) { + switch (name) { + case "DIRECTORY": + return "DIRECTORY" /* Directory */; + case "REGULAR": + return "REGULAR" /* Regular */; + case "SYMLINK": + return "SYMLINK" /* Symlink */; + case "UNKNOWN": + return "UNKNOWN" /* Unknown */; + default: + return name; + } +} +var FunctionCachePolicy; +((FunctionCachePolicy2) => { + FunctionCachePolicy2["Default"] = "Default"; + FunctionCachePolicy2["Never"] = "Never"; + FunctionCachePolicy2["PerSession"] = "PerSession"; +})(FunctionCachePolicy ||= {}); +function FunctionCachePolicyValueToName(value) { + switch (value) { + case "Default" /* Default */: + return "Default"; + case "Never" /* Never */: + return "Never"; + case "PerSession" /* PerSession */: + return "PerSession"; + default: + return value; + } +} +function FunctionCachePolicyNameToValue(name) { + switch (name) { + case "Default": + return "Default" /* Default */; + case "Never": + return "Never" /* Never */; + case "PerSession": + return "PerSession" /* PerSession */; + default: + return name; + } +} +var ImageLayerCompression; +((ImageLayerCompression2) => { + ImageLayerCompression2["EstarGz"] = "EStarGZ"; + ImageLayerCompression2["Estargz"] = "EStarGZ"; + ImageLayerCompression2["Gzip"] = "Gzip"; + ImageLayerCompression2["Uncompressed"] = "Uncompressed"; + ImageLayerCompression2["Zstd"] = "Zstd"; +})(ImageLayerCompression ||= {}); +function ImageLayerCompressionValueToName(value) { + switch (value) { + case "EStarGZ" /* EstarGz */: + return "EStarGZ"; + case "Gzip" /* Gzip */: + return "Gzip"; + case "Uncompressed" /* Uncompressed */: + return "Uncompressed"; + case "Zstd" /* Zstd */: + return "Zstd"; + default: + return value; + } +} +function ImageLayerCompressionNameToValue(name) { + switch (name) { + case "EStarGZ": + return "EStarGZ" /* EstarGz */; + case "Gzip": + return "Gzip" /* Gzip */; + case "Uncompressed": + return "Uncompressed" /* Uncompressed */; + case "Zstd": + return "Zstd" /* Zstd */; + default: + return name; + } +} +var ImageMediaTypes; +((ImageMediaTypes2) => { + ImageMediaTypes2["Docker"] = "DockerMediaTypes"; + ImageMediaTypes2["DockerMediaTypes"] = "DockerMediaTypes"; + ImageMediaTypes2["Oci"] = "OCIMediaTypes"; + ImageMediaTypes2["OcimediaTypes"] = "OCIMediaTypes"; +})(ImageMediaTypes ||= {}); +function ImageMediaTypesValueToName(value) { + switch (value) { + case "DockerMediaTypes" /* Docker */: + return "DOCKER"; + case "OCIMediaTypes" /* Oci */: + return "OCI"; + default: + return value; + } +} +function ImageMediaTypesNameToValue(name) { + switch (name) { + case "DOCKER": + return "DockerMediaTypes" /* Docker */; + case "OCI": + return "OCIMediaTypes" /* Oci */; + default: + return name; + } +} +var LLMContentBlockKind; +((LLMContentBlockKind2) => { + LLMContentBlockKind2["Text"] = "TEXT"; + LLMContentBlockKind2["Thinking"] = "THINKING"; + LLMContentBlockKind2["ToolCall"] = "TOOL_CALL"; + LLMContentBlockKind2["ToolResult"] = "TOOL_RESULT"; +})(LLMContentBlockKind ||= {}); +function LLMContentBlockKindValueToName(value) { + switch (value) { + case "TEXT" /* Text */: + return "TEXT"; + case "THINKING" /* Thinking */: + return "THINKING"; + case "TOOL_CALL" /* ToolCall */: + return "TOOL_CALL"; + case "TOOL_RESULT" /* ToolResult */: + return "TOOL_RESULT"; + default: + return value; + } +} +function LLMContentBlockKindNameToValue(name) { + switch (name) { + case "TEXT": + return "TEXT" /* Text */; + case "THINKING": + return "THINKING" /* Thinking */; + case "TOOL_CALL": + return "TOOL_CALL" /* ToolCall */; + case "TOOL_RESULT": + return "TOOL_RESULT" /* ToolResult */; + default: + return name; + } +} +var LLMMessageRole; +((LLMMessageRole2) => { + LLMMessageRole2["Assistant"] = "ASSISTANT"; + LLMMessageRole2["System"] = "SYSTEM"; + LLMMessageRole2["User"] = "USER"; +})(LLMMessageRole ||= {}); +function LLMMessageRoleValueToName(value) { + switch (value) { + case "ASSISTANT" /* Assistant */: + return "ASSISTANT"; + case "SYSTEM" /* System */: + return "SYSTEM"; + case "USER" /* User */: + return "USER"; + default: + return value; + } +} +function LLMMessageRoleNameToValue(name) { + switch (name) { + case "ASSISTANT": + return "ASSISTANT" /* Assistant */; + case "SYSTEM": + return "SYSTEM" /* System */; + case "USER": + return "USER" /* User */; + default: + return name; + } +} +var ModuleSourceExperimentalFeature; +((ModuleSourceExperimentalFeature2) => { + ModuleSourceExperimentalFeature2["SelfCalls"] = "SELF_CALLS"; +})(ModuleSourceExperimentalFeature ||= {}); +function ModuleSourceExperimentalFeatureValueToName(value) { + switch (value) { + case "SELF_CALLS" /* SelfCalls */: + return "SELF_CALLS"; + default: + return value; + } +} +function ModuleSourceExperimentalFeatureNameToValue(name) { + switch (name) { + case "SELF_CALLS": + return "SELF_CALLS" /* SelfCalls */; + default: + return name; + } +} +var ModuleSourceKind; +((ModuleSourceKind2) => { + ModuleSourceKind2["Dir"] = "DIR_SOURCE"; + ModuleSourceKind2["DirSource"] = "DIR_SOURCE"; + ModuleSourceKind2["Git"] = "GIT_SOURCE"; + ModuleSourceKind2["GitSource"] = "GIT_SOURCE"; + ModuleSourceKind2["Local"] = "LOCAL_SOURCE"; + ModuleSourceKind2["LocalSource"] = "LOCAL_SOURCE"; +})(ModuleSourceKind ||= {}); +function ModuleSourceKindValueToName(value) { + switch (value) { + case "DIR_SOURCE" /* Dir */: + return "DIR"; + case "GIT_SOURCE" /* Git */: + return "GIT"; + case "LOCAL_SOURCE" /* Local */: + return "LOCAL"; + default: + return value; + } +} +function ModuleSourceKindNameToValue(name) { + switch (name) { + case "DIR": + return "DIR_SOURCE" /* Dir */; + case "GIT": + return "GIT_SOURCE" /* Git */; + case "LOCAL": + return "LOCAL_SOURCE" /* Local */; + default: + return name; + } +} +var NetworkProtocol; +((NetworkProtocol2) => { + NetworkProtocol2["Tcp"] = "TCP"; + NetworkProtocol2["Udp"] = "UDP"; +})(NetworkProtocol ||= {}); +function NetworkProtocolValueToName(value) { + switch (value) { + case "TCP" /* Tcp */: + return "TCP"; + case "UDP" /* Udp */: + return "UDP"; + default: + return value; + } +} +function NetworkProtocolNameToValue(name) { + switch (name) { + case "TCP": + return "TCP" /* Tcp */; + case "UDP": + return "UDP" /* Udp */; + default: + return name; + } +} +var RegistryProtocol; +((RegistryProtocol2) => { + RegistryProtocol2["Http"] = "HTTP"; + RegistryProtocol2["Https"] = "HTTPS"; +})(RegistryProtocol ||= {}); +function RegistryProtocolValueToName(value) { + switch (value) { + case "HTTP" /* Http */: + return "HTTP"; + case "HTTPS" /* Https */: + return "HTTPS"; + default: + return value; + } +} +function RegistryProtocolNameToValue(name) { + switch (name) { + case "HTTP": + return "HTTP" /* Http */; + case "HTTPS": + return "HTTPS" /* Https */; + default: + return name; + } +} +var ReturnType; +((ReturnType2) => { + ReturnType2["Any"] = "ANY"; + ReturnType2["Failure"] = "FAILURE"; + ReturnType2["Success"] = "SUCCESS"; +})(ReturnType ||= {}); +function ReturnTypeValueToName(value) { + switch (value) { + case "ANY" /* Any */: + return "ANY"; + case "FAILURE" /* Failure */: + return "FAILURE"; + case "SUCCESS" /* Success */: + return "SUCCESS"; + default: + return value; + } +} +function ReturnTypeNameToValue(name) { + switch (name) { + case "ANY": + return "ANY" /* Any */; + case "FAILURE": + return "FAILURE" /* Failure */; + case "SUCCESS": + return "SUCCESS" /* Success */; + default: + return name; + } +} +var TypeDefKind; +((TypeDefKind2) => { + TypeDefKind2["Boolean"] = "BOOLEAN_KIND"; + TypeDefKind2["BooleanKind"] = "BOOLEAN_KIND"; + TypeDefKind2["Enum"] = "ENUM_KIND"; + TypeDefKind2["EnumKind"] = "ENUM_KIND"; + TypeDefKind2["Float"] = "FLOAT_KIND"; + TypeDefKind2["FloatKind"] = "FLOAT_KIND"; + TypeDefKind2["Input"] = "INPUT_KIND"; + TypeDefKind2["InputKind"] = "INPUT_KIND"; + TypeDefKind2["Integer"] = "INTEGER_KIND"; + TypeDefKind2["IntegerKind"] = "INTEGER_KIND"; + TypeDefKind2["Interface"] = "INTERFACE_KIND"; + TypeDefKind2["InterfaceKind"] = "INTERFACE_KIND"; + TypeDefKind2["List"] = "LIST_KIND"; + TypeDefKind2["ListKind"] = "LIST_KIND"; + TypeDefKind2["Object"] = "OBJECT_KIND"; + TypeDefKind2["ObjectKind"] = "OBJECT_KIND"; + TypeDefKind2["Scalar"] = "SCALAR_KIND"; + TypeDefKind2["ScalarKind"] = "SCALAR_KIND"; + TypeDefKind2["String"] = "STRING_KIND"; + TypeDefKind2["StringKind"] = "STRING_KIND"; + TypeDefKind2["Void"] = "VOID_KIND"; + TypeDefKind2["VoidKind"] = "VOID_KIND"; +})(TypeDefKind ||= {}); +function TypeDefKindValueToName(value) { + switch (value) { + case "BOOLEAN_KIND" /* Boolean */: + return "BOOLEAN"; + case "ENUM_KIND" /* Enum */: + return "ENUM"; + case "FLOAT_KIND" /* Float */: + return "FLOAT"; + case "INPUT_KIND" /* Input */: + return "INPUT"; + case "INTEGER_KIND" /* Integer */: + return "INTEGER"; + case "INTERFACE_KIND" /* Interface */: + return "INTERFACE"; + case "LIST_KIND" /* List */: + return "LIST"; + case "OBJECT_KIND" /* Object */: + return "OBJECT"; + case "SCALAR_KIND" /* Scalar */: + return "SCALAR"; + case "STRING_KIND" /* String */: + return "STRING"; + case "VOID_KIND" /* Void */: + return "VOID"; + default: + return value; + } +} +function TypeDefKindNameToValue(name) { + switch (name) { + case "BOOLEAN": + return "BOOLEAN_KIND" /* Boolean */; + case "ENUM": + return "ENUM_KIND" /* Enum */; + case "FLOAT": + return "FLOAT_KIND" /* Float */; + case "INPUT": + return "INPUT_KIND" /* Input */; + case "INTEGER": + return "INTEGER_KIND" /* Integer */; + case "INTERFACE": + return "INTERFACE_KIND" /* Interface */; + case "LIST": + return "LIST_KIND" /* List */; + case "OBJECT": + return "OBJECT_KIND" /* Object */; + case "SCALAR": + return "SCALAR_KIND" /* Scalar */; + case "STRING": + return "STRING_KIND" /* String */; + case "VOID": + return "VOID_KIND" /* Void */; + default: + return name; + } +} + +class Address extends BaseClient { + _id = undefined; + _value = undefined; + constructor(ctx, _id, _value) { + super(ctx); + this._id = _id; + this._value = _value; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + container = () => { + const ctx = this._ctx.select("container"); + return new Container(ctx); + }; + directory = (opts) => { + const ctx = this._ctx.select("directory", { ...opts }); + return new Directory(ctx); + }; + file = (opts) => { + const ctx = this._ctx.select("file", { ...opts }); + return new File(ctx); + }; + gitRef = () => { + const ctx = this._ctx.select("gitRef"); + return new GitRef(ctx); + }; + gitRepository = () => { + const ctx = this._ctx.select("gitRepository"); + return new GitRepository(ctx); + }; + secret = () => { + const ctx = this._ctx.select("secret"); + return new Secret(ctx); + }; + service = () => { + const ctx = this._ctx.select("service"); + return new Service(ctx); + }; + socket = () => { + const ctx = this._ctx.select("socket"); + return new Socket(ctx); + }; + value = async () => { + if (this._value) { + return this._value; + } + const ctx = this._ctx.select("value"); + const response = await ctx.execute(); + return response; + }; + volume = () => { + const ctx = this._ctx.select("volume"); + return new Volume(ctx); + }; +} + +class Binding extends BaseClient { + _id = undefined; + _asString = undefined; + _digest = undefined; + _isNull = undefined; + _name = undefined; + _typeName = undefined; + constructor(ctx, _id, _asString, _digest, _isNull, _name, _typeName) { + super(ctx); + this._id = _id; + this._asString = _asString; + this._digest = _digest; + this._isNull = _isNull; + this._name = _name; + this._typeName = _typeName; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asAddress = () => { + const ctx = this._ctx.select("asAddress"); + return new Address(ctx); + }; + asCacheVolume = () => { + const ctx = this._ctx.select("asCacheVolume"); + return new CacheVolume(ctx); + }; + asChangeset = () => { + const ctx = this._ctx.select("asChangeset"); + return new Changeset(ctx); + }; + asCheck = () => { + const ctx = this._ctx.select("asCheck"); + return new Check(ctx); + }; + asCheckGroup = () => { + const ctx = this._ctx.select("asCheckGroup"); + return new CheckGroup(ctx); + }; + asCloud = () => { + const ctx = this._ctx.select("asCloud"); + return new Cloud(ctx); + }; + asContainer = () => { + const ctx = this._ctx.select("asContainer"); + return new Container(ctx); + }; + asCurrentModuleAsSDK = () => { + const ctx = this._ctx.select("asCurrentModuleAsSDK"); + return new CurrentModuleAsSDK(ctx); + }; + asCurrentModuleAsSDKClient = () => { + const ctx = this._ctx.select("asCurrentModuleAsSDKClient"); + return new CurrentModuleAsSDKClient(ctx); + }; + asCurrentModuleAsSDKModule = () => { + const ctx = this._ctx.select("asCurrentModuleAsSDKModule"); + return new CurrentModuleAsSDKModule(ctx); + }; + asDiffStat = () => { + const ctx = this._ctx.select("asDiffStat"); + return new DiffStat(ctx); + }; + asDirectory = () => { + const ctx = this._ctx.select("asDirectory"); + return new Directory(ctx); + }; + asEnv = () => { + const ctx = this._ctx.select("asEnv"); + return new Env(ctx); + }; + asEnvFile = () => { + const ctx = this._ctx.select("asEnvFile"); + return new EnvFile(ctx); + }; + asFile = () => { + const ctx = this._ctx.select("asFile"); + return new File(ctx); + }; + asGenerator = () => { + const ctx = this._ctx.select("asGenerator"); + return new Generator(ctx); + }; + asGeneratorGroup = () => { + const ctx = this._ctx.select("asGeneratorGroup"); + return new GeneratorGroup(ctx); + }; + asGitRef = () => { + const ctx = this._ctx.select("asGitRef"); + return new GitRef(ctx); + }; + asGitRepository = () => { + const ctx = this._ctx.select("asGitRepository"); + return new GitRepository(ctx); + }; + asHTTPState = () => { + const ctx = this._ctx.select("asHTTPState"); + return new HTTPState(ctx); + }; + asJSONValue = () => { + const ctx = this._ctx.select("asJSONValue"); + return new JSONValue(ctx); + }; + asLLMContentBlock = () => { + const ctx = this._ctx.select("asLLMContentBlock"); + return new LLMContentBlock(ctx); + }; + asLLMMessage = () => { + const ctx = this._ctx.select("asLLMMessage"); + return new LLMMessage(ctx); + }; + asModule = () => { + const ctx = this._ctx.select("asModule"); + return new Module_(ctx); + }; + asModuleConfigClient = () => { + const ctx = this._ctx.select("asModuleConfigClient"); + return new ModuleConfigClient(ctx); + }; + asModuleSource = () => { + const ctx = this._ctx.select("asModuleSource"); + return new ModuleSource(ctx); + }; + asSchema = () => { + const ctx = this._ctx.select("asSchema"); + return new Schema(ctx); + }; + asSearchResult = () => { + const ctx = this._ctx.select("asSearchResult"); + return new SearchResult(ctx); + }; + asSearchSubmatch = () => { + const ctx = this._ctx.select("asSearchSubmatch"); + return new SearchSubmatch(ctx); + }; + asSecret = () => { + const ctx = this._ctx.select("asSecret"); + return new Secret(ctx); + }; + asService = () => { + const ctx = this._ctx.select("asService"); + return new Service(ctx); + }; + asSocket = () => { + const ctx = this._ctx.select("asSocket"); + return new Socket(ctx); + }; + asStat = () => { + const ctx = this._ctx.select("asStat"); + return new Stat(ctx); + }; + asString = async () => { + if (this._asString) { + return this._asString; + } + const ctx = this._ctx.select("asString"); + const response = await ctx.execute(); + return response; + }; + asUp = () => { + const ctx = this._ctx.select("asUp"); + return new Up(ctx); + }; + asUpGroup = () => { + const ctx = this._ctx.select("asUpGroup"); + return new UpGroup(ctx); + }; + asVolume = () => { + const ctx = this._ctx.select("asVolume"); + return new Volume(ctx); + }; + asWorkspace = () => { + const ctx = this._ctx.select("asWorkspace"); + return new Workspace(ctx); + }; + asWorkspaceGit = () => { + const ctx = this._ctx.select("asWorkspaceGit"); + return new WorkspaceGit(ctx); + }; + asWorkspaceMigration = () => { + const ctx = this._ctx.select("asWorkspaceMigration"); + return new WorkspaceMigration(ctx); + }; + asWorkspaceMigrationStep = () => { + const ctx = this._ctx.select("asWorkspaceMigrationStep"); + return new WorkspaceMigrationStep(ctx); + }; + asWorkspaceModule = () => { + const ctx = this._ctx.select("asWorkspaceModule"); + return new WorkspaceModule(ctx); + }; + asWorkspaceModuleSetting = () => { + const ctx = this._ctx.select("asWorkspaceModuleSetting"); + return new WorkspaceModuleSetting(ctx); + }; + asWorkspaceSDK = () => { + const ctx = this._ctx.select("asWorkspaceSDK"); + return new WorkspaceSDK(ctx); + }; + digest = async () => { + if (this._digest) { + return this._digest; + } + const ctx = this._ctx.select("digest"); + const response = await ctx.execute(); + return response; + }; + isNull = async () => { + if (this._isNull) { + return this._isNull; + } + const ctx = this._ctx.select("isNull"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + typeName = async () => { + if (this._typeName) { + return this._typeName; + } + const ctx = this._ctx.select("typeName"); + const response = await ctx.execute(); + return response; + }; +} + +class CacheVolume extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; +} + +class Changeset extends BaseClient { + _id = undefined; + _export = undefined; + _isEmpty = undefined; + _sync = undefined; + constructor(ctx, _id, _export, _isEmpty, _sync) { + super(ctx); + this._id = _id; + this._export = _export; + this._isEmpty = _isEmpty; + this._sync = _sync; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + addedPaths = async () => { + const ctx = this._ctx.select("addedPaths"); + const response = await ctx.execute(); + return response; + }; + after = () => { + const ctx = this._ctx.select("after"); + return new Directory(ctx); + }; + asPatch = () => { + const ctx = this._ctx.select("asPatch"); + return new File(ctx); + }; + before = () => { + const ctx = this._ctx.select("before"); + return new Directory(ctx); + }; + diffStats = async () => { + const ctx = this._ctx.select("diffStats").select("id"); + const response = await ctx.execute(); + return response.map((r) => new DiffStat(ctx.copy().selectNode(r.id, "DiffStat"))); + }; + export = async (path) => { + if (this._export) { + return this._export; + } + const ctx = this._ctx.select("export", { path }); + const response = await ctx.execute(); + return response; + }; + isEmpty = async () => { + if (this._isEmpty) { + return this._isEmpty; + } + const ctx = this._ctx.select("isEmpty"); + const response = await ctx.execute(); + return response; + }; + layer = () => { + const ctx = this._ctx.select("layer"); + return new Directory(ctx); + }; + modifiedPaths = async () => { + const ctx = this._ctx.select("modifiedPaths"); + const response = await ctx.execute(); + return response; + }; + removedPaths = async () => { + const ctx = this._ctx.select("removedPaths"); + const response = await ctx.execute(); + return response; + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new Changeset(ctx.copy().selectNode(response, "Changeset")); + }; + withChangeset = (changes, opts) => { + const metadata = { + onConflict: { is_enum: true, value_to_name: ChangesetMergeConflictValueToName } + }; + const ctx = this._ctx.select("withChangeset", { changes, ...opts, __metadata: metadata }); + return new Changeset(ctx); + }; + withChangesets = (changes, opts) => { + const metadata = { + onConflict: { is_enum: true, value_to_name: ChangesetsMergeConflictValueToName } + }; + const ctx = this._ctx.select("withChangesets", { changes, ...opts, __metadata: metadata }); + return new Changeset(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class Check extends BaseClient { + _id = undefined; + _checkType = undefined; + _completed = undefined; + _description = undefined; + _name = undefined; + _passed = undefined; + _resultEmoji = undefined; + constructor(ctx, _id, _checkType, _completed, _description, _name, _passed, _resultEmoji) { + super(ctx); + this._id = _id; + this._checkType = _checkType; + this._completed = _completed; + this._description = _description; + this._name = _name; + this._passed = _passed; + this._resultEmoji = _resultEmoji; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + checkType = async () => { + if (this._checkType) { + return this._checkType; + } + const ctx = this._ctx.select("checkType"); + const response = await ctx.execute(); + return response; + }; + completed = async () => { + if (this._completed) { + return this._completed; + } + const ctx = this._ctx.select("completed"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + error = () => { + const ctx = this._ctx.select("error"); + return new Error2(ctx); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + originalModule = () => { + const ctx = this._ctx.select("originalModule"); + return new Module_(ctx); + }; + passed = async () => { + if (this._passed) { + return this._passed; + } + const ctx = this._ctx.select("passed"); + const response = await ctx.execute(); + return response; + }; + path = async () => { + const ctx = this._ctx.select("path"); + const response = await ctx.execute(); + return response; + }; + resultEmoji = async () => { + if (this._resultEmoji) { + return this._resultEmoji; + } + const ctx = this._ctx.select("resultEmoji"); + const response = await ctx.execute(); + return response; + }; + run = () => { + const ctx = this._ctx.select("run"); + return new Check(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class CheckGroup extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + list = async () => { + const ctx = this._ctx.select("list").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Check(ctx.copy().selectNode(r.id, "Check"))); + }; + report = () => { + const ctx = this._ctx.select("report"); + return new File(ctx); + }; + run = (opts) => { + const ctx = this._ctx.select("run", { ...opts }); + return new CheckGroup(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class ClientFilesyncMirror extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; +} + +class Cloud extends BaseClient { + _id = undefined; + _traceURL = undefined; + constructor(ctx, _id, _traceURL) { + super(ctx); + this._id = _id; + this._traceURL = _traceURL; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + traceURL = async () => { + if (this._traceURL) { + return this._traceURL; + } + const ctx = this._ctx.select("traceURL"); + const response = await ctx.execute(); + return response; + }; +} + +class Container extends BaseClient { + _id = undefined; + _combinedOutput = undefined; + _envVariable = undefined; + _exists = undefined; + _exitCode = undefined; + _export = undefined; + _exportImage = undefined; + _imageRef = undefined; + _label = undefined; + _platform = undefined; + _publish = undefined; + _stderr = undefined; + _stdout = undefined; + _sync = undefined; + _up = undefined; + _user = undefined; + _workdir = undefined; + constructor(ctx, _id, _combinedOutput, _envVariable, _exists, _exitCode, _export, _exportImage, _imageRef, _label, _platform, _publish, _stderr, _stdout, _sync, _up, _user, _workdir) { + super(ctx); + this._id = _id; + this._combinedOutput = _combinedOutput; + this._envVariable = _envVariable; + this._exists = _exists; + this._exitCode = _exitCode; + this._export = _export; + this._exportImage = _exportImage; + this._imageRef = _imageRef; + this._label = _label; + this._platform = _platform; + this._publish = _publish; + this._stderr = _stderr; + this._stdout = _stdout; + this._sync = _sync; + this._up = _up; + this._user = _user; + this._workdir = _workdir; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asService = (opts) => { + const ctx = this._ctx.select("asService", { ...opts }); + return new Service(ctx); + }; + asTarball = (opts) => { + const metadata = { + forcedCompression: { is_enum: true, value_to_name: ImageLayerCompressionValueToName }, + mediaTypes: { is_enum: true, value_to_name: ImageMediaTypesValueToName } + }; + const ctx = this._ctx.select("asTarball", { ...opts, __metadata: metadata }); + return new File(ctx); + }; + combinedOutput = async () => { + if (this._combinedOutput) { + return this._combinedOutput; + } + const ctx = this._ctx.select("combinedOutput"); + const response = await ctx.execute(); + return response; + }; + defaultArgs = async () => { + const ctx = this._ctx.select("defaultArgs"); + const response = await ctx.execute(); + return response; + }; + directory = (path, opts) => { + const ctx = this._ctx.select("directory", { path, ...opts }); + return new Directory(ctx); + }; + dockerHealthcheck = () => { + const ctx = this._ctx.select("dockerHealthcheck"); + return new HealthcheckConfig(ctx); + }; + entrypoint = async () => { + const ctx = this._ctx.select("entrypoint"); + const response = await ctx.execute(); + return response; + }; + envVariable = async (name) => { + if (this._envVariable) { + return this._envVariable; + } + const ctx = this._ctx.select("envVariable", { name }); + const response = await ctx.execute(); + return response; + }; + envVariables = async () => { + const ctx = this._ctx.select("envVariables").select("id"); + const response = await ctx.execute(); + return response.map((r) => new EnvVariable(ctx.copy().selectNode(r.id, "EnvVariable"))); + }; + exists = async (path, opts) => { + if (this._exists) { + return this._exists; + } + const metadata = { + expectedType: { is_enum: true, value_to_name: ExistsTypeValueToName } + }; + const ctx = this._ctx.select("exists", { path, ...opts, __metadata: metadata }); + const response = await ctx.execute(); + return response; + }; + exitCode = async () => { + if (this._exitCode) { + return this._exitCode; + } + const ctx = this._ctx.select("exitCode"); + const response = await ctx.execute(); + return response; + }; + experimentalWithAllGPUs = () => { + const ctx = this._ctx.select("experimentalWithAllGPUs"); + return new Container(ctx); + }; + experimentalWithGPU = (devices) => { + const ctx = this._ctx.select("experimentalWithGPU", { devices }); + return new Container(ctx); + }; + export = async (path, opts) => { + if (this._export) { + return this._export; + } + const metadata = { + forcedCompression: { is_enum: true, value_to_name: ImageLayerCompressionValueToName }, + mediaTypes: { is_enum: true, value_to_name: ImageMediaTypesValueToName } + }; + const ctx = this._ctx.select("export", { path, ...opts, __metadata: metadata }); + const response = await ctx.execute(); + return response; + }; + exportImage = async (name, opts) => { + if (this._exportImage) { + return; + } + const metadata = { + forcedCompression: { is_enum: true, value_to_name: ImageLayerCompressionValueToName }, + mediaTypes: { is_enum: true, value_to_name: ImageMediaTypesValueToName } + }; + const ctx = this._ctx.select("exportImage", { name, ...opts, __metadata: metadata }); + await ctx.execute(); + }; + exposedPorts = async () => { + const ctx = this._ctx.select("exposedPorts").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Port(ctx.copy().selectNode(r.id, "Port"))); + }; + file = (path, opts) => { + const ctx = this._ctx.select("file", { path, ...opts }); + return new File(ctx); + }; + from = (address, opts) => { + const metadata = { + protocol: { is_enum: true, value_to_name: RegistryProtocolValueToName } + }; + const ctx = this._ctx.select("from", { address, ...opts, __metadata: metadata }); + return new Container(ctx); + }; + imageRef = async () => { + if (this._imageRef) { + return this._imageRef; + } + const ctx = this._ctx.select("imageRef"); + const response = await ctx.execute(); + return response; + }; + import_ = (source, opts) => { + const ctx = this._ctx.select("import", { source, ...opts }); + return new Container(ctx); + }; + label = async (name) => { + if (this._label) { + return this._label; + } + const ctx = this._ctx.select("label", { name }); + const response = await ctx.execute(); + return response; + }; + labels = async () => { + const ctx = this._ctx.select("labels").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Label(ctx.copy().selectNode(r.id, "Label"))); + }; + layer = (id, opts) => { + const metadata = { + forcedCompression: { is_enum: true, value_to_name: ImageLayerCompressionValueToName }, + mediaTypes: { is_enum: true, value_to_name: ImageMediaTypesValueToName } + }; + const ctx = this._ctx.select("layer", { id, ...opts, __metadata: metadata }); + return new File(ctx); + }; + manifest = (opts) => { + const metadata = { + forcedCompression: { is_enum: true, value_to_name: ImageLayerCompressionValueToName }, + mediaTypes: { is_enum: true, value_to_name: ImageMediaTypesValueToName } + }; + const ctx = this._ctx.select("manifest", { ...opts, __metadata: metadata }); + return new File(ctx); + }; + mounts = async () => { + const ctx = this._ctx.select("mounts"); + const response = await ctx.execute(); + return response; + }; + platform = async () => { + if (this._platform) { + return this._platform; + } + const ctx = this._ctx.select("platform"); + const response = await ctx.execute(); + return response; + }; + publish = async (address, opts) => { + if (this._publish) { + return this._publish; + } + const metadata = { + forcedCompression: { is_enum: true, value_to_name: ImageLayerCompressionValueToName }, + mediaTypes: { is_enum: true, value_to_name: ImageMediaTypesValueToName }, + protocol: { is_enum: true, value_to_name: RegistryProtocolValueToName } + }; + const ctx = this._ctx.select("publish", { address, ...opts, __metadata: metadata }); + const response = await ctx.execute(); + return response; + }; + rootfs = () => { + const ctx = this._ctx.select("rootfs"); + return new Directory(ctx); + }; + stat = (path, opts) => { + const ctx = this._ctx.select("stat", { path, ...opts }); + return new Stat(ctx); + }; + stderr = async () => { + if (this._stderr) { + return this._stderr; + } + const ctx = this._ctx.select("stderr"); + const response = await ctx.execute(); + return response; + }; + stdout = async () => { + if (this._stdout) { + return this._stdout; + } + const ctx = this._ctx.select("stdout"); + const response = await ctx.execute(); + return response; + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new Container(ctx.copy().selectNode(response, "Container")); + }; + terminal = (opts) => { + const ctx = this._ctx.select("terminal", { ...opts }); + return new Container(ctx); + }; + up = async (opts) => { + if (this._up) { + return; + } + const ctx = this._ctx.select("up", { ...opts }); + await ctx.execute(); + }; + user = async () => { + if (this._user) { + return this._user; + } + const ctx = this._ctx.select("user"); + const response = await ctx.execute(); + return response; + }; + withAnnotation = (name, value) => { + const ctx = this._ctx.select("withAnnotation", { name, value }); + return new Container(ctx); + }; + withDefaultArgs = (args) => { + const ctx = this._ctx.select("withDefaultArgs", { args }); + return new Container(ctx); + }; + withDefaultTerminalCmd = (args, opts) => { + const ctx = this._ctx.select("withDefaultTerminalCmd", { args, ...opts }); + return new Container(ctx); + }; + withDirectory = (path, source, opts) => { + const ctx = this._ctx.select("withDirectory", { path, source, ...opts }); + return new Container(ctx); + }; + withDockerHealthcheck = (args, opts) => { + const ctx = this._ctx.select("withDockerHealthcheck", { args, ...opts }); + return new Container(ctx); + }; + withEntrypoint = (args, opts) => { + const ctx = this._ctx.select("withEntrypoint", { args, ...opts }); + return new Container(ctx); + }; + withEnvFileVariables = (source) => { + const ctx = this._ctx.select("withEnvFileVariables", { source }); + return new Container(ctx); + }; + withEnvVariable = (name, value, opts) => { + const ctx = this._ctx.select("withEnvVariable", { name, value, ...opts }); + return new Container(ctx); + }; + withError = (err) => { + const ctx = this._ctx.select("withError", { err }); + return new Container(ctx); + }; + withExec = (args, opts) => { + const metadata = { + expect: { is_enum: true, value_to_name: ReturnTypeValueToName } + }; + const ctx = this._ctx.select("withExec", { args, ...opts, __metadata: metadata }); + return new Container(ctx); + }; + withExposedPort = (port, opts) => { + const metadata = { + protocol: { is_enum: true, value_to_name: NetworkProtocolValueToName } + }; + const ctx = this._ctx.select("withExposedPort", { port, ...opts, __metadata: metadata }); + return new Container(ctx); + }; + withFile = (path, source, opts) => { + const ctx = this._ctx.select("withFile", { path, source, ...opts }); + return new Container(ctx); + }; + withFiles = (path, sources, opts) => { + const ctx = this._ctx.select("withFiles", { path, sources, ...opts }); + return new Container(ctx); + }; + withLabel = (name, value) => { + const ctx = this._ctx.select("withLabel", { name, value }); + return new Container(ctx); + }; + withMountedCache = (path, cache, opts) => { + const metadata = { + sharing: { is_enum: true, value_to_name: CacheSharingModeValueToName } + }; + const ctx = this._ctx.select("withMountedCache", { path, cache, ...opts, __metadata: metadata }); + return new Container(ctx); + }; + withMountedDirectory = (path, source, opts) => { + const ctx = this._ctx.select("withMountedDirectory", { path, source, ...opts }); + return new Container(ctx); + }; + withMountedFile = (path, source, opts) => { + const ctx = this._ctx.select("withMountedFile", { path, source, ...opts }); + return new Container(ctx); + }; + withMountedSecret = (path, source, opts) => { + const ctx = this._ctx.select("withMountedSecret", { path, source, ...opts }); + return new Container(ctx); + }; + withMountedTemp = (path, opts) => { + const ctx = this._ctx.select("withMountedTemp", { path, ...opts }); + return new Container(ctx); + }; + withMountedVolume = (path, volume, opts) => { + const ctx = this._ctx.select("withMountedVolume", { path, volume, ...opts }); + return new Container(ctx); + }; + withNewFile = (path, contents, opts) => { + const ctx = this._ctx.select("withNewFile", { path, contents, ...opts }); + return new Container(ctx); + }; + withRegistryAuth = (address, username, secret) => { + const ctx = this._ctx.select("withRegistryAuth", { address, username, secret }); + return new Container(ctx); + }; + withRootfs = (directory) => { + const ctx = this._ctx.select("withRootfs", { directory }); + return new Container(ctx); + }; + withSecretVariable = (name, secret) => { + const ctx = this._ctx.select("withSecretVariable", { name, secret }); + return new Container(ctx); + }; + withServiceBinding = (alias, service) => { + const ctx = this._ctx.select("withServiceBinding", { alias, service }); + return new Container(ctx); + }; + withSymlink = (target, linkName, opts) => { + const ctx = this._ctx.select("withSymlink", { target, linkName, ...opts }); + return new Container(ctx); + }; + withUnixSocket = (path, source, opts) => { + const ctx = this._ctx.select("withUnixSocket", { path, source, ...opts }); + return new Container(ctx); + }; + withUser = (name) => { + const ctx = this._ctx.select("withUser", { name }); + return new Container(ctx); + }; + withVolatileVariable = (name, value) => { + const ctx = this._ctx.select("withVolatileVariable", { name, value }); + return new Container(ctx); + }; + withWorkdir = (path, opts) => { + const ctx = this._ctx.select("withWorkdir", { path, ...opts }); + return new Container(ctx); + }; + withoutAnnotation = (name) => { + const ctx = this._ctx.select("withoutAnnotation", { name }); + return new Container(ctx); + }; + withoutDefaultArgs = () => { + const ctx = this._ctx.select("withoutDefaultArgs"); + return new Container(ctx); + }; + withoutDirectory = (path, opts) => { + const ctx = this._ctx.select("withoutDirectory", { path, ...opts }); + return new Container(ctx); + }; + withoutDockerHealthcheck = () => { + const ctx = this._ctx.select("withoutDockerHealthcheck"); + return new Container(ctx); + }; + withoutEntrypoint = (opts) => { + const ctx = this._ctx.select("withoutEntrypoint", { ...opts }); + return new Container(ctx); + }; + withoutEnvVariable = (name) => { + const ctx = this._ctx.select("withoutEnvVariable", { name }); + return new Container(ctx); + }; + withoutExposedPort = (port, opts) => { + const metadata = { + protocol: { is_enum: true, value_to_name: NetworkProtocolValueToName } + }; + const ctx = this._ctx.select("withoutExposedPort", { port, ...opts, __metadata: metadata }); + return new Container(ctx); + }; + withoutFile = (path, opts) => { + const ctx = this._ctx.select("withoutFile", { path, ...opts }); + return new Container(ctx); + }; + withoutFiles = (paths, opts) => { + const ctx = this._ctx.select("withoutFiles", { paths, ...opts }); + return new Container(ctx); + }; + withoutLabel = (name) => { + const ctx = this._ctx.select("withoutLabel", { name }); + return new Container(ctx); + }; + withoutMount = (path, opts) => { + const ctx = this._ctx.select("withoutMount", { path, ...opts }); + return new Container(ctx); + }; + withoutRegistryAuth = (address) => { + const ctx = this._ctx.select("withoutRegistryAuth", { address }); + return new Container(ctx); + }; + withoutSecretVariable = (name) => { + const ctx = this._ctx.select("withoutSecretVariable", { name }); + return new Container(ctx); + }; + withoutUnixSocket = (path, opts) => { + const ctx = this._ctx.select("withoutUnixSocket", { path, ...opts }); + return new Container(ctx); + }; + withoutUser = () => { + const ctx = this._ctx.select("withoutUser"); + return new Container(ctx); + }; + withoutVolatileVariable = (name) => { + const ctx = this._ctx.select("withoutVolatileVariable", { name }); + return new Container(ctx); + }; + withoutWorkdir = () => { + const ctx = this._ctx.select("withoutWorkdir"); + return new Container(ctx); + }; + workdir = async () => { + if (this._workdir) { + return this._workdir; + } + const ctx = this._ctx.select("workdir"); + const response = await ctx.execute(); + return response; + }; + with = (arg) => { + return arg(this); + }; +} + +class CurrentModule extends BaseClient { + _id = undefined; + _name = undefined; + constructor(ctx, _id, _name) { + super(ctx); + this._id = _id; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asSDK = (opts) => { + const ctx = this._ctx.select("asSDK", { ...opts }); + return new CurrentModuleAsSDK(ctx); + }; + dependencies = async () => { + const ctx = this._ctx.select("dependencies").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Module_(ctx.copy().selectNode(r.id, "Module"))); + }; + generatedContextDirectory = () => { + const ctx = this._ctx.select("generatedContextDirectory"); + return new Directory(ctx); + }; + generators = (opts) => { + const ctx = this._ctx.select("generators", { ...opts }); + return new GeneratorGroup(ctx); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + source = () => { + const ctx = this._ctx.select("source"); + return new Directory(ctx); + }; + workdir = (path, opts) => { + const ctx = this._ctx.select("workdir", { path, ...opts }); + return new Directory(ctx); + }; + workdirFile = (path) => { + const ctx = this._ctx.select("workdirFile", { path }); + return new File(ctx); + }; +} + +class CurrentModuleAsSDK extends BaseClient { + _id = undefined; + _name = undefined; + constructor(ctx, _id, _name) { + super(ctx); + this._id = _id; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + clients = async () => { + const ctx = this._ctx.select("clients").select("id"); + const response = await ctx.execute(); + return response.map((r) => new CurrentModuleAsSDKClient(ctx.copy().selectNode(r.id, "CurrentModuleAsSDKClient"))); + }; + modules = async () => { + const ctx = this._ctx.select("modules").select("id"); + const response = await ctx.execute(); + return response.map((r) => new CurrentModuleAsSDKModule(ctx.copy().selectNode(r.id, "CurrentModuleAsSDKModule"))); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; +} + +class CurrentModuleAsSDKClient extends BaseClient { + _id = undefined; + _module = undefined; + _path = undefined; + _pin = undefined; + constructor(ctx, _id, _module, _path, _pin) { + super(ctx); + this._id = _id; + this._module = _module; + this._path = _path; + this._pin = _pin; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + module_ = async () => { + if (this._module) { + return this._module; + } + const ctx = this._ctx.select("module"); + const response = await ctx.execute(); + return response; + }; + moduleSource = () => { + const ctx = this._ctx.select("moduleSource"); + return new ModuleSource(ctx); + }; + path = async () => { + if (this._path) { + return this._path; + } + const ctx = this._ctx.select("path"); + const response = await ctx.execute(); + return response; + }; + pin = async () => { + if (this._pin) { + return this._pin; + } + const ctx = this._ctx.select("pin"); + const response = await ctx.execute(); + return response; + }; +} + +class CurrentModuleAsSDKModule extends BaseClient { + _id = undefined; + _path = undefined; + constructor(ctx, _id, _path) { + super(ctx); + this._id = _id; + this._path = _path; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + path = async () => { + if (this._path) { + return this._path; + } + const ctx = this._ctx.select("path"); + const response = await ctx.execute(); + return response; + }; +} + +class DiffStat extends BaseClient { + _id = undefined; + _addedLines = undefined; + _kind = undefined; + _oldPath = undefined; + _path = undefined; + _removedLines = undefined; + constructor(ctx, _id, _addedLines, _kind, _oldPath, _path, _removedLines) { + super(ctx); + this._id = _id; + this._addedLines = _addedLines; + this._kind = _kind; + this._oldPath = _oldPath; + this._path = _path; + this._removedLines = _removedLines; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + addedLines = async () => { + if (this._addedLines) { + return this._addedLines; + } + const ctx = this._ctx.select("addedLines"); + const response = await ctx.execute(); + return response; + }; + kind = async () => { + if (this._kind) { + return this._kind; + } + const ctx = this._ctx.select("kind"); + const response = await ctx.execute(); + return DiffStatKindNameToValue(response); + }; + oldPath = async () => { + if (this._oldPath) { + return this._oldPath; + } + const ctx = this._ctx.select("oldPath"); + const response = await ctx.execute(); + return response; + }; + path = async () => { + if (this._path) { + return this._path; + } + const ctx = this._ctx.select("path"); + const response = await ctx.execute(); + return response; + }; + removedLines = async () => { + if (this._removedLines) { + return this._removedLines; + } + const ctx = this._ctx.select("removedLines"); + const response = await ctx.execute(); + return response; + }; +} + +class Directory extends BaseClient { + _id = undefined; + _digest = undefined; + _exists = undefined; + _export = undefined; + _findUp = undefined; + _name = undefined; + _sync = undefined; + constructor(ctx, _id, _digest, _exists, _export, _findUp, _name, _sync) { + super(ctx); + this._id = _id; + this._digest = _digest; + this._exists = _exists; + this._export = _export; + this._findUp = _findUp; + this._name = _name; + this._sync = _sync; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asGit = () => { + const ctx = this._ctx.select("asGit"); + return new GitRepository(ctx); + }; + asModule = (opts) => { + const ctx = this._ctx.select("asModule", { ...opts }); + return new Module_(ctx); + }; + asModuleSource = (opts) => { + const ctx = this._ctx.select("asModuleSource", { ...opts }); + return new ModuleSource(ctx); + }; + asWorkspace = (opts) => { + const ctx = this._ctx.select("asWorkspace", { ...opts }); + return new Workspace(ctx); + }; + changes = (from) => { + const ctx = this._ctx.select("changes", { from }); + return new Changeset(ctx); + }; + chown = (path, owner) => { + const ctx = this._ctx.select("chown", { path, owner }); + return new Directory(ctx); + }; + diff = (other) => { + const ctx = this._ctx.select("diff", { other }); + return new Directory(ctx); + }; + digest = async () => { + if (this._digest) { + return this._digest; + } + const ctx = this._ctx.select("digest"); + const response = await ctx.execute(); + return response; + }; + directory = (path) => { + const ctx = this._ctx.select("directory", { path }); + return new Directory(ctx); + }; + dockerBuild = (opts) => { + const ctx = this._ctx.select("dockerBuild", { ...opts }); + return new Container(ctx); + }; + entries = async (opts) => { + const ctx = this._ctx.select("entries", { ...opts }); + const response = await ctx.execute(); + return response; + }; + exists = async (path, opts) => { + if (this._exists) { + return this._exists; + } + const metadata = { + expectedType: { is_enum: true, value_to_name: ExistsTypeValueToName } + }; + const ctx = this._ctx.select("exists", { path, ...opts, __metadata: metadata }); + const response = await ctx.execute(); + return response; + }; + export = async (path, opts) => { + if (this._export) { + return this._export; + } + const ctx = this._ctx.select("export", { path, ...opts }); + const response = await ctx.execute(); + return response; + }; + file = (path) => { + const ctx = this._ctx.select("file", { path }); + return new File(ctx); + }; + filter = (opts) => { + const ctx = this._ctx.select("filter", { ...opts }); + return new Directory(ctx); + }; + findUp = async (name, start) => { + if (this._findUp) { + return this._findUp; + } + const ctx = this._ctx.select("findUp", { name, start }); + const response = await ctx.execute(); + return response; + }; + glob = async (pattern) => { + const ctx = this._ctx.select("glob", { pattern }); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + search = async (opts) => { + const ctx = this._ctx.select("search", { ...opts }).select("id"); + const response = await ctx.execute(); + return response.map((r) => new SearchResult(ctx.copy().selectNode(r.id, "SearchResult"))); + }; + stat = (path, opts) => { + const ctx = this._ctx.select("stat", { path, ...opts }); + return new Stat(ctx); + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new Directory(ctx.copy().selectNode(response, "Directory")); + }; + terminal = (opts) => { + const ctx = this._ctx.select("terminal", { ...opts }); + return new Directory(ctx); + }; + withChanges = (changes) => { + const ctx = this._ctx.select("withChanges", { changes }); + return new Directory(ctx); + }; + withDirectory = (path, source, opts) => { + const ctx = this._ctx.select("withDirectory", { path, source, ...opts }); + return new Directory(ctx); + }; + withError = (err) => { + const ctx = this._ctx.select("withError", { err }); + return new Directory(ctx); + }; + withFile = (path, source, opts) => { + const ctx = this._ctx.select("withFile", { path, source, ...opts }); + return new Directory(ctx); + }; + withFiles = (path, sources, opts) => { + const ctx = this._ctx.select("withFiles", { path, sources, ...opts }); + return new Directory(ctx); + }; + withNewDirectory = (path, opts) => { + const ctx = this._ctx.select("withNewDirectory", { path, ...opts }); + return new Directory(ctx); + }; + withNewFile = (path, contents, opts) => { + const ctx = this._ctx.select("withNewFile", { path, contents, ...opts }); + return new Directory(ctx); + }; + withPatch = (patch) => { + const ctx = this._ctx.select("withPatch", { patch }); + return new Directory(ctx); + }; + withPatchFile = (patch) => { + const ctx = this._ctx.select("withPatchFile", { patch }); + return new Directory(ctx); + }; + withSymlink = (target, linkName) => { + const ctx = this._ctx.select("withSymlink", { target, linkName }); + return new Directory(ctx); + }; + withTimestamps = (timestamp) => { + const ctx = this._ctx.select("withTimestamps", { timestamp }); + return new Directory(ctx); + }; + withoutDirectory = (path) => { + const ctx = this._ctx.select("withoutDirectory", { path }); + return new Directory(ctx); + }; + withoutFile = (path) => { + const ctx = this._ctx.select("withoutFile", { path }); + return new Directory(ctx); + }; + withoutFiles = (paths) => { + const ctx = this._ctx.select("withoutFiles", { paths }); + return new Directory(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class Engine extends BaseClient { + _id = undefined; + _name = undefined; + constructor(ctx, _id, _name) { + super(ctx); + this._id = _id; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + clients = async () => { + const ctx = this._ctx.select("clients"); + const response = await ctx.execute(); + return response; + }; + localCache = () => { + const ctx = this._ctx.select("localCache"); + return new EngineCache(ctx); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; +} + +class EngineCache extends BaseClient { + _id = undefined; + _maxUsedSpace = undefined; + _minFreeSpace = undefined; + _prune = undefined; + _reservedSpace = undefined; + _targetSpace = undefined; + constructor(ctx, _id, _maxUsedSpace, _minFreeSpace, _prune, _reservedSpace, _targetSpace) { + super(ctx); + this._id = _id; + this._maxUsedSpace = _maxUsedSpace; + this._minFreeSpace = _minFreeSpace; + this._prune = _prune; + this._reservedSpace = _reservedSpace; + this._targetSpace = _targetSpace; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + entrySet = (opts) => { + const ctx = this._ctx.select("entrySet", { ...opts }); + return new EngineCacheEntrySet(ctx); + }; + maxUsedSpace = async () => { + if (this._maxUsedSpace) { + return this._maxUsedSpace; + } + const ctx = this._ctx.select("maxUsedSpace"); + const response = await ctx.execute(); + return response; + }; + minFreeSpace = async () => { + if (this._minFreeSpace) { + return this._minFreeSpace; + } + const ctx = this._ctx.select("minFreeSpace"); + const response = await ctx.execute(); + return response; + }; + prune = async (opts) => { + if (this._prune) { + return; + } + const ctx = this._ctx.select("prune", { ...opts }); + await ctx.execute(); + }; + reservedSpace = async () => { + if (this._reservedSpace) { + return this._reservedSpace; + } + const ctx = this._ctx.select("reservedSpace"); + const response = await ctx.execute(); + return response; + }; + targetSpace = async () => { + if (this._targetSpace) { + return this._targetSpace; + } + const ctx = this._ctx.select("targetSpace"); + const response = await ctx.execute(); + return response; + }; +} + +class EngineCacheEntry extends BaseClient { + _id = undefined; + _activelyUsed = undefined; + _createdTimeUnixNano = undefined; + _dagqlCall = undefined; + _description = undefined; + _diskSpaceBytes = undefined; + _mostRecentUseTimeUnixNano = undefined; + _recordType = undefined; + constructor(ctx, _id, _activelyUsed, _createdTimeUnixNano, _dagqlCall, _description, _diskSpaceBytes, _mostRecentUseTimeUnixNano, _recordType) { + super(ctx); + this._id = _id; + this._activelyUsed = _activelyUsed; + this._createdTimeUnixNano = _createdTimeUnixNano; + this._dagqlCall = _dagqlCall; + this._description = _description; + this._diskSpaceBytes = _diskSpaceBytes; + this._mostRecentUseTimeUnixNano = _mostRecentUseTimeUnixNano; + this._recordType = _recordType; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + activelyUsed = async () => { + if (this._activelyUsed) { + return this._activelyUsed; + } + const ctx = this._ctx.select("activelyUsed"); + const response = await ctx.execute(); + return response; + }; + createdTimeUnixNano = async () => { + if (this._createdTimeUnixNano) { + return this._createdTimeUnixNano; + } + const ctx = this._ctx.select("createdTimeUnixNano"); + const response = await ctx.execute(); + return response; + }; + dagqlCall = async () => { + if (this._dagqlCall) { + return this._dagqlCall; + } + const ctx = this._ctx.select("dagqlCall"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + diskSpaceBytes = async () => { + if (this._diskSpaceBytes) { + return this._diskSpaceBytes; + } + const ctx = this._ctx.select("diskSpaceBytes"); + const response = await ctx.execute(); + return response; + }; + mostRecentUseTimeUnixNano = async () => { + if (this._mostRecentUseTimeUnixNano) { + return this._mostRecentUseTimeUnixNano; + } + const ctx = this._ctx.select("mostRecentUseTimeUnixNano"); + const response = await ctx.execute(); + return response; + }; + recordType = async () => { + if (this._recordType) { + return this._recordType; + } + const ctx = this._ctx.select("recordType"); + const response = await ctx.execute(); + return response; + }; + recordTypes = async () => { + const ctx = this._ctx.select("recordTypes"); + const response = await ctx.execute(); + return response; + }; +} + +class EngineCacheEntrySet extends BaseClient { + _id = undefined; + _diskSpaceBytes = undefined; + _entryCount = undefined; + constructor(ctx, _id, _diskSpaceBytes, _entryCount) { + super(ctx); + this._id = _id; + this._diskSpaceBytes = _diskSpaceBytes; + this._entryCount = _entryCount; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + diskSpaceBytes = async () => { + if (this._diskSpaceBytes) { + return this._diskSpaceBytes; + } + const ctx = this._ctx.select("diskSpaceBytes"); + const response = await ctx.execute(); + return response; + }; + entries = async () => { + const ctx = this._ctx.select("entries").select("id"); + const response = await ctx.execute(); + return response.map((r) => new EngineCacheEntry(ctx.copy().selectNode(r.id, "EngineCacheEntry"))); + }; + entryCount = async () => { + if (this._entryCount) { + return this._entryCount; + } + const ctx = this._ctx.select("entryCount"); + const response = await ctx.execute(); + return response; + }; +} + +class EnumTypeDef extends BaseClient { + _id = undefined; + _description = undefined; + _name = undefined; + _sourceModuleName = undefined; + constructor(ctx, _id, _description, _name, _sourceModuleName) { + super(ctx); + this._id = _id; + this._description = _description; + this._name = _name; + this._sourceModuleName = _sourceModuleName; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + members = async () => { + const ctx = this._ctx.select("members").select("id"); + const response = await ctx.execute(); + return response.map((r) => new EnumValueTypeDef(ctx.copy().selectNode(r.id, "EnumValueTypeDef"))); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + sourceMap = () => { + const ctx = this._ctx.select("sourceMap"); + return new SourceMap(ctx); + }; + sourceModuleName = async () => { + if (this._sourceModuleName) { + return this._sourceModuleName; + } + const ctx = this._ctx.select("sourceModuleName"); + const response = await ctx.execute(); + return response; + }; + values = async () => { + const ctx = this._ctx.select("values").select("id"); + const response = await ctx.execute(); + return response.map((r) => new EnumValueTypeDef(ctx.copy().selectNode(r.id, "EnumValueTypeDef"))); + }; +} + +class EnumValueTypeDef extends BaseClient { + _id = undefined; + _deprecated = undefined; + _description = undefined; + _name = undefined; + _value = undefined; + constructor(ctx, _id, _deprecated, _description, _name, _value) { + super(ctx); + this._id = _id; + this._deprecated = _deprecated; + this._description = _description; + this._name = _name; + this._value = _value; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + deprecated = async () => { + if (this._deprecated) { + return this._deprecated; + } + const ctx = this._ctx.select("deprecated"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + sourceMap = () => { + const ctx = this._ctx.select("sourceMap"); + return new SourceMap(ctx); + }; + value = async () => { + if (this._value) { + return this._value; + } + const ctx = this._ctx.select("value"); + const response = await ctx.execute(); + return response; + }; +} + +class Env extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + check = (name) => { + const ctx = this._ctx.select("check", { name }); + return new Check(ctx); + }; + checks = (opts) => { + const ctx = this._ctx.select("checks", { ...opts }); + return new CheckGroup(ctx); + }; + input = (name) => { + const ctx = this._ctx.select("input", { name }); + return new Binding(ctx); + }; + inputs = async () => { + const ctx = this._ctx.select("inputs").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Binding(ctx.copy().selectNode(r.id, "Binding"))); + }; + output = (name) => { + const ctx = this._ctx.select("output", { name }); + return new Binding(ctx); + }; + outputs = async () => { + const ctx = this._ctx.select("outputs").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Binding(ctx.copy().selectNode(r.id, "Binding"))); + }; + services = (opts) => { + const ctx = this._ctx.select("services", { ...opts }); + return new UpGroup(ctx); + }; + withAddressInput = (name, value, description) => { + const ctx = this._ctx.select("withAddressInput", { name, value, description }); + return new Env(ctx); + }; + withAddressOutput = (name, description) => { + const ctx = this._ctx.select("withAddressOutput", { name, description }); + return new Env(ctx); + }; + withCacheVolumeInput = (name, value, description) => { + const ctx = this._ctx.select("withCacheVolumeInput", { name, value, description }); + return new Env(ctx); + }; + withCacheVolumeOutput = (name, description) => { + const ctx = this._ctx.select("withCacheVolumeOutput", { name, description }); + return new Env(ctx); + }; + withChangesetInput = (name, value, description) => { + const ctx = this._ctx.select("withChangesetInput", { name, value, description }); + return new Env(ctx); + }; + withChangesetOutput = (name, description) => { + const ctx = this._ctx.select("withChangesetOutput", { name, description }); + return new Env(ctx); + }; + withCheckGroupInput = (name, value, description) => { + const ctx = this._ctx.select("withCheckGroupInput", { name, value, description }); + return new Env(ctx); + }; + withCheckGroupOutput = (name, description) => { + const ctx = this._ctx.select("withCheckGroupOutput", { name, description }); + return new Env(ctx); + }; + withCheckInput = (name, value, description) => { + const ctx = this._ctx.select("withCheckInput", { name, value, description }); + return new Env(ctx); + }; + withCheckOutput = (name, description) => { + const ctx = this._ctx.select("withCheckOutput", { name, description }); + return new Env(ctx); + }; + withCloudInput = (name, value, description) => { + const ctx = this._ctx.select("withCloudInput", { name, value, description }); + return new Env(ctx); + }; + withCloudOutput = (name, description) => { + const ctx = this._ctx.select("withCloudOutput", { name, description }); + return new Env(ctx); + }; + withContainerInput = (name, value, description) => { + const ctx = this._ctx.select("withContainerInput", { name, value, description }); + return new Env(ctx); + }; + withContainerOutput = (name, description) => { + const ctx = this._ctx.select("withContainerOutput", { name, description }); + return new Env(ctx); + }; + withCurrentModule = () => { + const ctx = this._ctx.select("withCurrentModule"); + return new Env(ctx); + }; + withCurrentModuleAsSDKClientInput = (name, value, description) => { + const ctx = this._ctx.select("withCurrentModuleAsSDKClientInput", { name, value, description }); + return new Env(ctx); + }; + withCurrentModuleAsSDKClientOutput = (name, description) => { + const ctx = this._ctx.select("withCurrentModuleAsSDKClientOutput", { name, description }); + return new Env(ctx); + }; + withCurrentModuleAsSDKInput = (name, value, description) => { + const ctx = this._ctx.select("withCurrentModuleAsSDKInput", { name, value, description }); + return new Env(ctx); + }; + withCurrentModuleAsSDKModuleInput = (name, value, description) => { + const ctx = this._ctx.select("withCurrentModuleAsSDKModuleInput", { name, value, description }); + return new Env(ctx); + }; + withCurrentModuleAsSDKModuleOutput = (name, description) => { + const ctx = this._ctx.select("withCurrentModuleAsSDKModuleOutput", { name, description }); + return new Env(ctx); + }; + withCurrentModuleAsSDKOutput = (name, description) => { + const ctx = this._ctx.select("withCurrentModuleAsSDKOutput", { name, description }); + return new Env(ctx); + }; + withDiffStatInput = (name, value, description) => { + const ctx = this._ctx.select("withDiffStatInput", { name, value, description }); + return new Env(ctx); + }; + withDiffStatOutput = (name, description) => { + const ctx = this._ctx.select("withDiffStatOutput", { name, description }); + return new Env(ctx); + }; + withDirectoryInput = (name, value, description) => { + const ctx = this._ctx.select("withDirectoryInput", { name, value, description }); + return new Env(ctx); + }; + withDirectoryOutput = (name, description) => { + const ctx = this._ctx.select("withDirectoryOutput", { name, description }); + return new Env(ctx); + }; + withEnvFileInput = (name, value, description) => { + const ctx = this._ctx.select("withEnvFileInput", { name, value, description }); + return new Env(ctx); + }; + withEnvFileOutput = (name, description) => { + const ctx = this._ctx.select("withEnvFileOutput", { name, description }); + return new Env(ctx); + }; + withEnvInput = (name, value, description) => { + const ctx = this._ctx.select("withEnvInput", { name, value, description }); + return new Env(ctx); + }; + withEnvOutput = (name, description) => { + const ctx = this._ctx.select("withEnvOutput", { name, description }); + return new Env(ctx); + }; + withFileInput = (name, value, description) => { + const ctx = this._ctx.select("withFileInput", { name, value, description }); + return new Env(ctx); + }; + withFileOutput = (name, description) => { + const ctx = this._ctx.select("withFileOutput", { name, description }); + return new Env(ctx); + }; + withGeneratorGroupInput = (name, value, description) => { + const ctx = this._ctx.select("withGeneratorGroupInput", { name, value, description }); + return new Env(ctx); + }; + withGeneratorGroupOutput = (name, description) => { + const ctx = this._ctx.select("withGeneratorGroupOutput", { name, description }); + return new Env(ctx); + }; + withGeneratorInput = (name, value, description) => { + const ctx = this._ctx.select("withGeneratorInput", { name, value, description }); + return new Env(ctx); + }; + withGeneratorOutput = (name, description) => { + const ctx = this._ctx.select("withGeneratorOutput", { name, description }); + return new Env(ctx); + }; + withGitRefInput = (name, value, description) => { + const ctx = this._ctx.select("withGitRefInput", { name, value, description }); + return new Env(ctx); + }; + withGitRefOutput = (name, description) => { + const ctx = this._ctx.select("withGitRefOutput", { name, description }); + return new Env(ctx); + }; + withGitRepositoryInput = (name, value, description) => { + const ctx = this._ctx.select("withGitRepositoryInput", { name, value, description }); + return new Env(ctx); + }; + withGitRepositoryOutput = (name, description) => { + const ctx = this._ctx.select("withGitRepositoryOutput", { name, description }); + return new Env(ctx); + }; + withHTTPStateInput = (name, value, description) => { + const ctx = this._ctx.select("withHTTPStateInput", { name, value, description }); + return new Env(ctx); + }; + withHTTPStateOutput = (name, description) => { + const ctx = this._ctx.select("withHTTPStateOutput", { name, description }); + return new Env(ctx); + }; + withJSONValueInput = (name, value, description) => { + const ctx = this._ctx.select("withJSONValueInput", { name, value, description }); + return new Env(ctx); + }; + withJSONValueOutput = (name, description) => { + const ctx = this._ctx.select("withJSONValueOutput", { name, description }); + return new Env(ctx); + }; + withLLMContentBlockInput = (name, value, description) => { + const ctx = this._ctx.select("withLLMContentBlockInput", { name, value, description }); + return new Env(ctx); + }; + withLLMContentBlockOutput = (name, description) => { + const ctx = this._ctx.select("withLLMContentBlockOutput", { name, description }); + return new Env(ctx); + }; + withLLMMessageInput = (name, value, description) => { + const ctx = this._ctx.select("withLLMMessageInput", { name, value, description }); + return new Env(ctx); + }; + withLLMMessageOutput = (name, description) => { + const ctx = this._ctx.select("withLLMMessageOutput", { name, description }); + return new Env(ctx); + }; + withMainModule = (module_) => { + const ctx = this._ctx.select("withMainModule", { + module: module_ + }); + return new Env(ctx); + }; + withModule = (module_) => { + const ctx = this._ctx.select("withModule", { + module: module_ + }); + return new Env(ctx); + }; + withModuleConfigClientInput = (name, value, description) => { + const ctx = this._ctx.select("withModuleConfigClientInput", { name, value, description }); + return new Env(ctx); + }; + withModuleConfigClientOutput = (name, description) => { + const ctx = this._ctx.select("withModuleConfigClientOutput", { name, description }); + return new Env(ctx); + }; + withModuleInput = (name, value, description) => { + const ctx = this._ctx.select("withModuleInput", { name, value, description }); + return new Env(ctx); + }; + withModuleOutput = (name, description) => { + const ctx = this._ctx.select("withModuleOutput", { name, description }); + return new Env(ctx); + }; + withModuleSourceInput = (name, value, description) => { + const ctx = this._ctx.select("withModuleSourceInput", { name, value, description }); + return new Env(ctx); + }; + withModuleSourceOutput = (name, description) => { + const ctx = this._ctx.select("withModuleSourceOutput", { name, description }); + return new Env(ctx); + }; + withSchemaInput = (name, value, description) => { + const ctx = this._ctx.select("withSchemaInput", { name, value, description }); + return new Env(ctx); + }; + withSchemaOutput = (name, description) => { + const ctx = this._ctx.select("withSchemaOutput", { name, description }); + return new Env(ctx); + }; + withSearchResultInput = (name, value, description) => { + const ctx = this._ctx.select("withSearchResultInput", { name, value, description }); + return new Env(ctx); + }; + withSearchResultOutput = (name, description) => { + const ctx = this._ctx.select("withSearchResultOutput", { name, description }); + return new Env(ctx); + }; + withSearchSubmatchInput = (name, value, description) => { + const ctx = this._ctx.select("withSearchSubmatchInput", { name, value, description }); + return new Env(ctx); + }; + withSearchSubmatchOutput = (name, description) => { + const ctx = this._ctx.select("withSearchSubmatchOutput", { name, description }); + return new Env(ctx); + }; + withSecretInput = (name, value, description) => { + const ctx = this._ctx.select("withSecretInput", { name, value, description }); + return new Env(ctx); + }; + withSecretOutput = (name, description) => { + const ctx = this._ctx.select("withSecretOutput", { name, description }); + return new Env(ctx); + }; + withServiceInput = (name, value, description) => { + const ctx = this._ctx.select("withServiceInput", { name, value, description }); + return new Env(ctx); + }; + withServiceOutput = (name, description) => { + const ctx = this._ctx.select("withServiceOutput", { name, description }); + return new Env(ctx); + }; + withSocketInput = (name, value, description) => { + const ctx = this._ctx.select("withSocketInput", { name, value, description }); + return new Env(ctx); + }; + withSocketOutput = (name, description) => { + const ctx = this._ctx.select("withSocketOutput", { name, description }); + return new Env(ctx); + }; + withStatInput = (name, value, description) => { + const ctx = this._ctx.select("withStatInput", { name, value, description }); + return new Env(ctx); + }; + withStatOutput = (name, description) => { + const ctx = this._ctx.select("withStatOutput", { name, description }); + return new Env(ctx); + }; + withStringInput = (name, value, description) => { + const ctx = this._ctx.select("withStringInput", { name, value, description }); + return new Env(ctx); + }; + withStringOutput = (name, description) => { + const ctx = this._ctx.select("withStringOutput", { name, description }); + return new Env(ctx); + }; + withUpGroupInput = (name, value, description) => { + const ctx = this._ctx.select("withUpGroupInput", { name, value, description }); + return new Env(ctx); + }; + withUpGroupOutput = (name, description) => { + const ctx = this._ctx.select("withUpGroupOutput", { name, description }); + return new Env(ctx); + }; + withUpInput = (name, value, description) => { + const ctx = this._ctx.select("withUpInput", { name, value, description }); + return new Env(ctx); + }; + withUpOutput = (name, description) => { + const ctx = this._ctx.select("withUpOutput", { name, description }); + return new Env(ctx); + }; + withVolumeInput = (name, value, description) => { + const ctx = this._ctx.select("withVolumeInput", { name, value, description }); + return new Env(ctx); + }; + withVolumeOutput = (name, description) => { + const ctx = this._ctx.select("withVolumeOutput", { name, description }); + return new Env(ctx); + }; + withWorkspace = (workspace) => { + const ctx = this._ctx.select("withWorkspace", { workspace }); + return new Env(ctx); + }; + withWorkspaceGitInput = (name, value, description) => { + const ctx = this._ctx.select("withWorkspaceGitInput", { name, value, description }); + return new Env(ctx); + }; + withWorkspaceGitOutput = (name, description) => { + const ctx = this._ctx.select("withWorkspaceGitOutput", { name, description }); + return new Env(ctx); + }; + withWorkspaceInput = (name, value, description) => { + const ctx = this._ctx.select("withWorkspaceInput", { name, value, description }); + return new Env(ctx); + }; + withWorkspaceMigrationInput = (name, value, description) => { + const ctx = this._ctx.select("withWorkspaceMigrationInput", { name, value, description }); + return new Env(ctx); + }; + withWorkspaceMigrationOutput = (name, description) => { + const ctx = this._ctx.select("withWorkspaceMigrationOutput", { name, description }); + return new Env(ctx); + }; + withWorkspaceMigrationStepInput = (name, value, description) => { + const ctx = this._ctx.select("withWorkspaceMigrationStepInput", { name, value, description }); + return new Env(ctx); + }; + withWorkspaceMigrationStepOutput = (name, description) => { + const ctx = this._ctx.select("withWorkspaceMigrationStepOutput", { name, description }); + return new Env(ctx); + }; + withWorkspaceModuleInput = (name, value, description) => { + const ctx = this._ctx.select("withWorkspaceModuleInput", { name, value, description }); + return new Env(ctx); + }; + withWorkspaceModuleOutput = (name, description) => { + const ctx = this._ctx.select("withWorkspaceModuleOutput", { name, description }); + return new Env(ctx); + }; + withWorkspaceModuleSettingInput = (name, value, description) => { + const ctx = this._ctx.select("withWorkspaceModuleSettingInput", { name, value, description }); + return new Env(ctx); + }; + withWorkspaceModuleSettingOutput = (name, description) => { + const ctx = this._ctx.select("withWorkspaceModuleSettingOutput", { name, description }); + return new Env(ctx); + }; + withWorkspaceOutput = (name, description) => { + const ctx = this._ctx.select("withWorkspaceOutput", { name, description }); + return new Env(ctx); + }; + withWorkspaceSDKInput = (name, value, description) => { + const ctx = this._ctx.select("withWorkspaceSDKInput", { name, value, description }); + return new Env(ctx); + }; + withWorkspaceSDKOutput = (name, description) => { + const ctx = this._ctx.select("withWorkspaceSDKOutput", { name, description }); + return new Env(ctx); + }; + withoutOutputs = () => { + const ctx = this._ctx.select("withoutOutputs"); + return new Env(ctx); + }; + workspace = () => { + const ctx = this._ctx.select("workspace"); + return new Directory(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class EnvFile extends BaseClient { + _id = undefined; + _exists = undefined; + _get = undefined; + constructor(ctx, _id, _exists, _get) { + super(ctx); + this._id = _id; + this._exists = _exists; + this._get = _get; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asFile = () => { + const ctx = this._ctx.select("asFile"); + return new File(ctx); + }; + exists = async (name) => { + if (this._exists) { + return this._exists; + } + const ctx = this._ctx.select("exists", { name }); + const response = await ctx.execute(); + return response; + }; + get = async (name, opts) => { + if (this._get) { + return this._get; + } + const ctx = this._ctx.select("get", { name, ...opts }); + const response = await ctx.execute(); + return response; + }; + namespace_ = (prefix) => { + const ctx = this._ctx.select("namespace", { prefix }); + return new EnvFile(ctx); + }; + variables = async (opts) => { + const ctx = this._ctx.select("variables", { ...opts }).select("id"); + const response = await ctx.execute(); + return response.map((r) => new EnvVariable(ctx.copy().selectNode(r.id, "EnvVariable"))); + }; + withVariable = (name, value) => { + const ctx = this._ctx.select("withVariable", { name, value }); + return new EnvFile(ctx); + }; + withoutVariable = (name) => { + const ctx = this._ctx.select("withoutVariable", { name }); + return new EnvFile(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class EnvVariable extends BaseClient { + _id = undefined; + _name = undefined; + _value = undefined; + constructor(ctx, _id, _name, _value) { + super(ctx); + this._id = _id; + this._name = _name; + this._value = _value; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + value = async () => { + if (this._value) { + return this._value; + } + const ctx = this._ctx.select("value"); + const response = await ctx.execute(); + return response; + }; +} + +class Error2 extends BaseClient { + _id = undefined; + _message = undefined; + constructor(ctx, _id, _message) { + super(ctx); + this._id = _id; + this._message = _message; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + message = async () => { + if (this._message) { + return this._message; + } + const ctx = this._ctx.select("message"); + const response = await ctx.execute(); + return response; + }; + values = async () => { + const ctx = this._ctx.select("values").select("id"); + const response = await ctx.execute(); + return response.map((r) => new ErrorValue(ctx.copy().selectNode(r.id, "ErrorValue"))); + }; + withValue = (name, value) => { + const ctx = this._ctx.select("withValue", { name, value }); + return new Error2(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class ErrorValue extends BaseClient { + _id = undefined; + _name = undefined; + _value = undefined; + constructor(ctx, _id, _name, _value) { + super(ctx); + this._id = _id; + this._name = _name; + this._value = _value; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + value = async () => { + if (this._value) { + return this._value; + } + const ctx = this._ctx.select("value"); + const response = await ctx.execute(); + return response; + }; +} + +class _ExportableClient extends BaseClient { + _id = undefined; + _export = undefined; + constructor(ctx, _id, _export) { + super(ctx); + this._id = _id; + this._export = _export; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + export = async (path) => { + if (this._export) { + return this._export; + } + const ctx = this._ctx.select("export", { path }); + const response = await ctx.execute(); + return response; + }; +} + +class FieldTypeDef extends BaseClient { + _id = undefined; + _deprecated = undefined; + _description = undefined; + _name = undefined; + constructor(ctx, _id, _deprecated, _description, _name) { + super(ctx); + this._id = _id; + this._deprecated = _deprecated; + this._description = _description; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + deprecated = async () => { + if (this._deprecated) { + return this._deprecated; + } + const ctx = this._ctx.select("deprecated"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + sourceMap = () => { + const ctx = this._ctx.select("sourceMap"); + return new SourceMap(ctx); + }; + typeDef = () => { + const ctx = this._ctx.select("typeDef"); + return new TypeDef(ctx); + }; +} + +class File extends BaseClient { + _id = undefined; + _contents = undefined; + _digest = undefined; + _export = undefined; + _name = undefined; + _size = undefined; + _sync = undefined; + constructor(ctx, _id, _contents, _digest, _export, _name, _size, _sync) { + super(ctx); + this._id = _id; + this._contents = _contents; + this._digest = _digest; + this._export = _export; + this._name = _name; + this._size = _size; + this._sync = _sync; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asEnvFile = (opts) => { + const ctx = this._ctx.select("asEnvFile", { ...opts }); + return new EnvFile(ctx); + }; + asJSON = () => { + const ctx = this._ctx.select("asJSON"); + return new JSONValue(ctx); + }; + chown = (owner) => { + const ctx = this._ctx.select("chown", { owner }); + return new File(ctx); + }; + contents = async (opts) => { + if (this._contents) { + return this._contents; + } + const ctx = this._ctx.select("contents", { ...opts }); + const response = await ctx.execute(); + return response; + }; + digest = async (opts) => { + if (this._digest) { + return this._digest; + } + const ctx = this._ctx.select("digest", { ...opts }); + const response = await ctx.execute(); + return response; + }; + export = async (path, opts) => { + if (this._export) { + return this._export; + } + const ctx = this._ctx.select("export", { path, ...opts }); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + search = async (pattern, opts) => { + const ctx = this._ctx.select("search", { pattern, ...opts }).select("id"); + const response = await ctx.execute(); + return response.map((r) => new SearchResult(ctx.copy().selectNode(r.id, "SearchResult"))); + }; + size = async () => { + if (this._size) { + return this._size; + } + const ctx = this._ctx.select("size"); + const response = await ctx.execute(); + return response; + }; + stat = () => { + const ctx = this._ctx.select("stat"); + return new Stat(ctx); + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new File(ctx.copy().selectNode(response, "File")); + }; + withName = (name) => { + const ctx = this._ctx.select("withName", { name }); + return new File(ctx); + }; + withReplaced = (search, replacement, opts) => { + const ctx = this._ctx.select("withReplaced", { search, replacement, ...opts }); + return new File(ctx); + }; + withTimestamps = (timestamp) => { + const ctx = this._ctx.select("withTimestamps", { timestamp }); + return new File(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class Function_ extends BaseClient { + _id = undefined; + _deprecated = undefined; + _description = undefined; + _name = undefined; + _sourceModuleName = undefined; + constructor(ctx, _id, _deprecated, _description, _name, _sourceModuleName) { + super(ctx); + this._id = _id; + this._deprecated = _deprecated; + this._description = _description; + this._name = _name; + this._sourceModuleName = _sourceModuleName; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + args = async () => { + const ctx = this._ctx.select("args").select("id"); + const response = await ctx.execute(); + return response.map((r) => new FunctionArg(ctx.copy().selectNode(r.id, "FunctionArg"))); + }; + deprecated = async () => { + if (this._deprecated) { + return this._deprecated; + } + const ctx = this._ctx.select("deprecated"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + returnType = () => { + const ctx = this._ctx.select("returnType"); + return new TypeDef(ctx); + }; + sourceMap = () => { + const ctx = this._ctx.select("sourceMap"); + return new SourceMap(ctx); + }; + sourceModuleName = async () => { + if (this._sourceModuleName) { + return this._sourceModuleName; + } + const ctx = this._ctx.select("sourceModuleName"); + const response = await ctx.execute(); + return response; + }; + withArg = (name, typeDef, opts) => { + const ctx = this._ctx.select("withArg", { name, typeDef, ...opts }); + return new Function_(ctx); + }; + withCachePolicy = (policy, opts) => { + const metadata = { + policy: { is_enum: true, value_to_name: FunctionCachePolicyValueToName } + }; + const ctx = this._ctx.select("withCachePolicy", { policy, ...opts, __metadata: metadata }); + return new Function_(ctx); + }; + withCheck = () => { + const ctx = this._ctx.select("withCheck"); + return new Function_(ctx); + }; + withDeprecated = (opts) => { + const ctx = this._ctx.select("withDeprecated", { ...opts }); + return new Function_(ctx); + }; + withDescription = (description) => { + const ctx = this._ctx.select("withDescription", { description }); + return new Function_(ctx); + }; + withGenerator = () => { + const ctx = this._ctx.select("withGenerator"); + return new Function_(ctx); + }; + withSourceMap = (sourceMap) => { + const ctx = this._ctx.select("withSourceMap", { sourceMap }); + return new Function_(ctx); + }; + withUp = () => { + const ctx = this._ctx.select("withUp"); + return new Function_(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class FunctionArg extends BaseClient { + _id = undefined; + _defaultAddress = undefined; + _defaultPath = undefined; + _defaultValue = undefined; + _deprecated = undefined; + _description = undefined; + _name = undefined; + constructor(ctx, _id, _defaultAddress, _defaultPath, _defaultValue, _deprecated, _description, _name) { + super(ctx); + this._id = _id; + this._defaultAddress = _defaultAddress; + this._defaultPath = _defaultPath; + this._defaultValue = _defaultValue; + this._deprecated = _deprecated; + this._description = _description; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + defaultAddress = async () => { + if (this._defaultAddress) { + return this._defaultAddress; + } + const ctx = this._ctx.select("defaultAddress"); + const response = await ctx.execute(); + return response; + }; + defaultPath = async () => { + if (this._defaultPath) { + return this._defaultPath; + } + const ctx = this._ctx.select("defaultPath"); + const response = await ctx.execute(); + return response; + }; + defaultValue = async () => { + if (this._defaultValue) { + return this._defaultValue; + } + const ctx = this._ctx.select("defaultValue"); + const response = await ctx.execute(); + return response; + }; + deprecated = async () => { + if (this._deprecated) { + return this._deprecated; + } + const ctx = this._ctx.select("deprecated"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + ignore = async () => { + const ctx = this._ctx.select("ignore"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + sourceMap = () => { + const ctx = this._ctx.select("sourceMap"); + return new SourceMap(ctx); + }; + typeDef = () => { + const ctx = this._ctx.select("typeDef"); + return new TypeDef(ctx); + }; +} + +class FunctionCall extends BaseClient { + _id = undefined; + _name = undefined; + _parent = undefined; + _parentName = undefined; + _returnError = undefined; + _returnValue = undefined; + constructor(ctx, _id, _name, _parent, _parentName, _returnError, _returnValue) { + super(ctx); + this._id = _id; + this._name = _name; + this._parent = _parent; + this._parentName = _parentName; + this._returnError = _returnError; + this._returnValue = _returnValue; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + inputArgs = async () => { + const ctx = this._ctx.select("inputArgs").select("id"); + const response = await ctx.execute(); + return response.map((r) => new FunctionCallArgValue(ctx.copy().selectNode(r.id, "FunctionCallArgValue"))); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + parent = async () => { + if (this._parent) { + return this._parent; + } + const ctx = this._ctx.select("parent"); + const response = await ctx.execute(); + return response; + }; + parentName = async () => { + if (this._parentName) { + return this._parentName; + } + const ctx = this._ctx.select("parentName"); + const response = await ctx.execute(); + return response; + }; + returnError = async (error) => { + if (this._returnError) { + return; + } + const ctx = this._ctx.select("returnError", { error }); + await ctx.execute(); + }; + returnValue = async (value) => { + if (this._returnValue) { + return; + } + const ctx = this._ctx.select("returnValue", { value }); + await ctx.execute(); + }; +} + +class FunctionCallArgValue extends BaseClient { + _id = undefined; + _name = undefined; + _value = undefined; + constructor(ctx, _id, _name, _value) { + super(ctx); + this._id = _id; + this._name = _name; + this._value = _value; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + value = async () => { + if (this._value) { + return this._value; + } + const ctx = this._ctx.select("value"); + const response = await ctx.execute(); + return response; + }; +} + +class GeneratedCode extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + code = () => { + const ctx = this._ctx.select("code"); + return new Directory(ctx); + }; + vcsGeneratedPaths = async () => { + const ctx = this._ctx.select("vcsGeneratedPaths"); + const response = await ctx.execute(); + return response; + }; + vcsIgnoredPaths = async () => { + const ctx = this._ctx.select("vcsIgnoredPaths"); + const response = await ctx.execute(); + return response; + }; + withVCSGeneratedPaths = (paths) => { + const ctx = this._ctx.select("withVCSGeneratedPaths", { paths }); + return new GeneratedCode(ctx); + }; + withVCSIgnoredPaths = (paths) => { + const ctx = this._ctx.select("withVCSIgnoredPaths", { paths }); + return new GeneratedCode(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class Generator extends BaseClient { + _id = undefined; + _completed = undefined; + _description = undefined; + _isEmpty = undefined; + _name = undefined; + constructor(ctx, _id, _completed, _description, _isEmpty, _name) { + super(ctx); + this._id = _id; + this._completed = _completed; + this._description = _description; + this._isEmpty = _isEmpty; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + changes = () => { + const ctx = this._ctx.select("changes"); + return new Changeset(ctx); + }; + completed = async () => { + if (this._completed) { + return this._completed; + } + const ctx = this._ctx.select("completed"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + isEmpty = async () => { + if (this._isEmpty) { + return this._isEmpty; + } + const ctx = this._ctx.select("isEmpty"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + originalModule = () => { + const ctx = this._ctx.select("originalModule"); + return new Module_(ctx); + }; + path = async () => { + const ctx = this._ctx.select("path"); + const response = await ctx.execute(); + return response; + }; + run = () => { + const ctx = this._ctx.select("run"); + return new Generator(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class GeneratorGroup extends BaseClient { + _id = undefined; + _isEmpty = undefined; + constructor(ctx, _id, _isEmpty) { + super(ctx); + this._id = _id; + this._isEmpty = _isEmpty; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + changes = (opts) => { + const metadata = { + onConflict: { is_enum: true, value_to_name: ChangesetsMergeConflictValueToName } + }; + const ctx = this._ctx.select("changes", { ...opts, __metadata: metadata }); + return new Changeset(ctx); + }; + isEmpty = async () => { + if (this._isEmpty) { + return this._isEmpty; + } + const ctx = this._ctx.select("isEmpty"); + const response = await ctx.execute(); + return response; + }; + list = async () => { + const ctx = this._ctx.select("list").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Generator(ctx.copy().selectNode(r.id, "Generator"))); + }; + loadFailures = async () => { + const ctx = this._ctx.select("loadFailures"); + const response = await ctx.execute(); + return response; + }; + run = () => { + const ctx = this._ctx.select("run"); + return new GeneratorGroup(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class GitRef extends BaseClient { + _id = undefined; + _commit = undefined; + _ref = undefined; + constructor(ctx, _id, _commit, _ref) { + super(ctx); + this._id = _id; + this._commit = _commit; + this._ref = _ref; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asWorkspace = (opts) => { + const ctx = this._ctx.select("asWorkspace", { ...opts }); + return new Workspace(ctx); + }; + commit = async () => { + if (this._commit) { + return this._commit; + } + const ctx = this._ctx.select("commit"); + const response = await ctx.execute(); + return response; + }; + commonAncestor = (other) => { + const ctx = this._ctx.select("commonAncestor", { other }); + return new GitRef(ctx); + }; + ref = async () => { + if (this._ref) { + return this._ref; + } + const ctx = this._ctx.select("ref"); + const response = await ctx.execute(); + return response; + }; + tree = (opts) => { + const ctx = this._ctx.select("tree", { ...opts }); + return new Directory(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class GitRepository extends BaseClient { + _id = undefined; + _url = undefined; + constructor(ctx, _id, _url) { + super(ctx); + this._id = _id; + this._url = _url; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asWorkspace = (opts) => { + const ctx = this._ctx.select("asWorkspace", { ...opts }); + return new Workspace(ctx); + }; + branch = (name) => { + const ctx = this._ctx.select("branch", { name }); + return new GitRef(ctx); + }; + branches = async (opts) => { + const ctx = this._ctx.select("branches", { ...opts }); + const response = await ctx.execute(); + return response; + }; + commit = (id) => { + const ctx = this._ctx.select("commit", { id }); + return new GitRef(ctx); + }; + head = () => { + const ctx = this._ctx.select("head"); + return new GitRef(ctx); + }; + latestVersion = () => { + const ctx = this._ctx.select("latestVersion"); + return new GitRef(ctx); + }; + ref = (name) => { + const ctx = this._ctx.select("ref", { name }); + return new GitRef(ctx); + }; + tag = (name) => { + const ctx = this._ctx.select("tag", { name }); + return new GitRef(ctx); + }; + tags = async (opts) => { + const ctx = this._ctx.select("tags", { ...opts }); + const response = await ctx.execute(); + return response; + }; + uncommitted = () => { + const ctx = this._ctx.select("uncommitted"); + return new Changeset(ctx); + }; + url = async () => { + if (this._url) { + return this._url; + } + const ctx = this._ctx.select("url"); + const response = await ctx.execute(); + return response; + }; +} + +class HTTPState extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; +} + +class HealthcheckConfig extends BaseClient { + _id = undefined; + _interval = undefined; + _retries = undefined; + _shell = undefined; + _startInterval = undefined; + _startPeriod = undefined; + _timeout = undefined; + constructor(ctx, _id, _interval, _retries, _shell, _startInterval, _startPeriod, _timeout) { + super(ctx); + this._id = _id; + this._interval = _interval; + this._retries = _retries; + this._shell = _shell; + this._startInterval = _startInterval; + this._startPeriod = _startPeriod; + this._timeout = _timeout; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + args = async () => { + const ctx = this._ctx.select("args"); + const response = await ctx.execute(); + return response; + }; + interval = async () => { + if (this._interval) { + return this._interval; + } + const ctx = this._ctx.select("interval"); + const response = await ctx.execute(); + return response; + }; + retries = async () => { + if (this._retries) { + return this._retries; + } + const ctx = this._ctx.select("retries"); + const response = await ctx.execute(); + return response; + }; + shell = async () => { + if (this._shell) { + return this._shell; + } + const ctx = this._ctx.select("shell"); + const response = await ctx.execute(); + return response; + }; + startInterval = async () => { + if (this._startInterval) { + return this._startInterval; + } + const ctx = this._ctx.select("startInterval"); + const response = await ctx.execute(); + return response; + }; + startPeriod = async () => { + if (this._startPeriod) { + return this._startPeriod; + } + const ctx = this._ctx.select("startPeriod"); + const response = await ctx.execute(); + return response; + }; + timeout = async () => { + if (this._timeout) { + return this._timeout; + } + const ctx = this._ctx.select("timeout"); + const response = await ctx.execute(); + return response; + }; +} + +class Host extends BaseClient { + _id = undefined; + _findUp = undefined; + constructor(ctx, _id, _findUp) { + super(ctx); + this._id = _id; + this._findUp = _findUp; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + containerImage = (name) => { + const ctx = this._ctx.select("containerImage", { name }); + return new Container(ctx); + }; + directory = (path, opts) => { + const ctx = this._ctx.select("directory", { path, ...opts }); + return new Directory(ctx); + }; + file = (path, opts) => { + const ctx = this._ctx.select("file", { path, ...opts }); + return new File(ctx); + }; + findUp = async (name, opts) => { + if (this._findUp) { + return this._findUp; + } + const ctx = this._ctx.select("findUp", { name, ...opts }); + const response = await ctx.execute(); + return response; + }; + service = (ports, opts) => { + const ctx = this._ctx.select("service", { ports, ...opts }); + return new Service(ctx); + }; + tunnel = (service, opts) => { + const ctx = this._ctx.select("tunnel", { service, ...opts }); + return new Service(ctx); + }; + unixSocket = (path) => { + const ctx = this._ctx.select("unixSocket", { path }); + return new Socket(ctx); + }; +} + +class InputTypeDef extends BaseClient { + _id = undefined; + _name = undefined; + constructor(ctx, _id, _name) { + super(ctx); + this._id = _id; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + fields = async () => { + const ctx = this._ctx.select("fields").select("id"); + const response = await ctx.execute(); + return response.map((r) => new FieldTypeDef(ctx.copy().selectNode(r.id, "FieldTypeDef"))); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; +} + +class InterfaceTypeDef extends BaseClient { + _id = undefined; + _description = undefined; + _name = undefined; + _sourceModuleName = undefined; + constructor(ctx, _id, _description, _name, _sourceModuleName) { + super(ctx); + this._id = _id; + this._description = _description; + this._name = _name; + this._sourceModuleName = _sourceModuleName; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + functions = async () => { + const ctx = this._ctx.select("functions").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Function_(ctx.copy().selectNode(r.id, "Function"))); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + sourceMap = () => { + const ctx = this._ctx.select("sourceMap"); + return new SourceMap(ctx); + }; + sourceModuleName = async () => { + if (this._sourceModuleName) { + return this._sourceModuleName; + } + const ctx = this._ctx.select("sourceModuleName"); + const response = await ctx.execute(); + return response; + }; +} + +class JSONValue extends BaseClient { + _id = undefined; + _asBoolean = undefined; + _asInteger = undefined; + _asString = undefined; + _contents = undefined; + constructor(ctx, _id, _asBoolean, _asInteger, _asString, _contents) { + super(ctx); + this._id = _id; + this._asBoolean = _asBoolean; + this._asInteger = _asInteger; + this._asString = _asString; + this._contents = _contents; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asArray = async () => { + const ctx = this._ctx.select("asArray").select("id"); + const response = await ctx.execute(); + return response.map((r) => new JSONValue(ctx.copy().selectNode(r.id, "JSONValue"))); + }; + asBoolean = async () => { + if (this._asBoolean) { + return this._asBoolean; + } + const ctx = this._ctx.select("asBoolean"); + const response = await ctx.execute(); + return response; + }; + asInteger = async () => { + if (this._asInteger) { + return this._asInteger; + } + const ctx = this._ctx.select("asInteger"); + const response = await ctx.execute(); + return response; + }; + asString = async () => { + if (this._asString) { + return this._asString; + } + const ctx = this._ctx.select("asString"); + const response = await ctx.execute(); + return response; + }; + contents = async (opts) => { + if (this._contents) { + return this._contents; + } + const ctx = this._ctx.select("contents", { ...opts }); + const response = await ctx.execute(); + return response; + }; + field = (path) => { + const ctx = this._ctx.select("field", { path }); + return new JSONValue(ctx); + }; + fields = async () => { + const ctx = this._ctx.select("fields"); + const response = await ctx.execute(); + return response; + }; + newBoolean = (value) => { + const ctx = this._ctx.select("newBoolean", { value }); + return new JSONValue(ctx); + }; + newInteger = (value) => { + const ctx = this._ctx.select("newInteger", { value }); + return new JSONValue(ctx); + }; + newString = (value) => { + const ctx = this._ctx.select("newString", { value }); + return new JSONValue(ctx); + }; + withContents = (contents) => { + const ctx = this._ctx.select("withContents", { contents }); + return new JSONValue(ctx); + }; + withField = (path, value) => { + const ctx = this._ctx.select("withField", { path, value }); + return new JSONValue(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class LLM extends BaseClient { + _id = undefined; + _contextWindow = undefined; + _hasPending = undefined; + _lastReply = undefined; + _model = undefined; + _portableID = undefined; + _provider = undefined; + _replay = undefined; + _sync = undefined; + _tools = undefined; + _transcript = undefined; + constructor(ctx, _id, _contextWindow, _hasPending, _lastReply, _model, _portableID, _provider, _replay, _sync, _tools, _transcript) { + super(ctx); + this._id = _id; + this._contextWindow = _contextWindow; + this._hasPending = _hasPending; + this._lastReply = _lastReply; + this._model = _model; + this._portableID = _portableID; + this._provider = _provider; + this._replay = _replay; + this._sync = _sync; + this._tools = _tools; + this._transcript = _transcript; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + bindResult = (name) => { + const ctx = this._ctx.select("bindResult", { name }); + return new Binding(ctx); + }; + contextWindow = async () => { + if (this._contextWindow) { + return this._contextWindow; + } + const ctx = this._ctx.select("contextWindow"); + const response = await ctx.execute(); + return response; + }; + env = () => { + const ctx = this._ctx.select("env"); + return new Env(ctx); + }; + fork = (label) => { + const ctx = this._ctx.select("fork", { label }); + return new LLM(ctx); + }; + hasPending = async () => { + if (this._hasPending) { + return this._hasPending; + } + const ctx = this._ctx.select("hasPending"); + const response = await ctx.execute(); + return response; + }; + lastReply = async () => { + if (this._lastReply) { + return this._lastReply; + } + const ctx = this._ctx.select("lastReply"); + const response = await ctx.execute(); + return response; + }; + loop = (opts) => { + const ctx = this._ctx.select("loop", { ...opts }); + return new LLM(ctx); + }; + messages = async () => { + const ctx = this._ctx.select("messages").select("id"); + const response = await ctx.execute(); + return response.map((r) => new LLMMessage(ctx.copy().selectNode(r.id, "LLMMessage"))); + }; + model = async () => { + if (this._model) { + return this._model; + } + const ctx = this._ctx.select("model"); + const response = await ctx.execute(); + return response; + }; + portableID = async () => { + if (this._portableID) { + return this._portableID; + } + const ctx = this._ctx.select("portableID"); + const response = await ctx.execute(); + return response; + }; + provider = async () => { + if (this._provider) { + return this._provider; + } + const ctx = this._ctx.select("provider"); + const response = await ctx.execute(); + return response; + }; + replay = async () => { + const ctx = this._ctx.select("replay"); + const response = await ctx.execute(); + return new LLM(ctx.copy().selectNode(response, "LLM")); + }; + step = (opts) => { + const ctx = this._ctx.select("step", { ...opts }); + return new LLM(ctx); + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new LLM(ctx.copy().selectNode(response, "LLM")); + }; + tokenUsage = () => { + const ctx = this._ctx.select("tokenUsage"); + return new LLMTokenUsage(ctx); + }; + tools = async () => { + if (this._tools) { + return this._tools; + } + const ctx = this._ctx.select("tools"); + const response = await ctx.execute(); + return response; + }; + transcript = async () => { + if (this._transcript) { + return this._transcript; + } + const ctx = this._ctx.select("transcript"); + const response = await ctx.execute(); + return response; + }; + withBlockedFunction = (typeName, function_) => { + const ctx = this._ctx.select("withBlockedFunction", { + typeName, + function: function_ + }); + return new LLM(ctx); + }; + withEnv = (env) => { + const ctx = this._ctx.select("withEnv", { env }); + return new LLM(ctx); + }; + withMCPServer = (name, service) => { + const ctx = this._ctx.select("withMCPServer", { name, service }); + return new LLM(ctx); + }; + withModel = (model, opts) => { + const ctx = this._ctx.select("withModel", { model, ...opts }); + return new LLM(ctx); + }; + withObject = (tag, object) => { + const ctx = this._ctx.select("withObject", { tag, object }); + return new LLM(ctx); + }; + withPrompt = (prompt) => { + const ctx = this._ctx.select("withPrompt", { prompt }); + return new LLM(ctx); + }; + withPromptFile = (file) => { + const ctx = this._ctx.select("withPromptFile", { file }); + return new LLM(ctx); + }; + withResponse = (content, opts) => { + const ctx = this._ctx.select("withResponse", { content, ...opts }); + return new LLM(ctx); + }; + withStaticTools = () => { + const ctx = this._ctx.select("withStaticTools"); + return new LLM(ctx); + }; + withSystemPrompt = (prompt) => { + const ctx = this._ctx.select("withSystemPrompt", { prompt }); + return new LLM(ctx); + }; + withToolResult = (callId, content, errored) => { + const ctx = this._ctx.select("withToolResult", { callId, content, errored }); + return new LLM(ctx); + }; + withoutDefaultSystemPrompt = () => { + const ctx = this._ctx.select("withoutDefaultSystemPrompt"); + return new LLM(ctx); + }; + withoutMessageHistory = () => { + const ctx = this._ctx.select("withoutMessageHistory"); + return new LLM(ctx); + }; + withoutSystemPrompts = () => { + const ctx = this._ctx.select("withoutSystemPrompts"); + return new LLM(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class LLMContentBlock extends BaseClient { + _id = undefined; + _arguments = undefined; + _callId = undefined; + _errored = undefined; + _kind = undefined; + _signature = undefined; + _text = undefined; + _toolName = undefined; + constructor(ctx, _id, _arguments, _callId, _errored, _kind, _signature, _text, _toolName) { + super(ctx); + this._id = _id; + this._arguments = _arguments; + this._callId = _callId; + this._errored = _errored; + this._kind = _kind; + this._signature = _signature; + this._text = _text; + this._toolName = _toolName; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + arguments = async () => { + if (this._arguments) { + return this._arguments; + } + const ctx = this._ctx.select("arguments"); + const response = await ctx.execute(); + return response; + }; + callId = async () => { + if (this._callId) { + return this._callId; + } + const ctx = this._ctx.select("callId"); + const response = await ctx.execute(); + return response; + }; + errored = async () => { + if (this._errored) { + return this._errored; + } + const ctx = this._ctx.select("errored"); + const response = await ctx.execute(); + return response; + }; + kind = async () => { + if (this._kind) { + return this._kind; + } + const ctx = this._ctx.select("kind"); + const response = await ctx.execute(); + return LLMContentBlockKindNameToValue(response); + }; + signature = async () => { + if (this._signature) { + return this._signature; + } + const ctx = this._ctx.select("signature"); + const response = await ctx.execute(); + return response; + }; + text = async () => { + if (this._text) { + return this._text; + } + const ctx = this._ctx.select("text"); + const response = await ctx.execute(); + return response; + }; + toolName = async () => { + if (this._toolName) { + return this._toolName; + } + const ctx = this._ctx.select("toolName"); + const response = await ctx.execute(); + return response; + }; +} + +class LLMMessage extends BaseClient { + _id = undefined; + _role = undefined; + constructor(ctx, _id, _role) { + super(ctx); + this._id = _id; + this._role = _role; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + content = async () => { + const ctx = this._ctx.select("content").select("id"); + const response = await ctx.execute(); + return response.map((r) => new LLMContentBlock(ctx.copy().selectNode(r.id, "LLMContentBlock"))); + }; + role = async () => { + if (this._role) { + return this._role; + } + const ctx = this._ctx.select("role"); + const response = await ctx.execute(); + return LLMMessageRoleNameToValue(response); + }; + tokenUsage = () => { + const ctx = this._ctx.select("tokenUsage"); + return new LLMTokenUsage(ctx); + }; +} + +class LLMTokenUsage extends BaseClient { + _id = undefined; + _cachedTokenReads = undefined; + _cachedTokenWrites = undefined; + _inputTokens = undefined; + _outputTokens = undefined; + _totalTokens = undefined; + constructor(ctx, _id, _cachedTokenReads, _cachedTokenWrites, _inputTokens, _outputTokens, _totalTokens) { + super(ctx); + this._id = _id; + this._cachedTokenReads = _cachedTokenReads; + this._cachedTokenWrites = _cachedTokenWrites; + this._inputTokens = _inputTokens; + this._outputTokens = _outputTokens; + this._totalTokens = _totalTokens; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + cachedTokenReads = async () => { + if (this._cachedTokenReads) { + return this._cachedTokenReads; + } + const ctx = this._ctx.select("cachedTokenReads"); + const response = await ctx.execute(); + return response; + }; + cachedTokenWrites = async () => { + if (this._cachedTokenWrites) { + return this._cachedTokenWrites; + } + const ctx = this._ctx.select("cachedTokenWrites"); + const response = await ctx.execute(); + return response; + }; + inputTokens = async () => { + if (this._inputTokens) { + return this._inputTokens; + } + const ctx = this._ctx.select("inputTokens"); + const response = await ctx.execute(); + return response; + }; + outputTokens = async () => { + if (this._outputTokens) { + return this._outputTokens; + } + const ctx = this._ctx.select("outputTokens"); + const response = await ctx.execute(); + return response; + }; + totalTokens = async () => { + if (this._totalTokens) { + return this._totalTokens; + } + const ctx = this._ctx.select("totalTokens"); + const response = await ctx.execute(); + return response; + }; +} + +class Label extends BaseClient { + _id = undefined; + _name = undefined; + _value = undefined; + constructor(ctx, _id, _name, _value) { + super(ctx); + this._id = _id; + this._name = _name; + this._value = _value; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + value = async () => { + if (this._value) { + return this._value; + } + const ctx = this._ctx.select("value"); + const response = await ctx.execute(); + return response; + }; +} + +class ListTypeDef extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + elementTypeDef = () => { + const ctx = this._ctx.select("elementTypeDef"); + return new TypeDef(ctx); + }; +} + +class Module_ extends BaseClient { + _id = undefined; + _description = undefined; + _name = undefined; + _serve = undefined; + _sync = undefined; + constructor(ctx, _id, _description, _name, _serve, _sync) { + super(ctx); + this._id = _id; + this._description = _description; + this._name = _name; + this._serve = _serve; + this._sync = _sync; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + check = (name) => { + const ctx = this._ctx.select("check", { name }); + return new Check(ctx); + }; + checks = (opts) => { + const ctx = this._ctx.select("checks", { ...opts }); + return new CheckGroup(ctx); + }; + dependencies = async () => { + const ctx = this._ctx.select("dependencies").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Module_(ctx.copy().selectNode(r.id, "Module"))); + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + enums = async () => { + const ctx = this._ctx.select("enums").select("id"); + const response = await ctx.execute(); + return response.map((r) => new TypeDef(ctx.copy().selectNode(r.id, "TypeDef"))); + }; + generatedContextDirectory = () => { + const ctx = this._ctx.select("generatedContextDirectory"); + return new Directory(ctx); + }; + generator = (name) => { + const ctx = this._ctx.select("generator", { name }); + return new Generator(ctx); + }; + generators = (opts) => { + const ctx = this._ctx.select("generators", { ...opts }); + return new GeneratorGroup(ctx); + }; + interfaces = async () => { + const ctx = this._ctx.select("interfaces").select("id"); + const response = await ctx.execute(); + return response.map((r) => new TypeDef(ctx.copy().selectNode(r.id, "TypeDef"))); + }; + introspectionSchemaJSON = () => { + const ctx = this._ctx.select("introspectionSchemaJSON"); + return new File(ctx); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + objects = async () => { + const ctx = this._ctx.select("objects").select("id"); + const response = await ctx.execute(); + return response.map((r) => new TypeDef(ctx.copy().selectNode(r.id, "TypeDef"))); + }; + runtime = () => { + const ctx = this._ctx.select("runtime"); + return new Container(ctx); + }; + sdk = () => { + const ctx = this._ctx.select("sdk"); + return new SDKConfig(ctx); + }; + serve = async (opts) => { + if (this._serve) { + return; + } + const ctx = this._ctx.select("serve", { ...opts }); + await ctx.execute(); + }; + services = (opts) => { + const ctx = this._ctx.select("services", { ...opts }); + return new UpGroup(ctx); + }; + source = () => { + const ctx = this._ctx.select("source"); + return new ModuleSource(ctx); + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new Module_(ctx.copy().selectNode(response, "Module")); + }; + userDefaults = () => { + const ctx = this._ctx.select("userDefaults"); + return new EnvFile(ctx); + }; + withDescription = (description) => { + const ctx = this._ctx.select("withDescription", { description }); + return new Module_(ctx); + }; + withEnum = (enum_) => { + const ctx = this._ctx.select("withEnum", { + enum: enum_ + }); + return new Module_(ctx); + }; + withInterface = (iface) => { + const ctx = this._ctx.select("withInterface", { iface }); + return new Module_(ctx); + }; + withObject = (object) => { + const ctx = this._ctx.select("withObject", { object }); + return new Module_(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class ModuleConfigClient extends BaseClient { + _id = undefined; + _directory = undefined; + _generator = undefined; + constructor(ctx, _id, _directory, _generator) { + super(ctx); + this._id = _id; + this._directory = _directory; + this._generator = _generator; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + directory = async () => { + if (this._directory) { + return this._directory; + } + const ctx = this._ctx.select("directory"); + const response = await ctx.execute(); + return response; + }; + generator = async () => { + if (this._generator) { + return this._generator; + } + const ctx = this._ctx.select("generator"); + const response = await ctx.execute(); + return response; + }; +} + +class ModuleSource extends BaseClient { + _id = undefined; + _asString = undefined; + _cloneRef = undefined; + _commit = undefined; + _configExists = undefined; + _digest = undefined; + _engineVersion = undefined; + _htmlRepoURL = undefined; + _htmlURL = undefined; + _kind = undefined; + _localContextDirectoryPath = undefined; + _moduleName = undefined; + _moduleOriginalName = undefined; + _originalSubpath = undefined; + _pin = undefined; + _repoRootPath = undefined; + _sourceRootSubpath = undefined; + _sourceSubpath = undefined; + _sync = undefined; + _version = undefined; + constructor(ctx, _id, _asString, _cloneRef, _commit, _configExists, _digest, _engineVersion, _htmlRepoURL, _htmlURL, _kind, _localContextDirectoryPath, _moduleName, _moduleOriginalName, _originalSubpath, _pin, _repoRootPath, _sourceRootSubpath, _sourceSubpath, _sync, _version) { + super(ctx); + this._id = _id; + this._asString = _asString; + this._cloneRef = _cloneRef; + this._commit = _commit; + this._configExists = _configExists; + this._digest = _digest; + this._engineVersion = _engineVersion; + this._htmlRepoURL = _htmlRepoURL; + this._htmlURL = _htmlURL; + this._kind = _kind; + this._localContextDirectoryPath = _localContextDirectoryPath; + this._moduleName = _moduleName; + this._moduleOriginalName = _moduleOriginalName; + this._originalSubpath = _originalSubpath; + this._pin = _pin; + this._repoRootPath = _repoRootPath; + this._sourceRootSubpath = _sourceRootSubpath; + this._sourceSubpath = _sourceSubpath; + this._sync = _sync; + this._version = _version; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asModule = () => { + const ctx = this._ctx.select("asModule"); + return new Module_(ctx); + }; + asString = async () => { + if (this._asString) { + return this._asString; + } + const ctx = this._ctx.select("asString"); + const response = await ctx.execute(); + return response; + }; + blueprint = () => { + const ctx = this._ctx.select("blueprint"); + return new ModuleSource(ctx); + }; + clientSchemaIntrospectionJSON = () => { + const ctx = this._ctx.select("clientSchemaIntrospectionJSON"); + return new File(ctx); + }; + cloneRef = async () => { + if (this._cloneRef) { + return this._cloneRef; + } + const ctx = this._ctx.select("cloneRef"); + const response = await ctx.execute(); + return response; + }; + commit = async () => { + if (this._commit) { + return this._commit; + } + const ctx = this._ctx.select("commit"); + const response = await ctx.execute(); + return response; + }; + configClients = async () => { + const ctx = this._ctx.select("configClients").select("id"); + const response = await ctx.execute(); + return response.map((r) => new ModuleConfigClient(ctx.copy().selectNode(r.id, "ModuleConfigClient"))); + }; + configExists = async () => { + if (this._configExists) { + return this._configExists; + } + const ctx = this._ctx.select("configExists"); + const response = await ctx.execute(); + return response; + }; + contextDirectory = () => { + const ctx = this._ctx.select("contextDirectory"); + return new Directory(ctx); + }; + dependencies = async () => { + const ctx = this._ctx.select("dependencies").select("id"); + const response = await ctx.execute(); + return response.map((r) => new ModuleSource(ctx.copy().selectNode(r.id, "ModuleSource"))); + }; + digest = async () => { + if (this._digest) { + return this._digest; + } + const ctx = this._ctx.select("digest"); + const response = await ctx.execute(); + return response; + }; + directory = (path) => { + const ctx = this._ctx.select("directory", { path }); + return new Directory(ctx); + }; + engineVersion = async () => { + if (this._engineVersion) { + return this._engineVersion; + } + const ctx = this._ctx.select("engineVersion"); + const response = await ctx.execute(); + return response; + }; + generateLocalDependencies = (workspace) => { + const ctx = this._ctx.select("generateLocalDependencies", { workspace }); + return new Changeset(ctx); + }; + generatedContextChangeset = () => { + const ctx = this._ctx.select("generatedContextChangeset"); + return new Changeset(ctx); + }; + generatedContextDirectory = () => { + const ctx = this._ctx.select("generatedContextDirectory"); + return new Directory(ctx); + }; + htmlRepoURL = async () => { + if (this._htmlRepoURL) { + return this._htmlRepoURL; + } + const ctx = this._ctx.select("htmlRepoURL"); + const response = await ctx.execute(); + return response; + }; + htmlURL = async () => { + if (this._htmlURL) { + return this._htmlURL; + } + const ctx = this._ctx.select("htmlURL"); + const response = await ctx.execute(); + return response; + }; + introspectionSchemaJSON = () => { + const ctx = this._ctx.select("introspectionSchemaJSON"); + return new File(ctx); + }; + kind = async () => { + if (this._kind) { + return this._kind; + } + const ctx = this._ctx.select("kind"); + const response = await ctx.execute(); + return ModuleSourceKindNameToValue(response); + }; + localContextDirectoryPath = async () => { + if (this._localContextDirectoryPath) { + return this._localContextDirectoryPath; + } + const ctx = this._ctx.select("localContextDirectoryPath"); + const response = await ctx.execute(); + return response; + }; + moduleName = async () => { + if (this._moduleName) { + return this._moduleName; + } + const ctx = this._ctx.select("moduleName"); + const response = await ctx.execute(); + return response; + }; + moduleOriginalName = async () => { + if (this._moduleOriginalName) { + return this._moduleOriginalName; + } + const ctx = this._ctx.select("moduleOriginalName"); + const response = await ctx.execute(); + return response; + }; + originalSubpath = async () => { + if (this._originalSubpath) { + return this._originalSubpath; + } + const ctx = this._ctx.select("originalSubpath"); + const response = await ctx.execute(); + return response; + }; + pin = async () => { + if (this._pin) { + return this._pin; + } + const ctx = this._ctx.select("pin"); + const response = await ctx.execute(); + return response; + }; + repoRootPath = async () => { + if (this._repoRootPath) { + return this._repoRootPath; + } + const ctx = this._ctx.select("repoRootPath"); + const response = await ctx.execute(); + return response; + }; + sdk = () => { + const ctx = this._ctx.select("sdk"); + return new SDKConfig(ctx); + }; + sourceRootSubpath = async () => { + if (this._sourceRootSubpath) { + return this._sourceRootSubpath; + } + const ctx = this._ctx.select("sourceRootSubpath"); + const response = await ctx.execute(); + return response; + }; + sourceSubpath = async () => { + if (this._sourceSubpath) { + return this._sourceSubpath; + } + const ctx = this._ctx.select("sourceSubpath"); + const response = await ctx.execute(); + return response; + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new ModuleSource(ctx.copy().selectNode(response, "ModuleSource")); + }; + toolchains = async () => { + const ctx = this._ctx.select("toolchains").select("id"); + const response = await ctx.execute(); + return response.map((r) => new ModuleSource(ctx.copy().selectNode(r.id, "ModuleSource"))); + }; + updatedConfigDirectory = () => { + const ctx = this._ctx.select("updatedConfigDirectory"); + return new Directory(ctx); + }; + userDefaults = () => { + const ctx = this._ctx.select("userDefaults"); + return new EnvFile(ctx); + }; + version = async () => { + if (this._version) { + return this._version; + } + const ctx = this._ctx.select("version"); + const response = await ctx.execute(); + return response; + }; + withBlueprint = (blueprint) => { + const ctx = this._ctx.select("withBlueprint", { blueprint }); + return new ModuleSource(ctx); + }; + withClient = (generator, outputDir) => { + const ctx = this._ctx.select("withClient", { generator, outputDir }); + return new ModuleSource(ctx); + }; + withDependencies = (dependencies) => { + const ctx = this._ctx.select("withDependencies", { dependencies }); + return new ModuleSource(ctx); + }; + withEngineVersion = (version) => { + const ctx = this._ctx.select("withEngineVersion", { version }); + return new ModuleSource(ctx); + }; + withExperimentalFeatures = (features) => { + const ctx = this._ctx.select("withExperimentalFeatures", { features }); + return new ModuleSource(ctx); + }; + withIncludes = (patterns) => { + const ctx = this._ctx.select("withIncludes", { patterns }); + return new ModuleSource(ctx); + }; + withName = (name) => { + const ctx = this._ctx.select("withName", { name }); + return new ModuleSource(ctx); + }; + withSDK = (source) => { + const ctx = this._ctx.select("withSDK", { source }); + return new ModuleSource(ctx); + }; + withSourceSubpath = (path) => { + const ctx = this._ctx.select("withSourceSubpath", { path }); + return new ModuleSource(ctx); + }; + withToolchains = (toolchains) => { + const ctx = this._ctx.select("withToolchains", { toolchains }); + return new ModuleSource(ctx); + }; + withUpdateBlueprint = () => { + const ctx = this._ctx.select("withUpdateBlueprint"); + return new ModuleSource(ctx); + }; + withUpdateDependencies = (dependencies) => { + const ctx = this._ctx.select("withUpdateDependencies", { dependencies }); + return new ModuleSource(ctx); + }; + withUpdateToolchains = (toolchains) => { + const ctx = this._ctx.select("withUpdateToolchains", { toolchains }); + return new ModuleSource(ctx); + }; + withUpdatedClients = (clients) => { + const ctx = this._ctx.select("withUpdatedClients", { clients }); + return new ModuleSource(ctx); + }; + withoutBlueprint = () => { + const ctx = this._ctx.select("withoutBlueprint"); + return new ModuleSource(ctx); + }; + withoutClient = (path) => { + const ctx = this._ctx.select("withoutClient", { path }); + return new ModuleSource(ctx); + }; + withoutDependencies = (dependencies) => { + const ctx = this._ctx.select("withoutDependencies", { dependencies }); + return new ModuleSource(ctx); + }; + withoutExperimentalFeatures = (features) => { + const ctx = this._ctx.select("withoutExperimentalFeatures", { features }); + return new ModuleSource(ctx); + }; + withoutToolchains = (toolchains) => { + const ctx = this._ctx.select("withoutToolchains", { toolchains }); + return new ModuleSource(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class _NodeClient extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; +} + +class ObjectTypeDef extends BaseClient { + _id = undefined; + _deprecated = undefined; + _description = undefined; + _name = undefined; + _sourceModuleName = undefined; + constructor(ctx, _id, _deprecated, _description, _name, _sourceModuleName) { + super(ctx); + this._id = _id; + this._deprecated = _deprecated; + this._description = _description; + this._name = _name; + this._sourceModuleName = _sourceModuleName; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + constructor_ = () => { + const ctx = this._ctx.select("constructor"); + return new Function_(ctx); + }; + deprecated = async () => { + if (this._deprecated) { + return this._deprecated; + } + const ctx = this._ctx.select("deprecated"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + fields = async () => { + const ctx = this._ctx.select("fields").select("id"); + const response = await ctx.execute(); + return response.map((r) => new FieldTypeDef(ctx.copy().selectNode(r.id, "FieldTypeDef"))); + }; + functions = async () => { + const ctx = this._ctx.select("functions").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Function_(ctx.copy().selectNode(r.id, "Function"))); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + sourceMap = () => { + const ctx = this._ctx.select("sourceMap"); + return new SourceMap(ctx); + }; + sourceModuleName = async () => { + if (this._sourceModuleName) { + return this._sourceModuleName; + } + const ctx = this._ctx.select("sourceModuleName"); + const response = await ctx.execute(); + return response; + }; +} + +class Port extends BaseClient { + _id = undefined; + _description = undefined; + _experimentalSkipHealthcheck = undefined; + _port = undefined; + _protocol = undefined; + constructor(ctx, _id, _description, _experimentalSkipHealthcheck, _port, _protocol) { + super(ctx); + this._id = _id; + this._description = _description; + this._experimentalSkipHealthcheck = _experimentalSkipHealthcheck; + this._port = _port; + this._protocol = _protocol; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + experimentalSkipHealthcheck = async () => { + if (this._experimentalSkipHealthcheck) { + return this._experimentalSkipHealthcheck; + } + const ctx = this._ctx.select("experimentalSkipHealthcheck"); + const response = await ctx.execute(); + return response; + }; + port = async () => { + if (this._port) { + return this._port; + } + const ctx = this._ctx.select("port"); + const response = await ctx.execute(); + return response; + }; + protocol = async () => { + if (this._protocol) { + return this._protocol; + } + const ctx = this._ctx.select("protocol"); + const response = await ctx.execute(); + return NetworkProtocolNameToValue(response); + }; +} + +class Client extends BaseClient { + _id = undefined; + _defaultPlatform = undefined; + _version = undefined; + constructor(ctx, _id, _defaultPlatform, _version) { + super(ctx); + this._id = _id; + this._defaultPlatform = _defaultPlatform; + this._version = _version; + } + getGQLClient() { + return this._ctx.getGQLClient(); + } + id = async () => { + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + address = (value) => { + const ctx = this._ctx.select("address", { value }); + return new Address(ctx); + }; + cacheVolume = (key, opts) => { + const metadata = { + sharing: { is_enum: true, value_to_name: CacheSharingModeValueToName } + }; + const ctx = this._ctx.select("cacheVolume", { key, ...opts, __metadata: metadata }); + return new CacheVolume(ctx); + }; + changeset = () => { + const ctx = this._ctx.select("changeset"); + return new Changeset(ctx); + }; + cloud = () => { + const ctx = this._ctx.select("cloud"); + return new Cloud(ctx); + }; + container = (opts) => { + const ctx = this._ctx.select("container", { ...opts }); + return new Container(ctx); + }; + currentEnv = () => { + const ctx = this._ctx.select("currentEnv"); + return new Env(ctx); + }; + currentFunctionCall = () => { + const ctx = this._ctx.select("currentFunctionCall"); + return new FunctionCall(ctx); + }; + currentModule = () => { + const ctx = this._ctx.select("currentModule"); + return new CurrentModule(ctx); + }; + currentTypeDefs = async (opts) => { + const ctx = this._ctx.select("currentTypeDefs", { ...opts }).select("id"); + const response = await ctx.execute(); + return response.map((r) => new TypeDef(ctx.copy().selectNode(r.id, "TypeDef"))); + }; + currentWorkspace = () => { + const ctx = this._ctx.select("currentWorkspace"); + return new Workspace(ctx); + }; + defaultPlatform = async () => { + const ctx = this._ctx.select("defaultPlatform"); + const response = await ctx.execute(); + return response; + }; + directory = () => { + const ctx = this._ctx.select("directory"); + return new Directory(ctx); + }; + engine = () => { + const ctx = this._ctx.select("engine"); + return new Engine(ctx); + }; + env = (opts) => { + const ctx = this._ctx.select("env", { ...opts }); + return new Env(ctx); + }; + envFile = (opts) => { + const ctx = this._ctx.select("envFile", { ...opts }); + return new EnvFile(ctx); + }; + error = (message) => { + const ctx = this._ctx.select("error", { message }); + return new Error2(ctx); + }; + file = (name, contents, opts) => { + const ctx = this._ctx.select("file", { name, contents, ...opts }); + return new File(ctx); + }; + function_ = (name, returnType) => { + const ctx = this._ctx.select("function", { name, returnType }); + return new Function_(ctx); + }; + generatedCode = (code) => { + const ctx = this._ctx.select("generatedCode", { code }); + return new GeneratedCode(ctx); + }; + git = (url, opts) => { + const ctx = this._ctx.select("git", { url, ...opts }); + return new GitRepository(ctx); + }; + host = () => { + const ctx = this._ctx.select("host"); + return new Host(ctx); + }; + http = (url, opts) => { + const ctx = this._ctx.select("http", { url, ...opts }); + return new File(ctx); + }; + json = () => { + const ctx = this._ctx.select("json"); + return new JSONValue(ctx); + }; + llm = (opts) => { + const ctx = this._ctx.select("llm", { ...opts }); + return new LLM(ctx); + }; + module_ = () => { + const ctx = this._ctx.select("module"); + return new Module_(ctx); + }; + moduleSource = (refString, opts) => { + const metadata = { + requireKind: { is_enum: true, value_to_name: ModuleSourceKindValueToName } + }; + const ctx = this._ctx.select("moduleSource", { refString, ...opts, __metadata: metadata }); + return new ModuleSource(ctx); + }; + node = (id) => { + const ctx = this._ctx.select("node", { id }); + return new _NodeClient(ctx); + }; + schema = (json) => { + const ctx = this._ctx.select("schema", { json }); + return new Schema(ctx); + }; + secret = (uri, opts) => { + const ctx = this._ctx.select("secret", { uri, ...opts }); + return new Secret(ctx); + }; + setSecret = (name, plaintext) => { + const ctx = this._ctx.select("setSecret", { name, plaintext }); + return new Secret(ctx); + }; + sourceMap = (filename, line, column) => { + const ctx = this._ctx.select("sourceMap", { filename, line, column }); + return new SourceMap(ctx); + }; + sshfsVolume = (endpoint, privateKey, opts) => { + const ctx = this._ctx.select("sshfsVolume", { endpoint, privateKey, ...opts }); + return new Volume(ctx); + }; + typeDef = () => { + const ctx = this._ctx.select("typeDef"); + return new TypeDef(ctx); + }; + version = async () => { + const ctx = this._ctx.select("version"); + const response = await ctx.execute(); + return response; + }; +} + +class RemoteGitMirror extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; +} + +class SDKConfig extends BaseClient { + _id = undefined; + _debug = undefined; + _source = undefined; + constructor(ctx, _id, _debug, _source) { + super(ctx); + this._id = _id; + this._debug = _debug; + this._source = _source; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + debug = async () => { + if (this._debug) { + return this._debug; + } + const ctx = this._ctx.select("debug"); + const response = await ctx.execute(); + return response; + }; + source = async () => { + if (this._source) { + return this._source; + } + const ctx = this._ctx.select("source"); + const response = await ctx.execute(); + return response; + }; +} + +class ScalarTypeDef extends BaseClient { + _id = undefined; + _description = undefined; + _name = undefined; + _sourceModuleName = undefined; + constructor(ctx, _id, _description, _name, _sourceModuleName) { + super(ctx); + this._id = _id; + this._description = _description; + this._name = _name; + this._sourceModuleName = _sourceModuleName; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + sourceModuleName = async () => { + if (this._sourceModuleName) { + return this._sourceModuleName; + } + const ctx = this._ctx.select("sourceModuleName"); + const response = await ctx.execute(); + return response; + }; +} + +class Schema extends BaseClient { + _id = undefined; + _contents = undefined; + constructor(ctx, _id, _contents) { + super(ctx); + this._id = _id; + this._contents = _contents; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + contents = async () => { + if (this._contents) { + return this._contents; + } + const ctx = this._ctx.select("contents"); + const response = await ctx.execute(); + return response; + }; + merge = (moduleTypes, moduleName) => { + const ctx = this._ctx.select("merge", { moduleTypes, moduleName }); + return new Schema(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class SearchResult extends BaseClient { + _id = undefined; + _absoluteOffset = undefined; + _filePath = undefined; + _lineNumber = undefined; + _matchedLines = undefined; + constructor(ctx, _id, _absoluteOffset, _filePath, _lineNumber, _matchedLines) { + super(ctx); + this._id = _id; + this._absoluteOffset = _absoluteOffset; + this._filePath = _filePath; + this._lineNumber = _lineNumber; + this._matchedLines = _matchedLines; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + absoluteOffset = async () => { + if (this._absoluteOffset) { + return this._absoluteOffset; + } + const ctx = this._ctx.select("absoluteOffset"); + const response = await ctx.execute(); + return response; + }; + filePath = async () => { + if (this._filePath) { + return this._filePath; + } + const ctx = this._ctx.select("filePath"); + const response = await ctx.execute(); + return response; + }; + lineNumber = async () => { + if (this._lineNumber) { + return this._lineNumber; + } + const ctx = this._ctx.select("lineNumber"); + const response = await ctx.execute(); + return response; + }; + matchedLines = async () => { + if (this._matchedLines) { + return this._matchedLines; + } + const ctx = this._ctx.select("matchedLines"); + const response = await ctx.execute(); + return response; + }; + submatches = async () => { + const ctx = this._ctx.select("submatches").select("id"); + const response = await ctx.execute(); + return response.map((r) => new SearchSubmatch(ctx.copy().selectNode(r.id, "SearchSubmatch"))); + }; +} + +class SearchSubmatch extends BaseClient { + _id = undefined; + _end = undefined; + _start = undefined; + _text = undefined; + constructor(ctx, _id, _end, _start, _text) { + super(ctx); + this._id = _id; + this._end = _end; + this._start = _start; + this._text = _text; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + end = async () => { + if (this._end) { + return this._end; + } + const ctx = this._ctx.select("end"); + const response = await ctx.execute(); + return response; + }; + start = async () => { + if (this._start) { + return this._start; + } + const ctx = this._ctx.select("start"); + const response = await ctx.execute(); + return response; + }; + text = async () => { + if (this._text) { + return this._text; + } + const ctx = this._ctx.select("text"); + const response = await ctx.execute(); + return response; + }; +} + +class Secret extends BaseClient { + _id = undefined; + _name = undefined; + _plaintext = undefined; + _uri = undefined; + constructor(ctx, _id, _name, _plaintext, _uri) { + super(ctx); + this._id = _id; + this._name = _name; + this._plaintext = _plaintext; + this._uri = _uri; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + plaintext = async () => { + if (this._plaintext) { + return this._plaintext; + } + const ctx = this._ctx.select("plaintext"); + const response = await ctx.execute(); + return response; + }; + uri = async () => { + if (this._uri) { + return this._uri; + } + const ctx = this._ctx.select("uri"); + const response = await ctx.execute(); + return response; + }; +} + +class Service extends BaseClient { + _id = undefined; + _endpoint = undefined; + _hostname = undefined; + _start = undefined; + _stop = undefined; + _sync = undefined; + _up = undefined; + constructor(ctx, _id, _endpoint, _hostname, _start, _stop, _sync, _up) { + super(ctx); + this._id = _id; + this._endpoint = _endpoint; + this._hostname = _hostname; + this._start = _start; + this._stop = _stop; + this._sync = _sync; + this._up = _up; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + endpoint = async (opts) => { + if (this._endpoint) { + return this._endpoint; + } + const ctx = this._ctx.select("endpoint", { ...opts }); + const response = await ctx.execute(); + return response; + }; + hostname = async () => { + if (this._hostname) { + return this._hostname; + } + const ctx = this._ctx.select("hostname"); + const response = await ctx.execute(); + return response; + }; + ports = async () => { + const ctx = this._ctx.select("ports").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Port(ctx.copy().selectNode(r.id, "Port"))); + }; + start = async () => { + const ctx = this._ctx.select("start"); + const response = await ctx.execute(); + return new Service(ctx.copy().selectNode(response, "Service")); + }; + stop = async (opts) => { + const ctx = this._ctx.select("stop", { ...opts }); + const response = await ctx.execute(); + return new Service(ctx.copy().selectNode(response, "Service")); + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new Service(ctx.copy().selectNode(response, "Service")); + }; + terminal = (opts) => { + const ctx = this._ctx.select("terminal", { ...opts }); + return new Service(ctx); + }; + up = async (opts) => { + if (this._up) { + return; + } + const ctx = this._ctx.select("up", { ...opts }); + await ctx.execute(); + }; + withHostname = (hostname) => { + const ctx = this._ctx.select("withHostname", { hostname }); + return new Service(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class Socket extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; +} + +class SourceMap extends BaseClient { + _id = undefined; + _column = undefined; + _filename = undefined; + _line = undefined; + _module = undefined; + _url = undefined; + constructor(ctx, _id, _column, _filename, _line, _module, _url) { + super(ctx); + this._id = _id; + this._column = _column; + this._filename = _filename; + this._line = _line; + this._module = _module; + this._url = _url; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + column = async () => { + if (this._column) { + return this._column; + } + const ctx = this._ctx.select("column"); + const response = await ctx.execute(); + return response; + }; + filename = async () => { + if (this._filename) { + return this._filename; + } + const ctx = this._ctx.select("filename"); + const response = await ctx.execute(); + return response; + }; + line = async () => { + if (this._line) { + return this._line; + } + const ctx = this._ctx.select("line"); + const response = await ctx.execute(); + return response; + }; + module_ = async () => { + if (this._module) { + return this._module; + } + const ctx = this._ctx.select("module"); + const response = await ctx.execute(); + return response; + }; + url = async () => { + if (this._url) { + return this._url; + } + const ctx = this._ctx.select("url"); + const response = await ctx.execute(); + return response; + }; +} + +class Stat extends BaseClient { + _id = undefined; + _fileType = undefined; + _name = undefined; + _permissions = undefined; + _size = undefined; + constructor(ctx, _id, _fileType, _name, _permissions, _size) { + super(ctx); + this._id = _id; + this._fileType = _fileType; + this._name = _name; + this._permissions = _permissions; + this._size = _size; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + fileType = async () => { + if (this._fileType) { + return this._fileType; + } + const ctx = this._ctx.select("fileType"); + const response = await ctx.execute(); + return FileTypeNameToValue(response); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + permissions = async () => { + if (this._permissions) { + return this._permissions; + } + const ctx = this._ctx.select("permissions"); + const response = await ctx.execute(); + return response; + }; + size = async () => { + if (this._size) { + return this._size; + } + const ctx = this._ctx.select("size"); + const response = await ctx.execute(); + return response; + }; +} + +class _SyncerClient extends BaseClient { + _id = undefined; + _sync = undefined; + constructor(ctx, _id, _sync) { + super(ctx); + this._id = _id; + this._sync = _sync; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new _SyncerClient(ctx.copy().selectNode(response, "Syncer")); + }; +} + +class Terminal extends BaseClient { + _id = undefined; + _sync = undefined; + constructor(ctx, _id, _sync) { + super(ctx); + this._id = _id; + this._sync = _sync; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + sync = async () => { + const ctx = this._ctx.select("sync"); + const response = await ctx.execute(); + return new Terminal(ctx.copy().selectNode(response, "Terminal")); + }; +} + +class TypeDef extends BaseClient { + _id = undefined; + _kind = undefined; + _name = undefined; + _optional = undefined; + constructor(ctx, _id, _kind, _name, _optional) { + super(ctx); + this._id = _id; + this._kind = _kind; + this._name = _name; + this._optional = _optional; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + asEnum = () => { + const ctx = this._ctx.select("asEnum"); + return new EnumTypeDef(ctx); + }; + asInput = () => { + const ctx = this._ctx.select("asInput"); + return new InputTypeDef(ctx); + }; + asInterface = () => { + const ctx = this._ctx.select("asInterface"); + return new InterfaceTypeDef(ctx); + }; + asList = () => { + const ctx = this._ctx.select("asList"); + return new ListTypeDef(ctx); + }; + asObject = () => { + const ctx = this._ctx.select("asObject"); + return new ObjectTypeDef(ctx); + }; + asScalar = () => { + const ctx = this._ctx.select("asScalar"); + return new ScalarTypeDef(ctx); + }; + kind = async () => { + if (this._kind) { + return this._kind; + } + const ctx = this._ctx.select("kind"); + const response = await ctx.execute(); + return TypeDefKindNameToValue(response); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + optional = async () => { + if (this._optional) { + return this._optional; + } + const ctx = this._ctx.select("optional"); + const response = await ctx.execute(); + return response; + }; + withConstructor = (function_) => { + const ctx = this._ctx.select("withConstructor", { + function: function_ + }); + return new TypeDef(ctx); + }; + withEnum = (name, opts) => { + const ctx = this._ctx.select("withEnum", { name, ...opts }); + return new TypeDef(ctx); + }; + withEnumMember = (name, opts) => { + const ctx = this._ctx.select("withEnumMember", { name, ...opts }); + return new TypeDef(ctx); + }; + withEnumValue = (value, opts) => { + const ctx = this._ctx.select("withEnumValue", { value, ...opts }); + return new TypeDef(ctx); + }; + withField = (name, typeDef, opts) => { + const ctx = this._ctx.select("withField", { name, typeDef, ...opts }); + return new TypeDef(ctx); + }; + withFunction = (function_) => { + const ctx = this._ctx.select("withFunction", { + function: function_ + }); + return new TypeDef(ctx); + }; + withInterface = (name, opts) => { + const ctx = this._ctx.select("withInterface", { name, ...opts }); + return new TypeDef(ctx); + }; + withKind = (kind2) => { + const metadata = { + kind: { is_enum: true, value_to_name: TypeDefKindValueToName } + }; + const ctx = this._ctx.select("withKind", { kind: kind2, __metadata: metadata }); + return new TypeDef(ctx); + }; + withListOf = (elementType) => { + const ctx = this._ctx.select("withListOf", { elementType }); + return new TypeDef(ctx); + }; + withObject = (name, opts) => { + const ctx = this._ctx.select("withObject", { name, ...opts }); + return new TypeDef(ctx); + }; + withOptional = (optional) => { + const ctx = this._ctx.select("withOptional", { optional }); + return new TypeDef(ctx); + }; + withScalar = (name, opts) => { + const ctx = this._ctx.select("withScalar", { name, ...opts }); + return new TypeDef(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class Up extends BaseClient { + _id = undefined; + _description = undefined; + _name = undefined; + constructor(ctx, _id, _description, _name) { + super(ctx); + this._id = _id; + this._description = _description; + this._name = _name; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + originalModule = () => { + const ctx = this._ctx.select("originalModule"); + return new Module_(ctx); + }; + path = async () => { + const ctx = this._ctx.select("path"); + const response = await ctx.execute(); + return response; + }; + run = () => { + const ctx = this._ctx.select("run"); + return new Up(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class UpGroup extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + list = async () => { + const ctx = this._ctx.select("list").select("id"); + const response = await ctx.execute(); + return response.map((r) => new Up(ctx.copy().selectNode(r.id, "Up"))); + }; + run = () => { + const ctx = this._ctx.select("run"); + return new UpGroup(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class Volume extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; +} + +class Workspace extends BaseClient { + _id = undefined; + _address = undefined; + _configFile = undefined; + _configRead = undefined; + _cwd = undefined; + _export = undefined; + _findUp = undefined; + constructor(ctx, _id, _address, _configFile, _configRead, _cwd, _export, _findUp) { + super(ctx); + this._id = _id; + this._address = _address; + this._configFile = _configFile; + this._configRead = _configRead; + this._cwd = _cwd; + this._export = _export; + this._findUp = _findUp; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + address = async () => { + if (this._address) { + return this._address; + } + const ctx = this._ctx.select("address"); + const response = await ctx.execute(); + return response; + }; + changes = () => { + const ctx = this._ctx.select("changes"); + return new Changeset(ctx); + }; + checks = (opts) => { + const ctx = this._ctx.select("checks", { ...opts }); + return new CheckGroup(ctx); + }; + configFile = async () => { + if (this._configFile) { + return this._configFile; + } + const ctx = this._ctx.select("configFile"); + const response = await ctx.execute(); + return response; + }; + configRead = async (opts) => { + if (this._configRead) { + return this._configRead; + } + const ctx = this._ctx.select("configRead", { ...opts }); + const response = await ctx.execute(); + return response; + }; + cwd = async () => { + if (this._cwd) { + return this._cwd; + } + const ctx = this._ctx.select("cwd"); + const response = await ctx.execute(); + return response; + }; + directory = (path, opts) => { + const ctx = this._ctx.select("directory", { path, ...opts }); + return new Directory(ctx); + }; + envList = async () => { + const ctx = this._ctx.select("envList"); + const response = await ctx.execute(); + return response; + }; + export = async () => { + if (this._export) { + return; + } + const ctx = this._ctx.select("export"); + await ctx.execute(); + }; + file = (path) => { + const ctx = this._ctx.select("file", { path }); + return new File(ctx); + }; + findUp = async (name, opts) => { + if (this._findUp) { + return this._findUp; + } + const ctx = this._ctx.select("findUp", { name, ...opts }); + const response = await ctx.execute(); + return response; + }; + generators = (opts) => { + const ctx = this._ctx.select("generators", { ...opts }); + return new GeneratorGroup(ctx); + }; + git = () => { + const ctx = this._ctx.select("git"); + return new WorkspaceGit(ctx); + }; + glob = async (pattern) => { + const ctx = this._ctx.select("glob", { pattern }); + const response = await ctx.execute(); + return response; + }; + migrate = () => { + const ctx = this._ctx.select("migrate"); + return new WorkspaceMigration(ctx); + }; + module_ = (name) => { + const ctx = this._ctx.select("module", { name }); + return new WorkspaceModule(ctx); + }; + moduleSource = (path) => { + const ctx = this._ctx.select("moduleSource", { path }); + return new ModuleSource(ctx); + }; + modules = async () => { + const ctx = this._ctx.select("modules").select("id"); + const response = await ctx.execute(); + return response.map((r) => new WorkspaceModule(ctx.copy().selectNode(r.id, "WorkspaceModule"))); + }; + sdk = (name) => { + const ctx = this._ctx.select("sdk", { name }); + return new WorkspaceSDK(ctx); + }; + sdks = async () => { + const ctx = this._ctx.select("sdks").select("id"); + const response = await ctx.execute(); + return response.map((r) => new WorkspaceSDK(ctx.copy().selectNode(r.id, "WorkspaceSDK"))); + }; + search = async (opts) => { + const ctx = this._ctx.select("search", { ...opts }).select("id"); + const response = await ctx.execute(); + return response.map((r) => new SearchResult(ctx.copy().selectNode(r.id, "SearchResult"))); + }; + services = (opts) => { + const ctx = this._ctx.select("services", { ...opts }); + return new UpGroup(ctx); + }; + withChanges = (changes) => { + const ctx = this._ctx.select("withChanges", { changes }); + return new Workspace(ctx); + }; + withConfigEnv = (name, opts) => { + const ctx = this._ctx.select("withConfigEnv", { name, ...opts }); + return new Workspace(ctx); + }; + withConfigValue = (key, value, opts) => { + const ctx = this._ctx.select("withConfigValue", { key, value, ...opts }); + return new Workspace(ctx); + }; + withInitClient = (path, sdk, module_, opts) => { + const ctx = this._ctx.select("withInitClient", { + path, + sdk, + module: module_, + ...opts + }); + return new Workspace(ctx); + }; + withInitModule = (name, sdk, opts) => { + const ctx = this._ctx.select("withInitModule", { name, sdk, ...opts }); + return new Workspace(ctx); + }; + withModule = (ref, opts) => { + const ctx = this._ctx.select("withModule", { ref, ...opts }); + return new Workspace(ctx); + }; + withNewDirectory = (path, source) => { + const ctx = this._ctx.select("withNewDirectory", { path, source }); + return new Workspace(ctx); + }; + withNewFile = (path, contents, opts) => { + const ctx = this._ctx.select("withNewFile", { path, contents, ...opts }); + return new Workspace(ctx); + }; + withSDK = (ref, opts) => { + const ctx = this._ctx.select("withSDK", { ref, ...opts }); + return new Workspace(ctx); + }; + withUpdatedLock = () => { + const ctx = this._ctx.select("withUpdatedLock"); + return new Workspace(ctx); + }; + withWorkdir = (path) => { + const ctx = this._ctx.select("withWorkdir", { path }); + return new Workspace(ctx); + }; + withoutConfigEnv = (name, opts) => { + const ctx = this._ctx.select("withoutConfigEnv", { name, ...opts }); + return new Workspace(ctx); + }; + withoutConfigValue = (key, opts) => { + const ctx = this._ctx.select("withoutConfigValue", { key, ...opts }); + return new Workspace(ctx); + }; + withoutModule = (name, opts) => { + const ctx = this._ctx.select("withoutModule", { name, ...opts }); + return new Workspace(ctx); + }; + withoutSDK = (name, opts) => { + const ctx = this._ctx.select("withoutSDK", { name, ...opts }); + return new Workspace(ctx); + }; + with = (arg) => { + return arg(this); + }; +} + +class WorkspaceGit extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + head = () => { + const ctx = this._ctx.select("head"); + return new GitRef(ctx); + }; + uncommitted = () => { + const ctx = this._ctx.select("uncommitted"); + return new Changeset(ctx); + }; +} + +class WorkspaceMigration extends BaseClient { + _id = undefined; + constructor(ctx, _id) { + super(ctx); + this._id = _id; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + changes = () => { + const ctx = this._ctx.select("changes"); + return new Changeset(ctx); + }; + steps = async () => { + const ctx = this._ctx.select("steps").select("id"); + const response = await ctx.execute(); + return response.map((r) => new WorkspaceMigrationStep(ctx.copy().selectNode(r.id, "WorkspaceMigrationStep"))); + }; +} + +class WorkspaceMigrationStep extends BaseClient { + _id = undefined; + _code = undefined; + _description = undefined; + constructor(ctx, _id, _code, _description) { + super(ctx); + this._id = _id; + this._code = _code; + this._description = _description; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + changes = () => { + const ctx = this._ctx.select("changes"); + return new Changeset(ctx); + }; + code = async () => { + if (this._code) { + return this._code; + } + const ctx = this._ctx.select("code"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + warnings = async () => { + const ctx = this._ctx.select("warnings"); + const response = await ctx.execute(); + return response; + }; +} + +class WorkspaceModule extends BaseClient { + _id = undefined; + _entrypoint = undefined; + _name = undefined; + _source = undefined; + constructor(ctx, _id, _entrypoint, _name, _source) { + super(ctx); + this._id = _id; + this._entrypoint = _entrypoint; + this._name = _name; + this._source = _source; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + entrypoint = async () => { + if (this._entrypoint) { + return this._entrypoint; + } + const ctx = this._ctx.select("entrypoint"); + const response = await ctx.execute(); + return response; + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + settings = async () => { + const ctx = this._ctx.select("settings").select("id"); + const response = await ctx.execute(); + return response.map((r) => new WorkspaceModuleSetting(ctx.copy().selectNode(r.id, "WorkspaceModuleSetting"))); + }; + source = async () => { + if (this._source) { + return this._source; + } + const ctx = this._ctx.select("source"); + const response = await ctx.execute(); + return response; + }; +} + +class WorkspaceModuleSetting extends BaseClient { + _id = undefined; + _description = undefined; + _isList = undefined; + _key = undefined; + _value = undefined; + constructor(ctx, _id, _description, _isList, _key, _value) { + super(ctx); + this._id = _id; + this._description = _description; + this._isList = _isList; + this._key = _key; + this._value = _value; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + description = async () => { + if (this._description) { + return this._description; + } + const ctx = this._ctx.select("description"); + const response = await ctx.execute(); + return response; + }; + isList = async () => { + if (this._isList) { + return this._isList; + } + const ctx = this._ctx.select("isList"); + const response = await ctx.execute(); + return response; + }; + key = async () => { + if (this._key) { + return this._key; + } + const ctx = this._ctx.select("key"); + const response = await ctx.execute(); + return response; + }; + value = async () => { + if (this._value) { + return this._value; + } + const ctx = this._ctx.select("value"); + const response = await ctx.execute(); + return response; + }; +} + +class WorkspaceSDK extends BaseClient { + _id = undefined; + _name = undefined; + _ref = undefined; + constructor(ctx, _id, _name, _ref) { + super(ctx); + this._id = _id; + this._name = _name; + this._ref = _ref; + } + id = async () => { + if (this._id) { + return this._id; + } + const ctx = this._ctx.select("id"); + const response = await ctx.execute(); + return response; + }; + clients = async () => { + const ctx = this._ctx.select("clients").select("id"); + const response = await ctx.execute(); + return response.map((r) => new WorkspaceModule(ctx.copy().selectNode(r.id, "WorkspaceModule"))); + }; + modules = async () => { + const ctx = this._ctx.select("modules").select("id"); + const response = await ctx.execute(); + return response.map((r) => new WorkspaceModule(ctx.copy().selectNode(r.id, "WorkspaceModule"))); + }; + name = async () => { + if (this._name) { + return this._name; + } + const ctx = this._ctx.select("name"); + const response = await ctx.execute(); + return response; + }; + ref = async () => { + if (this._ref) { + return this._ref; + } + const ctx = this._ctx.select("ref"); + const response = await ctx.execute(); + return response; + }; +} +var dag = new Client; + +// src/index.ts +init_errors(); + +// src/connect.ts +var opentelemetry4 = __toESM(require_src(), 1); + +// src/common/graphql/connect.ts +init_client(); +async function withGQLClient(connectOpts, cb) { + if (process.env["DAGGER_SESSION_PORT"]) { + const port = process.env["DAGGER_SESSION_PORT"]; + if (!process.env["DAGGER_SESSION_TOKEN"]) { + throw new Error("DAGGER_SESSION_TOKEN must be set if DAGGER_SESSION_PORT is set"); + } + const token = process.env["DAGGER_SESSION_TOKEN"]; + return await cb(createGQLClient(Number(port), token)); + } + try { + const provisioning = await Promise.resolve().then(() => (init_provisioning(), exports_provisioning)); + return await provisioning.withEngineSession(connectOpts, cb); + } catch (e2) { + throw new Error(`failed to execute function with automatic provisioning: ${e2}`, { cause: e2 }); + } +} + +// src/connect.ts +async function connection(fct, cfg = {}) { + try { + initialize(); + await opentelemetry4.context.with(getContext(), async () => { + try { + await withGQLClient(cfg, async (gqlClient) => { + globalConnection.setGQLClient(gqlClient); + await fct(); + }); + } finally { + globalConnection.resetClient(); + } + }); + } finally { + await close(); + } +} +async function connect(cb, config = {}) { + await withGQLClient(config, async (gqlClient) => { + const connection2 = new Connection(gqlClient); + const ctx = new Context([], connection2); + const client = new Client(ctx); + try { + await client.version(); + } catch (e2) { + console.error("failed to check version compatibility:", e2); + } + return await cb(client); + }); +} +// src/module/registry.ts +init_errors(); +var import_reflect_metadata = __toESM(require_Reflect(), 1); + +class Registry { + object = () => { + return (constructor) => { + Reflect.defineMetadata(constructor.name, { class_: constructor }, this); + return constructor; + }; + }; + enumType = () => { + return (constructor) => { + return constructor; + }; + }; + field = (alias) => { + return (target, propertyKey) => {}; + }; + func = (opts) => { + return (target, propertyKey, descriptor) => {}; + }; + check = () => { + return (target, propertyKey, descriptor) => {}; + }; + generate = () => { + return (target, propertyKey, descriptor) => {}; + }; + up = () => { + return (target, propertyKey, descriptor) => descriptor; + }; + argument = (opts) => { + return (target, propertyKey, parameterIndex) => {}; + }; + buildClass(object, state) { + const resolver = Reflect.getMetadata(object, this); + if (!resolver) { + return object; + } + let r2 = Object.create(resolver.class_.prototype); + r2 = Object.assign(r2, state); + return r2; + } + async getResult(object, method, state, inputs) { + const resolver = Reflect.getMetadata(object, this); + if (!resolver) { + throw new UnknownDaggerError(`${object} is not register as a resolver`, {}); + } + if (method === "") { + return new resolver.class_(...Object.values(inputs)); + } + let r2 = Object.create(resolver.class_.prototype); + if (!r2[method]) { + throw new UnknownDaggerError(`${method} is not registered in the resolver ${object}`, {}); + } + r2 = Object.assign(r2, state); + return await r2[method](...Object.values(inputs)); + } +} +var registry = new Registry; +function getRegisteredClass(name) { + const meta = Reflect.getMetadata(name, registry); + return meta?.class_; +} + +// src/module/decorators.ts +var object = registry.object; +var func = registry.func; +var check = registry.check; +var generate = registry.generate; +var up = registry.up; +var field = registry.field; +var enumType = registry.enumType; +var argument = registry.argument; +// src/module/entrypoint/entrypoint.ts +init_ExecError(); +init_GraphQLRequestError(); + +// src/module/executor.ts +init_errors(); +class Executor { + modules; + daggerModule; + constructor(modules, daggerModule) { + this.modules = modules; + this.daggerModule = daggerModule; + } + getExportedObject(object2) { + const key = object2; + const module = this.modules.find((m3) => m3[key] !== undefined); + if (!module) { + throw new FunctionNotFound(`Object ${object2} not found`); + } + return module[key]; + } + hasObject(object2) { + return !!this.daggerModule.objects[object2]; + } + buildClass(object2, state) { + const daggerObject = this.daggerModule.objects[object2]; + if (!daggerObject) { + throw new FunctionNotFound(`Object ${object2} not found in the module`); + } + switch (daggerObject.kind()) { + case "class": { + const obj = this.getExportedObject(object2); + const instanciatedClass = Object.create(obj.prototype); + Object.assign(instanciatedClass, state); + return instanciatedClass; + } + case "object": { + return state; + } + } + } + buildInterface(iface, id) { + const interfaceObject = this.daggerModule.interfaces[iface]; + if (!interfaceObject) { + throw new Error(`Interface ${iface} not found in the module`); + } + const ifaceImpl = new InterfaceWrapper(this, this.daggerModule, `${this.daggerModule.name}${iface}`, id, interfaceObject.functions); + return ifaceImpl; + } + buildEnum(enumName, value) { + const enumObject = this.daggerModule.enums[enumName]; + if (!enumObject) { + return value; + } + if (!enumObject.values[value]) { + throw new Error(`Enum ${enumName} does not have member ${value}`); + } + return enumObject.values[value].value; + } + async getResult(object2, method, state, inputs) { + const obj = this.getExportedObject(object2); + if (method === "") { + return new obj(...Object.values(inputs)); + } + const builtObj = this.buildClass(object2, state); + if (!builtObj[method]) { + throw new FunctionNotFound(`Method ${method} not found`); + } + return await builtObj[method](...Object.values(inputs)); + } +} + +class InterfaceWrapper { + executor; + module; + ifaceName; + ifaceId; + fcts; + _ctx; + constructor(executor, module, ifaceName, ifaceId, fcts) { + this.executor = executor; + this.module = module; + this.ifaceName = ifaceName; + this.ifaceId = ifaceId; + this.fcts = fcts; + this._ctx = new Context([], new Connection(dag.getGQLClient())); + this._ctx = this._ctx.selectNode(ifaceId, ifaceName); + Object.entries(fcts).forEach(([name, fct]) => { + const argKeys = Object.keys(fct.arguments); + this[name] = async (...args) => { + const argsPayload = {}; + for (let i3 = 0;i3 < argKeys.length; i3++) { + if (args[i3] !== undefined) { + argsPayload[argKeys[i3]] = args[i3]; + } + } + this._ctx = this._ctx.select(name, argsPayload); + if (fct.returnType.kind === "INTERFACE_KIND" /* InterfaceKind */ || fct.returnType.kind === "OBJECT_KIND" /* ObjectKind */) { + return this; + } + if (fct.returnType.kind === "LIST_KIND" /* ListKind */) { + const listTypeDef = fct.returnType.typeDef; + if (listTypeDef.kind === "OBJECT_KIND" /* ObjectKind */ || listTypeDef.kind === "INTERFACE_KIND" /* InterfaceKind */) { + const typedef = listTypeDef; + const ids = await this._ctx.select("id").execute(); + if (this.module.interfaces[typedef.name]) { + return await Promise.all(ids.map(({ id }) => new InterfaceWrapper(this.executor, module, `${this.module.name}${typedef.name}`, id, this.module.interfaces[typedef.name].functions))); + } + return ids.map(({ id }) => { + const ctx = new Context([], new Connection(dag.getGQLClient())).selectNode(id, typedef.name); + const className = exports_client_gen[typedef.name] ? typedef.name : `${typedef.name}_`; + const cls = exports_client_gen[className]; + if (cls) { + return new cls(ctx); + } + throw new Error(`Generated client class not found for core type ${typedef.name}`); + }); + } + } + return await this._ctx.execute(); + }; + }); + } + async id() { + const ctx = this._ctx.select("id"); + return await ctx.execute(); + } +} + +// src/module/introspector/index.ts +init_errors(); + +// src/module/introspector/dagger_module/argument.ts +init_errors(); +import ts4 from "typescript"; + +// src/module/introspector/typescript_module/ast.ts +import * as path8 from "path"; +import ts3 from "typescript"; +init_errors(); + +// src/module/introspector/typescript_module/declarations.ts +import ts2 from "typescript"; +var isDeclarationOf = { + [ts2.SyntaxKind.ClassDeclaration]: ts2.isClassDeclaration, + [ts2.SyntaxKind.MethodDeclaration]: ts2.isMethodDeclaration, + [ts2.SyntaxKind.PropertyDeclaration]: ts2.isPropertyDeclaration, + [ts2.SyntaxKind.FunctionDeclaration]: ts2.isFunctionDeclaration, + [ts2.SyntaxKind.EnumDeclaration]: ts2.isEnumDeclaration, + [ts2.SyntaxKind.InterfaceDeclaration]: ts2.isInterfaceDeclaration, + [ts2.SyntaxKind.TypeAliasDeclaration]: ts2.isTypeAliasDeclaration +}; + +// src/module/introspector/typescript_module/ast.ts +var CLIENT_GEN_FILE = "client.gen.ts"; +var GENERATED_CLIENT_SUFFIX = ".gen.ts"; + +class AST { + files; + userModule; + checker; + sourceFiles; + generatedClientFiles; + constructor(files2, userModule2, generatedClientFiles = []) { + this.files = files2; + this.userModule = userModule2; + this.files = files2.map((f4) => path8.resolve(f4)); + this.generatedClientFiles = new Set(generatedClientFiles.map((f4) => path8.resolve(f4))); + const program = ts3.createProgram(files2, { + experimentalDecorators: true, + moduleResolution: ts3.ModuleResolutionKind.Node10, + target: ts3.ScriptTarget.ES2022 + }); + this.checker = program.getTypeChecker(); + this.sourceFiles = program.getSourceFiles().filter((file) => !file.isDeclarationFile); + } + isGeneratedClientFile(fileName) { + if (this.generatedClientFiles.size > 0) { + return this.generatedClientFiles.has(path8.resolve(fileName)); + } + return fileName.endsWith(GENERATED_CLIENT_SUFFIX); + } + findResolvedNodeByName(name, kind2) { + let result; + for (const sourceFile of this.sourceFiles) { + ts3.forEachChild(sourceFile, (node) => { + if (result !== undefined) + return; + if (!this.isGeneratedClientFile(sourceFile.fileName) && !this.files.includes(path8.resolve(sourceFile.fileName))) { + return; + } + if (kind2 !== undefined && node.kind === kind2) { + const isDeclarationValid = isDeclarationOf[kind2](node); + if (!isDeclarationValid) + return; + const convertedNode = node; + if (!convertedNode.name || convertedNode.name.getText() !== name) { + return; + } + const symbol = this.checker.getSymbolAtLocation(convertedNode.name); + if (!symbol) { + console.debug(`missing symbol for ${name} at ${sourceFile.fileName}:${node.pos}`); + return; + } + result = { + type: kind2, + node: convertedNode, + symbol, + file: sourceFile + }; + } + }); + } + return result; + } + findAllDeclarations(kind2) { + const results = []; + for (const sourceFile of this.sourceFiles) { + ts3.forEachChild(sourceFile, (node) => { + if (!this.isGeneratedClientFile(sourceFile.fileName) && !this.files.includes(path8.resolve(sourceFile.fileName))) { + return; + } + if (kind2 !== undefined && node.kind === kind2) { + const isDeclarationValid = isDeclarationOf[kind2](node); + if (!isDeclarationValid) + return; + const convertedNode = node; + if (!convertedNode.name) { + return; + } + const symbol = this.checker.getSymbolAtLocation(convertedNode.name); + if (!symbol) { + console.debug(`missing symbol for ${convertedNode.name.getText()} at ${sourceFile.fileName}:${node.pos}`); + return; + } + results.push({ + type: kind2, + node: convertedNode, + symbol, + file: sourceFile + }); + } + }); + } + return results; + } + getTypeFromTypeAlias(typeAlias) { + const symbol = this.getSymbolOrThrow(typeAlias.name); + return this.checker.getDeclaredTypeOfSymbol(symbol); + } + static getNodePosition(node) { + const sourceFile = node.getSourceFile(); + const position = ts3.getLineAndCharacterOfPosition(sourceFile, node.getStart()); + return `${sourceFile.fileName}:${position.line}:${position.character}`; + } + static getNodeLocation(node) { + const sourceFile = node.getSourceFile(); + const targetNode = node.name ?? node; + const position = ts3.getLineAndCharacterOfPosition(sourceFile, targetNode.getStart(sourceFile)); + const pathParts = path8.resolve(sourceFile.fileName).split(path8.sep); + const srcIndex = pathParts.indexOf("src", 2); + return { + filepath: pathParts.slice(srcIndex).join(path8.sep), + line: position.line + 1, + column: position.character + 1 + }; + } + getDocFromSymbol(symbol) { + return this.getSymbolDoc(symbol).description; + } + getSymbolDoc(symbol) { + const description = ts3.displayPartsToString(symbol.getDocumentationComment(this.checker)).trim(); + let deprecated; + let hasDeprecatedTag = false; + for (const tag of symbol.getJsDocTags()) { + if (tag.name !== "deprecated") + continue; + hasDeprecatedTag = true; + const text = tag.text?.map((part) => ("text" in part) ? part.text : part).join("") ?? ""; + deprecated = text.trim(); + break; + } + if (!hasDeprecatedTag) { + return { description }; + } + return { + description, + deprecated: deprecated ?? "" + }; + } + getSymbolOrThrow(node) { + const symbol = this.getSymbol(node); + if (!symbol) { + throw new IntrospectionError(`could not find symbol at ${AST.getNodePosition(node)}`); + } + return symbol; + } + getSignatureFromFunctionOrThrow(node) { + const signature = this.checker.getSignatureFromDeclaration(node); + if (!signature) { + throw new IntrospectionError(`could not find signature at ${AST.getNodePosition(node)}`); + } + return signature; + } + getSymbol(node) { + return this.checker.getSymbolAtLocation(node); + } + isNodeDecoratedWith(node, daggerDecorator) { + const decorators = ts3.getDecorators(node); + if (!decorators) { + return false; + } + const decorator = decorators.find((d) => d.expression.getText().startsWith(daggerDecorator)); + if (!decorator) { + return false; + } + if (!ts3.isCallExpression(decorator.expression)) { + throw new IntrospectionError(`decorator at ${AST.getNodePosition(node)} should be a call expression, please use ${daggerDecorator}() instead.`); + } + return true; + } + getDecoratorArgument(node, daggerDecorator, type, position = 0) { + const decorators = ts3.getDecorators(node); + if (!decorators) { + return; + } + const decorator = decorators.find((d) => d.expression.getText().startsWith(daggerDecorator)); + if (!decorator) { + return; + } + const argument2 = decorator.expression.arguments[position]; + if (!argument2) { + return; + } + switch (type) { + case "string": + return argument2.getText(); + case "object": + return this.resolveDecoratorArgumentValue(argument2); + } + } + resolveDecoratorArgumentValue(expression2) { + if (ts3.isObjectLiteralExpression(expression2)) { + const result = {}; + for (const property of expression2.properties) { + if (ts3.isPropertyAssignment(property)) { + result[this.getPropertyName(property.name)] = this.resolveParameterDefaultValue(property.initializer); + } else if (ts3.isShorthandPropertyAssignment(property)) { + result[property.name.getText()] = this.resolveParameterDefaultValue(property.name); + } + } + return result; + } + return this.resolveParameterDefaultValue(expression2); + } + getPropertyName(name) { + if (ts3.isStringLiteral(name) || ts3.isNumericLiteral(name)) { + return name.text; + } + return name.getText(); + } + unwrapTypeStringFromPromise(type) { + if (type.startsWith("Promise<")) { + return type.slice("Promise<".length, -">".length); + } + if (type.startsWith("Awaited<")) { + return type.slice("Awaited<".length, -">".length); + } + return type; + } + unwrapTypeStringFromArray(type) { + if (type.endsWith("[]")) { + return type.replace("[]", ""); + } + if (type.startsWith("Array<")) { + return type.slice("Array<".length, -">".length); + } + return type; + } + stringTypeToUnwrappedType(type) { + type = this.unwrapTypeStringFromPromise(type); + const extractedTypeFromArray = this.unwrapTypeStringFromArray(type); + if (extractedTypeFromArray !== type) { + return this.stringTypeToUnwrappedType(extractedTypeFromArray); + } + return type; + } + typeToStringType(type) { + const stringType = this.checker.typeToString(this.unwrapNullable(type)); + return this.stringTypeToUnwrappedType(stringType); + } + unwrapNullable(type) { + if (type.flags & ts3.TypeFlags.Union) { + return this.checker.getNonNullableType(type); + } + return type; + } + tsTypeToTypeDef(node, type) { + type = this.unwrapNullable(type); + if (type.flags & ts3.TypeFlags.String) + return { kind: "STRING_KIND" /* StringKind */ }; + if (type.flags & ts3.TypeFlags.Number) { + if (node.getText().includes("float")) { + return { kind: "FLOAT_KIND" /* FloatKind */ }; + } + return { kind: "INTEGER_KIND" /* IntegerKind */ }; + } + if (type.flags & ts3.TypeFlags.Boolean) + return { kind: "BOOLEAN_KIND" /* BooleanKind */ }; + if (type.flags & ts3.TypeFlags.Void) + return { kind: "VOID_KIND" /* VoidKind */ }; + if (type.flags & ts3.TypeFlags.Object) { + const objectType = type; + if (objectType.objectFlags & ts3.ObjectFlags.Reference) { + const typeArguments = this.checker.getTypeArguments(type); + switch (typeArguments.length) { + case 0: + break; + case 1: { + const typeArgument = typeArguments[0]; + if (type.symbol.getName() === "Promise") { + return this.tsTypeToTypeDef(node, typeArgument); + } + if (type.symbol.getName() === "Array") { + return { + kind: "LIST_KIND" /* ListKind */, + typeDef: this.tsTypeToTypeDef(node, typeArgument) + }; + } + return; + } + default: { + throw new IntrospectionError(`could not resolve type ${type.symbol.getName()} at ${AST.getNodePosition(node)}, dagger does not support generics with argument yet.`); + } + } + } + } + } + resolveParameterDefaultValueTypeReference(expression2, value) { + const type = typeof value; + switch (type) { + case "string": + case "number": + case "bigint": + case "boolean": + case "object": + return value; + default: + return; + } + } + getLiteralValueFromExpression(expression2) { + const type = this.checker.getTypeAtLocation(expression2); + if (!type) { + return; + } + const resolveLiteral = (t2) => { + if (t2.flags & ts3.TypeFlags.BooleanLiteral) { + const intrinsic = t2; + switch (intrinsic.intrinsicName) { + case "true": + return true; + case "false": + return false; + } + } + if (t2.flags & (ts3.TypeFlags.EnumLiteral | ts3.TypeFlags.StringLiteral | ts3.TypeFlags.NumberLiteral | ts3.TypeFlags.BigIntLiteral)) { + const literal = t2; + if (literal.value !== undefined) { + return literal.value; + } + const intrinsic = literal; + if (intrinsic.intrinsicName !== undefined) { + return intrinsic.intrinsicName; + } + } + return; + }; + if (type.isUnion()) { + for (const subtype of type.types) { + const literal = resolveLiteral(subtype); + if (literal !== undefined) { + return literal; + } + } + return; + } + return resolveLiteral(type); + } + warnUnresolvedDefaultValue(expression2) { + console.warn(`default value '${expression2.getText()}' at ${AST.getNodePosition(expression2)} cannot be resolved, dagger does not support object or function as default value. + The value will be ignored by the introspection and resolve at the runtime.`); + } + resolveParameterDefaultValue(expression) { + const kind = expression.kind; + switch (kind) { + case ts3.SyntaxKind.StringLiteral: + return `${eval(expression.getText())}`; + case ts3.SyntaxKind.NumericLiteral: + return parseInt(expression.getText()); + case ts3.SyntaxKind.TrueKeyword: + return true; + case ts3.SyntaxKind.FalseKeyword: + return false; + case ts3.SyntaxKind.NullKeyword: + return null; + case ts3.SyntaxKind.ArrayLiteralExpression: + return eval(expression.getText()); + case ts3.SyntaxKind.Identifier: { + const symbol = this.checker.getSymbolAtLocation(expression); + if (!symbol) { + throw new IntrospectionError(`could not resolve default value reference to the variable: '${expression.getText()}' from ${AST.getNodePosition(expression)}. Is it exported by the module?`); + } + const decl = symbol.valueDeclaration ?? symbol.declarations?.[0]; + if (!decl) { + this.warnUnresolvedDefaultValue(expression); + return; + } + if (ts3.isVariableDeclaration(decl) && decl.initializer) { + return this.resolveParameterDefaultValue(decl.initializer); + } + if (ts3.isEnumMember(decl)) { + const val = this.checker.getConstantValue(decl); + if (val !== undefined) + return val; + if (decl.initializer) + return this.resolveParameterDefaultValue(decl.initializer); + } + if (ts3.isImportSpecifier(decl)) { + const aliased = this.checker.getAliasedSymbol(symbol); + const aliasedDecl = aliased?.valueDeclaration ?? aliased?.declarations?.[0]; + if (aliasedDecl && ts3.isVariableDeclaration(aliasedDecl) && aliasedDecl.initializer) { + return this.resolveParameterDefaultValue(aliasedDecl.initializer); + } + } + this.warnUnresolvedDefaultValue(expression); + return; + } + case ts3.SyntaxKind.PropertyAccessExpression: { + const propertyAccess = expression; + const directConstant = this.checker.getConstantValue(propertyAccess); + if (directConstant !== undefined) { + return directConstant; + } + const nameSymbol = this.checker.getSymbolAtLocation(propertyAccess.name); + if (nameSymbol) { + const declarations = nameSymbol.declarations ?? []; + const decls = nameSymbol.valueDeclaration ? [nameSymbol.valueDeclaration, ...declarations] : declarations; + for (const decl of decls) { + if (ts3.isEnumMember(decl)) { + const val = this.checker.getConstantValue(decl); + if (val !== undefined) { + return val; + } + if (decl.initializer) { + return this.resolveParameterDefaultValue(decl.initializer); + } + } + } + } + const literal = this.getLiteralValueFromExpression(propertyAccess); + if (literal !== undefined) { + return literal; + } + this.warnUnresolvedDefaultValue(expression); + return; + } + default: { + this.warnUnresolvedDefaultValue(expression); + } + } + } +} +// src/module/introspector/typescript_module/typedef_utils.ts +init_errors(); +function isTypeDefResolved(typeDef) { + if (typeDef.kind !== "LIST_KIND" /* ListKind */) { + return true; + } + const arrayTypeDef = typeDef; + if (arrayTypeDef.typeDef === undefined) { + return false; + } + if (arrayTypeDef.typeDef.kind === "LIST_KIND" /* ListKind */) { + return isTypeDefResolved(arrayTypeDef.typeDef); + } + return true; +} +function resolveTypeDef(typeDef, reference) { + if (typeDef === undefined) { + return reference; + } + if (typeDef.kind === "LIST_KIND" /* ListKind */) { + const listTypeDef = typeDef; + listTypeDef.typeDef = resolveTypeDef(listTypeDef.typeDef, reference); + return listTypeDef; + } + throw new IntrospectionError(`type ${JSON.stringify(typeDef)} has already been resolved, it should not be overwritten ; reference: ${JSON.stringify(reference)}`); +} +// src/module/introspector/dagger_module/decorator.ts +var OBJECT_DECORATOR = object.name; +var FUNCTION_DECORATOR = func.name; +var CHECK_DECORATOR = check.name; +var GENERATOR_DECORATOR = generate.name; +var UP_DECORATOR = up.name; +var FIELD_DECORATOR = field.name; +var ARGUMENT_DECORATOR = argument.name; +var ENUM_DECORATOR = enumType.name; + +// src/module/introspector/dagger_module/locatable.ts +class Locatable { + __node; + constructor(__node) { + this.__node = __node; + } + getLocation() { + return AST.getNodeLocation(this.__node); + } +} + +// src/module/introspector/dagger_module/argument.ts +class DaggerArgument extends Locatable { + node; + ast; + name; + description; + deprecated; + _typeRef; + type; + isVariadic; + isNullable; + isOptional; + defaultPath; + defaultAddress; + ignore; + defaultValue; + symbol; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + this.symbol = this.ast.getSymbolOrThrow(node.name); + this.name = this.node.name.getText(); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + this.defaultValue = this.getDefaultValue(); + this.isVariadic = this.node.dotDotDotToken !== undefined; + this.isNullable = this.getIsNullable(); + this.isOptional = this.isVariadic || this.defaultValue === undefined && this.node.initializer !== undefined || this.isNullable || this.node.questionToken !== undefined; + if (this.deprecated !== undefined && !this.isOptional) { + throw new IntrospectionError(`argument ${this.name} is required and cannot be deprecated at ${AST.getNodePosition(this.node)}.`); + } + const decoratorArguments = this.ast.getDecoratorArgument(this.node, ARGUMENT_DECORATOR, "object"); + if (decoratorArguments) { + this.ignore = decoratorArguments.ignore; + this.defaultPath = decoratorArguments.defaultPath; + this.defaultAddress = decoratorArguments.defaultAddress; + if (this.defaultAddress) { + this.isOptional = true; + } + } + this.type = this.getType(); + } + getType() { + const type = this.ast.checker.getTypeAtLocation(this.node); + const typedef = this.ast.tsTypeToTypeDef(this.node, type); + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._typeRef = this.ast.typeToStringType(type); + } + return typedef; + } + getIsNullable() { + if (!this.node.type) { + return false; + } + if (ts4.isUnionTypeNode(this.node.type)) { + for (const _type of this.node.type.types) { + if (_type.getText() === "null") { + return true; + } + } + } + return false; + } + getDefaultValue() { + const initializer = this.node.initializer; + if (!initializer) { + return; + } + return this.ast.resolveParameterDefaultValue(initializer); + } + getReference() { + if (this._typeRef && (this.type === undefined || !isTypeDefResolved(this.type))) { + return this._typeRef; + } + return; + } + propagateReferences(references) { + if (!this._typeRef) { + return; + } + if (this.type && isTypeDefResolved(this.type)) { + return; + } + const typeDef = references[this._typeRef]; + if (!typeDef) { + throw new IntrospectionError(`could not find type reference for ${this._typeRef} at ${AST.getNodePosition(this.node)}.`); + } + this.type = resolveTypeDef(this.type, typeDef); + } + toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + type: this.type, + isVariadic: this.isVariadic, + isNullable: this.isNullable, + isOptional: this.isOptional, + defaultValue: this.defaultValue, + defaultPath: this.defaultPath, + defaultAddress: this.defaultAddress, + ignore: this.ignore + }; + } +} + +// src/module/introspector/dagger_module/constructor.ts +class DaggerConstructor { + node; + ast; + name = ""; + arguments = {}; + constructor(node, ast2) { + this.node = node; + this.ast = ast2; + const parameters = this.node.parameters; + for (const parameter of parameters) { + this.arguments[parameter.name.getText()] = new DaggerArgument(parameter, this.ast); + } + } + getArgsOrder() { + return Object.keys(this.arguments); + } + getReferences() { + const references = []; + for (const argument2 of Object.values(this.arguments)) { + const ref = argument2.getReference(); + if (ref) { + references.push(ref); + } + } + return references; + } + propagateReferences(references) { + for (const argument2 of Object.values(this.arguments)) { + argument2.propagateReferences(references); + } + } + toJSON() { + return { + arguments: this.arguments + }; + } +} +// src/module/introspector/dagger_module/enum.ts +init_errors(); +class DaggerEnumValue extends Locatable { + node; + ast; + name; + value; + description; + deprecated; + symbol; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + this.name = this.node.name.getText(); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + const initializer = this.node.initializer; + if (!initializer) { + throw new IntrospectionError(`enum ${this.name} at ${AST.getNodePosition(this.node)} has no value set to its member.`); + } + this.value = this.ast.resolveParameterDefaultValue(initializer); + } + toJSON() { + return { + name: this.name, + value: this.value, + description: this.description, + deprecated: this.deprecated + }; + } +} + +class DaggerEnum extends Locatable { + node; + ast; + name; + description; + values = {}; + symbol; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + this.name = this.node.name.getText(); + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + this.description = this.ast.getDocFromSymbol(this.symbol); + const members = this.node.members; + for (const member of members) { + const value = new DaggerEnumValue(member, this.ast); + this.values[value.name] = value; + } + } + toJSON() { + return { + name: this.name, + description: this.description, + values: this.values + }; + } +} +// src/module/introspector/dagger_module/enumClass.ts +init_errors(); +import ts5 from "typescript"; +class DaggerEnumClassValue extends Locatable { + node; + ast; + name; + value; + description; + deprecated; + symbol; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + this.name = this.node.name.getText(); + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + const initializer = this.node.initializer; + if (!initializer) { + throw new Error("Dagger enum value has no value set"); + } + this.value = this.ast.resolveParameterDefaultValue(initializer); + } + toJSON() { + return { + name: this.name, + value: this.value, + description: this.description, + deprecated: this.deprecated + }; + } +} + +class DaggerEnumClass extends Locatable { + node; + ast; + name; + description; + values = {}; + symbol; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + if (!this.node.name) { + throw new IntrospectionError(`could not resolve name of enum at ${AST.getNodePosition(node)}.`); + } + this.name = this.node.name.getText(); + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + this.description = this.ast.getDocFromSymbol(this.symbol); + const properties = this.node.members; + for (const property of properties) { + if (ts5.isPropertyDeclaration(property)) { + const value = new DaggerEnumClassValue(property, this.ast); + this.values[value.name] = value; + } + } + } + toJSON() { + return { + name: this.name, + description: this.description, + values: this.values + }; + } +} +// src/module/introspector/dagger_module/function.ts +init_errors(); +class DaggerFunction extends Locatable { + node; + ast; + name; + description; + deprecated; + _returnTypeRef; + returnType; + arguments = {}; + alias; + cache; + isCheck = false; + isGenerator = false; + isUp = false; + signature; + symbol; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + this.symbol = this.ast.getSymbolOrThrow(node.name); + this.signature = this.ast.getSignatureFromFunctionOrThrow(node); + this.name = this.node.name.getText(); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + const functionArguments = this.ast.getDecoratorArgument(this.node, FUNCTION_DECORATOR, "object"); + if (functionArguments) { + if (typeof functionArguments === "string") { + this.alias = functionArguments; + } else { + this.alias = functionArguments.alias; + this.cache = functionArguments.cache; + } + } + if (this.ast.isNodeDecoratedWith(this.node, CHECK_DECORATOR)) { + this.isCheck = true; + } + if (this.ast.isNodeDecoratedWith(this.node, GENERATOR_DECORATOR)) { + this.isGenerator = true; + } + if (this.ast.isNodeDecoratedWith(this.node, UP_DECORATOR)) { + this.isUp = true; + } + for (const parameter of this.node.parameters) { + this.arguments[parameter.name.getText()] = new DaggerArgument(parameter, this.ast); + } + this.returnType = this.getReturnType(); + } + getReturnType() { + const type = this.signature.getReturnType(); + const typedef = this.ast.tsTypeToTypeDef(this.node, type); + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._returnTypeRef = this.ast.typeToStringType(type); + } + return typedef; + } + getArgsOrder() { + return Object.keys(this.arguments); + } + getReferences() { + const references = []; + if (this._returnTypeRef && (this.returnType === undefined || !isTypeDefResolved(this.returnType))) { + references.push(this._returnTypeRef); + } + for (const argument2 of Object.values(this.arguments)) { + const reference = argument2.getReference(); + if (reference) { + references.push(reference); + } + } + return references; + } + propagateReferences(references) { + for (const argument2 of Object.values(this.arguments)) { + argument2.propagateReferences(references); + } + if (!this._returnTypeRef) { + return; + } + if (this.returnType && isTypeDefResolved(this.returnType)) { + return; + } + const typeDef = references[this._returnTypeRef]; + if (!typeDef) { + throw new IntrospectionError(`could not find type reference for ${this._returnTypeRef} at ${AST.getNodePosition(this.node)}.`); + } + this.returnType = resolveTypeDef(this.returnType, typeDef); + } + toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + alias: this.alias, + arguments: this.arguments, + returnType: this.returnType + }; + } +} +// src/module/introspector/dagger_module/module.ts +import ts10 from "typescript"; +init_errors(); + +// src/module/introspector/dagger_module/interface.ts +init_errors(); +import ts7 from "typescript"; + +// src/module/introspector/dagger_module/interfaceFunction.ts +init_errors(); +import ts6 from "typescript"; +class DaggerInterfaceFunction extends Locatable { + node; + ast; + name; + description; + deprecated; + _returnTypeRef; + returnType; + arguments = {}; + symbol; + signature; + alias; + cache; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + if (!this.node.name) { + throw new IntrospectionError(`could not resolve name of interface function at ${AST.getNodePosition(node)}`); + } + this.name = this.node.name.getText(); + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + const nodeType = this.node.type && ts6.isFunctionTypeNode(this.node.type) ? this.node.type : this.node; + const signature = this.ast.getSignatureFromFunctionOrThrow(nodeType); + for (const parameter of nodeType.parameters) { + this.arguments[parameter.name.getText()] = new DaggerArgument(parameter, this.ast); + } + const signatureReturnType = signature.getReturnType(); + const typedef = this.ast.tsTypeToTypeDef(this.node, signatureReturnType); + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._returnTypeRef = this.ast.typeToStringType(signatureReturnType); + } + this.returnType = typedef; + } + getReferences() { + const references = []; + if (this._returnTypeRef && (this.returnType === undefined || !isTypeDefResolved(this.returnType))) { + references.push(this._returnTypeRef); + } + for (const argument2 of Object.values(this.arguments)) { + const reference = argument2.getReference(); + if (reference) { + references.push(reference); + } + } + return references; + } + propagateReferences(references) { + for (const argument2 of Object.values(this.arguments)) { + argument2.propagateReferences(references); + } + if (!this._returnTypeRef) { + return; + } + if (this.returnType && isTypeDefResolved(this.returnType)) { + return; + } + const typeDef = references[this._returnTypeRef]; + if (!typeDef) { + throw new IntrospectionError(`could not find type reference for ${this._returnTypeRef} at ${AST.getNodePosition(this.node)}.`); + } + this.returnType = resolveTypeDef(this.returnType, typeDef); + } + toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + arguments: this.arguments, + returnType: this.returnType + }; + } +} + +// src/module/introspector/dagger_module/interface.ts +class DaggerInterface extends Locatable { + node; + ast; + name; + description; + functions = {}; + symbol; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + if (!this.node.name) { + throw new IntrospectionError(`could not resolve name of interface at ${AST.getNodePosition(node)}`); + } + this.name = this.node.name.getText(); + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + this.description = this.ast.getDocFromSymbol(this.symbol); + for (const member of this.node.members) { + if (!ts7.isPropertySignature(member) && !ts7.isMethodSignature(member)) { + continue; + } + if (member.type && ts7.isFunctionTypeNode(member.type) || ts7.isMethodSignature(member)) { + const daggerInterfaceFunction = new DaggerInterfaceFunction(member, this.ast); + this.functions[daggerInterfaceFunction.name] = daggerInterfaceFunction; + continue; + } + } + } + getReferences() { + const references = []; + for (const fn of Object.values(this.functions)) { + references.push(...fn.getReferences()); + } + return references.filter((v2, i3, arr) => arr.indexOf(v2) === i3); + } + propagateReferences(references) { + for (const fn of Object.values(this.functions)) { + fn.propagateReferences(references); + } + } + toJSON() { + return { + name: this.name, + description: this.description, + functions: this.functions + }; + } +} + +// src/module/introspector/dagger_module/object.ts +init_errors(); +import ts8 from "typescript"; + +// src/module/introspector/dagger_module/property.ts +init_errors(); +class DaggerProperty extends Locatable { + node; + ast; + name; + description; + deprecated; + alias; + isExposed; + symbol; + _typeRef; + type; + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + if (!this.node.name) { + throw new IntrospectionError(`could not resolve name of class at ${AST.getNodePosition(node)}.`); + } + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + this.name = this.node.name.getText(); + this.isExposed = this.ast.isNodeDecoratedWith(this.node, FUNCTION_DECORATOR) || this.ast.isNodeDecoratedWith(this.node, FIELD_DECORATOR); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + this.alias = this.getAlias(); + this.type = this.getType(); + } + getAlias() { + let alias = this.ast.getDecoratorArgument(this.node, FUNCTION_DECORATOR, "string"); + if (alias) { + return JSON.parse(alias.replace(/'/g, '"')); + } + alias = this.ast.getDecoratorArgument(this.node, FIELD_DECORATOR, "string"); + if (alias) { + return JSON.parse(alias.replace(/'/g, '"')); + } + } + getType() { + const type = this.ast.checker.getTypeAtLocation(this.node); + const typedef = this.ast.tsTypeToTypeDef(this.node, type); + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._typeRef = this.ast.typeToStringType(type); + } + return typedef; + } + getReference() { + if (this._typeRef && (this.type === undefined || !isTypeDefResolved(this.type))) { + return this._typeRef; + } + return; + } + propagateReferences(references) { + if (!this._typeRef) { + return; + } + if (this.type && isTypeDefResolved(this.type)) { + return; + } + const typeDef = references[this._typeRef]; + if (!typeDef) { + throw new IntrospectionError(`could not find type reference for ${this._typeRef} at ${AST.getNodePosition(this.node)}.`); + } + this.type = resolveTypeDef(this.type, typeDef); + } + toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + alias: this.alias, + type: this.type, + isExposed: this.isExposed + }; + } +} + +// src/module/introspector/dagger_module/object.ts +class DaggerObject extends Locatable { + node; + ast; + name; + description; + deprecated; + _constructor = undefined; + methods = {}; + properties = {}; + isExported = false; + isDefaultExport = false; + symbol; + kind() { + return "class"; + } + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + if (!this.node.name) { + throw new IntrospectionError(`could not resolve name of class at ${AST.getNodePosition(node)}.`); + } + this.name = this.node.name.getText(); + if (!this.ast.isNodeDecoratedWith(node, OBJECT_DECORATOR)) { + throw new IntrospectionError(`class ${this.name} at ${AST.getNodePosition(node)} is used by the module but not exposed with a dagger decorator.`); + } + const modifiers = ts8.getCombinedModifierFlags(this.node); + this.isExported = (modifiers & ts8.ModifierFlags.Export) !== 0; + this.isDefaultExport = (modifiers & ts8.ModifierFlags.Default) !== 0; + if (!this.isExported) { + console.warn(`missing export in class ${this.name} at ${AST.getNodePosition(node)} but it's used by the module.`); + } + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + for (const member of this.node.members) { + if (ts8.isPropertyDeclaration(member)) { + const property = new DaggerProperty(member, this.ast); + this.properties[property.alias ?? property.name] = property; + continue; + } + if (ts8.isConstructorDeclaration(member)) { + this._constructor = new DaggerConstructor(member, this.ast); + continue; + } + if (ts8.isMethodDeclaration(member) && this.ast.isNodeDecoratedWith(member, FUNCTION_DECORATOR)) { + const daggerFunction = new DaggerFunction(member, this.ast); + this.methods[daggerFunction.alias ?? daggerFunction.name] = daggerFunction; + continue; + } + } + } + getLocation() { + return AST.getNodeLocation(this.node); + } + getReferences() { + const references = []; + if (this._constructor) { + references.push(...this._constructor.getReferences()); + } + for (const property of Object.values(this.properties)) { + const ref = property.getReference(); + if (ref) { + references.push(ref); + } + } + for (const fn of Object.values(this.methods)) { + references.push(...fn.getReferences()); + } + return references.filter((v2, i3, arr) => arr.indexOf(v2) === i3); + } + propagateReferences(references) { + if (this._constructor) { + this._constructor.propagateReferences(references); + } + for (const property of Object.values(this.properties)) { + property.propagateReferences(references); + } + for (const fn of Object.values(this.methods)) { + fn.propagateReferences(references); + } + } + toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + constructor: this._constructor, + methods: this.methods, + properties: this.properties + }; + } +} + +// src/module/introspector/dagger_module/typeObject.ts +init_errors(); +import ts9 from "typescript"; + +// src/module/introspector/dagger_module/typeObjectProperty.ts +init_errors(); +class DaggerObjectTypeProperty extends Locatable { + node; + symbol; + ast; + name; + description; + deprecated; + alias = undefined; + isExposed = true; + _typeRef; + type; + constructor(node, symbol, ast2) { + super(node); + this.node = node; + this.symbol = symbol; + this.ast = ast2; + this.name = symbol.name; + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + const type = this.ast.checker.getTypeOfSymbolAtLocation(this.symbol, this.node); + this.type = this.ast.tsTypeToTypeDef(this.node, type); + if (this.type === undefined || !isTypeDefResolved(this.type)) { + this._typeRef = this.ast.typeToStringType(type); + } + } + getReference() { + if (this._typeRef && (this.type === undefined || !isTypeDefResolved(this.type))) { + return this._typeRef; + } + return; + } + propagateReferences(references) { + if (!this._typeRef) { + return; + } + if (this.type && isTypeDefResolved(this.type)) { + return; + } + const typeDef = references[this._typeRef]; + if (!typeDef) { + throw new IntrospectionError(`could not find type reference for ${this._typeRef}.`); + } + this.type = resolveTypeDef(this.type, typeDef); + } + toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + alias: this.alias, + type: this.type, + isExposed: this.isExposed + }; + } +} + +// src/module/introspector/dagger_module/typeObject.ts +class DaggerTypeObject extends Locatable { + node; + ast; + name; + description; + deprecated; + _constructor = undefined; + methods = {}; + properties = {}; + symbol; + kind() { + return "object"; + } + constructor(node, ast2) { + super(node); + this.node = node; + this.ast = ast2; + if (!this.node.name) { + throw new IntrospectionError(`could not resolve name of enum at ${AST.getNodePosition(node)}.`); + } + this.name = this.node.name.getText(); + this.symbol = this.ast.getSymbolOrThrow(this.node.name); + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol); + this.description = description; + this.deprecated = deprecated; + const type = this.ast.getTypeFromTypeAlias(this.node); + if (type.flags & ts9.TypeFlags.Object) { + const objectType = type; + const properties = objectType.getProperties(); + for (const property of properties) { + const daggerProperty = new DaggerObjectTypeProperty(this.node, property, this.ast); + this.properties[daggerProperty.name] = daggerProperty; + } + } + } + getLocation() { + return AST.getNodeLocation(this.node); + } + getReferences() { + const references = []; + for (const property of Object.values(this.properties)) { + const ref = property.getReference(); + if (ref) { + references.push(ref); + } + } + return references.filter((v2, i3, arr) => arr.indexOf(v2) === i3); + } + propagateReferences(references) { + for (const property of Object.values(this.properties)) { + property.propagateReferences(references); + } + } + toJSON() { + return { + name: this.name, + description: this.description, + properties: this.properties, + deprecated: this.deprecated + }; + } +} + +// src/module/introspector/dagger_module/module.ts +class DaggerModule { + name; + userModule; + ast; + objects = {}; + enums = {}; + interfaces = {}; + description; + references = { + float: { kind: "FLOAT_KIND" /* FloatKind */ } + }; + constructor(name, userModule2, ast2) { + this.name = name; + this.userModule = userModule2; + this.ast = ast2; + const classObjects = this.findClasses(); + for (const classObject of classObjects) { + const mainFileContent = classObject.file.getFullText(); + this.description = this.getDescription(mainFileContent); + const daggerObject = new DaggerObject(classObject.node, this.ast); + const objectName = classObject.node.name?.getText() || this.name; + this.objects[objectName] = daggerObject; + this.references[objectName] = { + kind: "OBJECT_KIND" /* ObjectKind */, + name: objectName + }; + this.resolveReferences(daggerObject.getReferences()); + this.propagateReferences(); + } + } + resolveReferences(references) { + if (references.length === 0) { + return; + } + for (const reference of references) { + if (this.references[reference]) { + continue; + } + const classRef = this.ast.findResolvedNodeByName(reference, ts10.SyntaxKind.ClassDeclaration); + if (classRef) { + if (this.ast.isGeneratedClientFile(classRef.file.fileName)) { + this.references[reference] = { + kind: "OBJECT_KIND" /* ObjectKind */, + name: reference + }; + continue; + } + if (this.ast.isNodeDecoratedWith(classRef.node, OBJECT_DECORATOR)) { + const daggerObject = new DaggerObject(classRef.node, this.ast); + this.objects[daggerObject.name] = daggerObject; + this.references[daggerObject.name] = { + kind: "OBJECT_KIND" /* ObjectKind */, + name: daggerObject.name + }; + this.resolveReferences(daggerObject.getReferences()); + continue; + } + if (this.ast.isNodeDecoratedWith(classRef.node, ENUM_DECORATOR)) { + const daggerEnum = new DaggerEnumClass(classRef.node, this.ast); + this.enums[daggerEnum.name] = daggerEnum; + this.references[daggerEnum.name] = { + kind: "ENUM_KIND" /* EnumKind */, + name: daggerEnum.name + }; + continue; + } + throw new IntrospectionError(`class ${reference} in ${AST.getNodePosition(classRef.node)} is used by the module but not exposed with a dagger decorator.`); + } + const enumRef = this.ast.findResolvedNodeByName(reference, ts10.SyntaxKind.EnumDeclaration); + if (enumRef) { + if (this.ast.isGeneratedClientFile(enumRef.file.fileName)) { + this.references[reference] = { + kind: "ENUM_KIND" /* EnumKind */, + name: reference + }; + continue; + } + const daggerEnum = new DaggerEnum(enumRef.node, this.ast); + this.enums[daggerEnum.name] = daggerEnum; + this.references[daggerEnum.name] = { + kind: "ENUM_KIND" /* EnumKind */, + name: daggerEnum.name + }; + continue; + } + const interfaceRef = this.ast.findResolvedNodeByName(reference, ts10.SyntaxKind.InterfaceDeclaration); + if (interfaceRef) { + const daggerInterface = new DaggerInterface(interfaceRef.node, this.ast); + this.interfaces[daggerInterface.name] = daggerInterface; + this.references[daggerInterface.name] = { + kind: "INTERFACE_KIND" /* InterfaceKind */, + name: daggerInterface.name + }; + this.resolveReferences(daggerInterface.getReferences()); + continue; + } + const typeAliasRef = this.ast.findResolvedNodeByName(reference, ts10.SyntaxKind.TypeAliasDeclaration); + if (typeAliasRef) { + this.resolveTypeAlias(reference, typeAliasRef); + continue; + } + if (reference === "String") { + throw new IntrospectionError(`Use of primitive 'String' type detected, please use 'string' instead.`); + } + if (reference === "Boolean") { + throw new IntrospectionError(`Use of primitive 'Boolean' type detected, please use 'boolean' instead.`); + } + if (reference === "Number") { + throw new IntrospectionError(`Use of primitive 'Number' type detected, please use 'number' instead.`); + } + throw new IntrospectionError(`could not resolve type reference for ${reference}.`); + } + } + resolveTypeAlias(reference, typeAlias) { + const type = this.ast.getTypeFromTypeAlias(typeAlias.node); + if (type.flags & ts10.TypeFlags.String) { + this.references[reference] = { kind: "STRING_KIND" /* StringKind */ }; + return; + } + if (type.flags & ts10.TypeFlags.Number) { + this.references[reference] = { kind: "INTEGER_KIND" /* IntegerKind */ }; + return; + } + if (type.flags & ts10.TypeFlags.Boolean) { + this.references[reference] = { kind: "BOOLEAN_KIND" /* BooleanKind */ }; + return; + } + if (type.flags & ts10.TypeFlags.Void) { + this.references[reference] = { kind: "VOID_KIND" /* VoidKind */ }; + return; + } + if (type.flags & ts10.TypeFlags.Intersection || type.flags & ts10.TypeFlags.Union) { + this.references[reference] = { + kind: "SCALAR_KIND" /* ScalarKind */, + name: reference + }; + return; + } + if (type.flags & ts10.TypeFlags.Object) { + if (this.ast.isGeneratedClientFile(typeAlias.file.fileName)) { + this.references[reference] = { + kind: "OBJECT_KIND" /* ObjectKind */, + name: reference + }; + return; + } + const daggerObject = new DaggerTypeObject(typeAlias.node, this.ast); + this.objects[daggerObject.name] = daggerObject; + this.references[daggerObject.name] = { + kind: "OBJECT_KIND" /* ObjectKind */, + name: daggerObject.name + }; + this.resolveReferences(daggerObject.getReferences()); + return; + } + throw new IntrospectionError(`could not resolve type reference for ${reference} at ${AST.getNodePosition(typeAlias.node)}`); + } + findClasses() { + const allClassDeclarations = this.ast.findAllDeclarations(ts10.SyntaxKind.ClassDeclaration); + const allClasses = []; + for (const classDecl of allClassDeclarations) { + const convertedDecl = classDecl; + if (convertedDecl.node.name && convertedDecl.node.name.getText() === this.name) { + return [convertedDecl]; + } + if (this.ast.isNodeDecoratedWith(classDecl.node, OBJECT_DECORATOR)) { + allClasses.push(convertedDecl); + } + } + return allClasses; + } + propagateReferences() { + for (const object2 of Object.values(this.objects)) { + object2.propagateReferences(this.references); + } + for (const interface_ of Object.values(this.interfaces)) { + interface_.propagateReferences(this.references); + } + } + getDescription(sourceFileContent) { + const regex = /^(?!.*import)[\s]*\/\*\*([\s\S]*?)\*\//; + const match = sourceFileContent.match(regex); + if (!match) { + return; + } + const comment = match[1].split(` +`).map((line) => line.replace(/^\s*\*\s?/, "")).join(` +`); + return comment.trim(); + } + toJSON() { + return { + name: this.name, + description: this.description, + objects: this.objects, + enums: this.enums, + interfaces: this.interfaces + }; + } +} +// src/module/entrypoint/load.ts +async function load2(files2) { + return await Promise.all(files2.map(async (f4) => await import(f4))); +} +function loadInvokedObject(module2, parentName) { + return module2.objects[parentName]; +} +function loadInvokedMethod(object3, ctx) { + if (ctx.fnName === "") { + return object3._constructor; + } + return object3.methods[ctx.fnName]; +} +async function loadArgs(executor, method, ctx) { + const args = {}; + for (const argName of method.getArgsOrder()) { + const argument3 = method.arguments[argName]; + if (!argument3) { + throw new Error(`could not find argument ${argName}`); + } + if (!argument3.type) { + throw new Error(`could not find type for argument ${argName}`); + } + const loadedArg = await loadValue(executor, ctx.fnArgs[argName], argument3.type); + if (argument3.isVariadic) { + for (const [i3, arg] of (loadedArg ?? []).entries()) { + args[`${argName}${i3}`] = arg; + } + continue; + } + if (argument3.isNullable && loadedArg === undefined && !argument3.defaultValue) { + args[argName] = null; + continue; + } + args[argName] = loadedArg; + } + return args; +} +async function loadParentState(executor, object3, ctx) { + const parentState = {}; + for (const [key, value] of Object.entries(ctx.parentArgs)) { + const property = object3.properties[key]; + if (!property) { + throw new Error(`could not find parent property ${key}`); + } + if (!property.type) { + throw new Error(`could not find type for parent property ${key}`); + } + parentState[property.name] = await loadValue(executor, value, property.type); + } + return parentState; +} +async function loadValue(executor, value, type) { + if (value === undefined) { + return value; + } + switch (type.kind) { + case "LIST_KIND" /* ListKind */: + return Promise.all(value.map(async (v2) => await loadValue(executor, v2, type.typeDef))); + case "OBJECT_KIND" /* ObjectKind */: { + const objectType = type.name; + if (executor.hasObject(objectType)) { + return executor.buildClass(objectType, value); + } + const ctx = new Context([], new Connection(dag.getGQLClient())).selectNode(value, objectType); + const className = exports_client_gen[objectType] ? objectType : `${objectType}_`; + const cls = exports_client_gen[className]; + if (cls) { + return new cls(ctx); + } + throw new Error(`Generated client class not found for core type ${objectType}`); + } + case "INTERFACE_KIND" /* InterfaceKind */: { + const interfaceType = type.name; + return executor.buildInterface(interfaceType, value); + } + case "ENUM_KIND" /* EnumKind */: { + const enumType2 = type.name; + return executor.buildEnum(enumType2, value); + } + case "STRING_KIND" /* StringKind */: + case "INTEGER_KIND" /* IntegerKind */: + case "BOOLEAN_KIND" /* BooleanKind */: + case "FLOAT_KIND" /* FloatKind */: + case "VOID_KIND" /* VoidKind */: + case "SCALAR_KIND" /* ScalarKind */: + return value; + default: + throw new Error(`unsupported type ${type.kind}`); + } +} +function loadObjectReturnType(module2, object3, method) { + const retType = method.returnType; + if (!retType) { + throw new Error(`could not find return type for ${method.name}`); + } + switch (retType.kind) { + case "LIST_KIND" /* ListKind */: { + let listType = retType; + while (listType.kind === "LIST_KIND" /* ListKind */) { + listType = listType.typeDef; + } + if (listType.kind === "ENUM_KIND" /* EnumKind */) { + return module2.enums[listType.name]; + } + return module2.objects[listType.name]; + } + case "OBJECT_KIND" /* ObjectKind */: + return module2.objects[retType.name]; + case "ENUM_KIND" /* EnumKind */: + return module2.enums[retType.name]; + default: + return object3; + } +} +async function loadResult(result, module2, object3) { + if (result && typeof result?.id === "function") { + return await result.id(); + } + if (Array.isArray(result)) { + result = await Promise.all(result.map(async (r2) => await loadResult(r2, module2, object3))); + return result; + } + if (typeof result === "object" && (object3 instanceof DaggerObject || object3 instanceof DaggerTypeObject)) { + const state = {}; + for (const [key, value] of Object.entries(result)) { + const property = Object.values(object3.properties).find((p2) => p2.name === key); + if (!property) { + throw new Error(`could not find result property ${key}`); + } + if (!property.type) { + throw new Error(`could not find type for result property ${key}`); + } + let referencedObject = undefined; + if (property.type.kind === "OBJECT_KIND" /* ObjectKind */) { + referencedObject = module2.objects[property.type.name]; + } + if (property.type.kind === "LIST_KIND" /* ListKind */) { + let _property = property.type; + while (_property.kind === "LIST_KIND" /* ListKind */) { + _property = _property.typeDef; + } + if (_property.kind === "OBJECT_KIND" /* ObjectKind */) { + referencedObject = module2.objects[_property.name]; + } + if (_property.kind === "ENUM_KIND" /* EnumKind */) { + referencedObject = module2.enums[_property.name]; + } + } + if (property.type.kind === "ENUM_KIND" /* EnumKind */) { + referencedObject = module2.enums[property.type.name]; + } + if (!referencedObject) { + referencedObject = object3; + } + state[property.alias ?? property.name] = await loadResult(value, module2, referencedObject); + } + return state; + } + if (object3 instanceof DaggerEnum || object3 instanceof DaggerEnumClass) { + const enumMember = Object.entries(object3.values).find(([, member]) => member.value === result); + if (!enumMember) { + return result; + } + return enumMember[0]; + } + return result; +} + +// src/module/introspector/case_convertor.ts +function convertToPascalCase(input) { + if (!input) { + return ""; + } + const words = input.split(/(?=[A-Z0-9])|[^a-zA-Z0-9]|(?<=[a-zA-Z])(?=\d)|(?<=\d)(?=[a-zA-Z])/g).filter((word) => word.length > 0); + const pascalCase = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(""); + return pascalCase; +} + +// src/module/introspector/index.ts +async function scan(files2, moduleName = "", loadModule = true, generatedClientFiles = []) { + if (files2.length === 0) { + throw new IntrospectionError("no files to introspect found"); + } + const formattedModuleName = convertToPascalCase(moduleName); + let userModule2 = []; + if (loadModule) { + userModule2 = await load2(files2); + } + const ast2 = new AST(files2, userModule2, generatedClientFiles); + const module2 = new DaggerModule(formattedModuleName, userModule2, ast2); + return module2; +} + +// src/module/entrypoint/invoke.ts +init_errors(); +function isConstructor(method) { + return method.name === ""; +} +function isFloat(num) { + return num % 1 !== 0; +} +async function invoke(executor, module2, ctx) { + const object3 = loadInvokedObject(module2, ctx.parentName); + if (!object3) { + throw new Error(`could not find object ${ctx.parentName}`); + } + const method = loadInvokedMethod(object3, ctx); + if (!method) { + throw new Error(`could not find method ${ctx.fnName}`); + } + const args = await loadArgs(executor, method, ctx); + const parentState = await loadParentState(executor, object3, ctx); + let result; + try { + result = await executor.getResult(object3.name, method.name, parentState, args); + } catch (e2) { + if (e2 instanceof FunctionNotFound) { + result = await registry.getResult(object3.name, method.name, parentState, args); + } else { + throw e2; + } + } + if (result) { + let returnType; + if (!isConstructor(method)) { + if (method.returnType.kind === "INTEGER_KIND" /* IntegerKind */ && isFloat(result)) { + throw new Error(`cannot return float '${result}' if return type is 'number' (integer), please use 'float' as return type instead`); + } + returnType = loadObjectReturnType(module2, object3, method); + } else { + returnType = object3; + } + result = await loadResult(result, module2, returnType); + } + return result; +} + +// src/module/entrypoint/register.ts +class Register { + module; + constructor(module2) { + this.module = module2; + } + async run() { + let mod = dag.module_(); + if (this.module.description) { + mod = mod.withDescription(this.module.description); + } + Object.values(this.module.objects).forEach((object3) => { + const objectOpts = { + description: object3.description, + sourceMap: addSourceMap(object3), + deprecated: object3.deprecated + }; + let typeDef = dag.typeDef().withObject(object3.name, objectOpts); + Object.values(object3.methods).forEach((method) => { + typeDef = typeDef.withFunction(this.addFunction(method)); + }); + Object.values(object3.properties).forEach((field2) => { + if (field2.isExposed) { + const fieldOpts = { + description: field2.description, + sourceMap: addSourceMap(field2), + deprecated: field2.deprecated + }; + typeDef = typeDef.withField(field2.alias ?? field2.name, addTypeDef(field2.type), fieldOpts); + } + }); + if (object3._constructor) { + typeDef = typeDef.withConstructor(this.addConstructor(object3._constructor, typeDef)); + } + mod = mod.withObject(typeDef); + }); + Object.values(this.module.enums).forEach((enum_) => { + let typeDef = dag.typeDef().withEnum(enum_.name, { + description: enum_.description, + sourceMap: addSourceMap(enum_) + }); + Object.values(enum_.values).forEach((value) => { + const memberOpts = { + value: value.value, + description: value.description, + sourceMap: addSourceMap(value), + deprecated: value.deprecated + }; + typeDef = typeDef.withEnumMember(value.name, memberOpts); + }); + mod = mod.withEnum(typeDef); + }); + Object.values(this.module.interfaces).forEach((interface_) => { + let typeDef = dag.typeDef().withInterface(interface_.name, { + description: interface_.description + }); + Object.values(interface_.functions).forEach((function_) => { + typeDef = typeDef.withFunction(this.addFunction(function_)); + }); + mod = mod.withInterface(typeDef); + }); + return await mod.id(); + } + addConstructor(constructor2, owner) { + return dag.function_("", owner).with(this.addArg(constructor2.arguments)); + } + addFunction(fct) { + let fnDef = dag.function_(fct.alias ?? fct.name, addTypeDef(fct.returnType)).withDescription(fct.description).withSourceMap(addSourceMap(fct)).with(this.addArg(fct.arguments)); + switch (fct.cache) { + case "never": { + fnDef = fnDef.withCachePolicy("Never" /* Never */); + break; + } + case "session": { + fnDef = fnDef.withCachePolicy("PerSession" /* PerSession */); + break; + } + case "": { + break; + } + default: { + const opts = { timeToLive: fct.cache }; + fnDef = fnDef.withCachePolicy("Default" /* Default */, opts); + } + } + if (fct.deprecated !== undefined) { + fnDef = fnDef.withDeprecated({ reason: fct.deprecated }); + } + if (fct.isCheck) { + fnDef = fnDef.withCheck(); + } + if (fct.isGenerator) { + fnDef = fnDef.withGenerator(); + } + if (fct.isUp) { + fnDef = fnDef.withUp(); + } + return fnDef; + } + addArg(args) { + return (fct) => { + Object.values(args).forEach((arg) => { + const opts = { + description: arg.description, + sourceMap: addSourceMap(arg), + deprecated: arg.deprecated + }; + let typeDef = addTypeDef(arg.type); + if (arg.isOptional) { + typeDef = typeDef.withOptional(true); + } + if ([arg.defaultValue, arg.defaultPath, arg.defaultAddress].filter((v2) => v2).length > 1) { + throw new Error("cannot set multiple defaults"); + } + if (arg.defaultValue !== undefined) { + const defaultValue = this.getDefaultValueFromArg(arg); + if (defaultValue === undefined) { + typeDef = typeDef.withOptional(true); + } else { + opts.defaultValue = JSON.stringify(defaultValue); + } + } + if (arg.defaultPath) { + opts.defaultPath = arg.defaultPath; + } + if (arg.defaultAddress) { + opts.defaultAddress = arg.defaultAddress; + } + if (arg.ignore) { + opts.ignore = arg.ignore; + } + fct = fct.withArg(arg.name, typeDef, opts); + }); + return fct; + }; + } + getDefaultValueFromArg(arg) { + if (!isPrimitiveType(arg.type)) { + return; + } + if (arg.type.kind !== "ENUM_KIND" /* EnumKind */) { + return arg.defaultValue; + } + const enumObj = this.module.enums[arg.type.name]; + if (!enumObj) { + return arg.defaultValue; + } + const enumMember = Object.entries(enumObj.values).find(([, member]) => member.value === arg.defaultValue); + if (!enumMember) { + throw new Error(`could not resolve default value '${arg.defaultValue}' for enum ${arg.type.name}`); + } + return enumMember[0]; + } +} +function addTypeDef(type) { + switch (type.kind) { + case "SCALAR_KIND" /* ScalarKind */: + return dag.typeDef().withScalar(type.name); + case "OBJECT_KIND" /* ObjectKind */: + return dag.typeDef().withObject(type.name); + case "LIST_KIND" /* ListKind */: + return dag.typeDef().withListOf(addTypeDef(type.typeDef)); + case "VOID_KIND" /* VoidKind */: + return dag.typeDef().withKind(type.kind).withOptional(true); + case "ENUM_KIND" /* EnumKind */: + return dag.typeDef().withEnum(type.name); + case "INTERFACE_KIND" /* InterfaceKind */: + return dag.typeDef().withInterface(type.name); + default: + return dag.typeDef().withKind(type.kind); + } +} +function addSourceMap(object3) { + const { filepath, line, column } = object3.getLocation(); + return dag.sourceMap(filepath, line, column); +} +function isPrimitiveType(type) { + return type.kind === "BOOLEAN_KIND" /* BooleanKind */ || type.kind === "INTEGER_KIND" /* IntegerKind */ || type.kind === "STRING_KIND" /* StringKind */ || type.kind === "FLOAT_KIND" /* FloatKind */ || type.kind === "ENUM_KIND" /* EnumKind */; +} + +// src/module/entrypoint/entrypoint.ts +async function entrypoint(files2) { + await connection(async () => { + const fnCall = dag.currentFunctionCall(); + const moduleName = await dag.currentModule().name(); + const scanResult = await scan(files2, moduleName); + const parentName = await fnCall.parentName(); + let result; + if (parentName === "") { + result = await new Register(scanResult).run(); + } else { + const fnName = await fnCall.name(); + const parentJson = JSON.parse(await fnCall.parent()); + const fnArgs = await fnCall.inputArgs(); + const args = {}; + const parentArgs = parentJson ?? {}; + for (const arg of fnArgs) { + args[await arg.name()] = JSON.parse(await arg.value()); + } + const modules = await load2(files2); + const executor = new Executor(modules, scanResult); + try { + result = await invoke(executor, scanResult, { + parentName, + fnName, + parentArgs, + fnArgs: args + }); + } catch (e2) { + await fnCall.returnError(formatError(e2)); + await close(); + process.exit(1); + } + } + if (result !== undefined && result !== null) { + result = JSON.stringify(result); + } else { + result = "null"; + } + await fnCall.returnValue(result); + }, { LogOutput: process.stdout }); +} +function formatError(e2) { + if (e2 instanceof Error) { + let error = dag.error(e2.message); + if (e2 instanceof ExecError || e2 instanceof GraphQLRequestError) { + Object.entries(e2.extensions ?? []).forEach(([key, value]) => { + if (value !== "" && value !== undefined && value !== null) { + error = error.withValue(key, JSON.stringify(value)); + } + }); + } + return error; + } + try { + return dag.error(JSON.stringify(e2)); + } catch { + return dag.error(String(e2)); + } +} +export { + up, + object, + getTracer, + getRegisteredClass, + generate, + func, + field, + enumType, + entrypoint, + dag, + connection, + connect, + check, + argument, + _SyncerClient, + _NodeClient, + _ExportableClient, + WorkspaceSDK, + WorkspaceModuleSetting, + WorkspaceModule, + WorkspaceMigrationStep, + WorkspaceMigration, + WorkspaceGit, + Workspace, + Volume, + UpGroup, + Up, + UnknownDaggerError, + TypeDefKindValueToName, + TypeDefKindNameToValue, + TypeDefKind, + TypeDef, + TooManyNestedObjectsError, + Terminal, + Stat, + SourceMap, + Socket, + Service, + Secret, + SearchSubmatch, + SearchResult, + Schema, + ScalarTypeDef, + SDKConfig, + ReturnTypeValueToName, + ReturnTypeNameToValue, + ReturnType, + RemoteGitMirror, + RegistryProtocolValueToName, + RegistryProtocolNameToValue, + RegistryProtocol, + Port, + ObjectTypeDef, + NotAwaitedRequestError, + NetworkProtocolValueToName, + NetworkProtocolNameToValue, + NetworkProtocol, + Module_, + ModuleSourceKindValueToName, + ModuleSourceKindNameToValue, + ModuleSourceKind, + ModuleSourceExperimentalFeatureValueToName, + ModuleSourceExperimentalFeatureNameToValue, + ModuleSourceExperimentalFeature, + ModuleSource, + ModuleConfigClient, + ListTypeDef, + Label, + LLMTokenUsage, + LLMMessageRoleValueToName, + LLMMessageRoleNameToValue, + LLMMessageRole, + LLMMessage, + LLMContentBlockKindValueToName, + LLMContentBlockKindNameToValue, + LLMContentBlockKind, + LLMContentBlock, + LLM, + JSONValue, + IntrospectionError, + InterfaceTypeDef, + InputTypeDef, + InitEngineSessionBinaryError, + ImageMediaTypesValueToName, + ImageMediaTypesNameToValue, + ImageMediaTypes, + ImageLayerCompressionValueToName, + ImageLayerCompressionNameToValue, + ImageLayerCompression, + Host, + HealthcheckConfig, + HTTPState, + GraphQLRequestError, + GraphQLClient, + GitRepository, + GitRef, + GeneratorGroup, + Generator, + GeneratedCode, + Function_, + FunctionNotFound, + FunctionCallArgValue, + FunctionCall, + FunctionCachePolicyValueToName, + FunctionCachePolicyNameToValue, + FunctionCachePolicy, + FunctionArg, + FileTypeValueToName, + FileTypeNameToValue, + FileType, + File, + FieldTypeDef, + ExistsTypeValueToName, + ExistsTypeNameToValue, + ExistsType, + ExecError, + ErrorValue, + Error2 as Error, + EnvVariable, + EnvFile, + Env, + EnumValueTypeDef, + EnumTypeDef, + EngineSessionError, + EngineSessionConnectionTimeoutError, + EngineSessionConnectParamsParseError, + EngineCacheEntrySet, + EngineCacheEntry, + EngineCache, + Engine, + ERROR_CODES, + DockerImageRefValidationError, + Directory, + DiffStatKindValueToName, + DiffStatKindNameToValue, + DiffStatKind, + DiffStat, + DaggerSDKError, + CurrentModuleAsSDKModule, + CurrentModuleAsSDKClient, + CurrentModuleAsSDK, + CurrentModule, + Context, + Container, + Cloud, + ClientFilesyncMirror, + Client, + CheckGroup, + Check, + ChangesetsMergeConflictValueToName, + ChangesetsMergeConflictNameToValue, + ChangesetsMergeConflict, + ChangesetMergeConflictValueToName, + ChangesetMergeConflictNameToValue, + ChangesetMergeConflict, + Changeset, + CacheVolume, + CacheSharingModeValueToName, + CacheSharingModeNameToValue, + CacheSharingMode, + Binding, + BaseClient, + Address +}; diff --git a/library/package.json b/library/package.json new file mode 100644 index 0000000..226b8dc --- /dev/null +++ b/library/package.json @@ -0,0 +1,86 @@ +{ + "name": "@dagger.io/dagger", + "version": "0.0.0", + "author": "hello@dagger.io", + "license": "Apache-2.0", + "types": "./dist/src/index.d.ts", + "type": "module", + "files": [ + "dist/" + ], + "exports": { + ".": "./dist/src/index.js", + "./telemetry": "./dist/src/telemetry/index.js" + }, + "engines": { + "node": ">=20" + }, + "main": "dist/src/index.js", + "dependencies": { + "@grpc/grpc-js": "^1.14.4", + "@lifeomic/axios-fetch": "^3.1.0", + "@opentelemetry/api": "^1.9.1", + "@opentelemetry/core": "^2.8.0", + "@opentelemetry/exporter-jaeger": "^2.8.0", + "@opentelemetry/exporter-trace-otlp-http": "^0.219.0", + "@opentelemetry/sdk-metrics": "^2.8.0", + "@opentelemetry/sdk-node": "^0.219.0", + "@opentelemetry/semantic-conventions": "^1.41.1", + "adm-zip": "^0.5.18", + "env-paths": "^4.0.0", + "execa": "^9.6.1", + "graphql": "^17.0.1", + "graphql-request": "^7.4.0", + "graphql-tag": "^2.12.7", + "node-color-log": "^14.0.0", + "node-fetch": "^3.3.2", + "reflect-metadata": "^0.2.2", + "tar": "^7.5.19", + "typescript": "^6.0.3" + }, + "scripts": { + "build": "tsc", + "watch": "tsc -w", + "test": "yarn run test:node", + "test:bun": "bun run --bun mocha", + "test:node": "mocha", + "test:generate-scan": "tsx ./introspector/test/testdata/generate_expected_scan.ts", + "lint": "yarn eslint --max-warnings=0 .", + "fmt": "yarn eslint --max-warnings=0 --fix .", + "docs:lint": "cd ../../docs/current_docs && eslint -c ../../sdk/typescript/eslint-docs.config.js --max-warnings=0 ./**/*.ts", + "docs:fmt": "cd ../../docs/current_docs && eslint --fix -c ../../sdk/typescript/eslint-docs.config.js --max-warnings=0 ./**/*.ts" + }, + "resolutions": { + "@grpc/grpc-js": "1.14.4", + "@trivago/prettier-plugin-sort-imports/lodash-es": "4.18.1", + "@trivago/prettier-plugin-sort-imports/minimatch": "9.0.9", + "**/@grpc/proto-loader/protobufjs": "7.6.1", + "**/@opentelemetry/otlp-transformer/protobufjs": "8.4.1", + "**/glob/minimatch": "9.0.9", + "form-data": "4.0.6", + "mocha/minimatch": "9.0.9", + "mocha/serialize-javascript": "7.0.3", + "tsx/esbuild": "0.28.1" + }, + "devDependencies": { + "@dagger.io/mocha": "^0.1.0", + "@eslint/js": "^10.0.1", + "@trivago/prettier-plugin-sort-imports": "^6.0.2", + "@types/adm-zip": "^0.5.8", + "@types/mocha": "^10.0.10", + "@types/node": "~26.0.1", + "@types/tar": "^7.0.87", + "@typescript-eslint/eslint-plugin": "^8.62.0", + "@typescript-eslint/parser": "^8.62.0", + "eslint": "^10.6.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-prettier": "^5.5.6", + "mocha": "^11.7.6", + "prettier": "^3.9.3", + "rollup": "^4.62.2", + "rollup-plugin-dts": "^6.4.1", + "ts-node": "^10.9.2", + "tsx": "^4.22.4", + "typescript-eslint": "^8.62.0" + } +} diff --git a/library/rollup.dts.config.mjs b/library/rollup.dts.config.mjs new file mode 100644 index 0000000..3ef5bcc --- /dev/null +++ b/library/rollup.dts.config.mjs @@ -0,0 +1,10 @@ +import dts from "rollup-plugin-dts" + +export default { + input: "./dist/src/index.d.ts", // or wherever your entrypoint is + output: { + file: "dist/core.d.ts", + format: "es", + }, + plugins: [dts()], +} diff --git a/library/src/api/.gitattributes b/library/src/api/.gitattributes new file mode 100644 index 0000000..44b95b4 --- /dev/null +++ b/library/src/api/.gitattributes @@ -0,0 +1 @@ +/client.gen.ts linguist-generated=true diff --git a/library/src/common/context.ts b/library/src/common/context.ts new file mode 100644 index 0000000..d5b1aeb --- /dev/null +++ b/library/src/common/context.ts @@ -0,0 +1,62 @@ +import { GraphQLClient } from "graphql-request" + +import { computeQuery, QueryTree } from "./graphql/compute_query.js" +import { globalConnection } from "./graphql/connection.js" + +export class Context { + constructor( + private _queryTree: QueryTree[] = [], + private _connection = globalConnection, + ) {} + + getGQLClient(): GraphQLClient { + return this._connection.getGQLClient() + } + + copy(): Context { + return new Context([], this._connection) + } + + select(operation: string, args?: Record): Context { + return new Context( + [...this._queryTree, { operation, args }], + this._connection, + ) + } + + /** + * Select via node(id:) with an inline fragment on the given type. + * Produces: node(id: "...") { ... on TypeName { children } } + */ + selectNode(id: string, typeName: string): Context { + return new Context( + [ + ...this._queryTree, + { operation: "node", args: { id }, inlineType: typeName }, + ], + this._connection, + ) + } + + execute(): Promise { + return computeQuery(this._queryTree, this._connection.getGQLClient()) + } +} + +/** + * Common base class for every generated API class (Client, Container, and + * dependency-contributed types). + * + * It lives here in the SDK runtime rather than in the generated client.gen.ts + * so that per-dependency generated files (e.g. hello.gen.ts) can `extends + * BaseClient` without importing a value from client.gen.ts — client.gen.ts + * `export *`s those dep files, so a value import would create an ESM cycle. + * client.gen.ts re-exports BaseClient to keep `import { BaseClient } from + * "./client.gen.js"` working for existing consumers. + */ +export class BaseClient { + /** + * @hidden + */ + constructor(protected _ctx: Context = new Context()) {} +} diff --git a/library/src/common/errors/DaggerSDKError.ts b/library/src/common/errors/DaggerSDKError.ts new file mode 100644 index 0000000..f62df3c --- /dev/null +++ b/library/src/common/errors/DaggerSDKError.ts @@ -0,0 +1,46 @@ +import { log } from "../utils.js" +import { ErrorCodes, ErrorNames } from "./errors-codes.js" + +export interface DaggerSDKErrorOptions { + cause?: Error +} + +/** + * The base error. Every other error inherits this error. + */ +export abstract class DaggerSDKError extends Error { + /** + * The name of the dagger error. + */ + abstract readonly name: ErrorNames + + /** + * The dagger specific error code. + * Use this to identify dagger errors programmatically. + */ + abstract readonly code: ErrorCodes + + /** + * The original error, which caused the DaggerSDKError. + */ + cause?: Error + + protected constructor(message: string, options?: DaggerSDKErrorOptions) { + super(message) + this.cause = options?.cause + } + + /** + * @hidden + */ + get [Symbol.toStringTag]() { + return this.name + } + + /** + * Pretty prints the error + */ + printStackTrace() { + log(this.stack) + } +} diff --git a/library/src/common/errors/DockerImageRefValidationError.ts b/library/src/common/errors/DockerImageRefValidationError.ts new file mode 100644 index 0000000..01f7f87 --- /dev/null +++ b/library/src/common/errors/DockerImageRefValidationError.ts @@ -0,0 +1,28 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +interface DockerImageRefValidationErrorOptions extends DaggerSDKErrorOptions { + ref: string +} + +/** + * This error is thrown if the passed image reference does not pass validation and is not compliant with the + * DockerImage constructor. + */ +export class DockerImageRefValidationError extends DaggerSDKError { + name = ERROR_NAMES.DockerImageRefValidationError + code = ERROR_CODES.DockerImageRefValidationError + + /** + * The docker image reference, which caused the error. + */ + ref: string + + /** + * @hidden + */ + constructor(message: string, options: DockerImageRefValidationErrorOptions) { + super(message, options) + this.ref = options?.ref + } +} diff --git a/library/src/common/errors/EngineSessionConnectParamsParseError.ts b/library/src/common/errors/EngineSessionConnectParamsParseError.ts new file mode 100644 index 0000000..65c3224 --- /dev/null +++ b/library/src/common/errors/EngineSessionConnectParamsParseError.ts @@ -0,0 +1,30 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +interface EngineSessionConnectParamsParseErrorOptions extends DaggerSDKErrorOptions { + parsedLine: string +} + +/** + * This error is thrown if the EngineSession does not manage to parse the required connection parameters from the session binary + */ +export class EngineSessionConnectParamsParseError extends DaggerSDKError { + name = ERROR_NAMES.EngineSessionConnectParamsParseError + code = ERROR_CODES.EngineSessionConnectParamsParseError + + /** + * the line, which caused the error during parsing, if the error was caused because of parsing. + */ + parsedLine: string + + /** + * @hidden + */ + constructor( + message: string, + options: EngineSessionConnectParamsParseErrorOptions, + ) { + super(message, options) + this.parsedLine = options.parsedLine + } +} diff --git a/library/src/common/errors/EngineSessionConnectionTimeoutError.ts b/library/src/common/errors/EngineSessionConnectionTimeoutError.ts new file mode 100644 index 0000000..65ddc44 --- /dev/null +++ b/library/src/common/errors/EngineSessionConnectionTimeoutError.ts @@ -0,0 +1,30 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +interface EngineSessionConnectionTimeoutErrorOptions extends DaggerSDKErrorOptions { + timeOutDuration: number +} + +/** + * This error is thrown if the EngineSession does not manage to parse the required port successfully because the sessions connection timed out. + */ +export class EngineSessionConnectionTimeoutError extends DaggerSDKError { + name = ERROR_NAMES.EngineSessionConnectionTimeoutError + code = ERROR_CODES.EngineSessionConnectionTimeoutError + + /** + * The duration until the timeout occurred in ms. + */ + timeOutDuration: number + + /** + * @hidden + */ + constructor( + message: string, + options: EngineSessionConnectionTimeoutErrorOptions, + ) { + super(message, options) + this.timeOutDuration = options.timeOutDuration + } +} diff --git a/library/src/common/errors/EngineSessionErrorOptions.ts b/library/src/common/errors/EngineSessionErrorOptions.ts new file mode 100644 index 0000000..ddc2076 --- /dev/null +++ b/library/src/common/errors/EngineSessionErrorOptions.ts @@ -0,0 +1,20 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +type EngineSessionErrorOptions = DaggerSDKErrorOptions + +/** + * This error is thrown if the EngineSession does not manage to parse the required port successfully because a EOF is read before any valid port. + * This usually happens if no connection can be established. + */ +export class EngineSessionError extends DaggerSDKError { + name = ERROR_NAMES.EngineSessionError + code = ERROR_CODES.EngineSessionError + + /** + * @hidden + */ + constructor(message: string, options?: EngineSessionErrorOptions) { + super(message, options) + } +} diff --git a/library/src/common/errors/ExecError.ts b/library/src/common/errors/ExecError.ts new file mode 100644 index 0000000..ed0b0c5 --- /dev/null +++ b/library/src/common/errors/ExecError.ts @@ -0,0 +1,57 @@ +import type { GraphQLErrorExtensions } from "graphql" + +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +interface ExecErrorOptions extends DaggerSDKErrorOptions { + cmd: string[] + exitCode: number + stdout: string + stderr: string + extensions?: GraphQLErrorExtensions +} + +/** + * API error from an exec operation in a pipeline. + */ +export class ExecError extends DaggerSDKError { + name = ERROR_NAMES.ExecError + code = ERROR_CODES.ExecError + + /** + * The command that caused the error. + */ + cmd: string[] + + /** + * The exit code of the command. + */ + exitCode: number + + /** + * The stdout of the command. + */ + stdout: string + + /** + * The stderr of the command. + */ + stderr: string + + /** + * GraphQL error extensions + */ + extensions?: GraphQLErrorExtensions + + /** + * @hidden + */ + constructor(message: string, options: ExecErrorOptions) { + super(message, options) + this.cmd = options.cmd + this.exitCode = options.exitCode + this.stdout = options.stdout + this.stderr = options.stderr + this.extensions = options.extensions + } +} diff --git a/library/src/common/errors/FunctionNotFound.ts b/library/src/common/errors/FunctionNotFound.ts new file mode 100644 index 0000000..6e00694 --- /dev/null +++ b/library/src/common/errors/FunctionNotFound.ts @@ -0,0 +1,11 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +export class FunctionNotFound extends DaggerSDKError { + name = ERROR_NAMES.ExecError + code = ERROR_CODES.ExecError + + constructor(message: string, options?: DaggerSDKErrorOptions) { + super(message, options) + } +} diff --git a/library/src/common/errors/GraphQLRequestError.ts b/library/src/common/errors/GraphQLRequestError.ts new file mode 100644 index 0000000..e153d74 --- /dev/null +++ b/library/src/common/errors/GraphQLRequestError.ts @@ -0,0 +1,42 @@ +import type { GraphQLErrorExtensions } from "graphql" +import { ClientError } from "graphql-request" + +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +interface GraphQLRequestErrorOptions extends DaggerSDKErrorOptions { + error: ClientError +} + +/** + * This error originates from the dagger engine. It means that some error was thrown and sent back via GraphQL. + */ +export class GraphQLRequestError extends DaggerSDKError { + name = ERROR_NAMES.GraphQLRequestError + code = ERROR_CODES.GraphQLRequestError + + /** + * The query and variables, which caused the error. + */ + requestContext: ClientError["request"] + + /** + * the GraphQL response containing the error. + */ + response: ClientError["response"] + + /** + * The GraphQL error extentions. + */ + extensions?: GraphQLErrorExtensions + + /** + * @hidden + */ + constructor(message: string, options: GraphQLRequestErrorOptions) { + super(message, options) + this.requestContext = options.error.request + this.response = options.error.response + this.extensions = options.error.response.errors?.[0]?.extensions + } +} diff --git a/library/src/common/errors/InitEngineSessionBinaryError.ts b/library/src/common/errors/InitEngineSessionBinaryError.ts new file mode 100644 index 0000000..b00aff2 --- /dev/null +++ b/library/src/common/errors/InitEngineSessionBinaryError.ts @@ -0,0 +1,17 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +/** + * This error is thrown if the dagger binary cannot be copied from the dagger docker image and copied to the local host. + */ +export class InitEngineSessionBinaryError extends DaggerSDKError { + name = ERROR_NAMES.InitEngineSessionBinaryError + code = ERROR_CODES.InitEngineSessionBinaryError + + /** + * @hidden + */ + constructor(message: string, options?: DaggerSDKErrorOptions) { + super(message, options) + } +} diff --git a/library/src/common/errors/IntrospectionError.ts b/library/src/common/errors/IntrospectionError.ts new file mode 100644 index 0000000..0963d19 --- /dev/null +++ b/library/src/common/errors/IntrospectionError.ts @@ -0,0 +1,11 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +export class IntrospectionError extends DaggerSDKError { + name = ERROR_NAMES.IntrospectionError + code = ERROR_CODES.IntrospectionError + + constructor(message: string, options?: DaggerSDKErrorOptions) { + super(message, options) + } +} diff --git a/library/src/common/errors/NotAwaitedRequestError.ts b/library/src/common/errors/NotAwaitedRequestError.ts new file mode 100644 index 0000000..878c494 --- /dev/null +++ b/library/src/common/errors/NotAwaitedRequestError.ts @@ -0,0 +1,17 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +/** + * This error is thrown when the compute function isn't awaited. + */ +export class NotAwaitedRequestError extends DaggerSDKError { + name = ERROR_NAMES.NotAwaitedRequestError + code = ERROR_CODES.NotAwaitedRequestError + + /** + * @hidden + */ + constructor(message: string, options?: DaggerSDKErrorOptions) { + super(message, options) + } +} diff --git a/library/src/common/errors/TooManyNestedObjectsError.ts b/library/src/common/errors/TooManyNestedObjectsError.ts new file mode 100644 index 0000000..71555a2 --- /dev/null +++ b/library/src/common/errors/TooManyNestedObjectsError.ts @@ -0,0 +1,27 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +interface TooManyNestedObjectsErrorOptions extends DaggerSDKErrorOptions { + response: unknown +} + +/** + * Dagger only expects one response value from the engine. If the engine returns more than one value this error is thrown. + */ +export class TooManyNestedObjectsError extends DaggerSDKError { + name = ERROR_NAMES.TooManyNestedObjectsError + code = ERROR_CODES.TooManyNestedObjectsError + + /** + * the response containing more than one value. + */ + response: unknown + + /** + * @hidden + */ + constructor(message: string, options: TooManyNestedObjectsErrorOptions) { + super(message, options) + this.response = options.response + } +} diff --git a/library/src/common/errors/UnknownDaggerError.ts b/library/src/common/errors/UnknownDaggerError.ts new file mode 100644 index 0000000..8ec9413 --- /dev/null +++ b/library/src/common/errors/UnknownDaggerError.ts @@ -0,0 +1,17 @@ +import { DaggerSDKError, DaggerSDKErrorOptions } from "./DaggerSDKError.js" +import { ERROR_CODES, ERROR_NAMES } from "./errors-codes.js" + +/** + * This error is thrown if the dagger SDK does not identify the error and just wraps the cause. + */ +export class UnknownDaggerError extends DaggerSDKError { + name = ERROR_NAMES.UnknownDaggerError + code = ERROR_CODES.UnknownDaggerError + + /** + * @hidden + */ + constructor(message: string, options: DaggerSDKErrorOptions) { + super(message, options) + } +} diff --git a/library/src/common/errors/errors-codes.ts b/library/src/common/errors/errors-codes.ts new file mode 100644 index 0000000..2a57599 --- /dev/null +++ b/library/src/common/errors/errors-codes.ts @@ -0,0 +1,68 @@ +export const ERROR_CODES = { + /** + * {@link GraphQLRequestError} + */ + GraphQLRequestError: "D100", + + /** + * {@link UnknownDaggerError} + */ + UnknownDaggerError: "D101", + + /** + * {@link TooManyNestedObjectsError} + */ + TooManyNestedObjectsError: "D102", + + /** + * {@link EngineSessionConnectParamsParseError} + */ + EngineSessionConnectParamsParseError: "D103", + + /** + * {@link EngineSessionConnectionTimeoutError} + */ + EngineSessionConnectionTimeoutError: "D104", + + /** + * {@link EngineSessionError} + */ + EngineSessionError: "D105", + + /** + * {@link InitEngineSessionBinaryError} + */ + InitEngineSessionBinaryError: "D106", + + /** + * {@link DockerImageRefValidationError} + */ + DockerImageRefValidationError: "D107", + + /** + * {@link NotAwaitedRequestError} + */ + NotAwaitedRequestError: "D108", + + /** + * (@link ExecError} + */ + ExecError: "D109", + + /** + * {@link IntrospectionError} + */ + IntrospectionError: "D110", +} as const + +type ErrorCodesType = typeof ERROR_CODES +export type ErrorNames = keyof ErrorCodesType +export type ErrorCodes = ErrorCodesType[ErrorNames] + +type ErrorNamesMap = { readonly [Key in ErrorNames]: Key } +export const ERROR_NAMES: ErrorNamesMap = ( + Object.keys(ERROR_CODES) as Array +).reduce( + (obj, item) => ({ ...obj, [item]: item }), + {} as ErrorNamesMap, +) diff --git a/library/src/common/errors/index.ts b/library/src/common/errors/index.ts new file mode 100644 index 0000000..5850a56 --- /dev/null +++ b/library/src/common/errors/index.ts @@ -0,0 +1,14 @@ +export { DaggerSDKError } from "./DaggerSDKError.js" +export { UnknownDaggerError } from "./UnknownDaggerError.js" +export { DockerImageRefValidationError } from "./DockerImageRefValidationError.js" +export { EngineSessionConnectParamsParseError } from "./EngineSessionConnectParamsParseError.js" +export { ExecError } from "./ExecError.js" +export { GraphQLRequestError } from "./GraphQLRequestError.js" +export { InitEngineSessionBinaryError } from "./InitEngineSessionBinaryError.js" +export { TooManyNestedObjectsError } from "./TooManyNestedObjectsError.js" +export { EngineSessionError } from "./EngineSessionErrorOptions.js" +export { EngineSessionConnectionTimeoutError } from "./EngineSessionConnectionTimeoutError.js" +export { NotAwaitedRequestError } from "./NotAwaitedRequestError.js" +export { FunctionNotFound } from "./FunctionNotFound.js" +export { IntrospectionError } from "./IntrospectionError.js" +export { ERROR_CODES } from "./errors-codes.js" diff --git a/library/src/common/graphql/client.ts b/library/src/common/graphql/client.ts new file mode 100644 index 0000000..29a010b --- /dev/null +++ b/library/src/common/graphql/client.ts @@ -0,0 +1,99 @@ +import * as opentelemetry from "@opentelemetry/api" +import { GraphQLClient } from "graphql-request" +import nodeFetch from "node-fetch" +import { + RequestInfo as NodeFetchRequestInfo, + RequestInit as NodeFetchRequestInit, +} from "node-fetch" + +import { isBun, isDeno } from "../utils.js" + +type BunRequestInit = RequestInit & { + timeout: false +} + +const createFetchWithTimeout = + (timeout: number) => + async (input: URL | RequestInfo, init?: RequestInit): Promise => { + if (init?.signal) { + throw new Error( + "Internal error: could not create fetch client with timeout", + ) + } + + const controller = new AbortController() + + const timerId = setTimeout(() => { + controller.abort() + }, timeout) + + try { + // Edge case for Deno that doesn't work as expected with node-fetch and would + // rather rely on its native fetch implementation + // See: https://github.com/dagger/dagger/issues/10546 + // Bun must also use its native fetch: the bundled node-fetch Headers class + // extends URLSearchParams, and Bun's non-standard URLSearchParams.prototype.toJSON + // brand check makes JSON.stringify throw on it, breaking ClientError construction + // (errors surface as UnknownDaggerError instead of ExecError). + if (isBun()) { + return await fetch( + input as RequestInfo, + { + ...(init as RequestInit), + signal: controller.signal, + // Dagger queries can run longer than Bun's native five-minute timeout. + timeout: false, + } as BunRequestInit, + ) + } + + if (isDeno()) { + return await fetch(input as RequestInfo, { + ...(init as RequestInit), + signal: controller.signal, + }) + } + + return (await nodeFetch(input as NodeFetchRequestInfo, { + ...(init as NodeFetchRequestInit), + signal: controller.signal, + })) as unknown as Response + } finally { + clearTimeout(timerId) + } + } + +/** + * Customer setter to inject trace parent into the request headers + * This is required because `graphql-request` 7.0.1 changes its header + * type to `Headers` which break the default open telemetry propagator. + */ +class CustomSetter { + set(carrier: Headers, key: string, value: string): void { + carrier.set(key, value) + } +} + +export function createGQLClient(port: number, token: string): GraphQLClient { + const client = new GraphQLClient(`http://127.0.0.1:${port}/query`, { + // 1 week timeout so we should never hit that one. + // This is to bypass the current graphql-request timeout, which depends on + // node-fetch and is 5minutes by default. + fetch: createFetchWithTimeout(1000 * 60 * 60 * 24 * 7), + headers: { + Authorization: "Basic " + Buffer.from(token + ":").toString("base64"), + }, + // Inject trace parent into the request headers so it can be correctly linked + requestMiddleware: async (req) => { + opentelemetry.propagation.inject( + opentelemetry.context.active(), + req.headers, + new CustomSetter(), + ) + + return req + }, + }) + + return client +} diff --git a/library/src/common/graphql/compute_query.ts b/library/src/common/graphql/compute_query.ts new file mode 100644 index 0000000..273816a --- /dev/null +++ b/library/src/common/graphql/compute_query.ts @@ -0,0 +1,277 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { ClientError, gql, GraphQLClient } from "graphql-request" + +import { + GraphQLRequestError, + TooManyNestedObjectsError, + UnknownDaggerError, + NotAwaitedRequestError, + ExecError, +} from "../errors/index.js" + +export type QueryTree = { + operation: string + args?: Record + // When set, children are wrapped in an inline fragment: + // operation(args) { ... on inlineType { children } } + inlineType?: string +} + +export type Metadata = { + [key: string]: { + is_enum?: boolean + value_to_name?: (value: any) => string + } +} + +/** + * Format argument into GraphQL query format. + */ +function buildArgs(args: any): string { + const metadata: Metadata = args.__metadata || {} + + // Remove unwanted quotes + const formatValue = (key: string, value: string) => { + // Special treatment for enumeration, they must be inserted without quotes + if (metadata[key]?.is_enum) { + return JSON.stringify(metadata[key].value_to_name?.(value)).replace( + /['"]+/g, + "", + ) + } + + return JSON.stringify(value).replace( + /\{"[a-zA-Z]+":|,"[a-zA-Z]+":/gi, + (str) => { + return str.replace(/"/g, "") + }, + ) + } + + if (args === undefined || args === null) { + return "" + } + + const formattedArgs = Object.entries(args).reduce( + (acc: any, [key, value]) => { + // Ignore internal metadata key + if (key === "__metadata") { + return acc + } + + if (value !== undefined && value !== null) { + acc.push(`${key}: ${formatValue(key, value as string)}`) + } + + return acc + }, + [], + ) + + if (formattedArgs.length === 0) { + return "" + } + + return `(${formattedArgs})` +} + +/** + * Find QueryTree, convert them into GraphQl query + * then compute and return the result to the appropriate field + */ +async function computeNestedQuery( + query: QueryTree[], + client: GraphQLClient, +): Promise { + // Check if there is a nested queryTree to be executed + const isQueryTree = (value: any) => value["_ctx"] !== undefined + + // Check if there is a nested array of queryTree to be executed + const isArrayQueryTree = (value: any[]) => + value.every((v) => v instanceof Object && isQueryTree(v)) + + // Prepare query tree for final query by computing nested queries + // and building it with their results. + const computeQueryTree = async (value: any): Promise => { + // Resolve sub queries if operation's args is a subquery + for (const op of value["_ctx"]["_queryTree"]) { + await computeNestedQuery([op], client) + } + + // push an id that will be used by the container + return buildQuery([ + ...value["_ctx"]["_queryTree"], + { + operation: "id", + }, + ]) + } + + // Remove all undefined args and assert args type + const queryToExec = query.filter((q): q is Required => !!q.args) + + for (const q of queryToExec) { + await Promise.all( + // Compute nested query for single object + Object.entries(q.args).map(async ([key, value]: any) => { + if (value instanceof Object && isQueryTree(value)) { + // push an id that will be used by the container + const getQueryTree = await computeQueryTree(value) + + q.args[key] = await compute(getQueryTree, client) + } + + // Compute nested query for array of object + if (Array.isArray(value) && isArrayQueryTree(value)) { + const tmp: any = q.args[key] + + for (let i = 0; i < value.length; i++) { + // push an id that will be used by the container + const getQueryTree = await computeQueryTree(value[i]) + + tmp[i] = await compute(getQueryTree, client) + } + + q.args[key] = tmp + } + }), + ) + } +} + +/** + * Convert the queryTree into a GraphQL query + * @param q + * @returns + */ +export function buildQuery(q: QueryTree[]): string { + const query = q.reduce((acc, { operation, args, inlineType }, i) => { + const qLen = q.length + const isLast = qLen - 1 === i + + acc += ` ${operation} ${args ? `${buildArgs(args)}` : ""}` + + if (!isLast) { + acc += " {" + if (inlineType) { + acc += ` ... on ${inlineType} {` + } + } else { + // Close inline fragments and braces + let closes = "" + for (let j = i - 1; j >= 0; j--) { + if (q[j].inlineType) { + closes += " }" + } + closes += " }" + } + acc += closes + } + + return acc + }, "") + + return `{${query} }` +} + +/** + * Convert querytree into a Graphql query then compute it + * @param q | QueryTree[] + * @param client | GraphQLClient + * @returns + */ +export async function computeQuery( + q: QueryTree[], + client: GraphQLClient, +): Promise { + await computeNestedQuery(q, client) + + const query = buildQuery(q) + + return await compute(query, client) +} + +/** + * Return a Graphql query result flattened + * @param response any + * @returns + */ +export function queryFlatten(response: any): T { + // Recursion break condition + // If our response is not an object or an array we assume we reached the value + if (!(response instanceof Object) || Array.isArray(response)) { + return response + } + + const keys = Object.keys(response) + + if (keys.length != 1) { + // Dagger is currently expecting to only return one value + // If the response is nested in a way were more than one object is nested inside throw an error + throw new TooManyNestedObjectsError( + "Too many nested objects inside graphql response", + { + response: response, + }, + ) + } + + const nestedKey = keys[0] + + return queryFlatten(response[nestedKey]) +} + +/** + * Send a GraphQL document to the server + * return a flatten result + * @hidden + */ +export async function compute( + query: string, + client: GraphQLClient, +): Promise { + let computeQuery: Awaited + try { + computeQuery = await client.request(gql` + ${query} + `) + } catch (e: any) { + if (e instanceof ClientError) { + const msg = e.response.errors?.[0]?.message ?? `API Error` + const ext = e.response.errors?.[0]?.extensions + + if (ext?._type === "EXEC_ERROR") { + throw new ExecError(msg, { + cmd: (ext.cmd as string[]) ?? [], + exitCode: (ext.exitCode as number) ?? -1, + stdout: (ext.stdout as string) ?? "", + stderr: (ext.stderr as string) ?? "", + extensions: ext, + }) + } + + throw new GraphQLRequestError(msg, { + error: e, + cause: e, + }) + } + + // Looking for connection error in case the function has not been awaited. + if (e.errno === "ECONNREFUSED") { + throw new NotAwaitedRequestError( + "Encountered an error while requesting data via graphql through a synchronous call. Make sure the function called is awaited.", + { cause: e }, + ) + } + + // Just throw the unknown error + throw new UnknownDaggerError( + "Encountered an unknown error while requesting data via graphql", + { + cause: e, + }, + ) + } + + return queryFlatten(computeQuery) +} diff --git a/library/src/common/graphql/connect.ts b/library/src/common/graphql/connect.ts new file mode 100644 index 0000000..34fe70d --- /dev/null +++ b/library/src/common/graphql/connect.ts @@ -0,0 +1,37 @@ +import { GraphQLClient } from "graphql-request" + +import { ConnectOpts } from "../../connectOpts.js" +import { createGQLClient } from "./client.js" + +/** + * Execute the callback with a GraphQL client connected to the Dagger engine. + * It automatically provisions the engine if needed. + */ +export async function withGQLClient( + connectOpts: ConnectOpts, + cb: (gqlClient: GraphQLClient) => Promise, +): Promise { + if (process.env["DAGGER_SESSION_PORT"]) { + const port = process.env["DAGGER_SESSION_PORT"] + if (!process.env["DAGGER_SESSION_TOKEN"]) { + throw new Error( + "DAGGER_SESSION_TOKEN must be set if DAGGER_SESSION_PORT is set", + ) + } + + const token = process.env["DAGGER_SESSION_TOKEN"] + + return await cb(createGQLClient(Number(port), token)) + } + + try { + const provisioning = await import("../../provisioning/index.js") + + return await provisioning.withEngineSession(connectOpts, cb) + } catch (e) { + throw new Error( + `failed to execute function with automatic provisioning: ${e}`, + { cause: e }, + ) + } +} diff --git a/library/src/common/graphql/connection.ts b/library/src/common/graphql/connection.ts new file mode 100644 index 0000000..9c503d4 --- /dev/null +++ b/library/src/common/graphql/connection.ts @@ -0,0 +1,27 @@ +import { GraphQLClient } from "graphql-request" + +/** + * Wraps the GraphQL client to allow lazy initialization and setting + * the GQL client of the global Dagger client instance (`dag`). + */ +export class Connection { + constructor(private _gqlClient?: GraphQLClient) {} + + resetClient() { + this._gqlClient = undefined + } + + setGQLClient(gqlClient: GraphQLClient) { + this._gqlClient = gqlClient + } + + getGQLClient(): GraphQLClient { + if (!this._gqlClient) { + throw new Error("GraphQL client is not set") + } + + return this._gqlClient + } +} + +export const globalConnection = new Connection() diff --git a/library/src/common/utils.ts b/library/src/common/utils.ts new file mode 100644 index 0000000..858caf2 --- /dev/null +++ b/library/src/common/utils.ts @@ -0,0 +1,14 @@ +import logger from "node-color-log" + +export const log = (stack?: string) => + logger.bgColor("red").color("black").log(stack) + +export function isDeno(): boolean { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return typeof (globalThis as any).Deno !== "undefined" +} + +export function isBun(): boolean { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return typeof (globalThis as any).Bun !== "undefined" +} diff --git a/library/src/connect.ts b/library/src/connect.ts new file mode 100644 index 0000000..bc0bc76 --- /dev/null +++ b/library/src/connect.ts @@ -0,0 +1,78 @@ +import * as opentelemetry from "@opentelemetry/api" +import { GraphQLClient } from "graphql-request" + +import { Client } from "./api/client.gen.js" +import { Context } from "./common/context.js" +import { withGQLClient } from "./common/graphql/connect.js" +import { Connection, globalConnection } from "./common/graphql/connection.js" +import { ConnectOpts } from "./connectOpts.js" +import * as telemetry from "./telemetry/telemetry.js" + +export type CallbackFct = (client: Client) => Promise + +/** + * connection executes the given function using the default global Dagger client. + * + * @example + * ```ts + * await connection( + * async () => { + * await dag + * .container() + * .from("alpine") + * .withExec(["apk", "add", "curl"]) + * .withExec(["curl", "https://dagger.io/"]) + * .sync() + * }, { LogOutput: process.stderr } + * ) + * ``` + */ +export async function connection( + fct: () => Promise, + cfg: ConnectOpts = {}, +) { + try { + telemetry.initialize() + + // Wrap connection into the opentelemetry context for propagation + await opentelemetry.context.with(telemetry.getContext(), async () => { + try { + await withGQLClient(cfg, async (gqlClient) => { + // Set the GQL client inside the global dagger client + globalConnection.setGQLClient(gqlClient) + + await fct() + }) + } finally { + globalConnection.resetClient() + } + }) + } finally { + await telemetry.close() + } +} + +/** + * connect runs GraphQL server and initializes a + * GraphQL client to execute query on it through its callback. + * This implementation is based on the existing Go SDK. + */ +export async function connect( + cb: CallbackFct, + config: ConnectOpts = {}, +): Promise { + await withGQLClient(config, async (gqlClient: GraphQLClient) => { + const connection = new Connection(gqlClient) + const ctx = new Context([], connection) + const client = new Client(ctx) + + // Warning shall be throw if versions are not compatible + try { + await client.version() + } catch (e) { + console.error("failed to check version compatibility:", e) + } + + return await cb(client) + }) +} diff --git a/library/src/connectOpts.ts b/library/src/connectOpts.ts new file mode 100644 index 0000000..e6ac55d --- /dev/null +++ b/library/src/connectOpts.ts @@ -0,0 +1,31 @@ +import { Writable } from "node:stream" + +/** + * ConnectOpts defines option used to connect to an engine. + */ +export interface ConnectOpts { + /** + * Use to overwrite Dagger workdir + * @defaultValue process.cwd() + */ + Workdir?: string + + /** + * Opt into loading workspace modules for this connection. + * By default, only the core API is exposed. + */ + LoadWorkspaceModules?: boolean + + /** + * Enable logs output + * @example + * LogOutput + * ```ts + * connect(async (client: Client) => { + const source = await client.host().workdir().id() + ... + }, {LogOutput: process.stdout}) + ``` + */ + LogOutput?: Writable +} diff --git a/library/src/index.ts b/library/src/index.ts new file mode 100644 index 0000000..9fe612a --- /dev/null +++ b/library/src/index.ts @@ -0,0 +1,23 @@ +export { GraphQLClient } from "graphql-request" + +// Telemetry +export * from "./telemetry/index.js" + +// Default client bindings +export * from "./api/client.gen.js" + +// Common errors +export * from "./common/errors/index.js" + +// Connection for library +export type { CallbackFct } from "./connect.js" +export { connect, connection } from "./connect.js" +export type { ConnectOpts } from "./connectOpts.js" + +// Export dagger connection context +export { Context, BaseClient } from "./common/context.js" + +// Module library +export * from "./module/decorators.js" +export { entrypoint } from "./module/entrypoint/entrypoint.js" +export { getRegisteredClass } from "./module/registry.js" diff --git a/library/src/module/decorators.ts b/library/src/module/decorators.ts new file mode 100644 index 0000000..2987bb6 --- /dev/null +++ b/library/src/module/decorators.ts @@ -0,0 +1,72 @@ +/** + * Expose the decorator publicly, so they insert data into the global registry. + */ +import { registry } from "./registry.js" + +/** + * The definition of the `@object` decorator that should be on top of any + * class module that must be exposed to the Dagger API. + * + */ +export const object = registry.object + +/** + * The definition of @func decorator that should be on top of any + * class' method that must be exposed to the Dagger API. + * + * @param alias The alias to use for the field when exposed on the API. + * @param cache The cache setting to use for that function. + */ +export const func = registry.func + +/** + * The definition of @check decorator that marks a function as a check. + * Checks are functions that return void/error to indicate pass/fail. + */ +export const check = registry.check + +/** + * The definition of @generate decorator that marks a function as a generator. + * Generators are functions that return a Changeset representing changes to be applied. + */ +export const generate = registry.generate + +/** + * The definition of @up decorator that marks a function as a service for dagger up. + */ +export const up = registry.up + +/** + * The definition of @field decorator that should be on top of any + * class' property that must be exposed to the Dagger API. + * + * @deprecated In favor of `@func` + * @param alias The alias to use for the field when exposed on the API. + */ +export const field = registry.field + +/** + * The definition of the `@enumType` decorator that should be on top of any + * class module that must be exposed to the Dagger API as enumeration. + * + * @deprecated In favor of using TypeScript `enum` types. + */ +export const enumType = registry.enumType + +/** + * Add a `@argument` decorator to an argument of type `Directory` or `File` to load + * its contents from the module context directory. + * + * The context directory is the git repository containing the module. + * If there's no git repository, the context directory is the directory containing + * the module source code. + * + * @param opts.defaultPath Only applies to arguments of type File or Directory. If the argument is not set, + * load it from the given path in the context directory. + * @param opts.ignore Only applies to arguments of type Directory. The ignore patterns are applied to the input directory, + * and matching entries are filtered out, in a cache-efficient manner.. + * + * Relative paths are relative to the current source files. + * Absolute paths are rooted to the module context directory. + */ +export const argument = registry.argument diff --git a/library/src/module/entrypoint/context.ts b/library/src/module/entrypoint/context.ts new file mode 100644 index 0000000..6c77cb5 --- /dev/null +++ b/library/src/module/entrypoint/context.ts @@ -0,0 +1,8 @@ +import { Args } from "../executor.js" + +export type InvokeCtx = { + parentName: string + fnName: string + parentArgs: Args + fnArgs: Args +} diff --git a/library/src/module/entrypoint/entrypoint.ts b/library/src/module/entrypoint/entrypoint.ts new file mode 100644 index 0000000..890e7d6 --- /dev/null +++ b/library/src/module/entrypoint/entrypoint.ts @@ -0,0 +1,107 @@ +import { dag, Error as DaggerError } from "../../api/client.gen.js" +import type { JSON } from "../../api/client.gen.js" +import { ExecError } from "../../common/errors/ExecError.js" +import { GraphQLRequestError } from "../../common/errors/GraphQLRequestError.js" +import { connection } from "../../connect.js" +import * as telemetry from "../../telemetry/telemetry.js" +import { Executor, Args } from "../executor.js" +import { scan } from "../introspector/index.js" +import { invoke } from "./invoke.js" +import { load } from "./load.js" +import { Register } from "./register.js" + +export async function entrypoint(files: string[]) { + // Start a Dagger session to get the call context + await connection( + async () => { + const fnCall = dag.currentFunctionCall() + const moduleName = await dag.currentModule().name() + const scanResult = await scan(files, moduleName) + const parentName = await fnCall.parentName() + + // Pre allocate the result, we got one in both case. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let result: any + + if (parentName === "") { + result = await new Register(scanResult).run() + } else { + // Invocation + const fnName = await fnCall.name() + const parentJson = JSON.parse(await fnCall.parent()) + const fnArgs = await fnCall.inputArgs() + + const args: Args = {} + const parentArgs: Args = parentJson ?? {} + + for (const arg of fnArgs) { + args[await arg.name()] = JSON.parse(await arg.value()) + } + + const modules = await load(files) + const executor = new Executor(modules, scanResult) + + try { + result = await invoke(executor, scanResult, { + parentName, + fnName, + parentArgs, + fnArgs: args, + }) + } catch (e: unknown) { + await fnCall.returnError(formatError(e)) + + // Closing telemetry here since the process is shutdown after + // so any parent's finally will not be executed. + // That way, we guarantee that the spans are flushed. + await telemetry.close() + + process.exit(1) + } + } + + // If result is set, we stringify it + if (result !== undefined && result !== null) { + result = JSON.stringify(result) + } else { + result = "null" + } + + // Send the result to Dagger + await fnCall.returnValue(result as string & { __JSON: never }) + }, + { LogOutput: process.stdout }, + ) +} + +/** + * Take the error thrown by the user module and stringify it so it can + * be returned to Dagger. + * + * If the error is an instance of Error, we stringify the message. + * If the error is an instance of ExecError, we stringify the message and add the + * extensions fields in the error object. + */ +function formatError(e: unknown): DaggerError { + if (e instanceof Error) { + let error = dag.error(e.message) + + // If the error is an instance of GraphQLError or a inherit type of it, + // we can add the extensions fields in the error object. + if (e instanceof ExecError || e instanceof GraphQLRequestError) { + Object.entries(e.extensions ?? []).forEach(([key, value]) => { + if (value !== "" && value !== undefined && value !== null) { + error = error.withValue(key, JSON.stringify(value) as JSON) + } + }) + } + + return error + } + + try { + return dag.error(JSON.stringify(e)) + } catch { + return dag.error(String(e)) + } +} diff --git a/library/src/module/entrypoint/introspection_entrypoint.ts b/library/src/module/entrypoint/introspection_entrypoint.ts new file mode 100644 index 0000000..7b8744a --- /dev/null +++ b/library/src/module/entrypoint/introspection_entrypoint.ts @@ -0,0 +1,134 @@ +import * as fs from "fs" +import * as path from "path" + +import { connection } from "../../connect.js" +import { scan } from "../introspector/index.js" +import { serializeIntrospection } from "../introspector/introspection_json.js" +import { serializeModule } from "../introspector/typedef_json.js" +import { Register } from "./register.js" + +async function introspection( + files: string[], + moduleName: string, + generatedClientFiles: string[], +) { + return await scan(files, moduleName, false, generatedClientFiles) +} + +const allowedExtensions = [".ts", ".mts"] + +function getTsSourceCodeFiles(dir: string): string[] { + return fs + .readdirSync(dir) + .map((file) => { + const filepath = path.join(dir, file) + + const stat = fs.statSync(filepath) + + if (stat.isDirectory()) { + return getTsSourceCodeFiles(filepath) + } + + const ext = path.extname(filepath) + if (allowedExtensions.find((allowedExt) => allowedExt === ext)) { + return [path.join(dir, file)] + } + + return [] + }) + .reduce((p, c) => [...c, ...p], []) +} + +// generatedClientFiles returns every `*.gen.ts` file sitting next to the given +// client file (client.gen.ts and each per-dependency .gen.ts). Falls back +// to just the client file if the directory can't be listed. +function generatedClientFiles(clientFile: string): string[] { + const dir = path.dirname(clientFile) + try { + const files = fs + .readdirSync(dir) + .filter((f) => f.endsWith(".gen.ts")) + .map((f) => path.join(dir, f)) + return files.length > 0 ? files : [clientFile] + } catch { + return [clientFile] + } +} + +async function main() { + const args = process.argv.slice(2) + if (args.length < 3) { + console.log( + "usage: introspection ", + ) + process.exit(1) + } + + const moduleName = args[0] + const userSourceCodeDir = args[1] + const typescriptClientFile = args[2] + + const userSourceCodeFiles = getTsSourceCodeFiles(userSourceCodeDir) + + // The generated client is split across `client.gen.ts` and one + // `.gen.ts` per dependency. Pass every `*.gen.ts` sibling so the + // introspector can resolve types contributed by dependencies (e.g. an enum + // re-exported from a dep file), not just those declared in client.gen.ts. + const clientGenFiles = generatedClientFiles(typescriptClientFile) + + const result = await introspection( + [...userSourceCodeFiles, ...clientGenFiles], + moduleName, + clientGenFiles, + ) + + if (process.env.DRY_RUN) { + console.log(JSON.stringify(result, null, 2)) + process.exit(0) + } + + // When EMIT_TYPEDEF_JSON_FILE is set, write the parsed DaggerModule as a + // stable JSON typedef. The Go-side `cmd/codegen generate-entrypoint` + // subcommand consumes that JSON to render the static dispatch + // __dagger.entrypoint.ts file. + const typedefJsonPath = process.env.EMIT_TYPEDEF_JSON_FILE + if (typedefJsonPath) { + const json = serializeModule(result) + await fs.promises.writeFile(typedefJsonPath, JSON.stringify(json)) + } + + // When EMIT_INTROSPECTION_JSON_FILE is set, write the module's own types as + // an introspection-shaped JSON. The Go-side Codegen merges it into the deps + // schema (dag.Schema().Merge) before generating the client bindings, so the + // bindings include the module's own types and self calls resolve without a + // runtime codegen pass. LEGACY_SHARED_ID_TYPES asks for per-type ID + // scalars, needed by pre-cutover schema views. + const introspectionJsonPath = process.env.EMIT_INTROSPECTION_JSON_FILE + if (introspectionJsonPath) { + const legacySharedIDTypes = process.env.LEGACY_SHARED_ID_TYPES !== undefined + const json = serializeIntrospection(result, { legacySharedIDTypes }) + await fs.promises.writeFile(introspectionJsonPath, JSON.stringify(json)) + } + + // The EMIT_* modes are file-only; only the legacy TYPEDEF_OUTPUT_FILE path + // needs an engine connection to register the module. + if ( + (typedefJsonPath || introspectionJsonPath) && + !process.env.TYPEDEF_OUTPUT_FILE + ) { + return + } + + // TODO(TomChv): move that logic inside the engine at some point + // so we don't even need a connection. + // Idea: We should output a JSON schema of the module that can be transformed + // into a Dagger module by the engine. + await connection(async () => { + const outputFilePath = process.env.TYPEDEF_OUTPUT_FILE ?? "/module-id.json" + const moduleID = await new Register(result).run() + + await fs.promises.writeFile(outputFilePath, JSON.stringify(moduleID)) + }) +} + +main() diff --git a/library/src/module/entrypoint/invoke.ts b/library/src/module/entrypoint/invoke.ts new file mode 100644 index 0000000..7ddfc69 --- /dev/null +++ b/library/src/module/entrypoint/invoke.ts @@ -0,0 +1,109 @@ +import { TypeDefKind } from "../../api/client.gen.js" +import { FunctionNotFound } from "../../common/errors/index.js" +import { Executor } from "../executor.js" +import { + DaggerConstructor as Constructor, + DaggerFunction as Method, + DaggerEnumBase, + DaggerModule, + DaggerObjectBase, +} from "../introspector/dagger_module/index.js" +import { registry } from "../registry.js" +import { InvokeCtx } from "./context.js" +import { + loadResult, + loadInvokedMethod, + loadInvokedObject, + loadArgs, + loadParentState, + loadObjectReturnType, +} from "./load.js" + +function isConstructor(method: Method | Constructor): method is Constructor { + return method.name === "" +} + +function isFloat(num: number): boolean { + return num % 1 !== 0 +} + +/** + * A wrapper around the registry to invoke a function. + * + * @param scanResult The result of the scan. + * @param parentName The name of the parent object. + * @param fnName The name of the function to call. + * @param parentArgs The arguments of the parent object. + * @param fnArgs The arguments of the function to call. + */ +export async function invoke( + executor: Executor, + module: DaggerModule, + ctx: InvokeCtx, +) { + const object = loadInvokedObject(module, ctx.parentName) + if (!object) { + throw new Error(`could not find object ${ctx.parentName}`) + } + + const method = loadInvokedMethod(object, ctx) + if (!method) { + throw new Error(`could not find method ${ctx.fnName}`) + } + + const args = await loadArgs(executor, method, ctx) + const parentState = await loadParentState(executor, object, ctx) + + // Disabling linter because the result could be anything. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let result: any + + try { + result = await executor.getResult( + object.name, + method.name, + parentState, + args, + ) + } catch (e) { + // If the function isn't found because it's + // not exported, we try to get the result from the registry. + if (e instanceof FunctionNotFound) { + result = await registry.getResult( + object.name, + method.name, + parentState, + args, + ) + } else { + throw e + } + } + + if (result) { + let returnType: DaggerObjectBase | DaggerEnumBase + + // Handle alias serialization by getting the return type to load + // if the function called isn't a constructor. + if (!isConstructor(method)) { + // Guard to catch if a user returned a float number but the function's return + // type is set to `number` (integer). + if ( + method.returnType!.kind === TypeDefKind.IntegerKind && + isFloat(result) + ) { + throw new Error( + `cannot return float '${result}' if return type is 'number' (integer), please use 'float' as return type instead`, + ) + } + + returnType = loadObjectReturnType(module, object, method) + } else { + returnType = object + } + + result = await loadResult(result, module, returnType) + } + + return result +} diff --git a/library/src/module/entrypoint/load.ts b/library/src/module/entrypoint/load.ts new file mode 100644 index 0000000..f18b7cc --- /dev/null +++ b/library/src/module/entrypoint/load.ts @@ -0,0 +1,373 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import Module from "node:module" + +import * as clientGen from "../../api/client.gen.js" +import { dag, TypeDefKind } from "../../api/client.gen.js" +import { Context } from "../../common/context.js" +import { Connection } from "../../common/graphql/connection.js" +import { Executor, Args } from "../executor.js" +import { + DaggerConstructor as Constructor, + DaggerFunction as Method, + DaggerEnum, + DaggerEnumBase, + DaggerModule, + DaggerObject, + DaggerObjectBase, + DaggerTypeObject, + DaggerEnumClass, +} from "../introspector/dagger_module/index.js" +import { TypeDef } from "../introspector/typedef.js" +import { InvokeCtx } from "./context.js" + +/** + * Import all given typescript files so that trigger their decorators + * and register their class and functions inside the Registry. + * + * @param files List of files to load. + */ +export async function load(files: string[]): Promise { + return await Promise.all(files.map(async (f) => await import(f))) +} + +/** + * Return the object invoked from the module. + * + * @param module The module to load the object from. + * @param parentName The name of the parent object. + */ +export function loadInvokedObject( + module: DaggerModule, + parentName: string, +): DaggerObject { + return module.objects[parentName] as DaggerObject +} + +export function loadInvokedMethod( + object: DaggerObject, + ctx: InvokeCtx, +): (Method | Constructor) | undefined { + if (ctx.fnName === "") { + return object._constructor + } + + return object.methods[ctx.fnName] +} + +/** + * Load the values of the arguments from the context. + * + * @param method Method to load the arguments from. + * @param ctx The context of the invocation. + */ +export async function loadArgs( + executor: Executor, + method: Method | Constructor, + ctx: InvokeCtx, +): Promise { + const args: Args = {} + + // Load arguments + for (const argName of method.getArgsOrder()) { + const argument = method.arguments[argName] + if (!argument) { + throw new Error(`could not find argument ${argName}`) + } + + if (!argument.type) { + throw new Error(`could not find type for argument ${argName}`) + } + + const loadedArg = await loadValue( + executor, + ctx.fnArgs[argName], + argument.type, + ) + + // If the argument is variadic, we need to load each args independently + // so it's correctly propagated when it's sent to the function. + // Note: variadic args are always last in the list of args. + if (argument.isVariadic) { + for (const [i, arg] of (loadedArg ?? []).entries()) { + args[`${argName}${i}`] = arg + } + + continue + } + + // If the argument is nullable and the loaded arg is undefined with no default value, we set it to null. + if ( + argument.isNullable && + loadedArg === undefined && + !argument.defaultValue + ) { + args[argName] = null + continue + } + + args[argName] = loadedArg + } + + return args +} + +/** + * Load the state of the parent object from the context. + * + * @param object The object to load the parent state from. + * @param ctx The context of the invocation. + */ +export async function loadParentState( + executor: Executor, + object: DaggerObject, + ctx: InvokeCtx, +): Promise { + const parentState: Args = {} + + for (const [key, value] of Object.entries(ctx.parentArgs)) { + const property = object.properties[key] + if (!property) { + throw new Error(`could not find parent property ${key}`) + } + + if (!property.type) { + throw new Error(`could not find type for parent property ${key}`) + } + + parentState[property.name] = await loadValue(executor, value, property.type) + } + + return parentState +} + +/** + * This function load the value as a Dagger type. + * + * Note: The JSON.parse() is required to remove extra quotes + */ +export async function loadValue( + executor: Executor, + value: any, + type: TypeDef, +): Promise { + // If value is undefinied, return it directly. + if (value === undefined) { + return value + } + + switch (type.kind) { + case TypeDefKind.ListKind: + return Promise.all( + value.map( + async (v: any) => + await loadValue( + executor, + v, + (type as TypeDef).typeDef, + ), + ), + ) + case TypeDefKind.ObjectKind: { + const objectType = (type as TypeDef).name + + // For module-defined types, reconstruct from fields. + // For core API types, the value is an ID string — load via node(id:). + if (executor.hasObject(objectType)) { + return executor.buildClass(objectType, value) + } + + // Core type: construct a typed SDK client via node(id:) + const ctx = new Context( + [], + new Connection(dag.getGQLClient()), + ).selectNode(value, objectType) + // Look up the class from the generated client exports (e.g. "Directory" -> Directory class) + // Some names collide with JS builtins and get a _ suffix (e.g. "Module" -> Module_) + const className = (clientGen as any)[objectType] + ? objectType + : `${objectType}_` + const cls = (clientGen as any)[className] + if (cls) { + return new cls(ctx) + } + throw new Error( + `Generated client class not found for core type ${objectType}`, + ) + } + case TypeDefKind.InterfaceKind: { + const interfaceType = (type as TypeDef).name + + return executor.buildInterface(interfaceType, value) + } + case TypeDefKind.EnumKind: { + const enumType = (type as TypeDef).name + + return executor.buildEnum(enumType, value) + } + // Cannot use `,` to specify multiple matching case so instead we use fallthrough. + case TypeDefKind.StringKind: + case TypeDefKind.IntegerKind: + case TypeDefKind.BooleanKind: + case TypeDefKind.FloatKind: + case TypeDefKind.VoidKind: + case TypeDefKind.ScalarKind: + return value + default: + throw new Error(`unsupported type ${type.kind}`) + } +} + +/** + * Load the object type from the return type of the method. + * This covers the case where the return type is an other object of the module. + * For example: `msg(): Message` where message is an object of the module. + * + * @param module The module to load the object from. + * @param object The current object to load the return type from. + * @param method The method to load the return type from. + */ +export function loadObjectReturnType( + module: DaggerModule, + object: DaggerObject, + method: Method, +): DaggerObjectBase | DaggerEnumBase { + const retType = method.returnType + if (!retType) { + throw new Error(`could not find return type for ${method.name}`) + } + + switch (retType.kind) { + case TypeDefKind.ListKind: { + // Loop until we find the original object type. + // This way we handle the list of list (e.g Object[][][]...[]) + let listType = retType + while (listType.kind === TypeDefKind.ListKind) { + listType = (listType as TypeDef).typeDef + } + + if (listType.kind === TypeDefKind.EnumKind) { + return module.enums[(listType as TypeDef).name] + } + + return module.objects[(listType as TypeDef).name] + } + case TypeDefKind.ObjectKind: + return module.objects[(retType as TypeDef).name] + case TypeDefKind.EnumKind: + return module.enums[(retType as TypeDef).name] + default: + return object + } +} + +export async function loadResult( + result: any, + module: DaggerModule, + object: DaggerObjectBase | DaggerEnumBase, +): Promise { + // Handle IDable objects + if (result && typeof result?.id === "function") { + return await result.id() + } + + // Handle arrays + if (Array.isArray(result)) { + result = await Promise.all( + result.map(async (r) => await loadResult(r, module, object)), + ) + + return result + } + + // Handle objects + if ( + typeof result === "object" && + (object instanceof DaggerObject || object instanceof DaggerTypeObject) + ) { + const state: any = {} + + for (const [key, value] of Object.entries(result)) { + const property = Object.values(object.properties).find( + (p) => p.name === key, + ) + if (!property) { + throw new Error(`could not find result property ${key}`) + } + + if (!property.type) { + throw new Error(`could not find type for result property ${key}`) + } + + let referencedObject: DaggerObjectBase | DaggerEnumBase | undefined = + undefined + + // Handle nested objects + if (property.type.kind === TypeDefKind.ObjectKind) { + referencedObject = + module.objects[ + (property.type as TypeDef).name + ] + } + + // Handle list of nested objects + if (property.type.kind === TypeDefKind.ListKind) { + let _property = property.type + + // Loop until we find the original type. + while (_property.kind === TypeDefKind.ListKind) { + _property = (_property as TypeDef).typeDef + } + + // If the original type is an object, we use it as the referenced object. + if (_property.kind === TypeDefKind.ObjectKind) { + referencedObject = + module.objects[(_property as TypeDef).name] + } + + // If the original type is a enum, we use it as the referenced object. + if (_property.kind === TypeDefKind.EnumKind) { + referencedObject = + module.enums[(_property as TypeDef).name] + } + } + + // Handle enums + if (property.type.kind === TypeDefKind.EnumKind) { + referencedObject = + module.enums[(property.type as TypeDef).name] + } + + // If there's no referenced object, we use the current object. + if (!referencedObject) { + referencedObject = object + } + + state[property.alias ?? property.name] = await loadResult( + value, + module, + referencedObject, + ) + } + + return state + } + + // If it's an enum, we need to resolve the enum member name instead of the value. + // A enum value A = "a" will be returned as "a" by the function so we need to + // transform it back to "A" to be sent as result to the engine. + if (object instanceof DaggerEnum || object instanceof DaggerEnumClass) { + const enumMember = Object.entries(object.values).find( + ([, member]) => member.value === result, + ) + + // If the enum member is not found, we return the result as is and let the engine handle it. + if (!enumMember) { + return result + } + + return enumMember[0] + } + + // Handle primitive types + return result +} diff --git a/library/src/module/entrypoint/register.ts b/library/src/module/entrypoint/register.ts new file mode 100644 index 0000000..0575528 --- /dev/null +++ b/library/src/module/entrypoint/register.ts @@ -0,0 +1,325 @@ +import { + dag, + Function_, + FunctionWithArgOpts, + ID, + TypeDef, + TypeDefKind, + TypeDefWithEnumMemberOpts, + TypeDefWithFieldOpts, + TypeDefWithObjectOpts, + SourceMap, + FunctionCachePolicy, + FunctionWithCachePolicyOpts, +} from "../../api/client.gen.js" +import { + DaggerArguments as Arguments, + DaggerConstructor as Constructor, + DaggerFunction as Method, + DaggerModule, + Locatable, + DaggerArgument, +} from "../introspector/dagger_module/index.js" +import { DaggerInterfaceFunction } from "../introspector/dagger_module/interfaceFunction.js" +import { + EnumTypeDef, + InterfaceTypeDef, + ListTypeDef, + ObjectTypeDef, + ScalarTypeDef, + TypeDef as ScannerTypeDef, +} from "../introspector/typedef.js" + +export class Register { + constructor(private readonly module: DaggerModule) {} + + /** + * Register the module in the engine and returns its ID + */ + async run(): Promise { + // Get a new module that we will fill in with all the types + let mod = dag.module_() + + // Add module description if any. + if (this.module.description) { + mod = mod.withDescription(this.module.description) + } + + // For each class scanned, register its type, method and properties in the module. + Object.values(this.module.objects).forEach((object) => { + const objectOpts: TypeDefWithObjectOpts = { + description: object.description, + sourceMap: addSourceMap(object), + deprecated: object.deprecated, + } + + // Register the class Typedef object in Dagger + let typeDef = dag.typeDef().withObject(object.name, objectOpts) + + // Register all functions (methods) to this object + Object.values(object.methods).forEach((method) => { + typeDef = typeDef.withFunction(this.addFunction(method)) + }) + + // Register all fields that belong to this object + Object.values(object.properties).forEach((field) => { + if (field.isExposed) { + const fieldOpts = { + description: field.description, + sourceMap: addSourceMap(field), + deprecated: field.deprecated, + } as TypeDefWithFieldOpts + + typeDef = typeDef.withField( + field.alias ?? field.name, + addTypeDef(field.type!), + fieldOpts, + ) + } + }) + + if (object._constructor) { + typeDef = typeDef.withConstructor( + this.addConstructor(object._constructor, typeDef), + ) + } + + // Add it to the module object + mod = mod.withObject(typeDef) + }) + + // Register all enums defined by this modules + Object.values(this.module.enums).forEach((enum_) => { + let typeDef = dag.typeDef().withEnum(enum_.name, { + description: enum_.description, + sourceMap: addSourceMap(enum_), + }) + + Object.values(enum_.values).forEach((value) => { + const memberOpts: TypeDefWithEnumMemberOpts = { + value: value.value, + description: value.description, + sourceMap: addSourceMap(value), + deprecated: value.deprecated, + } + + typeDef = typeDef.withEnumMember(value.name, memberOpts) + }) + + mod = mod.withEnum(typeDef) + }) + + // Register all interfaces defined by this module + Object.values(this.module.interfaces).forEach((interface_) => { + let typeDef = dag.typeDef().withInterface(interface_.name, { + description: interface_.description, + }) + + Object.values(interface_.functions).forEach((function_) => { + typeDef = typeDef.withFunction(this.addFunction(function_)) + }) + + mod = mod.withInterface(typeDef) + }) + + return await mod.id() + } + + /** + * Bind a constructor to the given object. + */ + addConstructor(constructor: Constructor, owner: TypeDef): Function_ { + return dag.function_("", owner).with(this.addArg(constructor.arguments)) + } + + /** + * Create a function in the Dagger API. + */ + addFunction(fct: Method | DaggerInterfaceFunction): Function_ { + let fnDef = dag + .function_(fct.alias ?? fct.name, addTypeDef(fct.returnType!)) + .withDescription(fct.description) + .withSourceMap(addSourceMap(fct)) + .with(this.addArg(fct.arguments)) + + switch (fct.cache) { + case "never": { + fnDef = fnDef.withCachePolicy(FunctionCachePolicy.Never) + break + } + case "session": { + fnDef = fnDef.withCachePolicy(FunctionCachePolicy.PerSession) + break + } + case "": { + break + } + default: { + const opts: FunctionWithCachePolicyOpts = { timeToLive: fct.cache } + fnDef = fnDef.withCachePolicy(FunctionCachePolicy.Default, opts) + } + } + + if (fct.deprecated !== undefined) { + fnDef = fnDef.withDeprecated({ reason: fct.deprecated }) + } + + if ((fct as Method).isCheck) { + fnDef = fnDef.withCheck() + } + + if ((fct as Method).isGenerator) { + fnDef = fnDef.withGenerator() + } + + if ((fct as Method).isUp) { + fnDef = fnDef.withUp() + } + + return fnDef + } + + /** + * Register all arguments in the function. + */ + addArg(args: Arguments): (fct: Function_) => Function_ { + return (fct: Function_): Function_ => { + Object.values(args).forEach((arg) => { + const opts: FunctionWithArgOpts = { + description: arg.description, + sourceMap: addSourceMap(arg), + deprecated: arg.deprecated, + } + + let typeDef = addTypeDef(arg.type!) + if (arg.isOptional) { + typeDef = typeDef.withOptional(true) + } + + // Check if both values are used, return an error if so. + if ( + [arg.defaultValue, arg.defaultPath, arg.defaultAddress].filter( + (v) => v, + ).length > 1 + ) { + throw new Error("cannot set multiple defaults") + } + + // We do not set the default value if it's not a primitive type, we let TypeScript + // resolve the default value during the runtime instead. + // If it has a default value but is not primitive, we set the value as optional + // to workaround the fact that the API isn't aware of the default value and will + // expect it to be set as required input. + if (arg.defaultValue !== undefined) { + const defaultValue = this.getDefaultValueFromArg(arg) + if (defaultValue === undefined) { + typeDef = typeDef.withOptional(true) + } else { + opts.defaultValue = JSON.stringify(defaultValue) as string & { + __JSON: never + } + } + } + + // If the argument is a contextual argument, it becomes optional. + if (arg.defaultPath) { + opts.defaultPath = arg.defaultPath + } + + if (arg.defaultAddress) { + opts.defaultAddress = arg.defaultAddress + } + + if (arg.ignore) { + opts.ignore = arg.ignore + } + + fct = fct.withArg(arg.name, typeDef, opts) + }) + + return fct + } + } + + /** + * Extract the default value from the argument. + * - If the argument isn't a primitive type, we can't resolve it so we make it optional and let the runtime + * resolve it on execution. + * - If the argument is a primitive type but not an enum, we resolve it directly. + * - If the argument is an enum but not registered in the module, it must be a core enum so we keep the value as is. + * - If the argument is an enum registered in the module, we resolve the value to the member name. + */ + getDefaultValueFromArg(arg: DaggerArgument): unknown | undefined { + if (!isPrimitiveType(arg.type!)) { + return undefined + } + + if (arg.type!.kind !== TypeDefKind.EnumKind) { + return arg.defaultValue + } + + const enumObj = this.module.enums[(arg.type! as EnumTypeDef).name] + if (!enumObj) { + // If the enum isn't found in the module, it may be a core enum so we keep the value + return arg.defaultValue + } + + // If it's a known enum, we need to resolve set the name of the member as default value instead of the actual value + const enumMember = Object.entries(enumObj.values).find( + ([, member]) => member.value === arg.defaultValue, + ) + + if (!enumMember) { + throw new Error( + `could not resolve default value '${arg.defaultValue}' for enum ${(arg.type! as EnumTypeDef).name}`, + ) + } + + return enumMember[0] + } +} + +/** + * Wrapper around TypeDef to return the right Dagger TypesDef with its options. + * + * This function only convert the Typedef into correct dagger call + * but, it's up to function above with more context to add documentation, + * define if it's an optional value or its default's. + * + * We cannot do it there because the Typedef can come from any source: + * a field, a param, a return value etc... + */ +function addTypeDef(type: ScannerTypeDef): TypeDef { + switch (type.kind) { + case TypeDefKind.ScalarKind: + return dag.typeDef().withScalar((type as ScalarTypeDef).name) + case TypeDefKind.ObjectKind: + return dag.typeDef().withObject((type as ObjectTypeDef).name) + case TypeDefKind.ListKind: + return dag.typeDef().withListOf(addTypeDef((type as ListTypeDef).typeDef)) + case TypeDefKind.VoidKind: + return dag.typeDef().withKind(type.kind).withOptional(true) + case TypeDefKind.EnumKind: + return dag.typeDef().withEnum((type as EnumTypeDef).name) + case TypeDefKind.InterfaceKind: + return dag.typeDef().withInterface((type as InterfaceTypeDef).name) + default: + return dag.typeDef().withKind(type.kind) + } +} + +function addSourceMap(object: Locatable): SourceMap { + const { filepath, line, column } = object.getLocation() + + return dag.sourceMap(filepath, line, column) +} + +function isPrimitiveType(type: ScannerTypeDef): boolean { + return ( + type.kind === TypeDefKind.BooleanKind || + type.kind === TypeDefKind.IntegerKind || + type.kind === TypeDefKind.StringKind || + type.kind === TypeDefKind.FloatKind || + type.kind === TypeDefKind.EnumKind + ) +} diff --git a/library/src/module/executor.ts b/library/src/module/executor.ts new file mode 100644 index 0000000..dae676d --- /dev/null +++ b/library/src/module/executor.ts @@ -0,0 +1,255 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/ban-ts-comment */ +import Module from "node:module" + +import * as clientGen from "../api/client.gen.js" +import { dag, TypeDefKind } from "../api/client.gen.js" +import { Context } from "../common/context.js" +import { FunctionNotFound } from "../common/errors/index.js" +import { Connection } from "../common/graphql/connection.js" +import { DaggerModule } from "./introspector/dagger_module/index.js" +import { DaggerInterfaceFunctions } from "./introspector/dagger_module/interfaceFunction.js" +import { TypeDef } from "./introspector/typedef.js" + +export type State = { [property: string]: any } + +export type Args = Record + +export class Executor { + constructor( + public readonly modules: Module[], + private readonly daggerModule: DaggerModule, + ) {} + + private getExportedObject(object: string): any { + const key = object as keyof Module + const module = this.modules.find((m) => m[key] !== undefined) + if (!module) { + throw new FunctionNotFound(`Object ${object} not found`) + } + + return module[key] + } + + hasObject(object: string): boolean { + return !!this.daggerModule.objects[object] + } + + buildClass(object: string, state: State): any { + const daggerObject = this.daggerModule.objects[object] + if (!daggerObject) { + throw new FunctionNotFound(`Object ${object} not found in the module`) + } + + switch (daggerObject.kind()) { + case "class": { + const obj = this.getExportedObject(object) + + const instanciatedClass = Object.create(obj.prototype) + Object.assign(instanciatedClass, state) + + return instanciatedClass + } + case "object": { + return state + } + } + } + + /** + * Transform a Dagger interface identifier into an implementation of this + * interface serves as module call binding to reach the true implementation. + */ + buildInterface(iface: string, id: string): any { + const interfaceObject = this.daggerModule.interfaces[iface] + if (!interfaceObject) { + throw new Error(`Interface ${iface} not found in the module`) + } + + const ifaceImpl = new InterfaceWrapper( + this, + this.daggerModule, + `${this.daggerModule.name}${iface}`, + id, + interfaceObject.functions, + ) + + return ifaceImpl + } + + /** + * Transfer a Dagger enum member name into its implemented value. + * An enum value A = "a" will be received as "A" by the entrypoint + * but should be transformed into "a" to be sent to the function. + * If the enum isn't found in the module, it may be a core enum so we keep the value + * as is. + */ + buildEnum(enumName: string, value: string): any { + const enumObject = this.daggerModule.enums[enumName] + if (!enumObject) { + return value + } + + if (!enumObject.values[value]) { + throw new Error(`Enum ${enumName} does not have member ${value}`) + } + + return enumObject.values[value].value + } + + async getResult( + object: string, + method: string, + state: State, + inputs: Args, + ): Promise { + const obj = this.getExportedObject(object) + + if (method === "") { + return new obj(...Object.values(inputs)) + } + + const builtObj = this.buildClass(object, state) + if (!builtObj[method]) { + throw new FunctionNotFound(`Method ${method} not found`) + } + + return await builtObj[method](...Object.values(inputs)) + } +} + +/** + * Interface Wrapper serves as dynaminc module binding so the module can + * call function of this interface. + * Because the actual interface implementation can come from any external modules, + * all resolution are done by API Call. + * + * @example + * ```ts + * interface Example { + * foo: () => Promise + * } + * + * class Test { + * @func() + * async callFoo(example: Example): Promise { + * // <- This example argument here is actually the Interface Wrapper, and `foo` will, + * // directly execute the API call to reach the given implementation. + * return example.foo() + * } + * } + * ``` + */ +class InterfaceWrapper { + private _ctx: Context + + constructor( + private readonly executor: Executor, + private readonly module: DaggerModule, + private readonly ifaceName: string, + private readonly ifaceId: string, + private readonly fcts: DaggerInterfaceFunctions, + ) { + this._ctx = new Context([], new Connection(dag.getGQLClient())) + + // Load the interface by its identifier via node(id:) + this._ctx = this._ctx.selectNode(ifaceId, ifaceName) + + Object.entries(fcts).forEach(([name, fct]) => { + const argKeys = Object.keys(fct.arguments) + + // Dynamically adding functions of the interface and it's resolvers. + // @ts-ignore + this[name] = async (...args: any[]) => { + // Fill up arguments of that function. + const argsPayload = {} + for (let i = 0; i < argKeys.length; i++) { + if (args[i] !== undefined) { + // @ts-ignore + argsPayload[argKeys[i]] = args[i] + } + } + + this._ctx = this._ctx.select(name, argsPayload) + + // If the function is returning an IDable, we don't need to execute it + // since it will be resolved later. + if ( + fct.returnType!.kind === TypeDefKind.InterfaceKind || + fct.returnType!.kind === TypeDefKind.ObjectKind + ) { + return this + } + + // If the function is returning a list, we may need to load the sub-objects + if (fct.returnType!.kind === TypeDefKind.ListKind) { + const listTypeDef = (fct.returnType as TypeDef) + .typeDef + + // If the list is an object or an interface, then we need to load the sub-objects. + if ( + listTypeDef.kind === TypeDefKind.ObjectKind || + listTypeDef.kind === TypeDefKind.InterfaceKind + ) { + const typedef = listTypeDef as + | TypeDef + | TypeDef + + // Resolves the call to get the list of IDs to load + const ids = await this._ctx + .select("id") + .execute>() + + // If the return type is an interface defined by that module, we need to load it through + // the interface wrapper + if (this.module.interfaces[typedef.name]) { + return await Promise.all( + ids.map( + ({ id }) => + new InterfaceWrapper( + this.executor, + module, + `${this.module.name}${typedef.name}`, + id, + this.module.interfaces[typedef.name].functions, + ), + ), + ) + } + + // Otherwise, we can just load the objects from the API + // using node(id:) with an inline fragment. + return ids.map(({ id }) => { + const ctx = new Context( + [], + new Connection(dag.getGQLClient()), + ).selectNode(id, typedef.name) + const className = (clientGen as any)[typedef.name] + ? typedef.name + : `${typedef.name}_` + const cls = (clientGen as any)[className] + if (cls) { + return new cls(ctx) + } + throw new Error( + `Generated client class not found for core type ${typedef.name}`, + ) + }) + } + } + + return await this._ctx.execute() + } + }) + } + + /** + * ID function to make the interface IDeable when serialized as return value to the + * Dagger API. + */ + public async id(): Promise { + const ctx = this._ctx.select("id") + + return await ctx.execute() + } +} diff --git a/library/src/module/introspector/case_convertor.ts b/library/src/module/introspector/case_convertor.ts new file mode 100644 index 0000000..a9ce98d --- /dev/null +++ b/library/src/module/introspector/case_convertor.ts @@ -0,0 +1,18 @@ +export function convertToPascalCase(input: string): string { + // Handle empty string case + if (!input) { + return "" + } + + // Split on word boundaries before uppercase letters, numbers, and special characters + const words = input + .split(/(?=[A-Z0-9])|[^a-zA-Z0-9]|(?<=[a-zA-Z])(?=\d)|(?<=\d)(?=[a-zA-Z])/g) + .filter((word) => word.length > 0) + + // Convert each word to proper case + const pascalCase = words + .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) + .join("") + + return pascalCase +} diff --git a/library/src/module/introspector/dagger_module/argument.ts b/library/src/module/introspector/dagger_module/argument.ts new file mode 100644 index 0000000..84c9ce7 --- /dev/null +++ b/library/src/module/introspector/dagger_module/argument.ts @@ -0,0 +1,169 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import ts from "typescript" + +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { ArgumentOptions } from "../../registry.js" +import { TypeDef } from "../typedef.js" +import { + AST, + isTypeDefResolved, + resolveTypeDef, +} from "../typescript_module/index.js" +import { ARGUMENT_DECORATOR } from "./decorator.js" +import { Locatable } from "./locatable.js" +import { References } from "./reference.js" + +export type DaggerArguments = { [name: string]: DaggerArgument } + +export class DaggerArgument extends Locatable { + public name: string + public description: string + public deprecated?: string + private _typeRef?: string + public type?: TypeDef + public isVariadic: boolean + public isNullable: boolean + public isOptional: boolean + public defaultPath?: string + public defaultAddress?: string + public ignore?: string[] + public defaultValue?: any + + private symbol: ts.Symbol + + constructor( + private readonly node: ts.ParameterDeclaration, + private readonly ast: AST, + ) { + super(node) + + this.symbol = this.ast.getSymbolOrThrow(node.name) + this.name = this.node.name.getText() + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + this.defaultValue = this.getDefaultValue() + this.isVariadic = this.node.dotDotDotToken !== undefined + this.isNullable = this.getIsNullable() + this.isOptional = + this.isVariadic || // if argument has ... + (this.defaultValue === undefined && // if argument has a default value that couldn't be resolved. + this.node.initializer !== undefined) || + this.isNullable || // if argument is nullable + this.node.questionToken !== undefined // if argument has ? + + if (this.deprecated !== undefined && !this.isOptional) { + throw new IntrospectionError( + `argument ${this.name} is required and cannot be deprecated at ${AST.getNodePosition(this.node)}.`, + ) + } + + const decoratorArguments = this.ast.getDecoratorArgument( + this.node, + ARGUMENT_DECORATOR, + "object", + ) + + if (decoratorArguments) { + this.ignore = decoratorArguments.ignore + this.defaultPath = decoratorArguments.defaultPath + this.defaultAddress = decoratorArguments.defaultAddress + + // If defaultAddress is set, the argument becomes optional + if (this.defaultAddress) { + this.isOptional = true + } + } + + this.type = this.getType() + } + + /** + * Get the type of the parameter. + * + * If for it's a complex type that cannot be + * resolve yet, we save its string representation for further reference. + */ + private getType(): TypeDef | undefined { + const type = this.ast.checker.getTypeAtLocation(this.node) + + const typedef = this.ast.tsTypeToTypeDef(this.node, type) + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._typeRef = this.ast.typeToStringType(type) + } + + return typedef + } + + private getIsNullable(): boolean { + if (!this.node.type) { + return false + } + + if (ts.isUnionTypeNode(this.node.type)) { + for (const _type of this.node.type.types) { + if (_type.getText() === "null") { + return true + } + } + } + + return false + } + + private getDefaultValue(): any { + const initializer = this.node.initializer + if (!initializer) { + return undefined + } + + return this.ast.resolveParameterDefaultValue(initializer) + } + + public getReference(): string | undefined { + if ( + this._typeRef && + (this.type === undefined || !isTypeDefResolved(this.type)) + ) { + return this._typeRef + } + + return undefined + } + + public propagateReferences(references: References) { + if (!this._typeRef) { + return + } + + if (this.type && isTypeDefResolved(this.type)) { + return + } + + const typeDef = references[this._typeRef] + if (!typeDef) { + throw new IntrospectionError( + `could not find type reference for ${this._typeRef} at ${AST.getNodePosition(this.node)}.`, + ) + } + + this.type = resolveTypeDef(this.type, typeDef) + } + + toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + type: this.type, + isVariadic: this.isVariadic, + isNullable: this.isNullable, + isOptional: this.isOptional, + defaultValue: this.defaultValue, + defaultPath: this.defaultPath, + defaultAddress: this.defaultAddress, + ignore: this.ignore, + } + } +} diff --git a/library/src/module/introspector/dagger_module/constructor.ts b/library/src/module/introspector/dagger_module/constructor.ts new file mode 100644 index 0000000..843ceea --- /dev/null +++ b/library/src/module/introspector/dagger_module/constructor.ts @@ -0,0 +1,53 @@ +import ts from "typescript" + +import { AST } from "../typescript_module/index.js" +import { DaggerArgument, DaggerArguments } from "./argument.js" +import { References } from "./reference.js" + +export class DaggerConstructor { + public name: string = "" + public arguments: DaggerArguments = {} + + constructor( + private readonly node: ts.ConstructorDeclaration, + private readonly ast: AST, + ) { + const parameters = this.node.parameters + + for (const parameter of parameters) { + this.arguments[parameter.name.getText()] = new DaggerArgument( + parameter, + this.ast, + ) + } + } + + public getArgsOrder(): string[] { + return Object.keys(this.arguments) + } + + public getReferences(): string[] { + const references: string[] = [] + + for (const argument of Object.values(this.arguments)) { + const ref = argument.getReference() + if (ref) { + references.push(ref) + } + } + + return references + } + + public propagateReferences(references: References) { + for (const argument of Object.values(this.arguments)) { + argument.propagateReferences(references) + } + } + + toJSON() { + return { + arguments: this.arguments, + } + } +} diff --git a/library/src/module/introspector/dagger_module/decorator.ts b/library/src/module/introspector/dagger_module/decorator.ts new file mode 100644 index 0000000..79e2d97 --- /dev/null +++ b/library/src/module/introspector/dagger_module/decorator.ts @@ -0,0 +1,29 @@ +import { + argument, + func, + object, + enumType, + field, + check, + generate, + up, +} from "../../decorators.js" + +export type DaggerDecorators = + | "object" + | "func" + | "check" + | "generate" + | "up" + | "argument" + | "enumType" + | "field" + +export const OBJECT_DECORATOR = object.name as DaggerDecorators +export const FUNCTION_DECORATOR = func.name as DaggerDecorators +export const CHECK_DECORATOR = check.name as DaggerDecorators +export const GENERATOR_DECORATOR = generate.name as DaggerDecorators +export const UP_DECORATOR = up.name as DaggerDecorators +export const FIELD_DECORATOR = field.name as DaggerDecorators +export const ARGUMENT_DECORATOR = argument.name as DaggerDecorators +export const ENUM_DECORATOR = enumType.name as DaggerDecorators diff --git a/library/src/module/introspector/dagger_module/enum.ts b/library/src/module/introspector/dagger_module/enum.ts new file mode 100644 index 0000000..2bddd4f --- /dev/null +++ b/library/src/module/introspector/dagger_module/enum.ts @@ -0,0 +1,82 @@ +import ts from "typescript" + +import { IntrospectionError } from "../../../common/errors/index.js" +import { AST } from "../typescript_module/index.js" +import { DaggerEnumBase, DaggerEnumBaseValue } from "./enumBase.js" +import { Locatable } from "./locatable.js" + +export type DaggerEnums = { [name: string]: DaggerEnum } +export type DaggerEnumValues = { [name: string]: DaggerEnumValue } + +export class DaggerEnumValue extends Locatable implements DaggerEnumBaseValue { + public name: string + public value: string + public description: string + public deprecated?: string + + private symbol: ts.Symbol + + constructor( + private readonly node: ts.EnumMember, + private readonly ast: AST, + ) { + super(node) + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + this.name = this.node.name.getText() + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + + const initializer = this.node.initializer + if (!initializer) { + throw new IntrospectionError( + `enum ${this.name} at ${AST.getNodePosition(this.node)} has no value set to its member.`, + ) + } + + this.value = this.ast.resolveParameterDefaultValue(initializer) + } + + toJSON() { + return { + name: this.name, + value: this.value, + description: this.description, + deprecated: this.deprecated, + } + } +} + +export class DaggerEnum extends Locatable implements DaggerEnumBase { + public name: string + public description: string + public values: DaggerEnumValues = {} + + private symbol: ts.Symbol + + constructor( + private readonly node: ts.EnumDeclaration, + private readonly ast: AST, + ) { + super(node) + + this.name = this.node.name.getText() + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + this.description = this.ast.getDocFromSymbol(this.symbol) + + const members = this.node.members + for (const member of members) { + const value = new DaggerEnumValue(member, this.ast) + + this.values[value.name] = value + } + } + + toJSON() { + return { + name: this.name, + description: this.description, + values: this.values, + } + } +} diff --git a/library/src/module/introspector/dagger_module/enumBase.ts b/library/src/module/introspector/dagger_module/enumBase.ts new file mode 100644 index 0000000..b499217 --- /dev/null +++ b/library/src/module/introspector/dagger_module/enumBase.ts @@ -0,0 +1,18 @@ +import { Locatable } from "./locatable.js" + +export interface DaggerEnumBaseValue extends Locatable { + name: string + value: string + description: string + deprecated?: string +} + +export type DaggerEnumBaseValues = { [name: string]: DaggerEnumBaseValue } + +export interface DaggerEnumBase extends Locatable { + name: string + description: string + values: DaggerEnumBaseValues +} + +export type DaggerEnumsBase = { [name: string]: DaggerEnumBase } diff --git a/library/src/module/introspector/dagger_module/enumClass.ts b/library/src/module/introspector/dagger_module/enumClass.ts new file mode 100644 index 0000000..3303230 --- /dev/null +++ b/library/src/module/introspector/dagger_module/enumClass.ts @@ -0,0 +1,91 @@ +import ts from "typescript" + +import { IntrospectionError } from "../../../common/errors/index.js" +import { AST } from "../typescript_module/index.js" +import { DaggerEnumBase, DaggerEnumBaseValue } from "./enumBase.js" +import { Locatable } from "./locatable.js" + +export type DaggerEnumClasses = { [name: string]: DaggerEnumClass } + +export type DaggerEnumClassValues = { [name: string]: DaggerEnumClassValue } + +export class DaggerEnumClassValue + extends Locatable + implements DaggerEnumBaseValue +{ + public name: string + public value: string + public description: string + public deprecated?: string + + private symbol: ts.Symbol + + constructor( + private readonly node: ts.PropertyDeclaration, + private readonly ast: AST, + ) { + super(node) + this.name = this.node.name.getText() + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + + const initializer = this.node.initializer + if (!initializer) { + throw new Error("Dagger enum value has no value set") + } + + this.value = this.ast.resolveParameterDefaultValue(initializer) + } + + toJSON() { + return { + name: this.name, + value: this.value, + description: this.description, + deprecated: this.deprecated, + } + } +} + +export class DaggerEnumClass extends Locatable implements DaggerEnumBase { + public name: string + public description: string + public values: DaggerEnumClassValues = {} + + private symbol: ts.Symbol + + constructor( + private readonly node: ts.ClassDeclaration, + private readonly ast: AST, + ) { + super(node) + + if (!this.node.name) { + throw new IntrospectionError( + `could not resolve name of enum at ${AST.getNodePosition(node)}.`, + ) + } + this.name = this.node.name.getText() + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + this.description = this.ast.getDocFromSymbol(this.symbol) + + const properties = this.node.members + for (const property of properties) { + if (ts.isPropertyDeclaration(property)) { + const value = new DaggerEnumClassValue(property, this.ast) + + this.values[value.name] = value + } + } + } + + toJSON() { + return { + name: this.name, + description: this.description, + values: this.values, + } + } +} diff --git a/library/src/module/introspector/dagger_module/function.ts b/library/src/module/introspector/dagger_module/function.ts new file mode 100644 index 0000000..1d7d881 --- /dev/null +++ b/library/src/module/introspector/dagger_module/function.ts @@ -0,0 +1,159 @@ +import ts from "typescript" + +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { FunctionOptions } from "../../registry.js" +import { TypeDef } from "../typedef.js" +import { + AST, + isTypeDefResolved, + resolveTypeDef, +} from "../typescript_module/index.js" +import { DaggerArgument, DaggerArguments } from "./argument.js" +import { + CHECK_DECORATOR, + FUNCTION_DECORATOR, + GENERATOR_DECORATOR, + UP_DECORATOR, +} from "./decorator.js" +import { Locatable } from "./locatable.js" +import { References } from "./reference.js" + +export type DaggerFunctions = { [name: string]: DaggerFunction } + +export class DaggerFunction extends Locatable { + public name: string + public description: string + public deprecated?: string + private _returnTypeRef?: string + public returnType?: TypeDef + public arguments: DaggerArguments = {} + public alias: string | undefined + public cache: string | undefined + public isCheck: boolean = false + public isGenerator: boolean = false + public isUp: boolean = false + + private signature: ts.Signature + private symbol: ts.Symbol + + constructor( + private readonly node: ts.MethodDeclaration, + private readonly ast: AST, + ) { + super(node) + + this.symbol = this.ast.getSymbolOrThrow(node.name) + this.signature = this.ast.getSignatureFromFunctionOrThrow(node) + this.name = this.node.name.getText() + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + + const functionArguments = this.ast.getDecoratorArgument< + FunctionOptions | string + >(this.node, FUNCTION_DECORATOR, "object") + if (functionArguments) { + if (typeof functionArguments === "string") { + // previously only a single arg was accepted for alias, so if there's just + // a string we intrepret it that way for backward compatibility + this.alias = functionArguments + } else { + this.alias = functionArguments.alias + this.cache = functionArguments.cache + } + } + + // Parse @check decorator + if (this.ast.isNodeDecoratedWith(this.node, CHECK_DECORATOR)) { + this.isCheck = true + } + + // Parse @generate decorator + if (this.ast.isNodeDecoratedWith(this.node, GENERATOR_DECORATOR)) { + this.isGenerator = true + } + + // Parse @up decorator + if (this.ast.isNodeDecoratedWith(this.node, UP_DECORATOR)) { + this.isUp = true + } + + for (const parameter of this.node.parameters) { + this.arguments[parameter.name.getText()] = new DaggerArgument( + parameter, + this.ast, + ) + } + this.returnType = this.getReturnType() + } + + private getReturnType(): TypeDef | undefined { + const type = this.signature.getReturnType() + + const typedef = this.ast.tsTypeToTypeDef(this.node, type) + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._returnTypeRef = this.ast.typeToStringType(type) + } + + return typedef + } + + public getArgsOrder(): string[] { + return Object.keys(this.arguments) + } + + public getReferences(): string[] { + const references: string[] = [] + + if ( + this._returnTypeRef && + (this.returnType === undefined || !isTypeDefResolved(this.returnType)) + ) { + references.push(this._returnTypeRef) + } + + for (const argument of Object.values(this.arguments)) { + const reference = argument.getReference() + if (reference) { + references.push(reference) + } + } + + return references + } + + public propagateReferences(references: References) { + for (const argument of Object.values(this.arguments)) { + argument.propagateReferences(references) + } + + if (!this._returnTypeRef) { + return + } + + if (this.returnType && isTypeDefResolved(this.returnType)) { + return + } + + const typeDef = references[this._returnTypeRef] + if (!typeDef) { + throw new IntrospectionError( + `could not find type reference for ${this._returnTypeRef} at ${AST.getNodePosition(this.node)}.`, + ) + } + + this.returnType = resolveTypeDef(this.returnType, typeDef) + } + + public toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + alias: this.alias, + arguments: this.arguments, + returnType: this.returnType, + } + } +} diff --git a/library/src/module/introspector/dagger_module/index.ts b/library/src/module/introspector/dagger_module/index.ts new file mode 100644 index 0000000..1316fbb --- /dev/null +++ b/library/src/module/introspector/dagger_module/index.ts @@ -0,0 +1,14 @@ +export * from "./constructor.js" +export * from "./argument.js" +export * from "./enum.js" +export * from "./enumBase.js" +export * from "./enumClass.js" +export * from "./function.js" +export * from "./module.js" +export * from "./object.js" +export * from "./objectBase.js" +export * from "./reference.js" +export * from "./typeObject.js" +export * from "./decorator.js" +export * from "./locatable.js" +export * from "./interface.js" diff --git a/library/src/module/introspector/dagger_module/interface.ts b/library/src/module/introspector/dagger_module/interface.ts new file mode 100644 index 0000000..295094a --- /dev/null +++ b/library/src/module/introspector/dagger_module/interface.ts @@ -0,0 +1,79 @@ +import ts from "typescript" + +import { IntrospectionError } from "../../../common/errors/index.js" +import { AST } from "../typescript_module/index.js" +import { + DaggerInterfaceFunction, + DaggerInterfaceFunctions, +} from "./interfaceFunction.js" +import { Locatable } from "./locatable.js" +import { References } from "./reference.js" + +export type DaggerInterfaces = { [name: string]: DaggerInterface } + +export class DaggerInterface extends Locatable { + public name: string + public description: string + public functions: DaggerInterfaceFunctions = {} + private symbol: ts.Symbol + + constructor( + private readonly node: ts.InterfaceDeclaration, + private readonly ast: AST, + ) { + super(node) + + if (!this.node.name) { + throw new IntrospectionError( + `could not resolve name of interface at ${AST.getNodePosition(node)}`, + ) + } + this.name = this.node.name.getText() + + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + this.description = this.ast.getDocFromSymbol(this.symbol) + + for (const member of this.node.members) { + if (!ts.isPropertySignature(member) && !ts.isMethodSignature(member)) { + continue + } + + // Check if it's a function + if ( + (member.type && ts.isFunctionTypeNode(member.type)) || + ts.isMethodSignature(member) + ) { + const daggerInterfaceFunction = new DaggerInterfaceFunction( + member, + this.ast, + ) + this.functions[daggerInterfaceFunction.name] = daggerInterfaceFunction + continue + } + + // TODO(TomChv): Add support for fields + } + } + + public getReferences(): string[] { + const references: string[] = [] + for (const fn of Object.values(this.functions)) { + references.push(...fn.getReferences()) + } + return references.filter((v, i, arr) => arr.indexOf(v) === i) + } + + public propagateReferences(references: References): void { + for (const fn of Object.values(this.functions)) { + fn.propagateReferences(references) + } + } + + public toJSON() { + return { + name: this.name, + description: this.description, + functions: this.functions, + } + } +} diff --git a/library/src/module/introspector/dagger_module/interfaceFunction.ts b/library/src/module/introspector/dagger_module/interfaceFunction.ts new file mode 100644 index 0000000..c4bdcdd --- /dev/null +++ b/library/src/module/introspector/dagger_module/interfaceFunction.ts @@ -0,0 +1,133 @@ +import ts from "typescript" + +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { TypeDef } from "../typedef.js" +import { + AST, + isTypeDefResolved, + resolveTypeDef, +} from "../typescript_module/index.js" +import { DaggerArgument, DaggerArguments } from "./argument.js" +import { Locatable } from "./locatable.js" +import { References } from "./reference.js" + +export type DaggerInterfaceFunctions = { + [name: string]: DaggerInterfaceFunction +} + +export class DaggerInterfaceFunction extends Locatable { + public name: string + public description: string + public deprecated?: string + private _returnTypeRef?: string + public returnType?: TypeDef + public arguments: DaggerArguments = {} + private symbol: ts.Symbol + private signature?: ts.Signature + + // Just placeholders to be compatible with `Method` during registration + public alias: undefined + public cache: undefined + + constructor( + private readonly node: ts.PropertySignature | ts.MethodSignature, + private readonly ast: AST, + ) { + super(node) + + if (!this.node.name) { + throw new IntrospectionError( + `could not resolve name of interface function at ${AST.getNodePosition(node)}`, + ) + } + this.name = this.node.name.getText() + + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + + // If it's a method signature, we can directly use it to get the signature props + // If it's a property kind signature, we need to get the signature from the type + // Examle: + // interface Foo { + // bar(): void // <- this is a method signature + // baz: () => string // <- this is a property kind signature + // } + const nodeType: ts.SignatureDeclaration = + this.node.type && ts.isFunctionTypeNode(this.node.type) + ? (this.node.type as ts.FunctionTypeNode) + : (this.node as ts.MethodSignature) + + const signature = this.ast.getSignatureFromFunctionOrThrow(nodeType) + + for (const parameter of nodeType.parameters) { + this.arguments[parameter.name.getText()] = new DaggerArgument( + parameter, + this.ast, + ) + } + + const signatureReturnType = signature.getReturnType() + const typedef = this.ast.tsTypeToTypeDef(this.node, signatureReturnType) + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._returnTypeRef = this.ast.typeToStringType(signatureReturnType) + } + this.returnType = typedef + } + + public getReferences(): string[] { + const references: string[] = [] + + if ( + this._returnTypeRef && + (this.returnType === undefined || !isTypeDefResolved(this.returnType)) + ) { + references.push(this._returnTypeRef) + } + + for (const argument of Object.values(this.arguments)) { + const reference = argument.getReference() + + if (reference) { + references.push(reference) + } + } + + return references + } + + public propagateReferences(references: References) { + for (const argument of Object.values(this.arguments)) { + argument.propagateReferences(references) + } + + if (!this._returnTypeRef) { + return + } + + if (this.returnType && isTypeDefResolved(this.returnType)) { + return + } + + const typeDef = references[this._returnTypeRef] + if (!typeDef) { + throw new IntrospectionError( + `could not find type reference for ${this._returnTypeRef} at ${AST.getNodePosition(this.node)}.`, + ) + } + + this.returnType = resolveTypeDef(this.returnType, typeDef) + } + + public toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + arguments: this.arguments, + returnType: this.returnType, + } + } +} diff --git a/library/src/module/introspector/dagger_module/locatable.ts b/library/src/module/introspector/dagger_module/locatable.ts new file mode 100644 index 0000000..88db0b4 --- /dev/null +++ b/library/src/module/introspector/dagger_module/locatable.ts @@ -0,0 +1,15 @@ +import ts from "typescript" + +import { AST, Location } from "../typescript_module/index.js" + +/** + * Locatable is a base class that any Dagger object can extend from to + * provide a location method. + */ +export class Locatable { + constructor(private readonly __node: ts.Node) {} + + getLocation(): Location { + return AST.getNodeLocation(this.__node) + } +} diff --git a/library/src/module/introspector/dagger_module/module.ts b/library/src/module/introspector/dagger_module/module.ts new file mode 100644 index 0000000..5df83fd --- /dev/null +++ b/library/src/module/introspector/dagger_module/module.ts @@ -0,0 +1,410 @@ +import Module from "node:module" +import ts from "typescript" + +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { AST, ResolvedNodeWithSymbol } from "../typescript_module/index.js" +import { ENUM_DECORATOR, OBJECT_DECORATOR } from "./decorator.js" +import { DaggerEnum } from "./enum.js" +import { DaggerEnumsBase } from "./enumBase.js" +import { DaggerEnumClass } from "./enumClass.js" +import { DaggerInterface, DaggerInterfaces } from "./interface.js" +import { DaggerObject } from "./object.js" +import { DaggerObjectsBase } from "./objectBase.js" +import { References } from "./reference.js" +import { DaggerTypeObject } from "./typeObject.js" + +/** + * DaggerModule represents a TypeScript module with a set of files + * with Dagger object conversion and notation. + * + * It starts from the module entrypoint (the class named the same as the module) and + * then recursively resolve every references to other declared identifiers. + * After resolution, it propagates all the references to the modules declarations + * and finally it generates the final Dagger module representation. + */ +export class DaggerModule { + /** + * An object is either a decorated class or a type alias object. + * Type alias objects cannot be decorated so they are resolved if referenced in the module. + * + * @example + * ```ts + * @object() + * export class MyObject { + * @func() + * public name: string + * } + * ``` + * + * @example + * ```ts + * export type Example = { + * name: string + * } + * ``` + */ + public objects: DaggerObjectsBase = {} + + /** + * An enum is typically a native TypeScript enum declared with the `enum` keyword. + * Decorated classes using `@enumType()` are still supported for backward compatibility. + * + * @example + * ```ts + * export enum Example { + * A = "a", + * B = "b", + * } + * ``` + */ + public enums: DaggerEnumsBase = {} + + /** + * An interface is declared using the `interface` keyword. + * + * @example + * ```ts + * export interface Example { + * foo: (): string + * asyncFoo: (): Promise + * } + * ``` + */ + public interfaces: DaggerInterfaces = {} + + public description: string | undefined + + private references: References = { + // Float is a special case, it's an alias of number but it serves to declare a float type + // in the Dagger API. + // So we auto register it because it will be detected as a referenced type by the introspector. + float: { kind: TypeDefKind.FloatKind }, + } + + constructor( + public name: string, + private userModule: Module[], + private ast: AST, + ) { + const classObjects = this.findClasses() + for (const classObject of classObjects) { + // This only applies to cloud. If this is the true main object, it is correct + // if this is a blueprint, the description will not matter in any situation + const mainFileContent = classObject.file.getFullText() + this.description = this.getDescription(mainFileContent) + + const daggerObject = new DaggerObject(classObject.node, this.ast) + const objectName = classObject.node.name?.getText() || this.name + + this.objects[objectName] = daggerObject + this.references[objectName] = { + kind: TypeDefKind.ObjectKind, + name: objectName, + } + + this.resolveReferences(daggerObject.getReferences()) + this.propagateReferences() + } + } + + /** + * Find the reference of the module and register it to the module references. + * + * To do so, we check the user module to find a corresponding symbol (name) for each of + * typedef we support. + * This only applies for: + * - classes + * - enums + * - scalars + * - interfaces + * + * If the reference is an object, a class or an interface, recursively find the references of the object. + * + * *Note*: If a class is referenced but not exported and not decorated with `@object()`, we throw an error + * because we aim to be explicit. (TomChv: Should we change this behaviour?) + */ + private resolveReferences(references: string[]) { + if (references.length === 0) { + return + } + + for (const reference of references) { + // If we already know that reference, we don't need to explore it again. + if (this.references[reference]) { + continue + } + + const classRef = this.ast.findResolvedNodeByName( + reference, + ts.SyntaxKind.ClassDeclaration, + ) + if (classRef) { + if (this.ast.isGeneratedClientFile(classRef.file.fileName)) { + this.references[reference] = { + kind: TypeDefKind.ObjectKind, + name: reference, + } + continue + } + + if (this.ast.isNodeDecoratedWith(classRef.node, OBJECT_DECORATOR)) { + const daggerObject = new DaggerObject(classRef.node, this.ast) + this.objects[daggerObject.name] = daggerObject + this.references[daggerObject.name] = { + kind: TypeDefKind.ObjectKind, + name: daggerObject.name, + } + + this.resolveReferences(daggerObject.getReferences()) + + continue + } + + if (this.ast.isNodeDecoratedWith(classRef.node, ENUM_DECORATOR)) { + const daggerEnum = new DaggerEnumClass(classRef.node, this.ast) + this.enums[daggerEnum.name] = daggerEnum + this.references[daggerEnum.name] = { + kind: TypeDefKind.EnumKind, + name: daggerEnum.name, + } + + // There should be no references in enums. + continue + } + + throw new IntrospectionError( + `class ${reference} in ${AST.getNodePosition(classRef.node)} is used by the module but not exposed with a dagger decorator.`, + ) + } + + const enumRef = this.ast.findResolvedNodeByName( + reference, + ts.SyntaxKind.EnumDeclaration, + ) + if (enumRef) { + if (this.ast.isGeneratedClientFile(enumRef.file.fileName)) { + this.references[reference] = { + kind: TypeDefKind.EnumKind, + name: reference, + } + continue + } + + // Typescript enum declaration cannot be decorated, so we don't check it. + const daggerEnum = new DaggerEnum(enumRef.node, this.ast) + this.enums[daggerEnum.name] = daggerEnum + this.references[daggerEnum.name] = { + kind: TypeDefKind.EnumKind, + name: daggerEnum.name, + } + + // There should be no reference in enums. + continue + } + + const interfaceRef = this.ast.findResolvedNodeByName( + reference, + ts.SyntaxKind.InterfaceDeclaration, + ) + if (interfaceRef) { + const daggerInterface = new DaggerInterface(interfaceRef.node, this.ast) + this.interfaces[daggerInterface.name] = daggerInterface + this.references[daggerInterface.name] = { + kind: TypeDefKind.InterfaceKind, + name: daggerInterface.name, + } + this.resolveReferences(daggerInterface.getReferences()) + continue + } + + const typeAliasRef = this.ast.findResolvedNodeByName( + reference, + ts.SyntaxKind.TypeAliasDeclaration, + ) + if (typeAliasRef) { + // The resolution is to big so we split it in a sub function. + this.resolveTypeAlias(reference, typeAliasRef) + + continue + } + + // Handle primitives here + if (reference === "String") { + throw new IntrospectionError( + `Use of primitive 'String' type detected, please use 'string' instead.`, + ) + } + + if (reference === "Boolean") { + throw new IntrospectionError( + `Use of primitive 'Boolean' type detected, please use 'boolean' instead.`, + ) + } + + if (reference === "Number") { + throw new IntrospectionError( + `Use of primitive 'Number' type detected, please use 'number' instead.`, + ) + } + + throw new IntrospectionError( + `could not resolve type reference for ${reference}.`, + ) + } + } + + /** + * Resolve type alias to the corresponding TypeDef. + * A type might refer to anything typeable in TypeScript but right now we supports: + * - `type Example = string` + * - `type Example = { prop: string}` + * - `type Example = number` + * - `type Example = boolean` + * - `type Example = void` + * + * If the reference is an object, we recursively resolve its references. + * If the type cannot be resolved or is not supported, we throw an error. + */ + private resolveTypeAlias( + reference: string, + typeAlias: ResolvedNodeWithSymbol, + ) { + const type = this.ast.getTypeFromTypeAlias(typeAlias.node) + + if (type.flags & ts.TypeFlags.String) { + this.references[reference] = { kind: TypeDefKind.StringKind } + + return + } + + if (type.flags & ts.TypeFlags.Number) { + this.references[reference] = { kind: TypeDefKind.IntegerKind } + + return + } + + if (type.flags & ts.TypeFlags.Boolean) { + this.references[reference] = { kind: TypeDefKind.BooleanKind } + + return + } + + if (type.flags & ts.TypeFlags.Void) { + this.references[reference] = { kind: TypeDefKind.VoidKind } + + return + } + + // Scalar are defined with string intersection such as `type MyScalar = string & { __MyScalar: never }` + if ( + type.flags & ts.TypeFlags.Intersection || + type.flags & ts.TypeFlags.Union + ) { + this.references[reference] = { + kind: TypeDefKind.ScalarKind, + name: reference, + } + + return + } + + if (type.flags & ts.TypeFlags.Object) { + if (this.ast.isGeneratedClientFile(typeAlias.file.fileName)) { + this.references[reference] = { + kind: TypeDefKind.ObjectKind, + name: reference, + } + + return + } + + const daggerObject = new DaggerTypeObject(typeAlias.node, this.ast) + this.objects[daggerObject.name] = daggerObject + this.references[daggerObject.name] = { + kind: TypeDefKind.ObjectKind, + name: daggerObject.name, + } + + this.resolveReferences(daggerObject.getReferences()) + + return + } + + throw new IntrospectionError( + `could not resolve type reference for ${reference} at ${AST.getNodePosition(typeAlias.node)}`, + ) + } + + /** + * Find the classes in the AST. Returns only our main class if it exists + */ + private findClasses(): ResolvedNodeWithSymbol[] { + const allClassDeclarations = this.ast.findAllDeclarations( + ts.SyntaxKind.ClassDeclaration, + ) + + const allClasses: ResolvedNodeWithSymbol[] = + [] + for (const classDecl of allClassDeclarations) { + const convertedDecl = + classDecl as ResolvedNodeWithSymbol + + // Check if the class matches this.name and return only that if so + if ( + convertedDecl.node.name && + convertedDecl.node.name.getText() === this.name + ) { + return [convertedDecl] + } + + // or we return all classes decorated with @object + if (this.ast.isNodeDecoratedWith(classDecl.node, OBJECT_DECORATOR)) { + allClasses.push(convertedDecl) + } + } + return allClasses + } + + /** + * Recursively propagate references to all objects properties and functions. + */ + private propagateReferences() { + for (const object of Object.values(this.objects)) { + object.propagateReferences(this.references) + } + + for (const interface_ of Object.values(this.interfaces)) { + interface_.propagateReferences(this.references) + } + } + + /** + * Get the top level comment of the file that contains the module entrypoint. + */ + private getDescription(sourceFileContent: string): string | undefined { + const regex = /^(?!.*import)[\s]*\/\*\*([\s\S]*?)\*\// + const match = sourceFileContent.match(regex) + + if (!match) { + return undefined + } + + const comment = match[1] + .split("\n") + .map((line) => line.replace(/^\s*\*\s?/, "")) + .join("\n") + + return comment.trim() + } + + toJSON() { + return { + name: this.name, + description: this.description, + objects: this.objects, + enums: this.enums, + interfaces: this.interfaces, + } + } +} diff --git a/library/src/module/introspector/dagger_module/object.ts b/library/src/module/introspector/dagger_module/object.ts new file mode 100644 index 0000000..5f7d8de --- /dev/null +++ b/library/src/module/introspector/dagger_module/object.ts @@ -0,0 +1,154 @@ +import ts from "typescript" + +import { IntrospectionError } from "../../../common/errors/index.js" +import { AST, Location } from "../typescript_module/index.js" +import { DaggerConstructor } from "./constructor.js" +import { FUNCTION_DECORATOR, OBJECT_DECORATOR } from "./decorator.js" +import { DaggerFunction, DaggerFunctions } from "./function.js" +import { Locatable } from "./locatable.js" +import { DaggerObjectBase } from "./objectBase.js" +import { DaggerProperties, DaggerProperty } from "./property.js" +import { References } from "./reference.js" + +/** + * Represents an object defined using the `class` keyword. + * + * The class may contains methods and fields, that may or may not be exposed to the Dagger API. + * + * @example + * ```ts + * type MyObject = { + * name: string + * age: number + * } + * ``` + */ +export class DaggerObject extends Locatable implements DaggerObjectBase { + public name: string + public description: string + public deprecated?: string + public _constructor: DaggerConstructor | undefined = undefined + public methods: DaggerFunctions = {} + public properties: DaggerProperties = {} + public isExported: boolean = false + public isDefaultExport: boolean = false + + private symbol: ts.Symbol + + kind(): "class" | "object" { + return "class" + } + + constructor( + private readonly node: ts.ClassDeclaration, + private readonly ast: AST, + ) { + super(node) + + if (!this.node.name) { + throw new IntrospectionError( + `could not resolve name of class at ${AST.getNodePosition(node)}.`, + ) + } + this.name = this.node.name.getText() + + if (!this.ast.isNodeDecoratedWith(node, OBJECT_DECORATOR)) { + throw new IntrospectionError( + `class ${this.name} at ${AST.getNodePosition(node)} is used by the module but not exposed with a dagger decorator.`, + ) + } + + const modifiers = ts.getCombinedModifierFlags(this.node) + this.isExported = (modifiers & ts.ModifierFlags.Export) !== 0 + // `export default class Foo` sets both Export and Default; the entrypoint + // must import it as a default import rather than a named one. + this.isDefaultExport = (modifiers & ts.ModifierFlags.Default) !== 0 + + if (!this.isExported) { + console.warn( + `missing export in class ${this.name} at ${AST.getNodePosition(node)} but it's used by the module.`, + ) + } + + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + + for (const member of this.node.members) { + if (ts.isPropertyDeclaration(member)) { + const property = new DaggerProperty(member, this.ast) + this.properties[property.alias ?? property.name] = property + + continue + } + + if (ts.isConstructorDeclaration(member)) { + this._constructor = new DaggerConstructor(member, this.ast) + + continue + } + + if ( + ts.isMethodDeclaration(member) && + this.ast.isNodeDecoratedWith(member, FUNCTION_DECORATOR) + ) { + const daggerFunction = new DaggerFunction(member, this.ast) + this.methods[daggerFunction.alias ?? daggerFunction.name] = + daggerFunction + + continue + } + } + } + + public getLocation(): Location { + return AST.getNodeLocation(this.node) + } + + public getReferences(): string[] { + const references: string[] = [] + + if (this._constructor) { + references.push(...this._constructor.getReferences()) + } + + for (const property of Object.values(this.properties)) { + const ref = property.getReference() + if (ref) { + references.push(ref) + } + } + + for (const fn of Object.values(this.methods)) { + references.push(...fn.getReferences()) + } + + return references.filter((v, i, arr) => arr.indexOf(v) === i) + } + + public propagateReferences(references: References): void { + if (this._constructor) { + this._constructor.propagateReferences(references) + } + + for (const property of Object.values(this.properties)) { + property.propagateReferences(references) + } + + for (const fn of Object.values(this.methods)) { + fn.propagateReferences(references) + } + } + + public toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + constructor: this._constructor, + methods: this.methods, + properties: this.properties, + } + } +} diff --git a/library/src/module/introspector/dagger_module/objectBase.ts b/library/src/module/introspector/dagger_module/objectBase.ts new file mode 100644 index 0000000..c9a71c4 --- /dev/null +++ b/library/src/module/introspector/dagger_module/objectBase.ts @@ -0,0 +1,36 @@ +import { TypeDefKind } from "../../../api/client.gen.js" +import { TypeDef } from "../typedef.js" +import { DaggerConstructor } from "./constructor.js" +import { DaggerFunctions } from "./function.js" +import { Locatable } from "./locatable.js" +import { References } from "./reference.js" + +export interface DaggerObjectPropertyBase extends Locatable { + name: string + description: string + deprecated?: string + alias?: string + isExposed: boolean + type?: TypeDef + + propagateReferences(references: References): void +} + +export type DaggerObjectPropertiesBase = { + [name: string]: DaggerObjectPropertyBase +} + +export interface DaggerObjectBase extends Locatable { + name: string + description: string + deprecated?: string + _constructor: DaggerConstructor | undefined + methods: DaggerFunctions + properties: DaggerObjectPropertiesBase + + kind(): "class" | "object" + + propagateReferences(references: References): void +} + +export type DaggerObjectsBase = { [name: string]: DaggerObjectBase } diff --git a/library/src/module/introspector/dagger_module/property.ts b/library/src/module/introspector/dagger_module/property.ts new file mode 100644 index 0000000..e5934f5 --- /dev/null +++ b/library/src/module/introspector/dagger_module/property.ts @@ -0,0 +1,130 @@ +import ts from "typescript" + +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { TypeDef } from "../typedef.js" +import { + AST, + isTypeDefResolved, + resolveTypeDef, +} from "../typescript_module/index.js" +import { FIELD_DECORATOR, FUNCTION_DECORATOR } from "./decorator.js" +import { Locatable } from "./locatable.js" +import { DaggerObjectPropertyBase } from "./objectBase.js" +import { References } from "./reference.js" + +export type DaggerProperties = { [name: string]: DaggerProperty } + +export class DaggerProperty + extends Locatable + implements DaggerObjectPropertyBase +{ + public name: string + public description: string + public deprecated?: string + public alias: string | undefined + public isExposed: boolean + + private symbol: ts.Symbol + private _typeRef?: string + public type?: TypeDef + + constructor( + private readonly node: ts.PropertyDeclaration, + private readonly ast: AST, + ) { + super(node) + + if (!this.node.name) { + throw new IntrospectionError( + `could not resolve name of class at ${AST.getNodePosition(node)}.`, + ) + } + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + this.name = this.node.name.getText() + + this.isExposed = + this.ast.isNodeDecoratedWith(this.node, FUNCTION_DECORATOR) || + this.ast.isNodeDecoratedWith(this.node, FIELD_DECORATOR) + + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + this.alias = this.getAlias() + this.type = this.getType() + } + + private getAlias(): string | undefined { + let alias = this.ast.getDecoratorArgument( + this.node, + FUNCTION_DECORATOR, + "string", + ) + + if (alias) { + return JSON.parse(alias.replace(/'/g, '"')) + } + + alias = this.ast.getDecoratorArgument( + this.node, + FIELD_DECORATOR, + "string", + ) + + if (alias) { + return JSON.parse(alias.replace(/'/g, '"')) + } + } + + private getType(): TypeDef | undefined { + const type = this.ast.checker.getTypeAtLocation(this.node) + + const typedef = this.ast.tsTypeToTypeDef(this.node, type) + if (typedef === undefined || !isTypeDefResolved(typedef)) { + this._typeRef = this.ast.typeToStringType(type) + } + + return typedef + } + + public getReference(): string | undefined { + if ( + this._typeRef && + (this.type === undefined || !isTypeDefResolved(this.type)) + ) { + return this._typeRef + } + + return undefined + } + + public propagateReferences(references: References): void { + if (!this._typeRef) { + return + } + + if (this.type && isTypeDefResolved(this.type)) { + return + } + + const typeDef = references[this._typeRef] + if (!typeDef) { + throw new IntrospectionError( + `could not find type reference for ${this._typeRef} at ${AST.getNodePosition(this.node)}.`, + ) + } + + this.type = resolveTypeDef(this.type, typeDef) + } + + public toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + alias: this.alias, + type: this.type, + isExposed: this.isExposed, + } + } +} diff --git a/library/src/module/introspector/dagger_module/reference.ts b/library/src/module/introspector/dagger_module/reference.ts new file mode 100644 index 0000000..c0b578b --- /dev/null +++ b/library/src/module/introspector/dagger_module/reference.ts @@ -0,0 +1,60 @@ +import { TypeDefKind } from "../../../api/client.gen.js" +import { TypeDef } from "../typedef.js" + +export type References = { [name: string]: TypeDef } + +export type ReferencableType = + | TypeDef + | TypeDef + | TypeDef + | TypeDef + | TypeDef + +export function isKindArray( + type: TypeDef, +): type is TypeDef { + return type.kind === TypeDefKind.ListKind +} + +export function isKindObject( + type: TypeDef, +): type is TypeDef { + return type.kind === TypeDefKind.ObjectKind +} + +export function isKindEnum( + type: TypeDef, +): type is TypeDef { + return type.kind === TypeDefKind.EnumKind +} + +export function isKindScalar( + type: TypeDef, +): type is TypeDef { + return type.kind === TypeDefKind.ScalarKind +} + +export function isReferencableTypeDef(type: TypeDef): boolean { + switch (type.kind) { + case TypeDefKind.ObjectKind: + return true + case TypeDefKind.EnumKind: + return true + case TypeDefKind.ScalarKind: + return true + case TypeDefKind.ListKind: + return isReferencableTypeDef(getTypeDefArrayBaseType(type)) + default: + return false + } +} + +export function getTypeDefArrayBaseType( + type: TypeDef, +): TypeDef { + if (isKindArray(type)) { + return getTypeDefArrayBaseType(type.typeDef) + } + + return type +} diff --git a/library/src/module/introspector/dagger_module/typeObject.ts b/library/src/module/introspector/dagger_module/typeObject.ts new file mode 100644 index 0000000..56a3549 --- /dev/null +++ b/library/src/module/introspector/dagger_module/typeObject.ts @@ -0,0 +1,111 @@ +import ts from "typescript" + +import { IntrospectionError } from "../../../common/errors/index.js" +import { AST, Location } from "../typescript_module/index.js" +import { Locatable } from "./locatable.js" +import { DaggerObjectBase } from "./objectBase.js" +import { References } from "./reference.js" +import { + DaggerObjectTypeProperties, + DaggerObjectTypeProperty, +} from "./typeObjectProperty.js" + +/** + * Represents an object defined using the `type` keyword. + * + * Type object can only contains fields, no methods are allowed. + * All fields are public and exposed to the Dagger API. + * + * @example + * ```ts + * @object() + * export class MyObject { + * @func() + * public name: string + * + * @func() + * async getName(): Promise { + * return this.name + * } + * } + * ``` + */ +export class DaggerTypeObject extends Locatable implements DaggerObjectBase { + public name: string + public description: string + public deprecated?: string + public _constructor = undefined + public methods = {} + public properties: DaggerObjectTypeProperties = {} + + private symbol: ts.Symbol + + kind(): "class" | "object" { + return "object" + } + + constructor( + private readonly node: ts.TypeAliasDeclaration, + private readonly ast: AST, + ) { + super(node) + + if (!this.node.name) { + throw new IntrospectionError( + `could not resolve name of enum at ${AST.getNodePosition(node)}.`, + ) + } + this.name = this.node.name.getText() + this.symbol = this.ast.getSymbolOrThrow(this.node.name) + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + + const type = this.ast.getTypeFromTypeAlias(this.node) + + if (type.flags & ts.TypeFlags.Object) { + const objectType = type as ts.ObjectType + const properties = objectType.getProperties() + for (const property of properties) { + const daggerProperty = new DaggerObjectTypeProperty( + this.node, + property, + this.ast, + ) + this.properties[daggerProperty.name] = daggerProperty + } + } + } + + public getLocation(): Location { + return AST.getNodeLocation(this.node) + } + + public getReferences(): string[] { + const references: string[] = [] + + for (const property of Object.values(this.properties)) { + const ref = property.getReference() + if (ref) { + references.push(ref) + } + } + + return references.filter((v, i, arr) => arr.indexOf(v) === i) + } + + public propagateReferences(references: References): void { + for (const property of Object.values(this.properties)) { + property.propagateReferences(references) + } + } + + toJSON() { + return { + name: this.name, + description: this.description, + properties: this.properties, + deprecated: this.deprecated, + } + } +} diff --git a/library/src/module/introspector/dagger_module/typeObjectProperty.ts b/library/src/module/introspector/dagger_module/typeObjectProperty.ts new file mode 100644 index 0000000..9db138f --- /dev/null +++ b/library/src/module/introspector/dagger_module/typeObjectProperty.ts @@ -0,0 +1,94 @@ +import ts from "typescript" + +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { TypeDef } from "../typedef.js" +import { + AST, + isTypeDefResolved, + resolveTypeDef, +} from "../typescript_module/index.js" +import { Locatable } from "./locatable.js" +import { DaggerObjectPropertyBase } from "./objectBase.js" +import { References } from "./reference.js" + +export type DaggerObjectTypeProperties = { + [name: string]: DaggerObjectTypeProperty +} + +export class DaggerObjectTypeProperty + extends Locatable + implements DaggerObjectPropertyBase +{ + public name: string + public description: string + public deprecated?: string + public alias = undefined + public isExposed: boolean = true + + private _typeRef?: string + public type?: TypeDef + + constructor( + private readonly node: ts.TypeAliasDeclaration, + private readonly symbol: ts.Symbol, + private readonly ast: AST, + ) { + super(node) + + this.name = symbol.name + const { description, deprecated } = this.ast.getSymbolDoc(this.symbol) + this.description = description + this.deprecated = deprecated + + const type = this.ast.checker.getTypeOfSymbolAtLocation( + this.symbol, + this.node, + ) + this.type = this.ast.tsTypeToTypeDef(this.node, type) + if (this.type === undefined || !isTypeDefResolved(this.type)) { + this._typeRef = this.ast.typeToStringType(type) + } + } + + public getReference(): string | undefined { + if ( + this._typeRef && + (this.type === undefined || !isTypeDefResolved(this.type)) + ) { + return this._typeRef + } + + return undefined + } + + public propagateReferences(references: References): void { + if (!this._typeRef) { + return + } + + if (this.type && isTypeDefResolved(this.type)) { + return + } + + const typeDef = references[this._typeRef] + if (!typeDef) { + throw new IntrospectionError( + `could not find type reference for ${this._typeRef}.`, + ) + } + + this.type = resolveTypeDef(this.type, typeDef) + } + + public toJSON() { + return { + name: this.name, + description: this.description, + deprecated: this.deprecated, + alias: this.alias, + type: this.type, + isExposed: this.isExposed, + } + } +} diff --git a/library/src/module/introspector/index.ts b/library/src/module/introspector/index.ts new file mode 100644 index 0000000..0828c1c --- /dev/null +++ b/library/src/module/introspector/index.ts @@ -0,0 +1,35 @@ +import Module from "node:module" + +import { IntrospectionError } from "../../common/errors/index.js" +import { load } from "../entrypoint/load.js" +import { convertToPascalCase } from "./case_convertor.js" +import { DaggerModule } from "./dagger_module/index.js" +import { AST } from "./typescript_module/index.js" + +export async function scan( + files: string[], + moduleName = "", + loadModule = true, + // generatedClientFiles is the explicit set of SDK-generated binding files + // (client.gen.ts and each .gen.ts). When provided, the AST uses it to + // tell generated code from user source instead of guessing by filename, + // which would misclassify a user file that happens to end in `.gen.ts`. + generatedClientFiles: string[] = [], +) { + if (files.length === 0) { + throw new IntrospectionError("no files to introspect found") + } + + const formattedModuleName = convertToPascalCase(moduleName) + + // Interpret the given typescript source files. + let userModule: Module[] = [] + if (loadModule) { + userModule = await load(files) + } + const ast = new AST(files, userModule, generatedClientFiles) + + const module = new DaggerModule(formattedModuleName, userModule, ast) + + return module +} diff --git a/library/src/module/introspector/introspection_json.ts b/library/src/module/introspector/introspection_json.ts new file mode 100644 index 0000000..2c54cae --- /dev/null +++ b/library/src/module/introspector/introspection_json.ts @@ -0,0 +1,689 @@ +import { TypeDefKind } from "../../api/client.gen.js" +import { DaggerArgument } from "./dagger_module/argument.js" +import { DaggerConstructor } from "./dagger_module/constructor.js" +import { DaggerEnumBase } from "./dagger_module/enumBase.js" +import { DaggerFunction } from "./dagger_module/function.js" +import { DaggerInterface } from "./dagger_module/interface.js" +import { DaggerInterfaceFunction } from "./dagger_module/interfaceFunction.js" +import { DaggerModule } from "./dagger_module/module.js" +import { + DaggerObjectBase, + DaggerObjectPropertyBase, +} from "./dagger_module/objectBase.js" +import { + EnumTypeDef, + InterfaceTypeDef, + ListTypeDef, + ObjectTypeDef, + ScalarTypeDef, + TypeDef, +} from "./typedef.js" + +// This file is the TypeScript counterpart of the Go SDK's +// `cmd/codegen/generator/go/templates/introspect_emit.go`. It walks a parsed +// `DaggerModule` and emits an introspection-shaped JSON of the module's own +// types, in the exact shape the engine schema tool (`dag.Schema().Merge`) and +// the client-bindings generator consume. It mirrors `Register` +// (`../entrypoint/register.ts`) — the source of truth for how each TypeScript +// construct becomes an engine TypeDef — so the merged schema matches what the +// engine builds from the same source, enabling self calls in the generated +// bindings without a runtime codegen pass. + +type TypeRef = { + kind: string + name?: string + ofType?: TypeRef +} + +type DirectiveArg = { name: string; value?: string } +type Directive = { name: string; args: DirectiveArg[] } + +type InputValue = { + name: string + description: string + defaultValue?: string + type: TypeRef + directives?: Directive[] + isDeprecated?: boolean + deprecationReason?: string +} + +type Field = { + name: string + description: string + type: TypeRef + args: InputValue[] + isDeprecated?: boolean + deprecationReason?: string + directives?: Directive[] +} + +type EnumValue = { + name: string + description: string + isDeprecated?: boolean + deprecationReason?: string +} + +type IntrospectionType = { + kind: string + name: string + description?: string + fields?: Field[] + enumValues?: EnumValue[] + interfaces: IntrospectionType[] +} + +type IntrospectionResponse = { + __schema: { + queryType: { name: string } + types: IntrospectionType[] + } +} + +const TypeKind = { + Scalar: "SCALAR", + Object: "OBJECT", + Interface: "INTERFACE", + Enum: "ENUM", + List: "LIST", + NonNull: "NON_NULL", +} as const + +const Scalar = { + Int: "Int", + Float: "Float", + String: "String", + Boolean: "Boolean", + Void: "Void", +} as const + +export type SerializeIntrospectionOptions = { + // When true, emit a per-type `ID` scalar for every object and interface, + // matching the Go SDK's `legacyGoSDKCompat` path: legacy (pre-cutover) schema + // views render module `id` fields as a `ID` alias, so those scalar types + // must exist in the merged schema or the generated bindings won't type-check. + legacySharedIDTypes?: boolean +} + +/** + * Serialize a parsed DaggerModule into an introspection JSON of the module's + * own types. The output is the `moduleTypes` argument to `Schema.Merge`. + */ +export function serializeIntrospection( + module: DaggerModule, + opts: SerializeIntrospectionOptions = {}, +): IntrospectionResponse { + const moduleName = module.name + const localTypeNames = collectLocalTypeNames(module) + + const types: IntrospectionType[] = [] + + for (const object of Object.values(module.objects)) { + types.push(introspectObject(object, moduleName, localTypeNames)) + } + for (const iface of Object.values(module.interfaces)) { + types.push(introspectInterface(iface, moduleName, localTypeNames)) + } + for (const enum_ of Object.values(module.enums)) { + types.push(introspectEnum(enum_, moduleName)) + } + + if (opts.legacySharedIDTypes) { + for (const t of [...types]) { + if (t.kind === TypeKind.Object || t.kind === TypeKind.Interface) { + types.push({ + kind: TypeKind.Scalar, + name: `${t.name}ID`, + description: "A unique identifier for an object.", + interfaces: [], + }) + } + } + } + + types.push(introspectQuery(module, moduleName, localTypeNames)) + + return { + __schema: { + queryType: { name: "Query" }, + types, + }, + } +} + +// collectLocalTypeNames returns the raw (un-namespaced) names of every type the +// module declares. Used to decide whether a referenced type name is +// module-local (and must be namespaced like the engine does) or a core / +// dependency type (already carrying its final schema name). +function collectLocalTypeNames(module: DaggerModule): Set { + const names = new Set() + for (const o of Object.values(module.objects)) names.add(o.name) + for (const i of Object.values(module.interfaces)) names.add(i.name) + for (const e of Object.values(module.enums)) names.add(e.name) + return names +} + +function introspectObject( + object: DaggerObjectBase, + moduleName: string, + local: Set, +): IntrospectionType { + const name = introspectTypeName(object.name, moduleName) + const fields: Field[] = [] + + for (const method of Object.values(object.methods)) { + if (toLowerCamel(method.name) === "id") { + continue + } + fields.push(introspectMethod(method, moduleName, local)) + } + + for (const field of Object.values(object.properties)) { + if (!field.isExposed) { + continue + } + if (toLowerCamel(field.alias ?? field.name) === "id") { + continue + } + fields.push(introspectProperty(field, moduleName, local)) + } + + fields.push(nodeIDField(name)) + + return { + kind: TypeKind.Object, + name, + description: trim(object.description), + interfaces: [], + fields, + } +} + +function introspectInterface( + iface: DaggerInterface, + moduleName: string, + local: Set, +): IntrospectionType { + const name = introspectTypeName(iface.name, moduleName) + const fields: Field[] = [] + for (const fn of Object.values(iface.functions)) { + if (toLowerCamel(fn.name) === "id") { + continue + } + fields.push(introspectMethod(fn, moduleName, local)) + } + fields.push(nodeIDField(name)) + return { + kind: TypeKind.Interface, + name, + description: trim(iface.description), + interfaces: [], + fields, + } +} + +function introspectEnum( + enum_: DaggerEnumBase, + moduleName: string, +): IntrospectionType { + const values: EnumValue[] = [] + for (const value of Object.values(enum_.values)) { + const ev: EnumValue = { + name: gqlEnumMemberName(value.name), + description: trim(value.description), + } + if (value.deprecated !== undefined) { + ev.isDeprecated = true + ev.deprecationReason = trim(value.deprecated) + } + values.push(ev) + } + return { + kind: TypeKind.Enum, + name: introspectTypeName(enum_.name, moduleName), + description: trim(enum_.description), + interfaces: [], + enumValues: values, + } +} + +// nodeIDField mirrors the `id` field the engine adds to every module object and +// interface (Node). The bindings key their ID marshalling on it, so without it a +// module type could not be passed as an object argument. +function nodeIDField(typeName: string): Field { + return { + name: "id", + description: `A unique identifier for this ${typeName}.`, + type: idRef(), + args: [], + } +} + +function introspectMethod( + fn: DaggerFunction | DaggerInterfaceFunction, + moduleName: string, + local: Set, +): Field { + const returnType = (fn as DaggerFunction).returnType + const field: Field = { + name: toLowerCamel((fn as DaggerFunction).alias ?? fn.name), + description: trim(fn.description), + type: returnType + ? introspectTypeRef(returnType, moduleName, local) + : voidRef(), + args: introspectArgs(fn.arguments, moduleName, local), + } + const deprecated = (fn as DaggerFunction).deprecated + if (deprecated !== undefined) { + field.isDeprecated = true + field.deprecationReason = trim(deprecated) + } + return field +} + +function introspectProperty( + field: DaggerObjectPropertyBase, + moduleName: string, + local: Set, +): Field { + const f: Field = { + name: toLowerCamel(field.alias ?? field.name), + description: trim(field.description), + type: field.type + ? introspectTypeRef(field.type, moduleName, local) + : voidRef(), + args: [], + } + if (field.deprecated !== undefined) { + f.isDeprecated = true + f.deprecationReason = trim(field.deprecated) + } + return f +} + +function introspectArgs( + args: Record, + moduleName: string, + local: Set, +): InputValue[] { + const out: InputValue[] = [] + for (const arg of Object.values(args)) { + out.push(introspectArg(arg, moduleName, local)) + } + return out +} + +// introspectArg mirrors Register.addArg: object/interface args are passed by ID +// with an `@expectedType` directive, optionality strips the NON_NULL wrapper and +// resolvable primitive defaults are carried as a JSON-encoded defaultValue. +function introspectArg( + arg: DaggerArgument, + moduleName: string, + local: Set, +): InputValue { + const { ref, expectedType } = introspectArgTypeRef( + arg.type, + moduleName, + local, + ) + + let type = ref + if (arg.isOptional && type.kind === TypeKind.NonNull && type.ofType) { + type = type.ofType + } + + const iv: InputValue = { + name: toLowerCamel(arg.name), + description: trim(arg.description), + type, + } + + if (expectedType) { + iv.directives = [ + { + name: "expectedType", + args: [{ name: "name", value: JSON.stringify(expectedType) }], + }, + ] + } + + const defaultValue = resolveDefaultValue(arg) + if (defaultValue !== undefined) { + iv.defaultValue = JSON.stringify(defaultValue) + } + + if (arg.deprecated !== undefined) { + iv.isDeprecated = true + iv.deprecationReason = trim(arg.deprecated) + } + + return iv +} + +// resolveDefaultValue mirrors Register.getDefaultValueFromArg: only primitive +// (and enum) defaults are carried in the schema; non-primitive defaults are +// resolved by the runtime instead, so they are omitted here. +function resolveDefaultValue(arg: DaggerArgument): unknown | undefined { + if (arg.defaultValue === undefined) { + return undefined + } + if (!isPrimitiveKind(arg.type?.kind)) { + return undefined + } + // Enum defaults would need to resolve the raw value back to the member name + // (as the engine registers them); omit rather than risk emitting an invalid + // wire value. Enum-typed args with a default are rare and the arg stays + // usable (just not defaulted in the generated binding). + if (arg.type?.kind === TypeDefKind.EnumKind) { + return undefined + } + return arg.defaultValue +} + +function introspectArgTypeRef( + spec: TypeDef | undefined, + moduleName: string, + local: Set, +): { ref: TypeRef; expectedType: string } { + if (!spec) { + return { ref: voidRef(), expectedType: "" } + } + switch (spec.kind) { + case TypeDefKind.ListKind: { + const { ref, expectedType } = introspectArgTypeRef( + (spec as ListTypeDef).typeDef, + moduleName, + local, + ) + return { + ref: nonNull({ kind: TypeKind.List, ofType: ref }), + expectedType, + } + } + case TypeDefKind.ObjectKind: + return { + ref: idRef(), + expectedType: refTypeName( + (spec as ObjectTypeDef).name, + moduleName, + local, + ), + } + case TypeDefKind.InterfaceKind: + return { + ref: idRef(), + expectedType: refTypeName( + (spec as InterfaceTypeDef).name, + moduleName, + local, + ), + } + default: + return { + ref: introspectTypeRef(spec, moduleName, local), + expectedType: "", + } + } +} + +// introspectTypeRef converts a scanner TypeDef into its introspection TypeRef. +// Nullability mirrors Register.addTypeDef: everything is NON_NULL except Void +// (arg-level optionality is applied separately by introspectArg). +function introspectTypeRef( + spec: TypeDef, + moduleName: string, + local: Set, +): TypeRef { + switch (spec.kind) { + case TypeDefKind.StringKind: + return nonNull(scalarRef(Scalar.String)) + case TypeDefKind.IntegerKind: + return nonNull(scalarRef(Scalar.Int)) + case TypeDefKind.BooleanKind: + return nonNull(scalarRef(Scalar.Boolean)) + case TypeDefKind.FloatKind: + return nonNull(scalarRef(Scalar.Float)) + case TypeDefKind.VoidKind: + return voidRef() + case TypeDefKind.ScalarKind: + return nonNull(scalarRef((spec as ScalarTypeDef).name)) + case TypeDefKind.ListKind: + return nonNull({ + kind: TypeKind.List, + ofType: introspectTypeRef( + (spec as ListTypeDef).typeDef, + moduleName, + local, + ), + }) + case TypeDefKind.ObjectKind: + return nonNull({ + kind: TypeKind.Object, + name: refTypeName((spec as ObjectTypeDef).name, moduleName, local), + }) + case TypeDefKind.InterfaceKind: + return nonNull({ + kind: TypeKind.Interface, + name: refTypeName((spec as InterfaceTypeDef).name, moduleName, local), + }) + case TypeDefKind.EnumKind: + return nonNull({ + kind: TypeKind.Enum, + name: refTypeName((spec as EnumTypeDef).name, moduleName, local), + }) + default: + return voidRef() + } +} + +// introspectQuery builds the Query type carrying the module's constructor field, +// used by Schema.Merge to install the module's entrypoint on the schema's Query. +function introspectQuery( + module: DaggerModule, + moduleName: string, + local: Set, +): IntrospectionType { + const query: IntrospectionType = { + kind: TypeKind.Object, + name: "Query", + interfaces: [], + fields: [], + } + + const mainObject = findMainObject(module, moduleName) + if (mainObject) { + const field: Field = { + name: toLowerCamel(moduleName), + description: "", + type: nonNull({ + kind: TypeKind.Object, + name: introspectTypeName(mainObject.name, moduleName), + }), + args: mainObject._constructor + ? introspectConstructorArgs(mainObject._constructor, moduleName, local) + : [], + } + query.fields!.push(field) + } + + return query +} + +function introspectConstructorArgs( + ctor: DaggerConstructor, + moduleName: string, + local: Set, +): InputValue[] { + return introspectArgs(ctor.arguments, moduleName, local) +} + +// findMainObject returns the module's main object — the one whose PascalCase +// name matches the module name — which carries the constructor. +function findMainObject( + module: DaggerModule, + moduleName: string, +): DaggerObjectBase | undefined { + const target = toPascal(moduleName) + for (const object of Object.values(module.objects)) { + if (toPascal(object.name) === target) { + return object + } + } + return undefined +} + +function scalarRef(name: string): TypeRef { + return { kind: TypeKind.Scalar, name } +} + +function nonNull(ofType: TypeRef): TypeRef { + return { kind: TypeKind.NonNull, ofType } +} + +function idRef(): TypeRef { + return nonNull(scalarRef("ID")) +} + +// voidRef is emitted nullable (no NON_NULL wrapper) because the engine always +// marks a Void return optional; a NON_NULL Void would diverge from the +// engine-built schema. +function voidRef(): TypeRef { + return scalarRef(Scalar.Void) +} + +function isPrimitiveKind(kind: TypeDefKind | undefined): boolean { + return ( + kind === TypeDefKind.BooleanKind || + kind === TypeDefKind.IntegerKind || + kind === TypeDefKind.StringKind || + kind === TypeDefKind.FloatKind || + kind === TypeDefKind.EnumKind + ) +} + +// refTypeName namespaces a referenced type name only when it is module-local, +// exactly as the engine namespaces module objects/interfaces/enums; core and +// dependency types already carry their final schema name. +function refTypeName( + name: string, + moduleName: string, + local: Set, +): string { + return local.has(name) ? introspectTypeName(name, moduleName) : toPascal(name) +} + +// introspectTypeName maps a module-local type name to the name the engine +// installs it under, mirroring introspect_emit.go's namespaceTypeName. +function introspectTypeName(name: string, moduleName: string): string { + return namespaceTypeName(name, moduleName) +} + +// namespaceTypeName mirrors the engine's namespaceObject (core/gqlformat.go) +// for the case where a type's final and original names are equal — always true +// for the module's own view of itself. Keep in sync. +function namespaceTypeName(typeName: string, moduleName: string): string { + const camel = toPascal(typeName) + const modName = toPascal(moduleName) + if (camel.startsWith(modName)) { + const rest = camel.slice(modName.length) + if (rest.length === 0) { + // The main module object keeps the module's name. + return modName + } + // Only treat the prefix as a namespace on a word boundary: type "Postman" + // in module "post" must become "PostPostman", while "PostMan" is already + // namespaced. + if (rest[0] >= "A" && rest[0] <= "Z") { + return camel + } + } + return toPascal(`${modName}_${typeName}`) +} + +// gqlEnumMemberName mirrors the engine's enum member naming +// (gqlEnumMemberName in core/gqlformat.go): already-conventional GraphQL member +// names such as HTTP2 are kept as-is, everything else becomes SCREAMING_SNAKE. +function gqlEnumMemberName(name: string): string { + if (isConventionalGraphQLEnumMemberName(name)) { + return name + } + return toScreamingSnake(name) +} + +function isConventionalGraphQLEnumMemberName(name: string): boolean { + if (name === "" || name.startsWith("__")) { + return false + } + for (let i = 0; i < name.length; i++) { + const c = name[i] + if (c >= "A" && c <= "Z") { + continue + } + if (i > 0 && ((c >= "0" && c <= "9") || c === "_")) { + continue + } + return false + } + return true +} + +function toScreamingSnake(input: string): string { + return input + .replace(/([a-z0-9])([A-Z])/g, "$1_$2") + .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2") + .replace(/([a-zA-Z])([0-9])/g, "$1_$2") + .replace(/[^a-zA-Z0-9]+/g, "_") + .replace(/^_+|_+$/g, "") + .toUpperCase() +} + +// toPascal / toLowerCamel are faithful ports of iancoleman/strcase +// ToCamel / ToLowerCamel — the exact functions the engine uses for +// gqlObjectName / gqlFieldName / gqlArgName. A different casing (e.g. the +// scanner's convertToPascalCase, which splits on every case boundary) would +// emit type/field names the engine never serves, breaking self calls. +function toPascal(name: string): string { + return toCamelInitCase(name, true) +} + +function toLowerCamel(name: string): string { + return toCamelInitCase(name, false) +} + +function toCamelInitCase(s: string, initCase: boolean): string { + s = s.trim() + if (s === "") { + return s + } + let out = "" + let capNext = initCase + for (let i = 0; i < s.length; i++) { + let v = s[i] + const isCap = v >= "A" && v <= "Z" + const isLow = v >= "a" && v <= "z" + if (capNext) { + if (isLow) { + v = v.toUpperCase() + } + } else if (i === 0) { + if (isCap) { + v = v.toLowerCase() + } + } + if (isCap || isLow) { + out += v + capNext = false + } else if (v >= "0" && v <= "9") { + out += v + capNext = true + } else { + capNext = v === "_" || v === " " || v === "-" || v === "." + } + } + return out +} + +function trim(s: string | undefined): string { + return (s ?? "").trim() +} diff --git a/library/src/module/introspector/typedef.ts b/library/src/module/introspector/typedef.ts new file mode 100644 index 0000000..1a09e57 --- /dev/null +++ b/library/src/module/introspector/typedef.ts @@ -0,0 +1,69 @@ +import { TypeDefKind } from "../../api/client.gen.js" + +/** + * Base type of argument, field or return type. + */ +export type BaseTypeDef = { + kind: TypeDefKind +} + +/** + * Extends the base type def if it's an object to add its name. + */ +export type ObjectTypeDef = BaseTypeDef & { + kind: TypeDefKind.ObjectKind + name: string +} + +/** + * Extends the base type def if it's an enum to add its name. + */ +export type EnumTypeDef = BaseTypeDef & { + kind: TypeDefKind.EnumKind + name: string +} + +/** + * Extends the base type def if it's an interface to add its name + */ +export type InterfaceTypeDef = BaseTypeDef & { + kind: TypeDefKind.InterfaceKind + name: string +} + +/** + * Extends the base typedef if it's a scalar to add its name and real type. + */ +export type ScalarTypeDef = BaseTypeDef & { + kind: TypeDefKind.ScalarKind + name: string +} + +/** + * Extends the base if it's a list to add its subtype. + */ +export type ListTypeDef = BaseTypeDef & { + kind: TypeDefKind.ListKind + typeDef: TypeDef +} + +/** + * A generic TypeDef that will dynamically add necessary properties + * depending on its type. + * + * If it's a type of kind scalar, it transforms the BaseTypeDef into a ScalarTypeDef. + * If it's type of kind object, it transforms the BaseTypeDef into an ObjectTypeDef. + * If it's a type of kind list, it transforms the BaseTypeDef into a ListTypeDef. + */ +export type TypeDef = + T extends TypeDefKind.ScalarKind + ? ScalarTypeDef + : T extends TypeDefKind.ObjectKind + ? ObjectTypeDef + : T extends TypeDefKind.ListKind + ? ListTypeDef + : T extends TypeDefKind.EnumKind + ? EnumTypeDef + : T extends TypeDefKind.InterfaceKind + ? InterfaceTypeDef + : BaseTypeDef diff --git a/library/src/module/introspector/typedef_json.ts b/library/src/module/introspector/typedef_json.ts new file mode 100644 index 0000000..fb20f42 --- /dev/null +++ b/library/src/module/introspector/typedef_json.ts @@ -0,0 +1,160 @@ +import { TypeDefKind } from "../../api/client.gen.js" +import { DaggerArgument } from "./dagger_module/argument.js" +import { + DaggerEnumBase, + DaggerEnumBaseValue, +} from "./dagger_module/enumBase.js" +import { DaggerFunction } from "./dagger_module/function.js" +import { DaggerInterface } from "./dagger_module/interface.js" +import { DaggerInterfaceFunction } from "./dagger_module/interfaceFunction.js" +import { DaggerModule } from "./dagger_module/module.js" +import { + DaggerObjectBase, + DaggerObjectPropertyBase, +} from "./dagger_module/objectBase.js" +import { ListTypeDef, ObjectTypeDef, TypeDef } from "./typedef.js" + +/** + * Serialize a parsed DaggerModule into a stable JSON shape that downstream + * codegen (in Go, see `cmd/codegen/generator/typescript/entrypoint.go`) can + * read to render the static dispatch entrypoint. + * + * This is intentionally a separate path from the existing `toJSON` methods + * so we can include fields the emitter needs (`kind`, `isExported`, + * `location`, `cache`, `isCheck`, ...) without disturbing other consumers. + */ +export function serializeModule(module: DaggerModule): unknown { + return { + name: module.name, + description: module.description, + objects: mapValues(module.objects, serializeObject), + enums: mapValues(module.enums, serializeEnum), + interfaces: mapValues(module.interfaces, serializeInterface), + } +} + +function serializeObject(obj: DaggerObjectBase) { + const isExported = (obj as DaggerObjectBase & { isExported?: boolean }) + .isExported + const isDefaultExport = ( + obj as DaggerObjectBase & { isDefaultExport?: boolean } + ).isDefaultExport + const ctor = obj._constructor + return { + name: obj.name, + kind: obj.kind(), + isExported: isExported !== false, + isDefaultExport: isDefaultExport === true, + description: obj.description, + deprecated: obj.deprecated, + location: obj.getLocation(), + constructor: ctor + ? { + name: ctor.name, + arguments: Object.values(ctor.arguments).map(serializeArgument), + } + : undefined, + methods: mapValues(obj.methods, serializeFunction), + properties: mapValues(obj.properties, serializeProperty), + } +} + +function serializeFunction(fn: DaggerFunction | DaggerInterfaceFunction) { + // Emit arguments as an ordered array — argument position matters for + // positional dispatch and Go's `map` iteration loses order. + const f = fn as DaggerFunction + return { + name: f.name, + alias: f.alias, + cache: f.cache, + description: f.description, + deprecated: f.deprecated, + isCheck: f.isCheck === true, + isGenerator: f.isGenerator === true, + isUp: f.isUp === true, + location: f.getLocation(), + returnType: f.returnType ? serializeType(f.returnType) : undefined, + arguments: Object.values(f.arguments).map(serializeArgument), + } +} + +function serializeArgument(arg: DaggerArgument) { + return { + name: arg.name, + description: arg.description, + deprecated: arg.deprecated, + type: arg.type ? serializeType(arg.type) : undefined, + isVariadic: arg.isVariadic === true, + isNullable: arg.isNullable === true, + isOptional: arg.isOptional === true, + defaultValue: arg.defaultValue, + defaultPath: arg.defaultPath, + defaultAddress: arg.defaultAddress, + ignore: arg.ignore, + location: arg.getLocation(), + } +} + +function serializeProperty(prop: DaggerObjectPropertyBase) { + return { + name: prop.name, + alias: prop.alias, + description: prop.description, + deprecated: prop.deprecated, + isExposed: prop.isExposed === true, + type: prop.type ? serializeType(prop.type) : undefined, + location: prop.getLocation(), + } +} + +function serializeEnum(enum_: DaggerEnumBase) { + return { + name: enum_.name, + description: enum_.description, + location: enum_.getLocation(), + values: mapValues(enum_.values, (v: DaggerEnumBaseValue) => ({ + name: v.name, + value: v.value, + description: v.description, + deprecated: v.deprecated, + location: v.getLocation(), + })), + } +} + +function serializeInterface(iface: DaggerInterface) { + return { + name: iface.name, + description: iface.description, + location: iface.getLocation(), + functions: mapValues(iface.functions, serializeFunction), + } +} + +function serializeType(t: TypeDef): unknown { + switch (t.kind) { + case TypeDefKind.ListKind: + return { + kind: t.kind, + typeDef: serializeType((t as ListTypeDef).typeDef), + } + case TypeDefKind.ObjectKind: + case TypeDefKind.EnumKind: + case TypeDefKind.InterfaceKind: + case TypeDefKind.ScalarKind: + return { kind: t.kind, name: (t as ObjectTypeDef).name } + default: + return { kind: t.kind } + } +} + +function mapValues( + obj: Record, + fn: (value: T) => U, +): Record { + const out: Record = {} + for (const [k, v] of Object.entries(obj)) { + out[k] = fn(v) + } + return out +} diff --git a/library/src/module/introspector/typescript_module/ast.ts b/library/src/module/introspector/typescript_module/ast.ts new file mode 100644 index 0000000..4c6ead9 --- /dev/null +++ b/library/src/module/introspector/typescript_module/ast.ts @@ -0,0 +1,737 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import Module from "node:module" +import * as path from "path" +import ts from "typescript" + +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { DaggerDecorators } from "../dagger_module/index.js" +import { TypeDef } from "../typedef.js" +import { DeclarationsMap, isDeclarationOf } from "./declarations.js" +import { Location } from "./location.js" + +export const CLIENT_GEN_FILE = "client.gen.ts" + +// Generated client files share the `.gen.ts` suffix: `client.gen.ts` plus one +// `.gen.ts` per dependency (dependency types are split into their own +// files). All of them are part of the SDK surface the introspector must search +// when resolving type references like a dependency-contributed enum. +export const GENERATED_CLIENT_SUFFIX = ".gen.ts" + +export type ResolvedNodeWithSymbol = { + type: T + node: DeclarationsMap[T] + symbol: ts.Symbol + file: ts.SourceFile +} + +export type SymbolDoc = { + description: string + deprecated?: string +} + +export class AST { + public checker: ts.TypeChecker + + private readonly sourceFiles: ts.SourceFile[] + + // Resolved paths of the SDK-generated binding files (client.gen.ts and each + // .gen.ts). Empty when the caller didn't supply them, in which case + // isGeneratedClientFile falls back to the `.gen.ts` suffix. + private readonly generatedClientFiles: Set + + constructor( + public readonly files: string[], + private readonly userModule: Module[], + generatedClientFiles: string[] = [], + ) { + this.files = files.map((f) => path.resolve(f)) + this.generatedClientFiles = new Set( + generatedClientFiles.map((f) => path.resolve(f)), + ) + const program = ts.createProgram(files, { + experimentalDecorators: true, + moduleResolution: ts.ModuleResolutionKind.Node10, + target: ts.ScriptTarget.ES2022, + }) + this.checker = program.getTypeChecker() + this.sourceFiles = program + .getSourceFiles() + .filter((file) => !file.isDeclarationFile) + } + + // isGeneratedClientFile reports whether a file is one of the SDK-generated + // bindings (client.gen.ts or a .gen.ts). It checks the explicit set when + // available, falling back to the `.gen.ts` suffix otherwise. + public isGeneratedClientFile(fileName: string): boolean { + if (this.generatedClientFiles.size > 0) { + return this.generatedClientFiles.has(path.resolve(fileName)) + } + return fileName.endsWith(GENERATED_CLIENT_SUFFIX) + } + + public findResolvedNodeByName( + name: string, + + /** + * Optionally look for a specific node kind if we already know + * what we're looking for. + */ + kind: T, + ): ResolvedNodeWithSymbol | undefined { + let result: ResolvedNodeWithSymbol | undefined + + for (const sourceFile of this.sourceFiles) { + ts.forEachChild(sourceFile, (node) => { + if (result !== undefined) return + + // Skip if it's not from a generated client file nor the user module. + // Generated files include client.gen.ts and every per-dependency + // .gen.ts (split out from the core client). + if ( + !this.isGeneratedClientFile(sourceFile.fileName) && + !this.files.includes(path.resolve(sourceFile.fileName)) + ) { + return + } + + if (kind !== undefined && node.kind === kind) { + const isDeclarationValid = isDeclarationOf[kind](node) + if (!isDeclarationValid) return + + const convertedNode = node as DeclarationsMap[typeof kind] + if (!convertedNode.name || convertedNode.name.getText() !== name) { + return + } + + const symbol = this.checker.getSymbolAtLocation(convertedNode.name) + if (!symbol) { + console.debug( + `missing symbol for ${name} at ${sourceFile.fileName}:${node.pos}`, + ) + return + } + + result = { + type: kind, + node: convertedNode, + symbol: symbol, + file: sourceFile, + } + } + }) + } + + return result + } + + public findAllDeclarations( + kind: T, + ): ResolvedNodeWithSymbol[] { + const results: ResolvedNodeWithSymbol[] = [] + + for (const sourceFile of this.sourceFiles) { + ts.forEachChild(sourceFile, (node) => { + // Skip if it's not from a generated client file nor the user module. + // Generated files include client.gen.ts and every per-dependency + // .gen.ts (split out from the core client). + if ( + !this.isGeneratedClientFile(sourceFile.fileName) && + !this.files.includes(path.resolve(sourceFile.fileName)) + ) { + return + } + + if (kind !== undefined && node.kind === kind) { + const isDeclarationValid = isDeclarationOf[kind](node) + if (!isDeclarationValid) return + + const convertedNode = node as DeclarationsMap[typeof kind] + if (!convertedNode.name) { + return + } + + const symbol = this.checker.getSymbolAtLocation(convertedNode.name) + if (!symbol) { + console.debug( + `missing symbol for ${convertedNode.name.getText()} at ${sourceFile.fileName}:${node.pos}`, + ) + return + } + + results.push({ + type: kind, + node: convertedNode, + symbol: symbol, + file: sourceFile, + }) + } + }) + } + + return results + } + + public getTypeFromTypeAlias(typeAlias: ts.TypeAliasDeclaration): ts.Type { + const symbol = this.getSymbolOrThrow(typeAlias.name) + + return this.checker.getDeclaredTypeOfSymbol(symbol) + } + + public static getNodePosition(node: ts.Node): string { + const sourceFile = node.getSourceFile() + + const position = ts.getLineAndCharacterOfPosition( + sourceFile, + node.getStart(), + ) + + return `${sourceFile.fileName}:${position.line}:${position.character}` + } + + /** + * Returns the location of the node in the source file. + * + * The filepath is relative to the module root directory. + * Ideally, we use the identifier of the node accessible by node.name but fallback + * to node itself if it's not available. + * + * The TypeScript SDK based it's line and column on index 0 but editors starts + * at 1 so we always add 1 to fix that difference. + */ + public static getNodeLocation( + node: ts.Node & { name?: ts.Identifier }, + ): Location { + const sourceFile = node.getSourceFile() + + // Use the identifier of the node if available. + const targetNode = node.name ?? node + + const position = ts.getLineAndCharacterOfPosition( + sourceFile, + targetNode.getStart(sourceFile), + ) + + // sourceFile.fileName is the absolute path to the file, we need to get the relative path + // from the module path so we exclude the module path from the given path. + // But since root will always start with `/src`, we want to catch the second `src` + // inside the module. + const pathParts = path.resolve(sourceFile.fileName).split(path.sep) + const srcIndex = pathParts.indexOf("src", 2) + + return { + filepath: pathParts.slice(srcIndex).join(path.sep), + line: position.line + 1, + column: position.character + 1, + } + } + + public getDocFromSymbol(symbol: ts.Symbol): string { + return this.getSymbolDoc(symbol).description + } + + public getSymbolDoc(symbol: ts.Symbol): SymbolDoc { + const description = ts + .displayPartsToString(symbol.getDocumentationComment(this.checker)) + .trim() + + let deprecated: string | undefined + let hasDeprecatedTag = false + + for (const tag of symbol.getJsDocTags()) { + if (tag.name !== "deprecated") continue + + hasDeprecatedTag = true + const text = + tag.text?.map((part) => ("text" in part ? part.text : part)).join("") ?? + "" + deprecated = text.trim() + break + } + + if (!hasDeprecatedTag) { + return { description } + } + + return { + description, + deprecated: deprecated ?? "", + } + } + + public getSymbolOrThrow(node: ts.Node): ts.Symbol { + const symbol = this.getSymbol(node) + if (!symbol) { + throw new IntrospectionError( + `could not find symbol at ${AST.getNodePosition(node)}`, + ) + } + + return symbol + } + + public getSignatureFromFunctionOrThrow( + node: ts.SignatureDeclaration, + ): ts.Signature { + const signature = this.checker.getSignatureFromDeclaration(node) + if (!signature) { + throw new IntrospectionError( + `could not find signature at ${AST.getNodePosition(node)}`, + ) + } + + return signature + } + + public getSymbol(node: ts.Node): ts.Symbol | undefined { + return this.checker.getSymbolAtLocation(node) + } + + public isNodeDecoratedWith( + node: ts.HasDecorators, + daggerDecorator: DaggerDecorators, + ): boolean { + const decorators = ts.getDecorators(node) + if (!decorators) { + return false + } + + const decorator = decorators.find((d) => + d.expression.getText().startsWith(daggerDecorator), + ) + if (!decorator) { + return false + } + + if (!ts.isCallExpression(decorator.expression)) { + throw new IntrospectionError( + `decorator at ${AST.getNodePosition(node)} should be a call expression, please use ${daggerDecorator}() instead.`, + ) + } + + return true + } + + public getDecoratorArgument( + node: ts.HasDecorators, + daggerDecorator: DaggerDecorators, + type: "string" | "object", + position = 0, + ): T | undefined { + const decorators = ts.getDecorators(node) + if (!decorators) { + return undefined + } + + const decorator = decorators.find((d) => + d.expression.getText().startsWith(daggerDecorator), + ) + if (!decorator) { + return undefined + } + + const argument = (decorator.expression as ts.CallExpression).arguments[ + position + ] + if (!argument) { + return undefined + } + + switch (type) { + case "string": + return argument.getText() as T + case "object": + return this.resolveDecoratorArgumentValue(argument) as T + } + } + + /** + * Resolve the value of a decorator argument expression. + * + * Decorator arguments may reference module-level constants, e.g. + * `@argument({ ignore: IGNORE })` or `@func({ alias: NAME })`. We therefore + * cannot simply `eval` the raw text: the referenced symbols are not in scope + * and the evaluation would throw. Instead we walk the expression and resolve + * each value through {@link resolveParameterDefaultValue}, which already knows + * how to follow identifiers, imports and enum members back to their literal + * values. + */ + private resolveDecoratorArgumentValue(expression: ts.Expression): any { + if (ts.isObjectLiteralExpression(expression)) { + const result: Record = {} + + for (const property of expression.properties) { + if (ts.isPropertyAssignment(property)) { + result[this.getPropertyName(property.name)] = + this.resolveParameterDefaultValue(property.initializer) + } else if (ts.isShorthandPropertyAssignment(property)) { + // `{ alias }` shorthand, resolve the value from the identifier. + result[property.name.getText()] = this.resolveParameterDefaultValue( + property.name, + ) + } + } + + return result + } + + // Non-object arguments, e.g. the string alias form `@func("alias")`. + return this.resolveParameterDefaultValue(expression) + } + + private getPropertyName(name: ts.PropertyName): string { + if (ts.isStringLiteral(name) || ts.isNumericLiteral(name)) { + return name.text + } + + return name.getText() + } + + public unwrapTypeStringFromPromise(type: string): string { + if (type.startsWith("Promise<")) { + return type.slice("Promise<".length, -">".length) + } + + if (type.startsWith("Awaited<")) { + return type.slice("Awaited<".length, -">".length) + } + + return type + } + + public unwrapTypeStringFromArray(type: string): string { + if (type.endsWith("[]")) { + return type.replace("[]", "") + } + + if (type.startsWith("Array<")) { + return type.slice("Array<".length, -">".length) + } + + return type + } + + public stringTypeToUnwrappedType(type: string): string { + type = this.unwrapTypeStringFromPromise(type) + + // If they are difference, that means we upwrapped the array. + const extractedTypeFromArray = this.unwrapTypeStringFromArray(type) + if (extractedTypeFromArray !== type) { + return this.stringTypeToUnwrappedType(extractedTypeFromArray) + } + + return type + } + + public typeToStringType(type: ts.Type): string { + const stringType = this.checker.typeToString(this.unwrapNullable(type)) + + return this.stringTypeToUnwrappedType(stringType) + } + + /** + * Strip `undefined` / `null` from a union type so the resolver sees the underlying + * type directly. Non-union types are returned as-is — in particular `void` must + * not be passed through `getNonNullableType`, which would collapse it to `never`. + */ + private unwrapNullable(type: ts.Type): ts.Type { + if (type.flags & ts.TypeFlags.Union) { + return this.checker.getNonNullableType(type) + } + return type + } + + public tsTypeToTypeDef( + node: ts.Node, + type: ts.Type, + ): TypeDef | undefined { + // Optional parameters/properties (e.g. `foo?: string`) are typed as `T | undefined` + // by the type checker. Strip the nullable parts so the downstream flag checks see + // the underlying `T` directly. + type = this.unwrapNullable(type) + + if (type.flags & ts.TypeFlags.String) + return { kind: TypeDefKind.StringKind } + if (type.flags & ts.TypeFlags.Number) { + // Float will be interpreted as number by the TypeScript compiler so we need to check if the + // text is "float" to know if it's a float or an integer. + // It can also be interpreted as a reference, but this is handled separately at an upper level. + if (node.getText().includes("float")) { + return { kind: TypeDefKind.FloatKind } + } + + return { kind: TypeDefKind.IntegerKind } + } + if (type.flags & ts.TypeFlags.Boolean) + return { kind: TypeDefKind.BooleanKind } + if (type.flags & ts.TypeFlags.Void) return { kind: TypeDefKind.VoidKind } + + // If a type has a flag Object, is can basically be anything. + // We firstly wants to see if it's a promise or an array so we can unwrap the + // actual type. + if (type.flags & ts.TypeFlags.Object) { + const objectType = type as ts.ObjectType + + // If it's a reference, that means it's a generic type like + // `Promise` or `number[]` or `Array`. + if (objectType.objectFlags & ts.ObjectFlags.Reference) { + const typeArguments = this.checker.getTypeArguments( + type as ts.TypeReference, + ) + + switch (typeArguments.length) { + case 0: + // Might change after to support more complex type + break + case 1: { + const typeArgument = typeArguments[0] + + if (type.symbol.getName() === "Promise") { + return this.tsTypeToTypeDef(node, typeArgument) + } + + if (type.symbol.getName() === "Array") { + return { + kind: TypeDefKind.ListKind, + typeDef: this.tsTypeToTypeDef(node, typeArgument), + } + } + + return undefined + } + default: { + throw new IntrospectionError( + `could not resolve type ${type.symbol.getName()} at ${AST.getNodePosition(node)}, dagger does not support generics with argument yet.`, + ) + } + } + } + } + } + + private resolveParameterDefaultValueTypeReference( + expression: ts.Expression, + value: any, + ): any { + const type = typeof value + + switch (type) { + case "string": + case "number": // float is also included here + case "bigint": + case "boolean": + case "object": + // Value will be jsonified on registration. + return value + default: + // If we cannot resolve the value, we skip it and let the value be resolved automatically by the runtime + return undefined + } + } + + // Try to extract literal values (enum members, string/number/boolean/bigint + // literals) directly from the type checker. Returns undefined if the + // expression is not a literal. + private getLiteralValueFromExpression( + expression: ts.Expression, + ): string | number | boolean | bigint | undefined { + const type = this.checker.getTypeAtLocation(expression) + if (!type) { + return undefined + } + + const resolveLiteral = ( + t: ts.Type, + ): string | number | boolean | bigint | undefined => { + if (t.flags & ts.TypeFlags.BooleanLiteral) { + const intrinsic = t as unknown as { intrinsicName?: string } + // Handle boolean value + switch (intrinsic.intrinsicName) { + case "true": + return true + case "false": + return false + } + } + + if ( + t.flags & + (ts.TypeFlags.EnumLiteral | + ts.TypeFlags.StringLiteral | + ts.TypeFlags.NumberLiteral | + ts.TypeFlags.BigIntLiteral) + ) { + const literal = t as ts.LiteralType + if (literal.value !== undefined) { + return literal.value as string | number | bigint + } + + // Some literals only expose `intrinsicName`. Example: + // const yes = true; function use(flag: boolean = yes) {} + // The checker reports `intrinsicName: "true"` without a `value`, so we fallback. + const intrinsic = literal as unknown as { intrinsicName?: string } + if (intrinsic.intrinsicName !== undefined) { + return intrinsic.intrinsicName as string + } + } + + return undefined + } + + if (type.isUnion()) { + // Walk union members to surface the literal. Example: + // ```ts + // const defaults = { proto: NetworkProtocol.Udp } + // function use(proto: NetworkProtocol = defaults.proto) {} + // ``` + // The checker reports `defaults.proto` as `NetworkProtocol.Tcp | NetworkProtocol.Udp`, + // so we inspect each subtype to recover the actual default value. + for (const subtype of type.types) { + const literal = resolveLiteral(subtype) + if (literal !== undefined) { + return literal + } + } + + return undefined + } + + return resolveLiteral(type) + } + + private warnUnresolvedDefaultValue(expression: ts.Expression): void { + console.warn( + `default value '${expression.getText()}' at ${AST.getNodePosition(expression)} cannot be resolved, dagger does not support object or function as default value. + The value will be ignored by the introspection and resolve at the runtime.`, + ) + } + + public resolveParameterDefaultValue(expression: ts.Expression): any { + const kind = expression.kind + + switch (kind) { + case ts.SyntaxKind.StringLiteral: + return `${eval(expression.getText())}` + case ts.SyntaxKind.NumericLiteral: + return parseInt(expression.getText()) + case ts.SyntaxKind.TrueKeyword: + return true + case ts.SyntaxKind.FalseKeyword: + return false + case ts.SyntaxKind.NullKeyword: + return null + case ts.SyntaxKind.ArrayLiteralExpression: + return eval(expression.getText()) + case ts.SyntaxKind.Identifier: { + const symbol = this.checker.getSymbolAtLocation(expression) + if (!symbol) { + throw new IntrospectionError( + `could not resolve default value reference to the variable: '${expression.getText()}' from ${AST.getNodePosition(expression)}. Is it exported by the module?`, + ) + } + + // Parse the default value from the variable declaration + // ``` + // export const foo = "A" + // + // function bar(baz: string = foo) {} + // ``` + const decl = symbol.valueDeclaration ?? symbol.declarations?.[0] + if (!decl) { + this.warnUnresolvedDefaultValue(expression) + + return undefined + } + + if (ts.isVariableDeclaration(decl) && decl.initializer) { + return this.resolveParameterDefaultValue(decl.initializer) + } + + // Parse the default value from the enum member + // ``` + // enum Foo { + // A = "a" + // } + // + // function bar(baz: string = Foo.A) {} + // ``` + if (ts.isEnumMember(decl)) { + const val = this.checker.getConstantValue(decl) + if (val !== undefined) return val + if (decl.initializer) + return this.resolveParameterDefaultValue(decl.initializer) + } + + // Parse the default value from the import specifier + // ``` + // import { foo } from "bar" + // + // function bar(baz: string = foo) {} + // ``` + if (ts.isImportSpecifier(decl)) { + const aliased = this.checker.getAliasedSymbol(symbol) + const aliasedDecl = + aliased?.valueDeclaration ?? aliased?.declarations?.[0] + if ( + aliasedDecl && + ts.isVariableDeclaration(aliasedDecl) && + aliasedDecl.initializer + ) { + return this.resolveParameterDefaultValue(aliasedDecl.initializer) + } + } + + // Warn the user if the default value cannot be resolved + this.warnUnresolvedDefaultValue(expression) + + return undefined + } + case ts.SyntaxKind.PropertyAccessExpression: { + const propertyAccess = expression as ts.PropertyAccessExpression + + // Quick path: TypeScript already computed the literal value. + const directConstant = this.checker.getConstantValue(propertyAccess) + if (directConstant !== undefined) { + return directConstant + } + + // Otherwise inspect the enum member backing the property accessor. + const nameSymbol = this.checker.getSymbolAtLocation(propertyAccess.name) + if (nameSymbol) { + const declarations = nameSymbol.declarations ?? [] + const decls = nameSymbol.valueDeclaration + ? [nameSymbol.valueDeclaration, ...declarations] + : declarations + + for (const decl of decls) { + if (ts.isEnumMember(decl)) { + const val = this.checker.getConstantValue(decl) + if (val !== undefined) { + return val + } + + if (decl.initializer) { + return this.resolveParameterDefaultValue(decl.initializer) + } + } + } + } + + // Fall back to literal type information if available. + const literal = this.getLiteralValueFromExpression(propertyAccess) + if (literal !== undefined) { + return literal + } + + // Warn the user if the default value cannot be resolved. + this.warnUnresolvedDefaultValue(expression) + + return undefined + } + default: { + // Warn the user if the default value cannot be resolved + this.warnUnresolvedDefaultValue(expression) + } + } + } +} diff --git a/library/src/module/introspector/typescript_module/declarations.ts b/library/src/module/introspector/typescript_module/declarations.ts new file mode 100644 index 0000000..711a351 --- /dev/null +++ b/library/src/module/introspector/typescript_module/declarations.ts @@ -0,0 +1,26 @@ +import ts from "typescript" + +export type DeclarationsMap = { + [ts.SyntaxKind.ClassDeclaration]: ts.ClassDeclaration + [ts.SyntaxKind.MethodDeclaration]: ts.MethodDeclaration + [ts.SyntaxKind.PropertyDeclaration]: ts.PropertyDeclaration + [ts.SyntaxKind.FunctionDeclaration]: ts.FunctionDeclaration + [ts.SyntaxKind.EnumDeclaration]: ts.EnumDeclaration + [ts.SyntaxKind.InterfaceDeclaration]: ts.InterfaceDeclaration + [ts.SyntaxKind.TypeAliasDeclaration]: ts.TypeAliasDeclaration +} + +export type Declarations = + T extends keyof DeclarationsMap ? DeclarationsMap[T] : ts.Node + +export const isDeclarationOf: { + [K in keyof DeclarationsMap]: (node: ts.Node) => node is DeclarationsMap[K] +} = { + [ts.SyntaxKind.ClassDeclaration]: ts.isClassDeclaration, + [ts.SyntaxKind.MethodDeclaration]: ts.isMethodDeclaration, + [ts.SyntaxKind.PropertyDeclaration]: ts.isPropertyDeclaration, + [ts.SyntaxKind.FunctionDeclaration]: ts.isFunctionDeclaration, + [ts.SyntaxKind.EnumDeclaration]: ts.isEnumDeclaration, + [ts.SyntaxKind.InterfaceDeclaration]: ts.isInterfaceDeclaration, + [ts.SyntaxKind.TypeAliasDeclaration]: ts.isTypeAliasDeclaration, +} diff --git a/library/src/module/introspector/typescript_module/index.ts b/library/src/module/introspector/typescript_module/index.ts new file mode 100644 index 0000000..d5a3794 --- /dev/null +++ b/library/src/module/introspector/typescript_module/index.ts @@ -0,0 +1,3 @@ +export * from "./ast.js" +export * from "./typedef_utils.js" +export * from "./location.js" diff --git a/library/src/module/introspector/typescript_module/location.ts b/library/src/module/introspector/typescript_module/location.ts new file mode 100644 index 0000000..ab02952 --- /dev/null +++ b/library/src/module/introspector/typescript_module/location.ts @@ -0,0 +1,5 @@ +export type Location = { + filepath: string + line: number + column: number +} diff --git a/library/src/module/introspector/typescript_module/typedef_utils.ts b/library/src/module/introspector/typescript_module/typedef_utils.ts new file mode 100644 index 0000000..18ae39b --- /dev/null +++ b/library/src/module/introspector/typescript_module/typedef_utils.ts @@ -0,0 +1,41 @@ +import { TypeDefKind } from "../../../api/client.gen.js" +import { IntrospectionError } from "../../../common/errors/index.js" +import { TypeDef } from "../typedef.js" + +export function isTypeDefResolved(typeDef: TypeDef): boolean { + if (typeDef.kind !== TypeDefKind.ListKind) { + return true + } + + const arrayTypeDef = typeDef as TypeDef + + if (arrayTypeDef.typeDef === undefined) { + return false + } + + if (arrayTypeDef.typeDef.kind === TypeDefKind.ListKind) { + return isTypeDefResolved(arrayTypeDef.typeDef) + } + + return true +} + +export function resolveTypeDef( + typeDef: TypeDef | undefined, + reference: TypeDef, +): TypeDef { + if (typeDef === undefined) { + return reference + } + + if (typeDef.kind === TypeDefKind.ListKind) { + const listTypeDef = typeDef as TypeDef + + listTypeDef.typeDef = resolveTypeDef(listTypeDef.typeDef, reference) + return listTypeDef + } + + throw new IntrospectionError( + `type ${JSON.stringify(typeDef)} has already been resolved, it should not be overwritten ; reference: ${JSON.stringify(reference)}`, + ) +} diff --git a/library/src/module/introspector/utils/files.ts b/library/src/module/introspector/utils/files.ts new file mode 100644 index 0000000..1e8f9d7 --- /dev/null +++ b/library/src/module/introspector/utils/files.ts @@ -0,0 +1,38 @@ +import * as fs from "fs" +import * as path from "path" + +/** + * Extensions supported by the loader. + */ +const allowedExtensions = [".ts", ".mts"] + +/** + * Returns a list of path of all files in the given directory + */ +export async function listFiles(dir = "."): Promise { + const res = await Promise.all( + fs.readdirSync(dir).map(async (file) => { + const filepath = path.join(dir, file) + + // Ignore node_modules and transpiled typescript + if (filepath.includes("node_modules") || filepath.includes("dist")) { + return [] + } + + const stat = fs.statSync(filepath) + + if (stat.isDirectory()) { + return await listFiles(filepath) + } + + const ext = path.extname(filepath) + if (allowedExtensions.find((allowedExt) => allowedExt === ext)) { + return [path.join(dir, file)] + } + + return [] + }), + ) + + return res.reduce((p, c) => [...c, ...p], []) +} diff --git a/library/src/module/registry.ts b/library/src/module/registry.ts new file mode 100644 index 0000000..95a6f46 --- /dev/null +++ b/library/src/module/registry.ts @@ -0,0 +1,276 @@ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// @experimentalDecorators +// @emitDecoratorMetadata +import "reflect-metadata" + +import { UnknownDaggerError } from "../common/errors/index.js" + +export type Class = { new (...args: any[]): any } + +export type State = { [property: string]: any } + +export type Args = Record + +/** + * Datastructures that store the class constructor to allow invoking it + * from the registry and store method's name. + */ +type RegistryClass = { + class_: Class +} + +export type ArgumentOptions = { + /** + * The contextual value to use for the argument. + * + * This should only be used for Directory/File or GitRepository/GitRef types. + * + * An absolute path would be related to the context source directory (the git repo root or the module source root). + * A relative path would be relative to the module source root. + */ + defaultPath?: string + + /** + * The default container address to use for the argument. + * + * This should only be used for Container types. + * + * If the argument is not set, the container will be loaded from this address. + */ + defaultAddress?: string + + /** + * Patterns to ignore when loading the contextual argument value. + * + * This should only be used for Directory types. + */ + ignore?: string[] +} + +export type FunctionOptions = { + /** + * The caching behavior of this function. + * "never" means no caching. + * "session" means caching only for the duration of the current client's session. + * A duration string (e.g., "5m", "1h") means persistent caching for that duration. + * By default, caching is enabled with a long default set by the engine. + */ + cache?: "never" | "session" | string + + /** + * An optional alias to use for the function when exposed on the API. + */ + alias?: string +} + +/** + * Registry stores class and method that have the @object decorator. + * + * This is a convenient way to make possible the invocation of class' function. + * + * The decorator @object store the class into the Registry, but also all the + * users method's name. + * It doesn't consider the `@func` decorator because this is + * used by the Dagger API to know what to expose or not. + * This might lead to unnecessary data register into the registry, but + * we use map as datastructure to optimize the searching process + * since we directly look through a key into the `class_` member of + * RegistryClass. + */ +export class Registry { + /** + * The definition of the @object decorator that should be on top of any + * class module that must be exposed to the Dagger API. + */ + object = (): ((constructor: T) => T) => { + return (constructor: T): T => { + Reflect.defineMetadata(constructor.name, { class_: constructor }, this) + + return constructor + } + } + + /** + * The definition of the @enum decorator that should be on top of any + * class module that must be exposed to the Dagger API as enumeration. + * + * @deprecated In favor of using TypeScript `enum` types. + */ + enumType = (): ((constructor: T) => T) => { + return (constructor: T): T => { + return constructor + } + } + + /** + * The definition of @field decorator that should be on top of any + * class' property that must be exposed to the Dagger API. + * + * @deprecated In favor of `@func` + * @param alias The alias to use for the field when exposed on the API. + */ + field = (alias?: string): ((target: object, propertyKey: string) => void) => { + return (target: object, propertyKey: string) => { + // A placeholder to declare field in the registry. + } + } + + /** + * The definition of @func decorator that should be on top of any + * class' method that must be exposed to the Dagger API. + */ + func = ( + opts?: FunctionOptions | string, + ): (( + target: object, + propertyKey: string | symbol, + descriptor?: PropertyDescriptor, + ) => void) => { + return ( + target: object, + propertyKey: string | symbol, + descriptor?: PropertyDescriptor, + ) => {} + } + + /** + * The definition of @check decorator that marks a function as a check. + */ + check = (): (( + target: object, + propertyKey: string | symbol, + descriptor?: PropertyDescriptor, + ) => void) => { + return ( + target: object, + propertyKey: string | symbol, + descriptor?: PropertyDescriptor, + ) => {} + } + + /** + * The definition of @generate decorator that marks a function as a generator. + */ + generate = (): (( + target: object, + propertyKey: string | symbol, + descriptor?: PropertyDescriptor, + ) => void) => { + return ( + target: object, + propertyKey: string | symbol, + descriptor?: PropertyDescriptor, + ) => {} + } + + /** + * The definition of @up decorator that marks a function as a service for dagger up. + */ + up = (): (( + target: object, + propertyKey: string, + descriptor: PropertyDescriptor, + ) => PropertyDescriptor) => { + return (target, propertyKey, descriptor) => descriptor + } + + argument = ( + opts?: ArgumentOptions, + ): (( + target: object, + propertyKey: string | undefined, + parameterIndex: number, + ) => void) => { + return ( + target: object, + propertyKey: string | undefined, + parameterIndex: number, + ) => {} + } + + /** + * Build a class that is part of the module itself so you can + * access its sub functions. + * + * If there's no class associated, return the object itself. + */ + buildClass(object: string, state: State): any { + const resolver = Reflect.getMetadata(object, this) as RegistryClass + if (!resolver) { + return object + } + + let r = Object.create(resolver.class_.prototype) + r = Object.assign(r, state) + + return r + } + + /** + * getResult check for the object and method in the registry and call it + * with the given input and state. + * + * This is the function responsible for any module methods execution. + * + * @param object The class to look for + * @param method The method to call in the class + * @param state The current state of the class + * @param inputs The input to send to the method to call + */ + async getResult( + object: string, + method: string, + state: State, + inputs: Args, + ): Promise { + // Retrieve the resolver class from its key + const resolver = Reflect.getMetadata(object, this) as RegistryClass + if (!resolver) { + throw new UnknownDaggerError( + `${object} is not register as a resolver`, + {}, + ) + } + + // If method is nil, apply the constructor. + if (method === "") { + return new resolver.class_(...Object.values(inputs)) + } + + // Instantiate the class without calling the constructor + let r = Object.create(resolver.class_.prototype) + + // Safety check to make sure the method called exist in the class + // to avoid the app to crash brutally. + if (!r[method]) { + throw new UnknownDaggerError( + `${method} is not registered in the resolver ${object}`, + {}, + ) + } + + // Apply state to the class + r = Object.assign(r, state) + + // Execute and return the result + return await r[method](...Object.values(inputs)) + } +} + +/** + * The default registry used in any module. + */ +export const registry = new Registry() + +/** + * Retrieve a class registered via the `@object()` decorator by its name. + * + * Useful for generated code (e.g. the static dispatch entrypoint) when the + * user's class isn't `export`'d but still needs to be reachable to construct + * instances and walk its prototype. + */ +export function getRegisteredClass(name: string): Class | undefined { + const meta = Reflect.getMetadata(name, registry) as RegistryClass | undefined + return meta?.class_ +} diff --git a/library/src/provisioning/.gitattributes b/library/src/provisioning/.gitattributes new file mode 100644 index 0000000..ab08022 --- /dev/null +++ b/library/src/provisioning/.gitattributes @@ -0,0 +1 @@ +/default.ts linguist-generated=true diff --git a/library/src/provisioning/bin.ts b/library/src/provisioning/bin.ts new file mode 100644 index 0000000..034269d --- /dev/null +++ b/library/src/provisioning/bin.ts @@ -0,0 +1,620 @@ +import AdmZip from "adm-zip" +import * as crypto from "crypto" +import envPaths from "env-paths" +import { execa, ResultPromise } from "execa" +import * as fs from "fs" +import { GraphQLClient } from "graphql-request" +import fetch from "node-fetch" +import * as os from "os" +import * as path from "path" +import * as process from "process" +import readline from "readline" +import * as tar from "tar" +import { fileURLToPath } from "url" + +import { + EngineSessionConnectionTimeoutError, + EngineSessionConnectParamsParseError, + EngineSessionError, + InitEngineSessionBinaryError, +} from "../common/errors/index.js" +import { createGQLClient } from "../common/graphql/client.js" +import { ConnectOpts, EngineConn, ConnectParams } from "./engineconn.js" + +let OVERRIDE_CLI_URL: string = "" +let OVERRIDE_CHECKSUMS_URL: string = "" +const CLI_HOST = "dl.dagger.io" + +class CLIReleaseUnavailableError extends Error { + constructor(message: string) { + super(message) + this.name = "CLIReleaseUnavailableError" + } +} + +export type ExecaChildProcess = ResultPromise<{ + stdio: "pipe" + reject: true + cleanup: true +}> + +/** + * Bin runs an engine session from a specified binary + */ +export class Bin implements EngineConn { + private _subProcess?: ExecaChildProcess + + private binPath?: string + private cliVersion?: string + + private readonly cacheDir = envPaths("dagger", { suffix: "" }).cache + + private readonly DAGGER_CLI_BIN_PREFIX = "dagger" + + constructor(binPath?: string, cliVersion?: string) { + this.binPath = binPath + this.cliVersion = cliVersion + } + + Addr(): string { + return "http://dagger" + } + + get subProcess(): ExecaChildProcess | undefined { + return this._subProcess + } + + async Connect(opts: ConnectOpts): Promise { + let downloadError: Error | undefined + + if (!this.binPath) { + try { + this.binPath = await this.downloadCLI(opts.LogOutput) + } catch (e) { + downloadError = e instanceof Error ? e : new Error(String(e)) + this.binPath = this.fallbackToLocalCLI(downloadError, opts.LogOutput) + } + } + + try { + return await this.runEngineSession(this.binPath, opts) + } catch (e) { + if (downloadError) { + const sessionError = e instanceof Error ? e : new Error(String(e)) + throw new AggregateError( + [downloadError, sessionError], + `${downloadError.message}\nfailed to use CLI from PATH "${this.binPath}": ${sessionError.message}`, + { cause: e }, + ) + } + throw e + } + } + + private async downloadCLI( + logOutput?: NodeJS.WritableStream, + ): Promise { + if (!this.cliVersion) { + throw new Error("cliVersion is not set") + } + + const binPath = this.buildBinPath() + + // Create a temporary bin file path + this.createCacheDir() + const tmpBinDownloadDir = fs.mkdtempSync( + path.join(this.cacheDir, `temp-${this.getRandomId()}`), + ) + const tmpBinPath = this.buildOsExePath( + tmpBinDownloadDir, + this.DAGGER_CLI_BIN_PREFIX, + ) + + try { + const expectedChecksum = await this.expectedChecksum() + + if (logOutput) { + logOutput.write("Downloading CLI... ") + } + + // download an archive and use appropriate extraction depending on platforms (zip on windows, tar.gz on other platforms) + const actualChecksum: string = await this.extractArchive( + tmpBinDownloadDir, + this.normalizedOS(), + ) + if (actualChecksum !== expectedChecksum) { + throw new Error( + `checksum mismatch: expected ${expectedChecksum}, got ${actualChecksum}`, + ) + } + fs.chmodSync(tmpBinPath, 0o700) + fs.renameSync(tmpBinPath, binPath) + fs.rmSync(tmpBinDownloadDir, { recursive: true }) + + if (logOutput) { + logOutput.write("OK!\n") + } + } catch (e) { + fs.rmSync(tmpBinDownloadDir, { recursive: true }) + throw new InitEngineSessionBinaryError( + `failed to download dagger cli binary: ${e}`, + { + cause: e as Error, + }, + ) + } + + // Remove all temporary binary files + // Ignore current dagger cli or other files that have not be + // created by this SDK. + try { + const files = fs.readdirSync(this.cacheDir) + files.forEach((file) => { + const filePath = path.join(this.cacheDir, file) + if ( + filePath === binPath || + !file.startsWith(this.DAGGER_CLI_BIN_PREFIX) + ) { + return + } + + fs.unlinkSync(filePath) + }) + } catch { + // Log the error but do not interrupt program. + console.error("could not clean up temporary binary files") + } + + return binPath + } + + private fallbackToLocalCLI( + downloadError: Error, + logOutput?: NodeJS.WritableStream, + ): string { + if (!this.hasCLIReleaseUnavailableError(downloadError)) { + throw downloadError + } + + let binPath: string + try { + binPath = this.findDaggerCLI() + } catch (e) { + const pathError = e instanceof Error ? e : new Error(String(e)) + throw new AggregateError( + [downloadError, pathError], + `${downloadError.message}\ndagger CLI not found in PATH: ${pathError.message}`, + { cause: e }, + ) + } + + const warningOutput = logOutput ?? process.stderr + warningOutput.write( + `CLI version ${this.cliVersion} is unavailable; using ${binPath} from PATH (version compatibility is not guaranteed).\n`, + ) + return binPath + } + + private hasCLIReleaseUnavailableError(error: Error): boolean { + const seen = new Set() + let current: Error | undefined = error + + while (current && !seen.has(current)) { + if (current instanceof CLIReleaseUnavailableError) { + return true + } + seen.add(current) + current = current.cause instanceof Error ? current.cause : undefined + } + return false + } + + private findDaggerCLI(): string { + const pathEnv = process.env.PATH + if (!pathEnv) { + throw new Error("PATH is not set") + } + + const platform = this.normalizedOS() + const pathImplementation = platform === "windows" ? path.win32 : path.posix + for (const candidate of this.daggerCLIPathCandidates( + platform, + pathEnv, + process.env.PATHEXT, + )) { + try { + fs.accessSync(candidate, fs.constants.X_OK) + if (!fs.statSync(candidate).isFile()) { + continue + } + } catch { + // Continue searching PATH. + continue + } + if (!pathImplementation.isAbsolute(candidate)) { + throw new Error( + `cannot run dagger executable found relative to the current directory: ${candidate}`, + ) + } + return candidate + } + + throw new Error("dagger executable was not found") + } + + private daggerCLIPathCandidates( + platform: string, + pathEnv: string, + pathExt: string | undefined, + ): string[] { + const windows = platform === "windows" + const pathImplementation = windows ? path.win32 : path.posix + const extensions = windows + ? this.windowsExecutableExtensions(pathExt) + : [""] + const candidates: string[] = [] + + for (let directory of pathEnv.split(pathImplementation.delimiter)) { + if (windows) { + // Match PowerShell and Go's exec.LookPath behavior. + if (directory === "") { + continue + } + directory = directory.replace(/^"(.*)"$/, "$1") + } else if (directory === "") { + // Match Unix shell semantics. + directory = "." + } + + for (const extension of extensions) { + candidates.push( + pathImplementation.join( + directory, + `${this.DAGGER_CLI_BIN_PREFIX}${extension}`, + ), + ) + } + } + return candidates + } + + private windowsExecutableExtensions(pathExt: string | undefined): string[] { + const value = pathExt || ".COM;.EXE;.BAT;.CMD" + return value + .toLowerCase() + .split(";") + .filter((extension) => extension !== "") + .map((extension) => + extension.startsWith(".") ? extension : `.${extension}`, + ) + } + + /** + * Traverse up the directory tree to find the package.json file and return the + * SDK version. + * @returns the SDK version or "n/a" if the version cannot be found. + */ + private getSDKVersion() { + const currentFileUrl = import.meta.url + const currentFilePath = fileURLToPath(currentFileUrl) + let currentPath = path.dirname(currentFilePath) + + while (currentPath !== path.parse(currentPath).root) { + const packageJsonPath = path.join(currentPath, "package.json") + if (fs.existsSync(packageJsonPath)) { + try { + const packageJsonContent = fs.readFileSync(packageJsonPath, "utf8") + const packageJson = JSON.parse(packageJsonContent) + return packageJson.version + } catch { + return "n/a" + } + } else { + currentPath = path.join(currentPath, "..") + } + } + } + + /** + * runEngineSession execute the engine binary and set up a GraphQL client that + * target this engine. + */ + private async runEngineSession( + binPath: string, + opts: ConnectOpts, + ): Promise { + const args = ["session"] + + const sdkVersion = this.getSDKVersion() + + const flagsAndValues = [ + { flag: "--workdir", value: opts.Workdir }, + { flag: "--project", value: opts.Project }, + { flag: "--label", value: "dagger.io/sdk.name:nodejs" }, + { flag: "--label", value: `dagger.io/sdk.version:${sdkVersion}` }, + ] + + flagsAndValues.forEach((pair) => { + if (pair.value) { + args.push(pair.flag, pair.value) + } + }) + + if (opts.LoadWorkspaceModules) { + args.push("--load-workspace-modules") + } + + if (opts.LogOutput) { + opts.LogOutput.write("Creating new Engine session... ") + } + + this._subProcess = execa(binPath, args, { + stdio: "pipe", + reject: true, + + // Kill the process if parent exit. + cleanup: true, + + // Set a long timeout to give time for any cache exports to pack layers up + // which currently has to happen synchronously with the session. + forceKillAfterDelay: 300000, + }) + + // Log the output if the user wants to. + if (opts.LogOutput) { + this._subProcess.stderr?.pipe(opts.LogOutput) + } + + const stdoutReader = readline.createInterface({ + input: this._subProcess?.stdout as NodeJS.ReadableStream, + }) + + const timeOutDuration = 300000 + + if (opts.LogOutput) { + opts.LogOutput.write("OK!\nEstablishing connection to Engine... ") + } + + const connectParams: ConnectParams = (await Promise.race([ + this.readConnectParams(stdoutReader), + new Promise((_, reject) => { + setTimeout(() => { + reject( + new EngineSessionConnectionTimeoutError( + "Engine connection timeout", + { + timeOutDuration, + }, + ), + ) + }, timeOutDuration).unref() // long timeout to account for extensions, though that should be optimized in future + }), + ])) as ConnectParams + + if (opts.LogOutput) { + opts.LogOutput.write("OK!\n") + } + + return createGQLClient(connectParams.port, connectParams.session_token) + } + + private async readConnectParams( + stdoutReader: readline.Interface, + ): Promise { + for await (const line of stdoutReader) { + // parse the line as json-encoded connect params + const connectParams = JSON.parse(line) as ConnectParams + if (connectParams.port && connectParams.session_token) { + return connectParams + } + throw new EngineSessionConnectParamsParseError( + `invalid connect params: ${line}`, + { + parsedLine: line, + }, + ) + } + + // Need to find a better way to handle this part + // At this stage something wrong happened, `for await` didn't return anything + // await the subprocess to catch the error + try { + await this.subProcess + } catch { + this.subProcess?.catch((e) => { + throw new EngineSessionError(e.stderr) + }) + } + } + + async Close(): Promise { + if (this.subProcess?.pid) { + this.subProcess.kill("SIGTERM") + } + } + + /** + * createCacheDir will create a cache directory on user + * host to store dagger binary. + * + * If set, it will use envPaths to determine system's cache directory, + * if not, it will use `$HOME/.cache` as base path. + * Nothing happens if the directory already exists. + */ + private createCacheDir(): void { + fs.mkdirSync(this.cacheDir, { mode: 0o700, recursive: true }) + } + + /** + * buildBinPath create a path to output dagger cli binary. + * + * It will store it in the cache directory with a name composed + * of the base engine session as constant and the engine identifier. + */ + private buildBinPath(): string { + return this.buildOsExePath( + this.cacheDir, + `${this.DAGGER_CLI_BIN_PREFIX}-${this.cliVersion}`, + ) + } + + /** + * buildExePath create a path to output dagger cli binary. + */ + private buildOsExePath(destinationDir: string, filename: string): string { + const binPath = path.join(destinationDir, filename) + + switch (this.normalizedOS()) { + case "windows": + return `${binPath}.exe` + default: + return binPath + } + } + + /** + * normalizedArch returns the architecture name used by the rest of our SDKs. + */ + private normalizedArch(): string { + switch (os.arch()) { + case "x64": + return "amd64" + default: + return os.arch() + } + } + + /** + * normalizedOS returns the os name used by the rest of our SDKs. + */ + private normalizedOS(): string { + switch (os.platform()) { + case "win32": + return "windows" + default: + return os.platform() + } + } + + private cliArchiveName(): string { + if (OVERRIDE_CLI_URL && OVERRIDE_CLI_URL != "") { + return path.basename(new URL(OVERRIDE_CLI_URL).pathname) + } + let ext = "tar.gz" + if (this.normalizedOS() === "windows") { + ext = "zip" + } + return `dagger_v${this.cliVersion}_${this.normalizedOS()}_${this.normalizedArch()}.${ext}` + } + + private cliArchiveURL(): string { + if (OVERRIDE_CLI_URL && OVERRIDE_CLI_URL != "") { + return OVERRIDE_CLI_URL + } + return `https://${CLI_HOST}/dagger/releases/${this.cliVersion}/${this.cliArchiveName()}` + } + + private cliChecksumURL(): string { + if (OVERRIDE_CHECKSUMS_URL && OVERRIDE_CHECKSUMS_URL != "") { + return OVERRIDE_CHECKSUMS_URL + } + return `https://${CLI_HOST}/dagger/releases/${this.cliVersion}/checksums.txt` + } + + private async checksumMap(): Promise> { + // download checksums.txt + const checksums = await fetch(this.cliChecksumURL()) + if (!checksums.ok) { + const message = `failed to download checksums.txt from ${this.cliChecksumURL()}: ${checksums.status} ${checksums.statusText}` + if (this.isCLIReleaseUnavailable(checksums.status)) { + throw new CLIReleaseUnavailableError(message) + } + throw new Error(message) + } + const checksumsText = await checksums.text() + // iterate over lines filling in map of filename -> checksum + const checksumMap = new Map() + for (const line of checksumsText.split("\n")) { + const [checksum, filename] = line.split(/\s+/) + checksumMap.set(filename, checksum) + } + return checksumMap + } + + private isCLIReleaseUnavailable(status: number): boolean { + // dl.dagger.io returns 403 for missing S3 objects. + return status === 403 || status === 404 + } + + private async expectedChecksum(): Promise { + const checksumMap = await this.checksumMap() + const expectedChecksum = checksumMap.get(this.cliArchiveName()) + if (!expectedChecksum) { + throw new Error( + `failed to find checksum for ${this.cliArchiveName()} in checksums.txt`, + ) + } + return expectedChecksum + } + + private async extractArchive(destDir: string, os: string): Promise { + // extract the dagger binary in the cli archive and return the archive of the .zip for windows and .tar.gz for other plateforms + const archiveResp = await fetch(this.cliArchiveURL()) + if (!archiveResp.ok) { + throw new Error( + `failed to download dagger cli archive from ${this.cliArchiveURL()}`, + ) + } + if (!archiveResp.body) { + throw new Error("archive response body is null") + } + + // create a temporary file to store the archive + const archivePath = path.join( + destDir, + os === "windows" ? "dagger.zip" : "dagger.tar.gz", + ) + const archiveFile = fs.createWriteStream(archivePath) + await new Promise((resolve, reject) => { + archiveResp.body?.pipe(archiveFile) + archiveResp.body?.on("error", reject) + archiveFile.on("finish", () => resolve(undefined)) + }) + + const actualChecksum = crypto + .createHash("sha256") + .update(fs.readFileSync(archivePath)) + .digest("hex") + + if (os === "windows") { + const zip = new AdmZip(archivePath) + // extract just dagger.exe to the destdir + zip.extractEntryTo("dagger.exe", destDir, false, true) + } else { + tar.extract({ + cwd: destDir, + file: archivePath, + sync: true, + }) + } + + return actualChecksum + } + + /** + * Generate a unix timestamp in nanosecond + */ + private getRandomId(): string { + return process.hrtime.bigint().toString() + } +} + +// Only meant for tests +export function _overrideCLIURL(url: string): void { + OVERRIDE_CLI_URL = url +} + +// Only meant for tests +export function _overrideCLIChecksumsURL(url: string): void { + OVERRIDE_CHECKSUMS_URL = url +} diff --git a/library/src/provisioning/default.ts b/library/src/provisioning/default.ts new file mode 100644 index 0000000..0d245a9 --- /dev/null +++ b/library/src/provisioning/default.ts @@ -0,0 +1,2 @@ +// Code generated by dagger. DO NOT EDIT. +export const CLI_VERSION = "1.0.0-beta.9" diff --git a/library/src/provisioning/engineconn.ts b/library/src/provisioning/engineconn.ts new file mode 100644 index 0000000..7b136d0 --- /dev/null +++ b/library/src/provisioning/engineconn.ts @@ -0,0 +1,34 @@ +import { GraphQLClient } from "graphql-request" +import { Writable } from "node:stream" + +export interface ConnectOpts { + Workdir?: string + Project?: string + LogOutput?: Writable + LoadWorkspaceModules?: boolean + Timeout?: number +} + +export interface ConnectParams { + port: number + session_token: string +} + +export interface EngineConn { + /** + * Library connection provisioning, it returns a ready to use GraphQL client + * connected to the Dagger engine. + * + * This test multiple options to connect to the Dagger Engine. + * 1. Check for already running engine through `DAGGER_SESSION_PORT` & `DAGGER_SESSION_TOKEN` + * environment variable. + * 2. Auto provision the engine from the Dagger CLI (install it if it doesn't exist) and + * connect the client. + */ + Connect: (opts: ConnectOpts) => Promise + + /** + * Close stops the current connection. + */ + Close: () => void +} diff --git a/library/src/provisioning/index.ts b/library/src/provisioning/index.ts new file mode 100644 index 0000000..4f4cba9 --- /dev/null +++ b/library/src/provisioning/index.ts @@ -0,0 +1,22 @@ +import { GraphQLClient } from "graphql-request" + +import { ConnectOpts } from "../connectOpts.js" +import { Bin } from "./bin.js" +import { CLI_VERSION } from "./default.js" + +export async function withEngineSession( + connectOpts: ConnectOpts, + cb: (gqlClient: GraphQLClient) => Promise, +): Promise { + const cliBin = process.env["_EXPERIMENTAL_DAGGER_CLI_BIN"] + const engineConn = new Bin(cliBin, CLI_VERSION) + const gqlClient = await engineConn.Connect(connectOpts) + + try { + const res = await cb(gqlClient) + + return res + } finally { + await engineConn.Close() + } +} diff --git a/library/src/telemetry/index.ts b/library/src/telemetry/index.ts new file mode 100644 index 0000000..f5f59a4 --- /dev/null +++ b/library/src/telemetry/index.ts @@ -0,0 +1,3 @@ +import { getTracer } from "./telemetry.js" + +export { getTracer } diff --git a/library/src/telemetry/init.ts b/library/src/telemetry/init.ts new file mode 100644 index 0000000..cd221d4 --- /dev/null +++ b/library/src/telemetry/init.ts @@ -0,0 +1,105 @@ +import { getBooleanFromEnv } from "@opentelemetry/core" +import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto" +import { NodeSDK } from "@opentelemetry/sdk-node" +import { + BatchSpanProcessor, + type SpanProcessor, +} from "@opentelemetry/sdk-trace-base" + +import { LiveProcessor } from "./live_processor.js" + +const SERVICE_NAME = "dagger-typescript-sdk" + +/* + * Look for variables prefixed with OTel to see if OpenTelemetry is configured. + */ +function otelConfigured(): boolean { + return Object.keys(process.env).some((key) => key.startsWith("OTEL_")) +} +/** + * Batch span processor scheduler delays. + * We set to 100ms so it's almost live. + */ +const NEARLY_IMMEDIATE = 100 + +/** + * A wrapper around the OpenTelemetry SDK to configure it for Dagger. + */ +export class DaggerOtelConfigurator { + private is_configured = false + + private sdk?: NodeSDK + + /** + * Initialize the Open Telemetry SDK if enabled or not already configured. + */ + initialize() { + if (this.is_configured) { + return + } + this.configure() + this.is_configured = true + } + + configure() { + if (!otelConfigured()) { + return + } + + if (getBooleanFromEnv("OTEL_SDK_DISABLED") ?? true) { + return + } + + this.setupEnv() + + const exporter = new OTLPTraceExporter() + + let processor: SpanProcessor + if (process.env.OTEL_EXPORTER_OTLP_TRACES_LIVE !== undefined) { + processor = new LiveProcessor(exporter, { + scheduledDelayMillis: NEARLY_IMMEDIATE, + }) + } else { + processor = new BatchSpanProcessor(exporter, { + scheduledDelayMillis: NEARLY_IMMEDIATE, + }) + } + + // Create the node SDK with the context manager, the resource and the exporter. + this.sdk = new NodeSDK({ + serviceName: SERVICE_NAME, + spanProcessors: [processor], + }) + + // Register the SDK to the OpenTelemetry API + this.sdk.start() + } + + /** + * Shutdown the Open Telemetry SDK to flush traces and metrics and close the connection. + */ + async close() { + if (this.sdk) { + await this.sdk.shutdown() + } + } + + /** + * Setup environment for auto-configuring the SDK. + */ + setupEnv() { + // TODO: The insecure flag should be set by the shim instead of the SDK. + Object.entries(process.env).forEach(([key, value]) => { + if ( + key.startsWith("OTEL_") && + key.endsWith("_ENDPOINT") && + value?.startsWith("http://") + ) { + const insecure = key.replace(/_ENDPOINT$/, "_INSECURE") + if (process.env[insecure] === undefined) { + process.env[insecure] = "true" + } + } + }) + } +} diff --git a/library/src/telemetry/live_processor.ts b/library/src/telemetry/live_processor.ts new file mode 100644 index 0000000..a148fb5 --- /dev/null +++ b/library/src/telemetry/live_processor.ts @@ -0,0 +1,15 @@ +import type { Context } from "@opentelemetry/api" +import { BatchSpanProcessor, type Span } from "@opentelemetry/sdk-trace-base" + +/** + * Live span processor implementation. + * + * It's a BatchSpanProcessor whose on_start calls on_end on the underlying + * SpanProcessor in order to send live telemetry. + */ +export class LiveProcessor extends BatchSpanProcessor { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + override onStart(_span: Span, _parentContext: Context): void { + this.onEnd(_span) + } +} diff --git a/library/src/telemetry/telemetry.ts b/library/src/telemetry/telemetry.ts new file mode 100644 index 0000000..adf1814 --- /dev/null +++ b/library/src/telemetry/telemetry.ts @@ -0,0 +1,48 @@ +import * as opentelemetry from "@opentelemetry/api" + +import { DaggerOtelConfigurator } from "./init.js" +import { Tracer } from "./tracer.js" + +const DAGGER_TRACER_NAME = "dagger.io/sdk.typescript" + +const configurator = new DaggerOtelConfigurator() + +export function initialize() { + configurator.initialize() +} + +export async function close() { + await configurator.close() +} + +/** + * Return a tracer to use with Dagger. + * + * The tracer is automatically initialized if not already done. + * As a conveniance function, you can use `withTracingSpan` that automatically close + * the span at the end of the function. + * + * You can add a custom name to the tracer based on your application. + */ +export function getTracer(name = DAGGER_TRACER_NAME): Tracer { + initialize() + return new Tracer(name) +} + +export function getContext() { + const ctx = opentelemetry.context.active() + + const spanCtx = opentelemetry.trace.getSpanContext(ctx) + if (spanCtx && opentelemetry.trace.isSpanContextValid(spanCtx)) { + return ctx + } + + const parentID = process.env.TRACEPARENT + if (parentID) { + return opentelemetry.propagation.extract(ctx, { + traceparent: parentID, + }) + } + + return ctx +} diff --git a/library/src/telemetry/tracer.ts b/library/src/telemetry/tracer.ts new file mode 100644 index 0000000..8ab57b3 --- /dev/null +++ b/library/src/telemetry/tracer.ts @@ -0,0 +1,64 @@ +import * as opentelemetry from "@opentelemetry/api" + +/** + * Tracer encapsulates the OpenTelemetry Tracer. + */ +export class Tracer { + private tracer: opentelemetry.Tracer + + constructor(name: string) { + this.tracer = opentelemetry.trace.getTracer(name) + } + + public startSpan( + name: string, + attributes?: opentelemetry.Attributes, + ): opentelemetry.Span { + return this.tracer.startSpan(name, { attributes }) + } + + /** + * Execute the functions with a custom span with the given name using startActiveSpan. + * The function executed will use the parent context of the function (it can be another span + * or the main function). + * + * @param name The name of the span + * @param fn The functions to execute + * + * startActiveSpan returns the result of the executed functions. + * + * The span is automatically ended when the function is done. + * The span is automatically marked as an error if the function throws an error. + * + * + * @example + * ``` + * return getTracer().startActiveSpan(name, async () => { + * return this.containerEcho("test").stdout() + * }) + * ``` + */ + public async startActiveSpan( + name: string, + fn: (span: opentelemetry.Span) => Promise, + attributes?: opentelemetry.Attributes, + ) { + return this.tracer.startActiveSpan(name, { attributes }, async (span) => { + try { + return await fn(span) + } catch (e) { + if (e instanceof Error) { + span.recordException(e) + span.setStatus({ + code: opentelemetry.SpanStatusCode.ERROR, + message: e.message, + }) + } + + throw e + } finally { + span.end() + } + }) + } +} diff --git a/library/tsconfig.json b/library/tsconfig.json new file mode 100644 index 0000000..7fa2afa --- /dev/null +++ b/library/tsconfig.json @@ -0,0 +1,25 @@ +{ + "include": ["./src/**/*"], + "exclude": [ + "**/testdata/*", + "./src/**/*.spec.ts", + ], + "compilerOptions": { + "target": "ES2022", + "strict": true, + "outDir": "./dist", + "rootDir": ".", + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "module": "Node16", + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "moduleResolution": "Node16", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "declaration": true, + "declarationMap": true + }, + "$schema": "https://json.schemastore.org/tsconfig", + "display": "dagger-nodejs-sdk" +} diff --git a/library/yarn.lock b/library/yarn.lock new file mode 100644 index 0000000..5a1e24d --- /dev/null +++ b/library/yarn.lock @@ -0,0 +1,3007 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@babel/code-frame@^7.27.1": + version "7.27.1" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.27.1.tgz#200f715e66d52a23b221a9435534a91cc13ad5be" + integrity sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg== + dependencies: + "@babel/helper-validator-identifier" "^7.27.1" + js-tokens "^4.0.0" + picocolors "^1.1.1" + +"@babel/code-frame@^7.29.0": + version "7.29.0" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.29.0.tgz#7cd7a59f15b3cc0dcd803038f7792712a7d0b15c" + integrity sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw== + dependencies: + "@babel/helper-validator-identifier" "^7.28.5" + js-tokens "^4.0.0" + picocolors "^1.1.1" + +"@babel/generator@^7.28.0", "@babel/generator@^7.28.5": + version "7.28.5" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.28.5.tgz#712722d5e50f44d07bc7ac9fe84438742dd61298" + integrity sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ== + dependencies: + "@babel/parser" "^7.28.5" + "@babel/types" "^7.28.5" + "@jridgewell/gen-mapping" "^0.3.12" + "@jridgewell/trace-mapping" "^0.3.28" + jsesc "^3.0.2" + +"@babel/helper-globals@^7.28.0": + version "7.28.0" + resolved "https://registry.yarnpkg.com/@babel/helper-globals/-/helper-globals-7.28.0.tgz#b9430df2aa4e17bc28665eadeae8aa1d985e6674" + integrity sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw== + +"@babel/helper-string-parser@^7.27.1": + version "7.27.1" + resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz#54da796097ab19ce67ed9f88b47bb2ec49367687" + integrity sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA== + +"@babel/helper-validator-identifier@^7.27.1": + version "7.27.1" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.27.1.tgz#a7054dcc145a967dd4dc8fee845a57c1316c9df8" + integrity sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow== + +"@babel/helper-validator-identifier@^7.28.5": + version "7.28.5" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz#010b6938fab7cb7df74aa2bbc06aa503b8fe5fb4" + integrity sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q== + +"@babel/parser@^7.27.2", "@babel/parser@^7.28.0", "@babel/parser@^7.28.5": + version "7.28.5" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.28.5.tgz#0b0225ee90362f030efd644e8034c99468893b08" + integrity sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ== + dependencies: + "@babel/types" "^7.28.5" + +"@babel/template@^7.27.2": + version "7.27.2" + resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.27.2.tgz#fa78ceed3c4e7b63ebf6cb39e5852fca45f6809d" + integrity sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw== + dependencies: + "@babel/code-frame" "^7.27.1" + "@babel/parser" "^7.27.2" + "@babel/types" "^7.27.1" + +"@babel/traverse@^7.28.0": + version "7.28.5" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.28.5.tgz#450cab9135d21a7a2ca9d2d35aa05c20e68c360b" + integrity sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ== + dependencies: + "@babel/code-frame" "^7.27.1" + "@babel/generator" "^7.28.5" + "@babel/helper-globals" "^7.28.0" + "@babel/parser" "^7.28.5" + "@babel/template" "^7.27.2" + "@babel/types" "^7.28.5" + debug "^4.3.1" + +"@babel/types@^7.27.1", "@babel/types@^7.28.0", "@babel/types@^7.28.5": + version "7.28.5" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.28.5.tgz#10fc405f60897c35f07e85493c932c7b5ca0592b" + integrity sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA== + dependencies: + "@babel/helper-string-parser" "^7.27.1" + "@babel/helper-validator-identifier" "^7.28.5" + +"@cspotcode/source-map-support@^0.8.0": + version "0.8.1" + resolved "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz" + integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw== + dependencies: + "@jridgewell/trace-mapping" "0.3.9" + +"@dagger.io/mocha@^0.1.0": + version "0.1.0" + resolved "https://registry.yarnpkg.com/@dagger.io/mocha/-/mocha-0.1.0.tgz#d788e6ec1617e7fb12c69f1df2c6f7043b53dc3a" + integrity sha512-PRyQdb1mtUJKz0urCSJKrwtnGYPtIqf5sD5smBwWmAezIn9yqwOZbpX8+jDxVHlhMK9UvdiVNsk3pNzzGtdEmg== + dependencies: + "@dagger.io/telemetry" "^0.0.5" + "@opentelemetry/sdk-node" "^0.209.0" + "@types/mocha" "^10.0.10" + require-in-the-middle "^8.0.1" + +"@dagger.io/telemetry@^0.0.5": + version "0.0.5" + resolved "https://registry.yarnpkg.com/@dagger.io/telemetry/-/telemetry-0.0.5.tgz#9760d27f0169d0ea3bd2681d89590697bd3caec0" + integrity sha512-5W3ojuFghusbdNsI2HQmHjtvSasOsWhkK4Iu7ogU5Ssv+PKkLWPwCKXLipPlQ62WrQzoYXLlORTKT0/kHW6m1Q== + dependencies: + "@opentelemetry/sdk-node" "^0.209.0" + +"@esbuild/aix-ppc64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz#7a01a8d2ec2fbb2dac78adad09b0fa781e4082be" + integrity sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ== + +"@esbuild/android-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz#b540a27d14e4afd058496a4dbec4d3f414db110a" + integrity sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg== + +"@esbuild/android-arm@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.28.1.tgz#704bd297de6d762de54eabbeafbf55f6756abe2f" + integrity sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ== + +"@esbuild/android-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/android-x64/-/android-x64-0.28.1.tgz#d1cb166d34b0fbf0fe8ab460a5594f24a378701e" + integrity sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng== + +"@esbuild/darwin-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz#1034b26457fc886368fe61bbd09f653f6afa8e54" + integrity sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q== + +"@esbuild/darwin-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz#65556a432a1e4d72032d8218c1932fcca1a49772" + integrity sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ== + +"@esbuild/freebsd-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz#2e61e0592f9030d7e3dae18ee25ebc535918aef6" + integrity sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw== + +"@esbuild/freebsd-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz#c95ec289959ef8079c4dca817a1e2c4be66b9bd3" + integrity sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ== + +"@esbuild/linux-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz#40b22175dda06182f3ee8141186c5ff304c4a717" + integrity sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g== + +"@esbuild/linux-arm@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz#c09a0f67917592ac0de892a9be4d3814debd2a6c" + integrity sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ== + +"@esbuild/linux-ia32@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz#a580f9c676797833891e519fc7a1337c8afd8db3" + integrity sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w== + +"@esbuild/linux-loong64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz#46452cf321dc7f9e91c2fa780a56bb56e79cd68b" + integrity sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg== + +"@esbuild/linux-mips64el@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz#4211b3184dd6608f53dcb22e39f5d34ee08852c8" + integrity sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ== + +"@esbuild/linux-ppc64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz#697857c2a61cb9b0b6bb6652e40c1dc5e1ca8e5d" + integrity sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ== + +"@esbuild/linux-riscv64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz#d192943eb146a40ac4c6497d0cf7be35b986bf08" + integrity sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ== + +"@esbuild/linux-s390x@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz#acea0356da0e0ebc08f97cf7b9c2e401e1e648dc" + integrity sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag== + +"@esbuild/linux-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz#6f0c3ce0cb64c534b70c4c45ecb2c16d34e35dfd" + integrity sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA== + +"@esbuild/netbsd-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz#8bcd77077a0dce3378b574fedb26d2a253b73d36" + integrity sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw== + +"@esbuild/netbsd-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz#e7fb2a01e99c830c94e6623cd9fefb4c8fb58347" + integrity sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg== + +"@esbuild/openbsd-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz#c52909372db8b86e2c55e05a8940033b5660a3b2" + integrity sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q== + +"@esbuild/openbsd-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz#c427b9be5a64c262ff9a7eb70b5fbbaadf446c6c" + integrity sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw== + +"@esbuild/openharmony-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz#dc9b147baca2e6c4b3c85571741ef4860a489097" + integrity sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg== + +"@esbuild/sunos-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz#ce866d12df13c15e4c99f073a3d466f6e0649b3a" + integrity sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ== + +"@esbuild/win32-arm64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz#7468e3692d01d629d5941e5d83817bb80f9e39b4" + integrity sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA== + +"@esbuild/win32-ia32@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz#a5bc0063fb2bcab6d0ed63f2a1537958bc269ec6" + integrity sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg== + +"@esbuild/win32-x64@0.28.1": + version "0.28.1" + resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz#10064ee44f4347b90c9a02b446bbf80a91632b12" + integrity sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A== + +"@eslint-community/eslint-utils@^4.8.0", "@eslint-community/eslint-utils@^4.9.1": + version "4.9.1" + resolved "https://registry.yarnpkg.com/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz#4e90af67bc51ddee6cdef5284edf572ec376b595" + integrity sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ== + dependencies: + eslint-visitor-keys "^3.4.3" + +"@eslint-community/regexpp@^4.12.2": + version "4.12.2" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.12.2.tgz#bccdf615bcf7b6e8db830ec0b8d21c9a25de597b" + integrity sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew== + +"@eslint/config-array@^0.23.5": + version "0.23.5" + resolved "https://registry.yarnpkg.com/@eslint/config-array/-/config-array-0.23.5.tgz#56e86d243049195d8acc0c06a1b3dfdc3fa3de95" + integrity sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA== + dependencies: + "@eslint/object-schema" "^3.0.5" + debug "^4.3.1" + minimatch "^10.2.4" + +"@eslint/config-helpers@^0.6.0": + version "0.6.0" + resolved "https://registry.yarnpkg.com/@eslint/config-helpers/-/config-helpers-0.6.0.tgz#ef9a36881d39dfd5dbeac22b0da997fabfb08b03" + integrity sha512-ii6Bw9jJ2zi2cWA2Z+9/QZ/+3DX6kwaV5Q986D/CdP3Lap3w/pgQZ373FV7byY/i7L4IRH/G43I5dz1ClsCbpA== + dependencies: + "@eslint/core" "^1.2.1" + +"@eslint/core@^1.2.1": + version "1.2.1" + resolved "https://registry.yarnpkg.com/@eslint/core/-/core-1.2.1.tgz#c1da7cd1b82fa8787f98b5629fb811848a1b63ce" + integrity sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ== + dependencies: + "@types/json-schema" "^7.0.15" + +"@eslint/js@^10.0.1": + version "10.0.1" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-10.0.1.tgz#1e8a876f50117af8ab67e47d5ad94d38d6622583" + integrity sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA== + +"@eslint/object-schema@^3.0.5": + version "3.0.5" + resolved "https://registry.yarnpkg.com/@eslint/object-schema/-/object-schema-3.0.5.tgz#88e9bf4d11d2b19c082e78ebe7ce88724a5eb091" + integrity sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw== + +"@eslint/plugin-kit@^0.7.2": + version "0.7.2" + resolved "https://registry.yarnpkg.com/@eslint/plugin-kit/-/plugin-kit-0.7.2.tgz#4b0962f3f2c7ce8bc98b3ecfe34525c09d2cb729" + integrity sha512-+CNAzxglkrpNf/kKywqQfk74QjtceuOE7Qm+AF8miRvPF/wmmK5+OJOgVh3AVTT3RP2mH3+FOaxlE5v72owk0A== + dependencies: + "@eslint/core" "^1.2.1" + levn "^0.4.1" + +"@graphql-typed-document-node/core@^3.2.0": + version "3.2.0" + resolved "https://registry.npmjs.org/@graphql-typed-document-node/core/-/core-3.2.0.tgz" + integrity sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ== + +"@grpc/grpc-js@1.14.4", "@grpc/grpc-js@^1.14.3", "@grpc/grpc-js@^1.14.4", "@grpc/grpc-js@^1.7.1": + version "1.14.4" + resolved "https://registry.yarnpkg.com/@grpc/grpc-js/-/grpc-js-1.14.4.tgz#e73ff57d97802f063999545f43ebb2b1eca65d9d" + integrity sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ== + dependencies: + "@grpc/proto-loader" "^0.8.0" + "@js-sdsl/ordered-map" "^4.4.2" + +"@grpc/proto-loader@^0.8.0": + version "0.8.0" + resolved "https://registry.yarnpkg.com/@grpc/proto-loader/-/proto-loader-0.8.0.tgz#b6c324dd909c458a0e4aa9bfd3d69cf78a4b9bd8" + integrity sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ== + dependencies: + lodash.camelcase "^4.3.0" + long "^5.0.0" + protobufjs "^7.5.3" + yargs "^17.7.2" + +"@humanfs/core@^0.19.1": + version "0.19.1" + resolved "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz" + integrity sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA== + +"@humanfs/node@^0.16.6": + version "0.16.6" + resolved "https://registry.npmjs.org/@humanfs/node/-/node-0.16.6.tgz" + integrity sha512-YuI2ZHQL78Q5HbhDiBA1X4LmYdXCKCMQIfw0pw7piHJwyREFebJUvrQN4cMssyES6x+vfUbx1CIpaQUKYdQZOw== + dependencies: + "@humanfs/core" "^0.19.1" + "@humanwhocodes/retry" "^0.3.0" + +"@humanwhocodes/module-importer@^1.0.1": + version "1.0.1" + resolved "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz" + integrity sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA== + +"@humanwhocodes/retry@^0.3.0": + version "0.3.0" + resolved "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.3.0.tgz" + integrity sha512-d2CGZR2o7fS6sWB7DG/3a95bGKQyHMACZ5aW8qGkkqQpUoZV6C0X7Pc7l4ZNMZkfNBf4VWNe9E1jRsf0G146Ew== + +"@humanwhocodes/retry@^0.4.2": + version "0.4.2" + resolved "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.2.tgz" + integrity sha512-xeO57FpIu4p1Ri3Jq/EXq4ClRm86dVF2z/+kvFnyqVYRavTZmaFaUBbWCOuuTh0o/g7DSsk6kc2vrS4Vl5oPOQ== + +"@isaacs/cliui@^8.0.2": + version "8.0.2" + resolved "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz" + integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA== + dependencies: + string-width "^5.1.2" + string-width-cjs "npm:string-width@^4.2.0" + strip-ansi "^7.0.1" + strip-ansi-cjs "npm:strip-ansi@^6.0.1" + wrap-ansi "^8.1.0" + wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" + +"@isaacs/fs-minipass@^4.0.0": + version "4.0.1" + resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" + integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== + dependencies: + minipass "^7.0.4" + +"@jridgewell/gen-mapping@^0.3.12", "@jridgewell/gen-mapping@^0.3.5": + version "0.3.13" + resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" + integrity sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA== + dependencies: + "@jridgewell/sourcemap-codec" "^1.5.0" + "@jridgewell/trace-mapping" "^0.3.24" + +"@jridgewell/remapping@^2.3.5": + version "2.3.5" + resolved "https://registry.yarnpkg.com/@jridgewell/remapping/-/remapping-2.3.5.tgz#375c476d1972947851ba1e15ae8f123047445aa1" + integrity sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ== + dependencies: + "@jridgewell/gen-mapping" "^0.3.5" + "@jridgewell/trace-mapping" "^0.3.24" + +"@jridgewell/resolve-uri@^3.0.3", "@jridgewell/resolve-uri@^3.1.0": + version "3.1.2" + resolved "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz" + integrity sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw== + +"@jridgewell/sourcemap-codec@^1.4.10", "@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.5.0", "@jridgewell/sourcemap-codec@^1.5.5": + version "1.5.5" + resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz#6912b00d2c631c0d15ce1a7ab57cd657f2a8f8ba" + integrity sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og== + +"@jridgewell/trace-mapping@0.3.9": + version "0.3.9" + resolved "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz" + integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== + dependencies: + "@jridgewell/resolve-uri" "^3.0.3" + "@jridgewell/sourcemap-codec" "^1.4.10" + +"@jridgewell/trace-mapping@^0.3.24": + version "0.3.25" + resolved "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz" + integrity sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ== + dependencies: + "@jridgewell/resolve-uri" "^3.1.0" + "@jridgewell/sourcemap-codec" "^1.4.14" + +"@jridgewell/trace-mapping@^0.3.28": + version "0.3.31" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz#db15d6781c931f3a251a3dac39501c98a6082fd0" + integrity sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw== + dependencies: + "@jridgewell/resolve-uri" "^3.1.0" + "@jridgewell/sourcemap-codec" "^1.4.14" + +"@js-sdsl/ordered-map@^4.4.2": + version "4.4.2" + resolved "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz" + integrity sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw== + +"@lifeomic/axios-fetch@^3.1.0": + version "3.1.0" + resolved "https://registry.npmjs.org/@lifeomic/axios-fetch/-/axios-fetch-3.1.0.tgz" + integrity sha512-C6ceAnh8W19KuekFsCiK1A+AMBirQFTnoEqMZQ7HE6VXJ18zjGofdXxLU8RTo2gZp/yZK5ufmPwIvRtejj1gxg== + dependencies: + "@types/node-fetch" "^2.5.10" + +"@opentelemetry/api-logs@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/api-logs/-/api-logs-0.209.0.tgz#5f322cdfd9fded3fb006e5d685a37877caef8464" + integrity sha512-xomnUNi7TiAGtOgs0tb54LyrjRZLu9shJGGwkcN7NgtiPYOpNnKLkRJtzZvTjD/w6knSZH9sFZcUSUovYOPg6A== + dependencies: + "@opentelemetry/api" "^1.3.0" + +"@opentelemetry/api-logs@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/api-logs/-/api-logs-0.219.0.tgz#3303f10f43e6ff1741f8f6019e43a92723781630" + integrity sha512-FFx7YnaYJlIjqWW/AG/yAZ0L/NEY724PipXXXQLdtZPbLwBGbUMTGL1i/esI56TWfTUXxhLfpgrnWJCG8aUJyg== + dependencies: + "@opentelemetry/api" "^1.3.0" + +"@opentelemetry/api@^1.3.0", "@opentelemetry/api@^1.9.1": + version "1.9.1" + resolved "https://registry.yarnpkg.com/@opentelemetry/api/-/api-1.9.1.tgz#c1b0346de336ba55af2d5a7970882037baedec05" + integrity sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q== + +"@opentelemetry/configuration@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/configuration/-/configuration-0.209.0.tgz#1b38bf570af2a3e025171e166e128bf7b526a983" + integrity sha512-naJLdv5PDvz2CEZh0XfLM5vZgPc/y+Xr4UW+Gj6jm3AkcGaknIUHSD54lA3G3s6Y32mkQbhlxMTbM97KUwsogQ== + dependencies: + "@opentelemetry/core" "2.3.0" + yaml "^2.0.0" + +"@opentelemetry/configuration@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/configuration/-/configuration-0.219.0.tgz#cb950aaa77bdb921a3fd636dc792f8beb712be17" + integrity sha512-wXZUYv4ngu43nA4WEhuXNacm46LW+17LRM8nKyIhBzroRA24PBYjMnakwzR/w777nFUB5xlgsYTTeuXxumZM1Q== + dependencies: + "@opentelemetry/core" "2.8.0" + yaml "^2.0.0" + +"@opentelemetry/context-async-hooks@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/context-async-hooks/-/context-async-hooks-2.3.0.tgz#0188115066cf2a5e7d65244f40a0ebf1cb6e5787" + integrity sha512-hGcsT0qDP7Il1L+qT3JFpiGl1dCjF794Bb4yCRCYdr7XC0NwHtOF3ngF86Gk6TUnsakbyQsDQ0E/S4CU0F4d4g== + +"@opentelemetry/context-async-hooks@2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/context-async-hooks/-/context-async-hooks-2.8.0.tgz#24381ef388bc28d53fa8dad72dfd1429acc82016" + integrity sha512-/3FIraneMcng67SUJCxvyInk/oxzwsxyadufk0wwfOBLf5wqtAGX4MoQASwSbndBPeARzBryUM9Azr5kHIdWLw== + +"@opentelemetry/core@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/core/-/core-2.3.0.tgz#7c01a73973072d3a7a466cd723f257f06b1a8811" + integrity sha512-PcmxJQzs31cfD0R2dE91YGFcLxOSN4Bxz7gez5UwSUjCai8BwH/GI5HchfVshHkWdTkUs0qcaPJgVHKXUp7I3A== + dependencies: + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/core@2.8.0", "@opentelemetry/core@^2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/core/-/core-2.8.0.tgz#f6e86de3688bdb54a6ca8f4935363a5b588ae91c" + integrity sha512-hd1Lfh8p545nNz+jq1Ejfz+Mn1hyLuxYn1YzTfFNrxr8urEWMNQLPf1Th8kjOH+HxwawCrtgBp8JpBUR4ZSgww== + dependencies: + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/exporter-jaeger@^2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-jaeger/-/exporter-jaeger-2.8.0.tgz#9ea71246710570fc3375d235a04d39c3227e9103" + integrity sha512-fPXK9zj/gKCOFM30MMmVhiVBrF831dSCoja7gX24FBcBl8h2H+mwgr+RYqcGlBXNihhmxI6iS1RMchYZjqTzkg== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + jaeger-client "^3.15.0" + +"@opentelemetry/exporter-logs-otlp-grpc@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.209.0.tgz#fa3911fb5d0f8f3a210bdb335bb4a35142eed868" + integrity sha512-dQFCxgti3PDjjulxi9tGKqh86YQOZoVKy21m1fEJX9lEn+Afq1Qo1lR86+8Bc+PuBA9EFs1csAV8Z7BNuOvCPA== + dependencies: + "@grpc/grpc-js" "^1.7.1" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-grpc-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/sdk-logs" "0.209.0" + +"@opentelemetry/exporter-logs-otlp-grpc@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.219.0.tgz#d828e7495d05c54fd51a6495094eaf9e485805c1" + integrity sha512-7SvzDCIclHWAcCwZ1MTOLcwn4BVNPGI3QxS/DJraPNe1TTL+4TvUBq5zeQV8tsnYvtDN7wKW2qocVmaCP2l7sQ== + dependencies: + "@grpc/grpc-js" "^1.14.3" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-grpc-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/sdk-logs" "0.219.0" + +"@opentelemetry/exporter-logs-otlp-http@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.209.0.tgz#49a79dc1509299694e4716f05f94fe4439549b21" + integrity sha512-8sI1bDnoIRzCmT5zX2pNY2I+jD0UEoBr54dzvuzi1oz8Tt0Q9H6d8Bfn5+WoJJaGByewbSwoe8EtaBgSK74jKQ== + dependencies: + "@opentelemetry/api-logs" "0.209.0" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/sdk-logs" "0.209.0" + +"@opentelemetry/exporter-logs-otlp-http@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.219.0.tgz#3a4764ec408efdf9c573cfc3e4ffc41392694d3b" + integrity sha512-mhl2HL6GmZI8b8PwPfqMws/5ovJfbRTxwc9Y5agVVHiQ+e5SL1btsFr/kJDgt7YCexDtsUn5HAreHQO9szFS0A== + dependencies: + "@opentelemetry/api-logs" "0.219.0" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/sdk-logs" "0.219.0" + +"@opentelemetry/exporter-logs-otlp-proto@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.209.0.tgz#a5f18188292410af2d3c14cdbeea7649550578c4" + integrity sha512-wf8Nt5BTyT6ZjKA7c9zMhTTcsPedVXQ+j2oTuKB2uzvr13zgVrbRJ2U4Z6jBoiYst4d+qR7Iga7rGI51KWrjbw== + dependencies: + "@opentelemetry/api-logs" "0.209.0" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-logs" "0.209.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + +"@opentelemetry/exporter-logs-otlp-proto@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.219.0.tgz#de0431c17a944928471ffab1dcea9e02e70271ac" + integrity sha512-Ayw4Gf71PS9jhBVaYywa4WsajnqfDehMkTdVH3TSAVHqPcsAv/AhH/wTNRYNt99szeYr6Gbd/D6RjZD77wAxHg== + dependencies: + "@opentelemetry/api-logs" "0.219.0" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-logs" "0.219.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + +"@opentelemetry/exporter-metrics-otlp-grpc@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.209.0.tgz#9bd3d028501993e247637926d962928ed6c49b07" + integrity sha512-YaqQlwSbpyS3yHyVdY7D/FNjq8XzJw9cshyDs++HkPXK7fTat9NqbBio33n3zx1rEW+eEdHzlnaSxkATZxBa5w== + dependencies: + "@grpc/grpc-js" "^1.7.1" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/exporter-metrics-otlp-http" "0.209.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-grpc-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-metrics" "2.3.0" + +"@opentelemetry/exporter-metrics-otlp-grpc@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.219.0.tgz#b9d1ede26f45adfbcbf087dd7d4065dfc1268121" + integrity sha512-6LaaSrPxK5L55bXevWajvOMxGOpNm0n12tG53TeZaUeNzXwLPg6d2KCC1zAlGsojan+xRG71mA4Qqs9K2VVrKQ== + dependencies: + "@grpc/grpc-js" "^1.14.3" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/exporter-metrics-otlp-http" "0.219.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-grpc-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-metrics" "2.8.0" + +"@opentelemetry/exporter-metrics-otlp-http@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.209.0.tgz#3825983e8af8800bc081beba8e44eb43dc21b23f" + integrity sha512-XVRnuoaQJ9UNNk6Us/GTs20B+dN6gq0q/pb2Is72XJPnVjszLGyNoteQrlexDFos1OS6vnmTs/FnmIvcrsYy5A== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-metrics" "2.3.0" + +"@opentelemetry/exporter-metrics-otlp-http@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.219.0.tgz#aed2238678486434cff020cbdfef07b24f1370b6" + integrity sha512-6CaDRbMVHZSDWzNXwrR8y/H4B/Z1eMNnkHiPQlTx3Ojz2OHY4X/aff/UC4P/3pHUQSuTfi3oh2UsPPZppw+Vrg== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-metrics" "2.8.0" + +"@opentelemetry/exporter-metrics-otlp-proto@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.209.0.tgz#614e989b9593a46ff766d0618f3340998d36d1cd" + integrity sha512-XyN2inpV9N1OP0Nq+lEjYnf5W6tx2xC4cNxSJ9QI4E+EpY5ND6tRenVSsPOtNbAaWEsH2Bny+I90WUei7UW0MA== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/exporter-metrics-otlp-http" "0.209.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-metrics" "2.3.0" + +"@opentelemetry/exporter-metrics-otlp-proto@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.219.0.tgz#7a7a20dba913f00c115fb48901502680c41e23dc" + integrity sha512-DUS7XyIiEnoeccQUvuKy0G2/YqeKhpN8FVIrGbrLNIVMj10yeIFLRzRv0tibCI2kXXvlTTABVexGAk78wHk2ug== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/exporter-metrics-otlp-http" "0.219.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-metrics" "2.8.0" + +"@opentelemetry/exporter-prometheus@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.209.0.tgz#71a47b2066124be24770576a921bd4083d1353bd" + integrity sha512-+exk5rU32/OFvvgdT4g8OV4jyuhON4tzLXXhEYBPQv0WrlcD6DJT2iw4F+2QLiMONOIgSV+f0NTo+0HZKFUa/g== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-metrics" "2.3.0" + +"@opentelemetry/exporter-prometheus@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.219.0.tgz#8ea911269156f3cd4f08a1e8e5727df3f316b687" + integrity sha512-TxOnJ85eWJY5JyOJsNMXiRTYlkDcOv0u3KbXEzWCc+tUS9sjL/BC6BcdxZ0B9r2OFVqsrZFXUzSD2sZUy42Ucw== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-metrics" "2.8.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/exporter-trace-otlp-grpc@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.209.0.tgz#8ec646a30fdd386a7d2be87c6aa46deb493e81eb" + integrity sha512-UVPX9BGDpqc6on4TaWEB8kZl8ofKtuD+/l1uorEqeU4agl1iHjPFHcn39u4Q5DrArSKK+8Ob7yIM0wLehvJkhQ== + dependencies: + "@grpc/grpc-js" "^1.7.1" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-grpc-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + +"@opentelemetry/exporter-trace-otlp-grpc@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.219.0.tgz#ef421636a3e360b4e8e1d26a2cae0d6f49c5187a" + integrity sha512-BkDNv1UD6BscW19MxbAxVmSYSSFuyeqR6buV2/HTYqA7GrR0EbTFzqG6h86T3PtXmpdbsWjMGLDdjG2rikG27Q== + dependencies: + "@grpc/grpc-js" "^1.14.3" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-grpc-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + +"@opentelemetry/exporter-trace-otlp-http@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.209.0.tgz#5cc17df6e483901ae9b5a71c11ed86aa83909dfd" + integrity sha512-mqTGX3brr+aoDZgrx+m/9OKgCAh/Ufv0OpqmozN9L9z39IGtkvcMMjFGio061PjOB9fBzrsB8jYapYscVeve2g== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + +"@opentelemetry/exporter-trace-otlp-http@0.219.0", "@opentelemetry/exporter-trace-otlp-http@^0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.219.0.tgz#37ad13bd871fe5d983754bb2ad2e2ac2f3e167ec" + integrity sha512-9t6SvBXXBEjOBcIzgozvBbd3jWrv3Gt3ngGhl1fhdZ/zRc7oZDVOFEqbi2zlBpW9BXhgDMKv422J0DL/3iQWfw== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + +"@opentelemetry/exporter-trace-otlp-proto@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.209.0.tgz#d13878fa4d5be04e6c8ea7c589988d88bf6dab3d" + integrity sha512-+bZvcwc/XahdFor3Wa3Yz8HmTkQLzZh369XuHWuujrkrkC0bW3/7ZfViWUR7lieneuTu2BWFbMu3N1wj2euCAg== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + +"@opentelemetry/exporter-trace-otlp-proto@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.219.0.tgz#cec3c1da46bb3ac5774461830634d6509b797bf1" + integrity sha512-lF/LUBfhOFmxJa+SQsLN7ziV4MHa2pyKgOM6JNehSOfU+npjM4gwm9oIKEJrzrWcexMcqydiyoFy0XCb1Ql3wQ== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + +"@opentelemetry/exporter-zipkin@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-zipkin/-/exporter-zipkin-2.3.0.tgz#e186649ee051d7319e5d2812ffb450ab968fb85e" + integrity sha512-v26Cf5HX7fnKxjiQ7gnKTx0pHuuUNzicIQgFbn9GsD54ozy55+ESQmk4cBUSBOBtnEdUpTx3GEHA65ksJvzRcA== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/exporter-zipkin@2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/exporter-zipkin/-/exporter-zipkin-2.8.0.tgz#03f5ca641f611fc15b9530d2a2ec6238a167bda1" + integrity sha512-Mj84UkEa17BK2o903VTXW3wM8CrSZexGs4tRGVZVIMM9ni1T6TuGx5IrRfoWKAbshx42D5/kc7YV+axypLPYyA== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/instrumentation@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/instrumentation/-/instrumentation-0.209.0.tgz#93bf7dbcd10242c629ebd73d7017287dfecfac90" + integrity sha512-Cwe863ojTCnFlxVuuhG7s6ODkAOzKsAEthKAcI4MDRYz1OmGWYnmSl4X2pbyS+hBxVTdvfZePfoEA01IjqcEyw== + dependencies: + "@opentelemetry/api-logs" "0.209.0" + import-in-the-middle "^2.0.0" + require-in-the-middle "^8.0.0" + +"@opentelemetry/instrumentation@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/instrumentation/-/instrumentation-0.219.0.tgz#84399affd8ee4a12cb199f325c4858654d8dedee" + integrity sha512-X5t7I8GyIO9rmGHwoedZLREpQqrF1WW2nxzNNym6HOKpFiE+rvqV3ngC0xcZVO2YwIGf3KKmRdWrYwdwz3H9RQ== + dependencies: + "@opentelemetry/api-logs" "0.219.0" + import-in-the-middle "^3.0.0" + require-in-the-middle "^8.0.0" + +"@opentelemetry/otlp-exporter-base@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.209.0.tgz#02af0a168516272b59bd0d7b636b1cb05ee0bdf4" + integrity sha512-co5H3wptA8itNf14dOBQBtNlEagMnRf52eo3BC8PwnROrcDfuPw27CjhkxX0+7ywoyOOunwzMWzvig2Qe/Gqlg== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-transformer" "0.209.0" + +"@opentelemetry/otlp-exporter-base@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.219.0.tgz#68f4908f45f6df577d8e1c5b42761645f01cffc5" + integrity sha512-zvIxQX/AZUVKDU+hCuYx+7UkiP7GRdnk1ZbFQRYzHvYp47cAWR4j3IhoPhV9KaeXEv2xdGq3IA6PnpzDmLcmSA== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-transformer" "0.219.0" + +"@opentelemetry/otlp-grpc-exporter-base@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.209.0.tgz#94e444bd87cb5ac0625fcb7cc834ffc59ba2a226" + integrity sha512-4U+9twc/yzTWWFWLaNkL9nl4i163/+y1KuonLY/57IHEdLsSkEW74A1XMRC9+4CgYpRxtEEiT4Gi9yUl49CFJQ== + dependencies: + "@grpc/grpc-js" "^1.7.1" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/otlp-exporter-base" "0.209.0" + "@opentelemetry/otlp-transformer" "0.209.0" + +"@opentelemetry/otlp-grpc-exporter-base@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.219.0.tgz#626713dc38a8879cbc95304832971e6daa889248" + integrity sha512-iIk/s8QQu39zpTrRRmsW/Eg3SE2+Hg8tLWepr2FLRgmwUpNd0IpCTLJEHJ77hpt4hgIS8MAh44UYI4xQPZwWlw== + dependencies: + "@grpc/grpc-js" "^1.14.3" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-transformer" "0.219.0" + +"@opentelemetry/otlp-transformer@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/otlp-transformer/-/otlp-transformer-0.209.0.tgz#692b6decee4b7db08477feb7fa8e3430a984dd8d" + integrity sha512-YITtvJIrzEa1Okbjv9lwJluZVXYM6SuafpQTi0hOTCosa7lu/EA7azvpoJx12EReBZqBm+3Wh0Zabm/01RjNJA== + dependencies: + "@opentelemetry/api-logs" "0.209.0" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-logs" "0.209.0" + "@opentelemetry/sdk-metrics" "2.3.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + protobufjs "8.0.0" + +"@opentelemetry/otlp-transformer@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/otlp-transformer/-/otlp-transformer-0.219.0.tgz#86305b29f564220666f6e410b7eded57bb5e6c3a" + integrity sha512-aaYKAyXhw9VchKZVGOopD3Gw/kPsyrX2c6IQ0AW32mTjqmZOh5Y6Gf5OYqTNqVktAeBjmFinhyFaCwW6GYK9YQ== + dependencies: + "@opentelemetry/api-logs" "0.219.0" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-logs" "0.219.0" + "@opentelemetry/sdk-metrics" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + +"@opentelemetry/propagator-b3@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/propagator-b3/-/propagator-b3-2.3.0.tgz#cefb21f0fc95fd590c782eebbd62ca55268599b0" + integrity sha512-afilfxwb6THEpZknzwDknGR6YL3xe4u7lq8drf18wAdXhtXjK1mHb8DuhbjR55v0j+U1oiToEmAS1TwY4xj46w== + dependencies: + "@opentelemetry/core" "2.3.0" + +"@opentelemetry/propagator-b3@2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/propagator-b3/-/propagator-b3-2.8.0.tgz#d8dadd951831cc96bc2e44eadf04d2b3d1a9b320" + integrity sha512-SazlvuSKi5533rPHTW2TwBwdMakhjZST4SYs0YauuvfGDkT13KbG1gJS75hV0uWVeevhtVP9sAIlaZLTHdSbMg== + dependencies: + "@opentelemetry/core" "2.8.0" + +"@opentelemetry/propagator-jaeger@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/propagator-jaeger/-/propagator-jaeger-2.3.0.tgz#4056de2c3a3fc8a39122a196188a407730e15e2b" + integrity sha512-1SPtVuU5wF9NSrkpdu78B2Nta+Vi7xjRRZ2OGhmV1Ju8TSsTL4LCrty9uBxPdkGI4J/HISwRsaMt8GdM4P3HqA== + dependencies: + "@opentelemetry/core" "2.3.0" + +"@opentelemetry/propagator-jaeger@2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/propagator-jaeger/-/propagator-jaeger-2.8.0.tgz#b8866476fd4a3953dd660a6ab5dc8e2b618dd9e8" + integrity sha512-Xnz9zZvvQzUw+9DrOn0MomR7BxFCkA2pcfXBQuHC28ndJpSbjLs7knzYb05kw5SyCjSsEWombkZMgGcJSk8JVg== + dependencies: + "@opentelemetry/core" "2.8.0" + +"@opentelemetry/resources@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/resources/-/resources-2.3.0.tgz#bfa1c9363b028e322cd4b4d597dc05e8a7cc92a8" + integrity sha512-shlr2l5g+87J8wqYlsLyaUsgKVRO7RtX70Ckd5CtDOWtImZgaUDmf4Z2ozuSKQLM2wPDR0TE/3bPVBNJtRm/cQ== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/resources@2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/resources/-/resources-2.8.0.tgz#9bcb658ab6254f33099f4a95544b40d6f53cc946" + integrity sha512-qmXQ27ilDbUK/vGMqwL8D4/rhn76C+sherM4wTbjlfknR8Nvfc/hCxjRJPhkzZzUsPiNg16SA31NxMabwttRjg== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/sdk-logs@0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-logs/-/sdk-logs-0.209.0.tgz#2f7b4a7e79b678569bcb68792faf3f489fcd59c8" + integrity sha512-dGlYTZaLQaj1GlKWIcWDQofSyKu+Nbq28Rcqo6meQ60OhSune1Wn+dnOQPwQnI6nfhWoTxGR00EJm1UCrkR2Gg== + dependencies: + "@opentelemetry/api-logs" "0.209.0" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/resources" "2.3.0" + +"@opentelemetry/sdk-logs@0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-logs/-/sdk-logs-0.219.0.tgz#002433237908d24fa9e7f17eb4963f25f03d655c" + integrity sha512-s6lTKRakaPClvKoWHRChxnXjDMkM/TQ30ff78jN6EBGf7MI7VzANE5PU3f4z9qDUudWjvZjOLHG0rBnBKYvoXA== + dependencies: + "@opentelemetry/api-logs" "0.219.0" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/sdk-metrics@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-metrics/-/sdk-metrics-2.3.0.tgz#dd15effe00b0654dd40dacf1a7d332262c4e84ea" + integrity sha512-P+bYQgJHf6hRKgsR7xDnbNPDP+x1DwGtse6gHAPZ/iwMGbtQPVvhyFK1lseow5o3kLxNEaQv4lDqAF/vpRdXxA== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/resources" "2.3.0" + +"@opentelemetry/sdk-metrics@2.8.0", "@opentelemetry/sdk-metrics@^2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-metrics/-/sdk-metrics-2.8.0.tgz#c3f908d9e7e02fb855673fcfd4b298ce279e61f1" + integrity sha512-UDBGaj6W0Rgy5rTTaoxs8gVGF/aGkAKyjurJv7se6wjRxJu7FoquTLT/vt54DZfo4crbprYfhX/SOK9+BPw1qg== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/resources" "2.8.0" + +"@opentelemetry/sdk-node@^0.209.0": + version "0.209.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-node/-/sdk-node-0.209.0.tgz#72f15a33a963d6557ff9957a0e8fa504159eb282" + integrity sha512-r1f8i6Gl/hpWnFP6rARBL6ZLOdheJin6HfTwgkjXmLH7T3+Ef7f2ATF8ERyqvP1ESY/gEyeBc0o6dQs3MjaO6Q== + dependencies: + "@opentelemetry/api-logs" "0.209.0" + "@opentelemetry/configuration" "0.209.0" + "@opentelemetry/context-async-hooks" "2.3.0" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/exporter-logs-otlp-grpc" "0.209.0" + "@opentelemetry/exporter-logs-otlp-http" "0.209.0" + "@opentelemetry/exporter-logs-otlp-proto" "0.209.0" + "@opentelemetry/exporter-metrics-otlp-grpc" "0.209.0" + "@opentelemetry/exporter-metrics-otlp-http" "0.209.0" + "@opentelemetry/exporter-metrics-otlp-proto" "0.209.0" + "@opentelemetry/exporter-prometheus" "0.209.0" + "@opentelemetry/exporter-trace-otlp-grpc" "0.209.0" + "@opentelemetry/exporter-trace-otlp-http" "0.209.0" + "@opentelemetry/exporter-trace-otlp-proto" "0.209.0" + "@opentelemetry/exporter-zipkin" "2.3.0" + "@opentelemetry/instrumentation" "0.209.0" + "@opentelemetry/propagator-b3" "2.3.0" + "@opentelemetry/propagator-jaeger" "2.3.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/sdk-logs" "0.209.0" + "@opentelemetry/sdk-metrics" "2.3.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + "@opentelemetry/sdk-trace-node" "2.3.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/sdk-node@^0.219.0": + version "0.219.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-node/-/sdk-node-0.219.0.tgz#a269bfbe122249bcc2027b67cfdcca4bded254b5" + integrity sha512-NWLpWLEb8gV3+JBHYoIrktbM385wyHpRJoh3J/4Q52d4PR+AlPMNGJT3DzBUrDSUEVbKAXoHR+EDAPxtiNcj8g== + dependencies: + "@opentelemetry/api-logs" "0.219.0" + "@opentelemetry/configuration" "0.219.0" + "@opentelemetry/context-async-hooks" "2.8.0" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/exporter-logs-otlp-grpc" "0.219.0" + "@opentelemetry/exporter-logs-otlp-http" "0.219.0" + "@opentelemetry/exporter-logs-otlp-proto" "0.219.0" + "@opentelemetry/exporter-metrics-otlp-grpc" "0.219.0" + "@opentelemetry/exporter-metrics-otlp-http" "0.219.0" + "@opentelemetry/exporter-metrics-otlp-proto" "0.219.0" + "@opentelemetry/exporter-prometheus" "0.219.0" + "@opentelemetry/exporter-trace-otlp-grpc" "0.219.0" + "@opentelemetry/exporter-trace-otlp-http" "0.219.0" + "@opentelemetry/exporter-trace-otlp-proto" "0.219.0" + "@opentelemetry/exporter-zipkin" "2.8.0" + "@opentelemetry/instrumentation" "0.219.0" + "@opentelemetry/otlp-exporter-base" "0.219.0" + "@opentelemetry/otlp-grpc-exporter-base" "0.219.0" + "@opentelemetry/propagator-b3" "2.8.0" + "@opentelemetry/propagator-jaeger" "2.8.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/sdk-logs" "0.219.0" + "@opentelemetry/sdk-metrics" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + "@opentelemetry/sdk-trace-node" "2.8.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/sdk-trace-base@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.3.0.tgz#fa104711bdbf9af68e110a746aa03e711e72fdac" + integrity sha512-B0TQ2e9h0ETjpI+eGmCz8Ojb+lnYms0SE3jFwEKrN/PK4aSVHU28AAmnOoBmfub+I3jfgPwvDJgomBA5a7QehQ== + dependencies: + "@opentelemetry/core" "2.3.0" + "@opentelemetry/resources" "2.3.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/sdk-trace-base@2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.8.0.tgz#ec9c1d69e2e6fba256c9df0c8e8d67d42386d52b" + integrity sha512-mhU4jp+vW0mGbFRd+GeXHvmfA4aDqWjBjLC3pE5XMpLs0IE2ryYb019Ts2AQrOq67gaTF25D91+fgvEHDZEnuQ== + dependencies: + "@opentelemetry/core" "2.8.0" + "@opentelemetry/resources" "2.8.0" + "@opentelemetry/semantic-conventions" "^1.29.0" + +"@opentelemetry/sdk-trace-node@2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.3.0.tgz#e86ca849b809cc9e15321fc1969dcd313e551415" + integrity sha512-oGsG3vIiC8zYjOWE4CgtS6d2gQhp4pT04AI9UL1wtJOxTSNVZiiIPgHnOp/qKJSwkD4YJHSohi6inSilPmGM2Q== + dependencies: + "@opentelemetry/context-async-hooks" "2.3.0" + "@opentelemetry/core" "2.3.0" + "@opentelemetry/sdk-trace-base" "2.3.0" + +"@opentelemetry/sdk-trace-node@2.8.0": + version "2.8.0" + resolved "https://registry.yarnpkg.com/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.8.0.tgz#cbf68f817a15bf4ca5d9ff9fb60ef3a73f61337d" + integrity sha512-nZt9OGufioAc3AfoLTqA9bsAeaMJAictYDdI2VcNQ+PmT+3rfKjAZDZvgPfd8VPX0O5Bw1hdQF6kDK8VSpZiWg== + dependencies: + "@opentelemetry/context-async-hooks" "2.8.0" + "@opentelemetry/core" "2.8.0" + "@opentelemetry/sdk-trace-base" "2.8.0" + +"@opentelemetry/semantic-conventions@^1.29.0", "@opentelemetry/semantic-conventions@^1.41.1": + version "1.41.1" + resolved "https://registry.yarnpkg.com/@opentelemetry/semantic-conventions/-/semantic-conventions-1.41.1.tgz#b04e7151c5913a7a006d4f465479da75efb98a7a" + integrity sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA== + +"@pkgjs/parseargs@^0.11.0": + version "0.11.0" + resolved "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz" + integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== + +"@pkgr/core@^0.3.6": + version "0.3.6" + resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.3.6.tgz#3569708bd4be4d8870ba32bf1c456dac81600d97" + integrity sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA== + +"@protobufjs/aspromise@^1.1.1", "@protobufjs/aspromise@^1.1.2": + version "1.1.2" + resolved "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz" + integrity sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ== + +"@protobufjs/base64@^1.1.2": + version "1.1.2" + resolved "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz" + integrity sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg== + +"@protobufjs/codegen@^2.0.5": + version "2.0.5" + resolved "https://registry.yarnpkg.com/@protobufjs/codegen/-/codegen-2.0.5.tgz#d9315ad7cf3f30aac70bda3c068443dc6f143659" + integrity sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g== + +"@protobufjs/eventemitter@^1.1.1": + version "1.1.1" + resolved "https://registry.yarnpkg.com/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz#d512cb26c0ae026091ee2c1167f1be6faf5c842a" + integrity sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg== + +"@protobufjs/fetch@^1.1.1": + version "1.1.1" + resolved "https://registry.yarnpkg.com/@protobufjs/fetch/-/fetch-1.1.1.tgz#4d6fc00c8fb64016a5c81b469d549046350f1065" + integrity sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw== + dependencies: + "@protobufjs/aspromise" "^1.1.1" + +"@protobufjs/float@^1.0.2": + version "1.0.2" + resolved "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz" + integrity sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ== + +"@protobufjs/inquire@^1.1.2": + version "1.1.2" + resolved "https://registry.yarnpkg.com/@protobufjs/inquire/-/inquire-1.1.2.tgz#ae64fbc014ff44c8bfad03dd4c93cd2d6a4c82db" + integrity sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw== + +"@protobufjs/path@^1.1.2": + version "1.1.2" + resolved "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz" + integrity sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA== + +"@protobufjs/pool@^1.1.0": + version "1.1.0" + resolved "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz" + integrity sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw== + +"@protobufjs/utf8@^1.1.1": + version "1.1.1" + resolved "https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.1.tgz#eaee5900122c110a3dbcb728c0597014a2621774" + integrity sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg== + +"@rollup/rollup-android-arm-eabi@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.2.tgz#5e9849b661c2229cf967a08dbe2dbbe9e8c991e5" + integrity sha512-6o7ZLZK+BeenkZCFNDXqpbjw9bD6nuWonvS/lwQJp7NoVVxm6p3qE7qQ5jGuBjiFsgvqjD8mZAU5oWxTmbOeOg== + +"@rollup/rollup-android-arm64@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.2.tgz#5b0699ee5dd484b222c9ed74aff43c91ea8b17f8" + integrity sha512-BaH7BllCACHoH1LguOU56UItGfUWjujlO65kS9LAodViaN4bwIKd7oeW/ZHJ/4ljr/7MIiENnNy3HJ0zXv8Zkw== + +"@rollup/rollup-darwin-arm64@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.2.tgz#8bc52c9d7a3ce8d0533c351a9c935de781daa06f" + integrity sha512-v39RCCvj4He82I9sFmk+M1VZ0PLM9sfsLVikjfx2hYBNALhrrOR2D3JjQA6AhlaSOgcR+RzrKY7e1+bT6SUO/A== + +"@rollup/rollup-darwin-x64@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.2.tgz#ba2ef3e8fb310f0af35588f270cfa5aa96e48764" + integrity sha512-yl0y2vq3S3lHeuXhEdss6TWfKW8vkujImO12tn4ZkG/4oghr09LvdYm2RElVjokTQiUvDUGXLGsYeLqUMCKpGA== + +"@rollup/rollup-freebsd-arm64@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.2.tgz#93b10bdbfe8ada226b8bc0c02ef6b7f544474d96" + integrity sha512-tT4pvt4qXD+vEoezupCWi+a1F0vvDiksiHc+PxRlYTOH1I6/X4id9jPxTP+Fg+545euaFT1jJVs4CEdHZAU1vw== + +"@rollup/rollup-freebsd-x64@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.2.tgz#3e8aa38ef3c9c300946871e3fdbb0c30e0a20f86" + integrity sha512-6nU5F2wCW+qvCBhTn1pdIU3bzsIoF7EUwsCDRxilWGprQR6yd508YnH9+OKFCwpfS8pjZqDUmnCAr7exax0XCg== + +"@rollup/rollup-linux-arm-gnueabihf@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.2.tgz#1d7994384bb0ad1bc41921b506e1642d4f9d7fc3" + integrity sha512-n1GJHPOvpIfhi3TmrCeh6S6URt9BFCt0KQE3qvexyGCTAKpR4Lg+eWvNZEqu7epxwus/8ElT3hacYEucm49SZg== + +"@rollup/rollup-linux-arm-musleabihf@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.2.tgz#a6540f47cf844a56b80ca9ff95d2acdfb2cef97b" + integrity sha512-JqgflS8wEB+UXV/vS1RpRbifGBeN4D5lz8D8oOFbFZw4vedvdOgCFAjfBmIMdW3yL10XpQQ0Ambepw6MXrhOnA== + +"@rollup/rollup-linux-arm64-gnu@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.2.tgz#404f2045651840cbf48da91ba6d0f490f0bc2cbf" + integrity sha512-wnFJkogWvN4jm/hQRF2UBaeUmk20j5+DmHvoyWii2b8HJDyvz1MF2OU/6ynXt2KR63rbZLWkFpoytpdc/yBuSA== + +"@rollup/rollup-linux-arm64-musl@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.2.tgz#a3404ffddf7b474b48c99b9c893b6247bb765ba5" + integrity sha512-HVu2bp0zhvJ8xHEV9+UUs7S90VadmBSY3LcIMvozbPo4AuMGDWlz3ymHLHZPX4hR67TKTt8Qp5PJ5RBg/i+RMQ== + +"@rollup/rollup-linux-loong64-gnu@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.2.tgz#e8aac6d549b377945e349882f199b7c8eb75ca38" + integrity sha512-mQqqAV8QaoSgr9I2fKDLY2BAVvmKjWoGiu/cSYQonsLvtqwEn1E4QYfnCOcp5zoEqNhsDYin1s6jx/VJmrxlZg== + +"@rollup/rollup-linux-loong64-musl@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.2.tgz#6e2e44ea50310b3a582078a915e5feb879c820d4" + integrity sha512-IxKLoxCQ2IWi6bT2akyDUBGsOImDKB+sPp4EsTmwFQ/fMwpCKm8uLSSgP/Kx/QYUgKis6SEZ5/Nlhup0DIA0PQ== + +"@rollup/rollup-linux-ppc64-gnu@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.2.tgz#6898302da6d77a0537cde64b2b4c6b60659bd110" + integrity sha512-Mk5ha2RQSgyFfmYYLkBpPnUk8D8FriBxesO1u9O75X0mHgXL1UQcH5Itl2lurWL2tj0RxV9b9tJgipac0hRY9A== + +"@rollup/rollup-linux-ppc64-musl@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.2.tgz#333717c95dd5a66bef8f63e7ef8a9fd845fd18d0" + integrity sha512-CjvEnqJL/0/TQ3TXX3OPIJ/kmBellrWd4heXUmHeJlTnmwjKpSJzoehLaL6Xk0ZnMHBu9dZuFADNOrtjF4v+2w== + +"@rollup/rollup-linux-riscv64-gnu@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.2.tgz#81bc06ba380352004d01f4826eb7cdccefa05bad" + integrity sha512-1SiZbzwdkaDURsew/tSOrooKiYy7EQGT6m8ufavAi9NEyQb/6VuIxFXAL1fqa4iZe3g4NbNk4P7J32z2tw5Mgg== + +"@rollup/rollup-linux-riscv64-musl@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.2.tgz#95a7cd39de21389ad6788a5284eaaa738e29ca4c" + integrity sha512-nQts12zJ3NQRoE6uYljOH89v7szzLDvG2JD/vsX+vGXU8w/At1GowTZ5/7qeFQ8m7L55rpR8Okugnuo5bgjy2Q== + +"@rollup/rollup-linux-s390x-gnu@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.2.tgz#06e6db2ec1bc48b5374c7923ef83c2eb024b2452" + integrity sha512-E9/ll019jhPIJgpzfZoIkBGhcz+kKNgVWYRY0zr9srBdPPFVpvOKW8VaJKUbeK+eZXyQF9ltME+Kk6affeaPgg== + +"@rollup/rollup-linux-x64-gnu@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.2.tgz#5dc818988285e09e88790c6462def72413df2da3" + integrity sha512-5BqxR/pshjey51iliyzTD5Xi3EN0aLmQ2lZ3lvefVV9c82BvrLo2/6OT55iifpWBufs6kdwWbuOKS841DrmK9A== + +"@rollup/rollup-linux-x64-musl@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.2.tgz#2080f4a93349e9afd34be6fc1a37e01fc8bfc80f" + integrity sha512-uNN83XxQrRAh/w0/pmAfibcwyb6YWt4gP+dpnQKPVJshAloQ785ii8CT8ZCIxkGg9opVsvAlGhFitSm6D1Jjpg== + +"@rollup/rollup-openbsd-x64@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.2.tgz#21d64a8acb66221724b923e51af5333df1af044b" + integrity sha512-srjEIxSH3LRnJN6THczDHWQplqEMFiAJrTab0msUryh9kwNpkICf3Ea6q6MN/2cZwRFUNx5w+h6Hpi4QuHS6Zg== + +"@rollup/rollup-openharmony-arm64@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.2.tgz#8e0fcd9d02141e337b4c5b5cff576cb9a76b1ba0" + integrity sha512-8hOJnxgbyObnCm5AlRA3A931xX19xq80RjVTKgJOvEKWqJruP/Uf12IbAOaDjjEXYRewwHLfmF0YRIdK3OwKWA== + +"@rollup/rollup-win32-arm64-msvc@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.2.tgz#bdb4cc4efd58efe808203347f0f5463f0ea16e52" + integrity sha512-mmF4AY1i0hG/bLWUctUq59gtmgaSIRa3cu/A3JFRp/sCNEme2bgDEiDS22P9FbnJB8NJNF4jPJiSP5RHQpUTDg== + +"@rollup/rollup-win32-ia32-msvc@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.2.tgz#dbaebde5afd24eae0eefe915d901632e7cb59860" + integrity sha512-DZgkknc6jhHrk46V25vbAM0zZkyP0nSDkJB8/dRkLTxv470dOmWDqGoEJl/9A0dFfS7yE3REOwNDxpHwSLSt0Q== + +"@rollup/rollup-win32-x64-gnu@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.2.tgz#84109e85fea5f8f1353499f96578fdc2a0e8b138" + integrity sha512-T6xr6ucWSFto+VGajA8YH26LdpHRuP4YLHEKAtCWvJDOlnmWcDZVCI2Jmjr+IFHDlt2zRaTAKE4tfjTaWLgJBg== + +"@rollup/rollup-win32-x64-msvc@4.62.2": + version "4.62.2" + resolved "https://registry.yarnpkg.com/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.2.tgz#3671ce3f9b928d5c01f879792d5c0b60ae14d4ad" + integrity sha512-BfzEnDJOt9T8M989/lA37EcJgat01wLRnoi5dQf3QzOH7jzpqTAzdDbVfRljVr5r+jzKqpbHeyOfAaXxAd0PAA== + +"@sec-ant/readable-stream@^0.4.1": + version "0.4.1" + resolved "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz" + integrity sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg== + +"@sindresorhus/merge-streams@^4.0.0": + version "4.0.0" + resolved "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-4.0.0.tgz" + integrity sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ== + +"@trivago/prettier-plugin-sort-imports@^6.0.2": + version "6.0.2" + resolved "https://registry.yarnpkg.com/@trivago/prettier-plugin-sort-imports/-/prettier-plugin-sort-imports-6.0.2.tgz#b30948c4d22a84f00ae9133bcabd0603de3c0261" + integrity sha512-3DgfkukFyC/sE/VuYjaUUWoFfuVjPK55vOFDsxD56XXynFMCZDYFogH2l/hDfOsQAm1myoU/1xByJ3tWqtulXA== + dependencies: + "@babel/generator" "^7.28.0" + "@babel/parser" "^7.28.0" + "@babel/traverse" "^7.28.0" + "@babel/types" "^7.28.0" + javascript-natural-sort "^0.7.1" + lodash-es "^4.17.21" + minimatch "^9.0.0" + parse-imports-exports "^0.2.4" + +"@tsconfig/node10@^1.0.7": + version "1.0.11" + resolved "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz" + integrity sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw== + +"@tsconfig/node12@^1.0.7": + version "1.0.11" + resolved "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz" + integrity sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag== + +"@tsconfig/node14@^1.0.0": + version "1.0.3" + resolved "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz" + integrity sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow== + +"@tsconfig/node16@^1.0.2": + version "1.0.4" + resolved "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz" + integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA== + +"@types/adm-zip@^0.5.8": + version "0.5.8" + resolved "https://registry.yarnpkg.com/@types/adm-zip/-/adm-zip-0.5.8.tgz#d4ee920d9fbef78061d039fa7c4776de7a0bb1af" + integrity sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q== + dependencies: + "@types/node" "*" + +"@types/esrecurse@^4.3.1": + version "4.3.1" + resolved "https://registry.yarnpkg.com/@types/esrecurse/-/esrecurse-4.3.1.tgz#6f636af962fbe6191b830bd676ba5986926bccec" + integrity sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw== + +"@types/estree@1.0.9", "@types/estree@^1.0.6", "@types/estree@^1.0.8": + version "1.0.9" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.9.tgz#cf3f0e876d7bee15a93ab925b82bf570a3904a24" + integrity sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg== + +"@types/json-schema@^7.0.15": + version "7.0.15" + resolved "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz" + integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== + +"@types/mocha@^10.0.10": + version "10.0.10" + resolved "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz" + integrity sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q== + +"@types/node-fetch@^2.5.10": + version "2.6.11" + resolved "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz" + integrity sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g== + dependencies: + "@types/node" "*" + form-data "^4.0.0" + +"@types/node@*", "@types/node@>=13.7.0", "@types/node@~26.0.1": + version "26.0.1" + resolved "https://registry.yarnpkg.com/@types/node/-/node-26.0.1.tgz#4a60e2c7a6d68bd261e265f8983bfe1601263ce3" + integrity sha512-fc3KiUoBt6kie0N9bIW3E47vZsuaMf0PM2AaUpLCLT0s/LvX1nxAim6Fc049cNxODPpGm6qRAuUOB86SkRuPQw== + dependencies: + undici-types "~8.3.0" + +"@types/tar@^7.0.87": + version "7.0.87" + resolved "https://registry.yarnpkg.com/@types/tar/-/tar-7.0.87.tgz#c661779e6b3be698965781982a1df1c979af2b87" + integrity sha512-3IxNBV8LeY5oi2ZFpvAhOtW1+mHswkzM7BuisVrwJgPv67GBO2rkLPQlEKtzfHuLdhDDczhkCZeT+RuizMay4A== + dependencies: + tar "*" + +"@typescript-eslint/eslint-plugin@8.62.0", "@typescript-eslint/eslint-plugin@^8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.62.0.tgz#ef482aab65b9b2c0abf92d36d670a0d270bcef4c" + integrity sha512-o+mpz7EYiMzXoySXiKmzlabIvTVqUuK5yLrAedRPRDA0IpPFMUV1IXt6OqljIxX/kumN6EjUYp41Hqelh6p/Dw== + dependencies: + "@eslint-community/regexpp" "^4.12.2" + "@typescript-eslint/scope-manager" "8.62.0" + "@typescript-eslint/type-utils" "8.62.0" + "@typescript-eslint/utils" "8.62.0" + "@typescript-eslint/visitor-keys" "8.62.0" + ignore "^7.0.5" + natural-compare "^1.4.0" + ts-api-utils "^2.5.0" + +"@typescript-eslint/parser@8.62.0", "@typescript-eslint/parser@^8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-8.62.0.tgz#8533094fb44427f50b82813c6d3876782f20dc3e" + integrity sha512-dzHeT2gySzZtLDsuqxU9AkYgIsQoHAHtRBpOqM+Ofzx1Bwrd2RcCjQJ+6iQbsHOIR6NS33bF2W1k3blN1zLDrA== + dependencies: + "@typescript-eslint/scope-manager" "8.62.0" + "@typescript-eslint/types" "8.62.0" + "@typescript-eslint/typescript-estree" "8.62.0" + "@typescript-eslint/visitor-keys" "8.62.0" + debug "^4.4.3" + +"@typescript-eslint/project-service@8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/project-service/-/project-service-8.62.0.tgz#ab74c1abb4959fb4c3ba7d7edc6554ee245db990" + integrity sha512-wexnCqiTg7BOGtbLDftYpRWlmLq4xfoMd7BKFR6Y75sZS3QmRKLdN3yWLhmIYgqMmP/OXWpj3H8odkb5nGURCQ== + dependencies: + "@typescript-eslint/tsconfig-utils" "^8.62.0" + "@typescript-eslint/types" "^8.62.0" + debug "^4.4.3" + +"@typescript-eslint/scope-manager@8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-8.62.0.tgz#a7a7b428d32444bc9a4fe16f24a78fc124283fd4" + integrity sha512-1lX38kNxXIRb8mEc3lbq5mdHq1Pf2+U0nFU65KfT18mtPxxl0fvjuEE92mHuXPuCtElJhOrddOpyMlM3Z0umEA== + dependencies: + "@typescript-eslint/types" "8.62.0" + "@typescript-eslint/visitor-keys" "8.62.0" + +"@typescript-eslint/tsconfig-utils@8.62.0", "@typescript-eslint/tsconfig-utils@^8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.62.0.tgz#9440a673581c6d9de308c4d5803dd52ed5d71729" + integrity sha512-y2GAdB6ykaXUvuspbYnizQc4oDDz0Tz/Yc7iWrXf9mx8vm/L/0vLHCe0tS2boG96Zy+DivnVDQ9ZUEWoHqqx1g== + +"@typescript-eslint/type-utils@8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-8.62.0.tgz#6f64d813ed9f340d796baed40cdab86b8e9a491a" + integrity sha512-+g5O3j0w2ldzC86Pv6fvbO/xhAonbJFIdf/MKQ1d30gndlsVzUOE83ldfSE15Qrl9fhFjK6AovHs5Wpp6vx86w== + dependencies: + "@typescript-eslint/types" "8.62.0" + "@typescript-eslint/typescript-estree" "8.62.0" + "@typescript-eslint/utils" "8.62.0" + debug "^4.4.3" + ts-api-utils "^2.5.0" + +"@typescript-eslint/types@8.62.0", "@typescript-eslint/types@^8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-8.62.0.tgz#601427c10203d9f0f34f0b3e474df735eb12b593" + integrity sha512-KvAclkktORPvM54TgLgA4z9HIV1M8zOgw9ZVNXl9f/8dLYfXYX1wkMXP7qmabpijQRV5bHJLOmoyGQbLMaUYeg== + +"@typescript-eslint/typescript-estree@8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.62.0.tgz#b96b55d02e26aa09434421c3fa678e525ca09a4c" + integrity sha512-+hVbNxtW64pIcZWDPGbyaKF7vp2IBTVY5ma1blwwksrjdsbdqqEKvJWMGbBofei4F6Dovx1M0RJgoFeNu2279A== + dependencies: + "@typescript-eslint/project-service" "8.62.0" + "@typescript-eslint/tsconfig-utils" "8.62.0" + "@typescript-eslint/types" "8.62.0" + "@typescript-eslint/visitor-keys" "8.62.0" + debug "^4.4.3" + minimatch "^10.2.2" + semver "^7.7.3" + tinyglobby "^0.2.15" + ts-api-utils "^2.5.0" + +"@typescript-eslint/utils@8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-8.62.0.tgz#b5228524ca1ee51af40e156c82d425dec3e01cfe" + integrity sha512-82r66fi9zYwZ+mTq3vKgwjbZ1PVk/DJzrXFLpG6RnBbdvH8TEGVHIs9H4d2drhkOzf0syZuD/OZvvlu6GDbP4g== + dependencies: + "@eslint-community/eslint-utils" "^4.9.1" + "@typescript-eslint/scope-manager" "8.62.0" + "@typescript-eslint/types" "8.62.0" + "@typescript-eslint/typescript-estree" "8.62.0" + +"@typescript-eslint/visitor-keys@8.62.0": + version "8.62.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.62.0.tgz#b6daab190bf8f18612f5b86323469a12288c6b31" + integrity sha512-CY3uyFSRbcQv3nnSv8S0+lDftMVz6P963PoRlxrV7ew/Md564g9ut60PYzdLM5qW4jFn93GBF+Soi90ISAN+GQ== + dependencies: + "@typescript-eslint/types" "8.62.0" + eslint-visitor-keys "^5.0.0" + +acorn-import-attributes@^1.9.5: + version "1.9.5" + resolved "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz" + integrity sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ== + +acorn-jsx@^5.3.2: + version "5.3.2" + resolved "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz" + integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== + +acorn-walk@^8.1.1: + version "8.3.3" + resolved "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.3.tgz" + integrity sha512-MxXdReSRhGO7VlFe1bRG/oI7/mdLV9B9JJT0N8vZOhF7gFRR5l3M8W9G8JxmKV+JC5mGqJ0QvqfSOLsCPa4nUw== + dependencies: + acorn "^8.11.0" + +acorn@^8.11.0, acorn@^8.15.0, acorn@^8.4.1: + version "8.15.0" + resolved "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz" + integrity sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg== + +acorn@^8.16.0: + version "8.16.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.16.0.tgz#4ce79c89be40afe7afe8f3adb902a1f1ce9ac08a" + integrity sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw== + +adm-zip@^0.5.18: + version "0.5.18" + resolved "https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.5.18.tgz#283a05f2bf1e3fd315f0f31cde29b7a6e3c1619d" + integrity sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng== + +ajv@^6.14.0: + version "6.14.0" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.14.0.tgz#fd067713e228210636ebb08c60bd3765d6dbe73a" + integrity sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw== + dependencies: + fast-deep-equal "^3.1.1" + fast-json-stable-stringify "^2.0.0" + json-schema-traverse "^0.4.1" + uri-js "^4.2.2" + +ansi-color@^0.2.1: + version "0.2.1" + resolved "https://registry.npmjs.org/ansi-color/-/ansi-color-0.2.1.tgz" + integrity sha512-bF6xLaZBLpOQzgYUtYEhJx090nPSZk1BQ/q2oyBK9aMMcJHzx9uXGCjI2Y+LebsN4Jwoykr0V9whbPiogdyHoQ== + +ansi-regex@^5.0.1: + version "5.0.1" + resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz" + integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== + +ansi-regex@^6.0.1: + version "6.0.1" + resolved "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.0.1.tgz" + integrity sha512-n5M855fKb2SsfMIiFFoVrABHJC8QtHwVx+mHWP3QcEqBHYienj5dHSgjbxtC0WEZXYt4wcD6zrQElDPhFuZgfA== + +ansi-styles@^4.0.0, ansi-styles@^4.1.0: + version "4.3.0" + resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz" + integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== + dependencies: + color-convert "^2.0.1" + +ansi-styles@^6.1.0: + version "6.2.1" + resolved "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz" + integrity sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug== + +arg@^4.1.0: + version "4.1.3" + resolved "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz" + integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA== + +argparse@^2.0.1: + version "2.0.1" + resolved "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz" + integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== + +asynckit@^0.4.0: + version "0.4.0" + resolved "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz" + integrity sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q== + +balanced-match@^1.0.0: + version "1.0.2" + resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz" + integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== + +balanced-match@^4.0.2: + version "4.0.3" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-4.0.3.tgz#6337a2f23e0604a30481423432f99eac603599f9" + integrity sha512-1pHv8LX9CpKut1Zp4EXey7Z8OfH11ONNH6Dhi2WDUt31VVZFXZzKwXcysBgqSumFCmR+0dqjMK5v5JiFHzi0+g== + +brace-expansion@^2.0.2: + version "2.1.1" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.1.1.tgz#c68b1c4111c76aae3a6fba55d496cee10c39dad8" + integrity sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA== + dependencies: + balanced-match "^1.0.0" + +brace-expansion@^5.0.2: + version "5.0.2" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-5.0.2.tgz#b6c16d0791087af6c2bc463f52a8142046c06b6f" + integrity sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw== + dependencies: + balanced-match "^4.0.2" + +browser-stdout@^1.3.1: + version "1.3.1" + resolved "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz" + integrity sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw== + +bufrw@^1.2.1: + version "1.4.0" + resolved "https://registry.npmjs.org/bufrw/-/bufrw-1.4.0.tgz" + integrity sha512-sWm8iPbqvL9+5SiYxXH73UOkyEbGQg7kyHQmReF89WJHQJw2eV4P/yZ0E+b71cczJ4pPobVhXxgQcmfSTgGHxQ== + dependencies: + ansi-color "^0.2.1" + error "^7.0.0" + hexer "^1.5.0" + xtend "^4.0.0" + +call-bind-apply-helpers@^1.0.1, call-bind-apply-helpers@^1.0.2: + version "1.0.2" + resolved "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz" + integrity sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ== + dependencies: + es-errors "^1.3.0" + function-bind "^1.1.2" + +camelcase@^6.0.0: + version "6.3.0" + resolved "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz" + integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA== + +chalk@^4.1.0: + version "4.1.2" + resolved "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz" + integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + +chokidar@^4.0.1: + version "4.0.3" + resolved "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz" + integrity sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA== + dependencies: + readdirp "^4.0.1" + +chownr@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" + integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== + +cjs-module-lexer@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-2.2.0.tgz#b3ca5101843389259ade7d88c77bd06ce55849ca" + integrity sha512-4bHTS2YuzUvtoLjdy+98ykbNB5jS0+07EvFNXerqZQJ89F7DI6ET7OQo/HJuW6K0aVsKA9hj9/RVb2kQVOrPDQ== + +cliui@^8.0.1: + version "8.0.1" + resolved "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz" + integrity sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ== + dependencies: + string-width "^4.2.0" + strip-ansi "^6.0.1" + wrap-ansi "^7.0.0" + +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + +combined-stream@^1.0.8: + version "1.0.8" + resolved "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz" + integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== + dependencies: + delayed-stream "~1.0.0" + +convert-source-map@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-2.0.0.tgz#4b560f649fc4e918dd0ab75cf4961e8bc882d82a" + integrity sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg== + +create-require@^1.1.0: + version "1.1.1" + resolved "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz" + integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== + +cross-spawn@^7.0.0, cross-spawn@^7.0.6: + version "7.0.6" + resolved "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz" + integrity sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA== + dependencies: + path-key "^3.1.0" + shebang-command "^2.0.0" + which "^2.0.1" + +data-uri-to-buffer@^4.0.0: + version "4.0.1" + resolved "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz" + integrity sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A== + +debug@^4.3.1, debug@^4.3.2, debug@^4.3.5, debug@^4.4.3: + version "4.4.3" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.3.tgz#c6ae432d9bd9662582fce08709b038c58e9e3d6a" + integrity sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA== + dependencies: + ms "^2.1.3" + +decamelize@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz" + integrity sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ== + +deep-is@^0.1.3: + version "0.1.4" + resolved "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz" + integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ== + +delayed-stream@~1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz" + integrity sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ== + +diff@^4.0.1: + version "4.0.2" + resolved "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz" + integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== + +diff@^7.0.0: + version "7.0.0" + resolved "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz" + integrity sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw== + +dunder-proto@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz" + integrity sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A== + dependencies: + call-bind-apply-helpers "^1.0.1" + es-errors "^1.3.0" + gopd "^1.2.0" + +eastasianwidth@^0.2.0: + version "0.2.0" + resolved "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz" + integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== + +emoji-regex@^8.0.0: + version "8.0.0" + resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz" + integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== + +emoji-regex@^9.2.2: + version "9.2.2" + resolved "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz" + integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== + +env-paths@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-4.0.0.tgz#d0bb1f84a81d2542581bf7b7e8085d0683b39097" + integrity sha512-pxP8eL2SwwaTRi/KHYwLYXinDs7gL3jxFcBYmEdYfZmZXbaVDvdppd0XBU8qVz03rDfKZMXg1omHCbsJjZrMsw== + dependencies: + is-safe-filename "^0.1.0" + +error@7.0.2, error@^7.0.0: + version "7.0.2" + resolved "https://registry.npmjs.org/error/-/error-7.0.2.tgz" + integrity sha512-UtVv4l5MhijsYUxPJo4390gzfZvAnTHreNnDjnTZaKIiZ/SemXxAhBkYSKtWa5RtBXbLP8tMgn/n0RUa/H7jXw== + dependencies: + string-template "~0.2.1" + xtend "~4.0.0" + +es-define-property@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz" + integrity sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g== + +es-errors@^1.3.0: + version "1.3.0" + resolved "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz" + integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw== + +es-object-atoms@^1.0.0, es-object-atoms@^1.1.1: + version "1.1.1" + resolved "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz" + integrity sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA== + dependencies: + es-errors "^1.3.0" + +es-set-tostringtag@^2.1.0: + version "2.1.0" + resolved "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz" + integrity sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA== + dependencies: + es-errors "^1.3.0" + get-intrinsic "^1.2.6" + has-tostringtag "^1.0.2" + hasown "^2.0.2" + +esbuild@0.28.1, esbuild@~0.28.0: + version "0.28.1" + resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.28.1.tgz#ef45b4634c9c9d97a296aea4114a5f9840f95578" + integrity sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw== + optionalDependencies: + "@esbuild/aix-ppc64" "0.28.1" + "@esbuild/android-arm" "0.28.1" + "@esbuild/android-arm64" "0.28.1" + "@esbuild/android-x64" "0.28.1" + "@esbuild/darwin-arm64" "0.28.1" + "@esbuild/darwin-x64" "0.28.1" + "@esbuild/freebsd-arm64" "0.28.1" + "@esbuild/freebsd-x64" "0.28.1" + "@esbuild/linux-arm" "0.28.1" + "@esbuild/linux-arm64" "0.28.1" + "@esbuild/linux-ia32" "0.28.1" + "@esbuild/linux-loong64" "0.28.1" + "@esbuild/linux-mips64el" "0.28.1" + "@esbuild/linux-ppc64" "0.28.1" + "@esbuild/linux-riscv64" "0.28.1" + "@esbuild/linux-s390x" "0.28.1" + "@esbuild/linux-x64" "0.28.1" + "@esbuild/netbsd-arm64" "0.28.1" + "@esbuild/netbsd-x64" "0.28.1" + "@esbuild/openbsd-arm64" "0.28.1" + "@esbuild/openbsd-x64" "0.28.1" + "@esbuild/openharmony-arm64" "0.28.1" + "@esbuild/sunos-x64" "0.28.1" + "@esbuild/win32-arm64" "0.28.1" + "@esbuild/win32-ia32" "0.28.1" + "@esbuild/win32-x64" "0.28.1" + +escalade@^3.1.1: + version "3.1.2" + resolved "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz" + integrity sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA== + +escape-string-regexp@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz" + integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== + +eslint-config-prettier@^10.1.8: + version "10.1.8" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz#15734ce4af8c2778cc32f0b01b37b0b5cd1ecb97" + integrity sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w== + +eslint-plugin-prettier@^5.5.6: + version "5.5.6" + resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.6.tgz#363ebe4d769bce157ccdd8129ce3efd91dc62564" + integrity sha512-ifetmTcxWfz+4qRW3pH/ujdTq2jQIj59AxJMIN26K5avYgU8dxycUETQonWiW+wPrYXA0j3Try0l1CnwVQtDqQ== + dependencies: + prettier-linter-helpers "^1.0.1" + synckit "^0.11.13" + +eslint-scope@^9.1.2: + version "9.1.2" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-9.1.2.tgz#b9de6ace2fab1cff24d2e58d85b74c8fcea39802" + integrity sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ== + dependencies: + "@types/esrecurse" "^4.3.1" + "@types/estree" "^1.0.8" + esrecurse "^4.3.0" + estraverse "^5.2.0" + +eslint-visitor-keys@^3.4.3: + version "3.4.3" + resolved "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz" + integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== + +eslint-visitor-keys@^5.0.0, eslint-visitor-keys@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz#9e3c9489697824d2d4ce3a8ad12628f91e9f59be" + integrity sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA== + +eslint@^10.6.0: + version "10.6.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-10.6.0.tgz#e1b4059c582be950c7088c9b55f984738b243c27" + integrity sha512-6lVbcqSodALYo+4ELD0heG6lFiFxnLMuLkiMi2qV8LMp54N8tE8FT1GMH+ev4Ti00nFjNze2+Su6DsV5OQW3Dg== + dependencies: + "@eslint-community/eslint-utils" "^4.8.0" + "@eslint-community/regexpp" "^4.12.2" + "@eslint/config-array" "^0.23.5" + "@eslint/config-helpers" "^0.6.0" + "@eslint/core" "^1.2.1" + "@eslint/plugin-kit" "^0.7.2" + "@humanfs/node" "^0.16.6" + "@humanwhocodes/module-importer" "^1.0.1" + "@humanwhocodes/retry" "^0.4.2" + "@types/estree" "^1.0.6" + ajv "^6.14.0" + cross-spawn "^7.0.6" + debug "^4.3.2" + escape-string-regexp "^4.0.0" + eslint-scope "^9.1.2" + eslint-visitor-keys "^5.0.1" + espree "^11.2.0" + esquery "^1.7.0" + esutils "^2.0.2" + fast-deep-equal "^3.1.3" + file-entry-cache "^8.0.0" + find-up "^5.0.0" + glob-parent "^6.0.2" + ignore "^5.2.0" + imurmurhash "^0.1.4" + is-glob "^4.0.0" + json-stable-stringify-without-jsonify "^1.0.1" + minimatch "^10.2.4" + natural-compare "^1.4.0" + optionator "^0.9.3" + +espree@^11.2.0: + version "11.2.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-11.2.0.tgz#01d5e47dc332aaba3059008362454a8cc34ccaa5" + integrity sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw== + dependencies: + acorn "^8.16.0" + acorn-jsx "^5.3.2" + eslint-visitor-keys "^5.0.1" + +esquery@^1.7.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.7.0.tgz#08d048f261f0ddedb5bae95f46809463d9c9496d" + integrity sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g== + dependencies: + estraverse "^5.1.0" + +esrecurse@^4.3.0: + version "4.3.0" + resolved "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz" + integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== + dependencies: + estraverse "^5.2.0" + +estraverse@^5.1.0, estraverse@^5.2.0: + version "5.3.0" + resolved "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz" + integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== + +esutils@^2.0.2: + version "2.0.3" + resolved "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz" + integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== + +execa@^9.6.1: + version "9.6.1" + resolved "https://registry.yarnpkg.com/execa/-/execa-9.6.1.tgz#5b90acedc6bdc0fa9b9a6ddf8f9cbb0c75a7c471" + integrity sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA== + dependencies: + "@sindresorhus/merge-streams" "^4.0.0" + cross-spawn "^7.0.6" + figures "^6.1.0" + get-stream "^9.0.0" + human-signals "^8.0.1" + is-plain-obj "^4.1.0" + is-stream "^4.0.1" + npm-run-path "^6.0.0" + pretty-ms "^9.2.0" + signal-exit "^4.1.0" + strip-final-newline "^4.0.0" + yoctocolors "^2.1.1" + +fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: + version "3.1.3" + resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" + integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== + +fast-diff@^1.1.2: + version "1.3.0" + resolved "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz" + integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== + +fast-json-stable-stringify@^2.0.0: + version "2.1.0" + resolved "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz" + integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== + +fast-levenshtein@^2.0.6: + version "2.0.6" + resolved "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz" + integrity sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw== + +fdir@^6.5.0: + version "6.5.0" + resolved "https://registry.yarnpkg.com/fdir/-/fdir-6.5.0.tgz#ed2ab967a331ade62f18d077dae192684d50d350" + integrity sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg== + +fetch-blob@^3.1.2, fetch-blob@^3.1.4: + version "3.2.0" + resolved "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz" + integrity sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ== + dependencies: + node-domexception "^1.0.0" + web-streams-polyfill "^3.0.3" + +figures@^6.1.0: + version "6.1.0" + resolved "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz" + integrity sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg== + dependencies: + is-unicode-supported "^2.0.0" + +file-entry-cache@^8.0.0: + version "8.0.0" + resolved "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz" + integrity sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ== + dependencies: + flat-cache "^4.0.0" + +find-up@^5.0.0: + version "5.0.0" + resolved "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz" + integrity sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng== + dependencies: + locate-path "^6.0.0" + path-exists "^4.0.0" + +flat-cache@^4.0.0: + version "4.0.1" + resolved "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz" + integrity sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw== + dependencies: + flatted "^3.2.9" + keyv "^4.5.4" + +flat@^5.0.2: + version "5.0.2" + resolved "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz" + integrity sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ== + +flatted@^3.2.9: + version "3.3.1" + resolved "https://registry.npmjs.org/flatted/-/flatted-3.3.1.tgz" + integrity sha512-X8cqMLLie7KsNUDSdzeN8FYK9rEt4Dt67OsG/DNGnYTSDBG4uFAJFBnUeiV+zCVAvwFy56IjM9sH51jVaEhNxw== + +foreground-child@^3.1.0: + version "3.2.1" + resolved "https://registry.npmjs.org/foreground-child/-/foreground-child-3.2.1.tgz" + integrity sha512-PXUUyLqrR2XCWICfv6ukppP96sdFwWbNEnfEMt7jNsISjMsvaLNinAHNDYyvkyU+SZG2BTSbT5NjG+vZslfGTA== + dependencies: + cross-spawn "^7.0.0" + signal-exit "^4.0.1" + +form-data@4.0.6, form-data@^4.0.0: + version "4.0.6" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.6.tgz#28e864e1b786dbebb68db1f452f9635278665827" + integrity sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ== + dependencies: + asynckit "^0.4.0" + combined-stream "^1.0.8" + es-set-tostringtag "^2.1.0" + hasown "^2.0.4" + mime-types "^2.1.35" + +formdata-polyfill@^4.0.10: + version "4.0.10" + resolved "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz" + integrity sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g== + dependencies: + fetch-blob "^3.1.2" + +fsevents@~2.3.2, fsevents@~2.3.3: + version "2.3.3" + resolved "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz" + integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== + +function-bind@^1.1.2: + version "1.1.2" + resolved "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz" + integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA== + +get-caller-file@^2.0.5: + version "2.0.5" + resolved "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz" + integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== + +get-intrinsic@^1.2.6: + version "1.3.0" + resolved "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz" + integrity sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ== + dependencies: + call-bind-apply-helpers "^1.0.2" + es-define-property "^1.0.1" + es-errors "^1.3.0" + es-object-atoms "^1.1.1" + function-bind "^1.1.2" + get-proto "^1.0.1" + gopd "^1.2.0" + has-symbols "^1.1.0" + hasown "^2.0.2" + math-intrinsics "^1.1.0" + +get-proto@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz" + integrity sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g== + dependencies: + dunder-proto "^1.0.1" + es-object-atoms "^1.0.0" + +get-stream@^9.0.0: + version "9.0.1" + resolved "https://registry.npmjs.org/get-stream/-/get-stream-9.0.1.tgz" + integrity sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA== + dependencies: + "@sec-ant/readable-stream" "^0.4.1" + is-stream "^4.0.1" + +glob-parent@^6.0.2: + version "6.0.2" + resolved "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz" + integrity sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A== + dependencies: + is-glob "^4.0.3" + +glob@^10.4.5: + version "10.5.0" + resolved "https://registry.yarnpkg.com/glob/-/glob-10.5.0.tgz#8ec0355919cd3338c28428a23d4f24ecc5fe738c" + integrity sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg== + dependencies: + foreground-child "^3.1.0" + jackspeak "^3.1.2" + minimatch "^9.0.4" + minipass "^7.1.2" + package-json-from-dist "^1.0.0" + path-scurry "^1.11.1" + +gopd@^1.2.0: + version "1.2.0" + resolved "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz" + integrity sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg== + +graphql-request@^7.4.0: + version "7.4.0" + resolved "https://registry.yarnpkg.com/graphql-request/-/graphql-request-7.4.0.tgz#97a1fc871e79f682d816963446ac6b7f99c963f9" + integrity sha512-xfr+zFb/QYbs4l4ty0dltqiXIp07U6sl+tOKAb0t50/EnQek6CVVBLjETXi+FghElytvgaAWtIOt3EV7zLzIAQ== + dependencies: + "@graphql-typed-document-node/core" "^3.2.0" + +graphql-tag@^2.12.7: + version "2.12.7" + resolved "https://registry.yarnpkg.com/graphql-tag/-/graphql-tag-2.12.7.tgz#4c82de0af91679b1940f149819fc8351801ed130" + integrity sha512-xnE/NFzy+0eIesvAsREJZ284zTl/wYuBAvpsFSDhRGRdRHdnE90M21Q3xAWyYInb0J756c6x0pIQ62+vtvOs1Q== + dependencies: + tslib "^2.1.0" + +graphql@^17.0.1: + version "17.0.1" + resolved "https://registry.yarnpkg.com/graphql/-/graphql-17.0.1.tgz#43dbd7b152944c31dab264212f102894886e5f9f" + integrity sha512-8eWbg5Zcv/8o20nzEjHUGPTj20MLFJjc5kagbIPxbaeGxvFwpitJhemEC/k17n5+UD4M/9ea5rTuce78mELujQ== + +has-flag@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz" + integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== + +has-symbols@^1.0.3, has-symbols@^1.1.0: + version "1.1.0" + resolved "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz" + integrity sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ== + +has-tostringtag@^1.0.2: + version "1.0.2" + resolved "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz" + integrity sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw== + dependencies: + has-symbols "^1.0.3" + +hasown@^2.0.2: + version "2.0.2" + resolved "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz" + integrity sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ== + dependencies: + function-bind "^1.1.2" + +hasown@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/hasown/-/hasown-2.0.4.tgz#8c62d8cb90beb2aad5d0a5b67581ad9854c3f003" + integrity sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A== + dependencies: + function-bind "^1.1.2" + +he@^1.2.0: + version "1.2.0" + resolved "https://registry.npmjs.org/he/-/he-1.2.0.tgz" + integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== + +hexer@^1.5.0: + version "1.5.0" + resolved "https://registry.npmjs.org/hexer/-/hexer-1.5.0.tgz" + integrity sha512-dyrPC8KzBzUJ19QTIo1gXNqIISRXQ0NwteW6OeQHRN4ZuZeHkdODfj0zHBdOlHbRY8GqbqK57C9oWSvQZizFsg== + dependencies: + ansi-color "^0.2.1" + minimist "^1.1.0" + process "^0.10.0" + xtend "^4.0.0" + +human-signals@^8.0.1: + version "8.0.1" + resolved "https://registry.npmjs.org/human-signals/-/human-signals-8.0.1.tgz" + integrity sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ== + +ignore@^5.2.0: + version "5.3.1" + resolved "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz" + integrity sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw== + +ignore@^7.0.5: + version "7.0.5" + resolved "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz" + integrity sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg== + +import-in-the-middle@^2.0.0: + version "2.0.6" + resolved "https://registry.yarnpkg.com/import-in-the-middle/-/import-in-the-middle-2.0.6.tgz#1972337bfe020d05f6b5e020c13334567436324f" + integrity sha512-3vZV3jX0XRFW3EJDTwzWoZa+RH1b8eTTx6YOCjglrLyPuepwoBti1k3L2dKwdCUrnVEfc5CuRuGstaC/uQJJaw== + dependencies: + acorn "^8.15.0" + acorn-import-attributes "^1.9.5" + cjs-module-lexer "^2.2.0" + module-details-from-path "^1.0.4" + +import-in-the-middle@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/import-in-the-middle/-/import-in-the-middle-3.0.0.tgz#720c12b4c07ea58b32a54667e70a022e18cc36a3" + integrity sha512-OnGy+eYT7wVejH2XWgLRgbmzujhhVIATQH0ztIeRilwHBjTeG3pD+XnH3PKX0r9gJ0BuJmJ68q/oh9qgXnNDQg== + dependencies: + acorn "^8.15.0" + acorn-import-attributes "^1.9.5" + cjs-module-lexer "^2.2.0" + module-details-from-path "^1.0.4" + +imurmurhash@^0.1.4: + version "0.1.4" + resolved "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz" + integrity sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA== + +is-extglob@^2.1.1: + version "2.1.1" + resolved "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz" + integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== + +is-fullwidth-code-point@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz" + integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== + +is-glob@^4.0.0, is-glob@^4.0.3: + version "4.0.3" + resolved "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz" + integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== + dependencies: + is-extglob "^2.1.1" + +is-path-inside@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/is-path-inside/-/is-path-inside-3.0.3.tgz#d231362e53a07ff2b0e0ea7fed049161ffd16283" + integrity sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ== + +is-plain-obj@^2.1.0: + version "2.1.0" + resolved "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz" + integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA== + +is-plain-obj@^4.1.0: + version "4.1.0" + resolved "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz" + integrity sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg== + +is-safe-filename@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-safe-filename/-/is-safe-filename-0.1.1.tgz#fb22eead097c614c47aa674de5d79a1648a53e66" + integrity sha512-4SrR7AdnY11LHfDKTZY1u6Ga3RuxZdl3YKWWShO5iyuG5h8QS4GD2tOb04peBJ5I7pXbR+CGBNEhTcwK+FzN3g== + +is-stream@^4.0.1: + version "4.0.1" + resolved "https://registry.npmjs.org/is-stream/-/is-stream-4.0.1.tgz" + integrity sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A== + +is-unicode-supported@^0.1.0: + version "0.1.0" + resolved "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz" + integrity sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw== + +is-unicode-supported@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.0.0.tgz" + integrity sha512-FRdAyx5lusK1iHG0TWpVtk9+1i+GjrzRffhDg4ovQ7mcidMQ6mj+MhKPmvh7Xwyv5gIS06ns49CA7Sqg7lC22Q== + +isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz" + integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== + +jackspeak@^3.1.2: + version "3.4.3" + resolved "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz" + integrity sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw== + dependencies: + "@isaacs/cliui" "^8.0.2" + optionalDependencies: + "@pkgjs/parseargs" "^0.11.0" + +jaeger-client@^3.15.0: + version "3.19.0" + resolved "https://registry.npmjs.org/jaeger-client/-/jaeger-client-3.19.0.tgz" + integrity sha512-M0c7cKHmdyEUtjemnJyx/y9uX16XHocL46yQvyqDlPdvAcwPDbHrIbKjQdBqtiE4apQ/9dmr+ZLJYYPGnurgpw== + dependencies: + node-int64 "^0.4.0" + opentracing "^0.14.4" + thriftrw "^3.5.0" + uuid "^8.3.2" + xorshift "^1.1.1" + +javascript-natural-sort@^0.7.1: + version "0.7.1" + resolved "https://registry.npmjs.org/javascript-natural-sort/-/javascript-natural-sort-0.7.1.tgz" + integrity sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw== + +js-tokens@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz" + integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== + +js-yaml@^4.1.0: + version "4.1.0" + resolved "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz" + integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA== + dependencies: + argparse "^2.0.1" + +jsesc@^3.0.2: + version "3.1.0" + resolved "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz" + integrity sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA== + +json-buffer@3.0.1: + version "3.0.1" + resolved "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz" + integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== + +json-schema-traverse@^0.4.1: + version "0.4.1" + resolved "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz" + integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== + +json-stable-stringify-without-jsonify@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz" + integrity sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw== + +keyv@^4.5.4: + version "4.5.4" + resolved "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz" + integrity sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw== + dependencies: + json-buffer "3.0.1" + +levn@^0.4.1: + version "0.4.1" + resolved "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz" + integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== + dependencies: + prelude-ls "^1.2.1" + type-check "~0.4.0" + +locate-path@^6.0.0: + version "6.0.0" + resolved "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz" + integrity sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw== + dependencies: + p-locate "^5.0.0" + +lodash-es@4.18.1, lodash-es@^4.17.21: + version "4.18.1" + resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.18.1.tgz#b962eeb80d9d983a900bf342961fb7418ca10b1d" + integrity sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A== + +lodash.camelcase@^4.3.0: + version "4.3.0" + resolved "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz" + integrity sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA== + +log-symbols@^4.1.0: + version "4.1.0" + resolved "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz" + integrity sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg== + dependencies: + chalk "^4.1.0" + is-unicode-supported "^0.1.0" + +long@^2.4.0: + version "2.4.0" + resolved "https://registry.npmjs.org/long/-/long-2.4.0.tgz" + integrity sha512-ijUtjmO/n2A5PaosNG9ZGDsQ3vxJg7ZW8vsY8Kp0f2yIZWhSJvjmegV7t+9RPQKxKrvj8yKGehhS+po14hPLGQ== + +long@^5.0.0: + version "5.2.3" + resolved "https://registry.npmjs.org/long/-/long-5.2.3.tgz" + integrity sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q== + +long@^5.3.2: + version "5.3.2" + resolved "https://registry.yarnpkg.com/long/-/long-5.3.2.tgz#1d84463095999262d7d7b7f8bfd4a8cc55167f83" + integrity sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA== + +lru-cache@^10.2.0: + version "10.4.3" + resolved "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz" + integrity sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ== + +magic-string@^0.30.21: + version "0.30.21" + resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.30.21.tgz#56763ec09a0fa8091df27879fd94d19078c00d91" + integrity sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ== + dependencies: + "@jridgewell/sourcemap-codec" "^1.5.5" + +make-error@^1.1.1: + version "1.3.6" + resolved "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz" + integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== + +math-intrinsics@^1.1.0: + version "1.1.0" + resolved "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz" + integrity sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g== + +mime-db@1.52.0: + version "1.52.0" + resolved "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz" + integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg== + +mime-types@^2.1.35: + version "2.1.35" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a" + integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw== + dependencies: + mime-db "1.52.0" + +minimatch@9.0.9, minimatch@^9.0.0, minimatch@^9.0.4, minimatch@^9.0.5: + version "9.0.9" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.9.tgz#9b0cb9fcb78087f6fd7eababe2511c4d3d60574e" + integrity sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg== + dependencies: + brace-expansion "^2.0.2" + +minimatch@^10.2.2, minimatch@^10.2.4: + version "10.2.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-10.2.4.tgz#465b3accbd0218b8281f5301e27cedc697f96fde" + integrity sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg== + dependencies: + brace-expansion "^5.0.2" + +minimist@^1.1.0: + version "1.2.8" + resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz" + integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== + +"minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.0.4, minipass@^7.1.2: + version "7.1.2" + resolved "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz" + integrity sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw== + +minizlib@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" + integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== + dependencies: + minipass "^7.1.2" + +mocha@^11.7.6: + version "11.7.6" + resolved "https://registry.yarnpkg.com/mocha/-/mocha-11.7.6.tgz#ebbe22989d04cbb9424a36307320476624c41a33" + integrity sha512-nS9xOGbw2I3cjCpxwZAEJ9xK9lmJ08vEkQvLtz4du9ZrF9UrjRpeJGiIgl2Z+Qs++pmB4ecDe48Fwsh+j+j7xA== + dependencies: + browser-stdout "^1.3.1" + chokidar "^4.0.1" + debug "^4.3.5" + diff "^7.0.0" + escape-string-regexp "^4.0.0" + find-up "^5.0.0" + glob "^10.4.5" + he "^1.2.0" + is-path-inside "^3.0.3" + js-yaml "^4.1.0" + log-symbols "^4.1.0" + minimatch "^9.0.5" + ms "^2.1.3" + picocolors "^1.1.1" + serialize-javascript "^6.0.2" + strip-json-comments "^3.1.1" + supports-color "^8.1.1" + workerpool "^9.2.0" + yargs "^17.7.2" + yargs-parser "^21.1.1" + yargs-unparser "^2.0.0" + +module-details-from-path@^1.0.3: + version "1.0.3" + resolved "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.3.tgz" + integrity sha512-ySViT69/76t8VhE1xXHK6Ch4NcDd26gx0MzKXLO+F7NOtnqH68d9zF94nT8ZWSxXh8ELOERsnJO/sWt1xZYw5A== + +module-details-from-path@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/module-details-from-path/-/module-details-from-path-1.0.4.tgz#b662fdcd93f6c83d3f25289da0ce81c8d9685b94" + integrity sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w== + +ms@^2.1.3: + version "2.1.3" + resolved "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz" + integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== + +natural-compare@^1.4.0: + version "1.4.0" + resolved "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz" + integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== + +node-color-log@^14.0.0: + version "14.0.0" + resolved "https://registry.yarnpkg.com/node-color-log/-/node-color-log-14.0.0.tgz#7546b3bfd1738b8f21860ab25dda631ff5e8e8c1" + integrity sha512-vGZzpRBVzXsQO9o0CZvIrbqDu/X8IpC2W9eEkb5Q+o4TI4IpGS25QAKC4m2116A26UpX1AJ7rGZv+A9VgjkCrA== + +node-domexception@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz" + integrity sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ== + +node-fetch@^3.3.2: + version "3.3.2" + resolved "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz" + integrity sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA== + dependencies: + data-uri-to-buffer "^4.0.0" + fetch-blob "^3.1.4" + formdata-polyfill "^4.0.10" + +node-int64@^0.4.0: + version "0.4.0" + resolved "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz" + integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw== + +npm-run-path@^6.0.0: + version "6.0.0" + resolved "https://registry.npmjs.org/npm-run-path/-/npm-run-path-6.0.0.tgz" + integrity sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA== + dependencies: + path-key "^4.0.0" + unicorn-magic "^0.3.0" + +opentracing@^0.14.4: + version "0.14.7" + resolved "https://registry.npmjs.org/opentracing/-/opentracing-0.14.7.tgz" + integrity sha512-vz9iS7MJ5+Bp1URw8Khvdyw1H/hGvzHWlKQ7eRrQojSCDL1/SrWfrY9QebLw97n2deyRtzHRC3MkQfVNUCo91Q== + +optionator@^0.9.3: + version "0.9.4" + resolved "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz" + integrity sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g== + dependencies: + deep-is "^0.1.3" + fast-levenshtein "^2.0.6" + levn "^0.4.1" + prelude-ls "^1.2.1" + type-check "^0.4.0" + word-wrap "^1.2.5" + +p-limit@^3.0.2: + version "3.1.0" + resolved "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz" + integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ== + dependencies: + yocto-queue "^0.1.0" + +p-locate@^5.0.0: + version "5.0.0" + resolved "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz" + integrity sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw== + dependencies: + p-limit "^3.0.2" + +package-json-from-dist@^1.0.0: + version "1.0.0" + resolved "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.0.tgz" + integrity sha512-dATvCeZN/8wQsGywez1mzHtTlP22H8OEfPrVMLNr4/eGa+ijtLn/6M5f0dY8UKNrC2O9UCU6SSoG3qRKnt7STw== + +parse-imports-exports@^0.2.4: + version "0.2.4" + resolved "https://registry.yarnpkg.com/parse-imports-exports/-/parse-imports-exports-0.2.4.tgz#e3fb3b5e264cfb55c25b5dfcbe7f410f8dc4e7af" + integrity sha512-4s6vd6dx1AotCx/RCI2m7t7GCh5bDRUtGNvRfHSP2wbBQdMi67pPe7mtzmgwcaQ8VKK/6IB7Glfyu3qdZJPybQ== + dependencies: + parse-statements "1.0.11" + +parse-ms@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz" + integrity sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw== + +parse-statements@1.0.11: + version "1.0.11" + resolved "https://registry.yarnpkg.com/parse-statements/-/parse-statements-1.0.11.tgz#8787c5d383ae5746568571614be72b0689584344" + integrity sha512-HlsyYdMBnbPQ9Jr/VgJ1YF4scnldvJpJxCVx6KgqPL4dxppsWrJHCIIxQXMJrqGnsRkNPATbeMJ8Yxu7JMsYcA== + +path-exists@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz" + integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== + +path-key@^3.1.0: + version "3.1.1" + resolved "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz" + integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== + +path-key@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz" + integrity sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ== + +path-scurry@^1.11.1: + version "1.11.1" + resolved "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz" + integrity sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA== + dependencies: + lru-cache "^10.2.0" + minipass "^5.0.0 || ^6.0.2 || ^7.0.0" + +picocolors@^1.1.1: + version "1.1.1" + resolved "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz" + integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== + +picomatch@^4.0.3: + version "4.0.3" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.3.tgz#796c76136d1eead715db1e7bad785dedd695a042" + integrity sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q== + +prelude-ls@^1.2.1: + version "1.2.1" + resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz" + integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== + +prettier-linter-helpers@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.1.tgz#6a31f88a4bad6c7adda253de12ba4edaea80ebcd" + integrity sha512-SxToR7P8Y2lWmv/kTzVLC1t/GDI2WGjMwNhLLE9qtH8Q13C+aEmuRlzDst4Up4s0Wc8sF2M+J57iB3cMLqftfg== + dependencies: + fast-diff "^1.1.2" + +prettier@^3.9.3: + version "3.9.3" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.9.3.tgz#4caabe6fb955e8b8f13319f25872522ece519534" + integrity sha512-HWmu+K+zvHNpaMfSnYeqdqrDbR16cuIXaPx8WoHaviQkDJh1/0BNtOZmHVQI5jc3wXv0H1yXc9wjvFdXh+n3hQ== + +pretty-ms@^9.2.0: + version "9.2.0" + resolved "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.2.0.tgz" + integrity sha512-4yf0QO/sllf/1zbZWYnvWw3NxCQwLXKzIj0G849LSufP15BXKM0rbD2Z3wVnkMfjdn/CB0Dpp444gYAACdsplg== + dependencies: + parse-ms "^4.0.0" + +process@^0.10.0: + version "0.10.1" + resolved "https://registry.npmjs.org/process/-/process-0.10.1.tgz" + integrity sha512-dyIett8dgGIZ/TXKUzeYExt7WA6ldDzys9vTDU/cCA9L17Ypme+KzS+NjQCjpn9xsvi/shbMC+yP/BcFMBz0NA== + +protobufjs@7.6.1, protobufjs@^7.5.3: + version "7.6.1" + resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-7.6.1.tgz#6320bb08c3be7dcfc6f9193ee03d3a4643f1eb37" + integrity sha512-4K0myLaWL5EteuSAro91EGFgcfVgxb64Jx+7oDAY6GOkXD4M69yuSEljNcInGVCA5sOPxmZ/EqDLj2x0Q0+Ygg== + dependencies: + "@protobufjs/aspromise" "^1.1.2" + "@protobufjs/base64" "^1.1.2" + "@protobufjs/codegen" "^2.0.5" + "@protobufjs/eventemitter" "^1.1.1" + "@protobufjs/fetch" "^1.1.1" + "@protobufjs/float" "^1.0.2" + "@protobufjs/inquire" "^1.1.2" + "@protobufjs/path" "^1.1.2" + "@protobufjs/pool" "^1.1.0" + "@protobufjs/utf8" "^1.1.1" + "@types/node" ">=13.7.0" + long "^5.3.2" + +protobufjs@8.0.0, protobufjs@8.4.1: + version "8.4.1" + resolved "https://registry.yarnpkg.com/protobufjs/-/protobufjs-8.4.1.tgz#3ba4b27e50e1f6ef901455e747224f86c32c6aea" + integrity sha512-oXf2UgIty8jnwfN4yvL1x79VLhL5uiKjZJbSGXGCIUmHmItTP4eS/UIlWDCeNx3seg+ujfn9vDlPMSrsh7wO+Q== + dependencies: + long "^5.3.2" + +punycode@^2.1.0: + version "2.3.1" + resolved "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz" + integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg== + +readdirp@^4.0.1: + version "4.1.2" + resolved "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz" + integrity sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg== + +reflect-metadata@^0.2.2: + version "0.2.2" + resolved "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz" + integrity sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q== + +require-directory@^2.1.1: + version "2.1.1" + resolved "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz" + integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q== + +require-in-the-middle@^8.0.0, require-in-the-middle@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz#dbde2587f669398626d56b20c868ab87bf01cce4" + integrity sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ== + dependencies: + debug "^4.3.5" + module-details-from-path "^1.0.3" + +rollup-plugin-dts@^6.4.1: + version "6.4.1" + resolved "https://registry.yarnpkg.com/rollup-plugin-dts/-/rollup-plugin-dts-6.4.1.tgz#9bec10f1b796ed022f76ff799429123c33aa88b7" + integrity sha512-l//F3Zf7ID5GoOfLfD8kroBjQKEKpy1qfhtAdnpibFZMffPaylrg1CoDC2vGkPeTeyxUe4bVFCln2EFuL7IGGg== + dependencies: + "@jridgewell/remapping" "^2.3.5" + "@jridgewell/sourcemap-codec" "^1.5.5" + convert-source-map "^2.0.0" + magic-string "^0.30.21" + optionalDependencies: + "@babel/code-frame" "^7.29.0" + +rollup@^4.62.2: + version "4.62.2" + resolved "https://registry.yarnpkg.com/rollup/-/rollup-4.62.2.tgz#d90fc4cb811f071303c890b779595634f35f9541" + integrity sha512-RFnrW4lhXA3s3eqHDZvN654g8OTjzRfqpIRJYczCGB6HzphckVAi/Qh4tbPUbRuDi7s1Llv8g/NspLkttY3gTA== + dependencies: + "@types/estree" "1.0.9" + optionalDependencies: + "@rollup/rollup-android-arm-eabi" "4.62.2" + "@rollup/rollup-android-arm64" "4.62.2" + "@rollup/rollup-darwin-arm64" "4.62.2" + "@rollup/rollup-darwin-x64" "4.62.2" + "@rollup/rollup-freebsd-arm64" "4.62.2" + "@rollup/rollup-freebsd-x64" "4.62.2" + "@rollup/rollup-linux-arm-gnueabihf" "4.62.2" + "@rollup/rollup-linux-arm-musleabihf" "4.62.2" + "@rollup/rollup-linux-arm64-gnu" "4.62.2" + "@rollup/rollup-linux-arm64-musl" "4.62.2" + "@rollup/rollup-linux-loong64-gnu" "4.62.2" + "@rollup/rollup-linux-loong64-musl" "4.62.2" + "@rollup/rollup-linux-ppc64-gnu" "4.62.2" + "@rollup/rollup-linux-ppc64-musl" "4.62.2" + "@rollup/rollup-linux-riscv64-gnu" "4.62.2" + "@rollup/rollup-linux-riscv64-musl" "4.62.2" + "@rollup/rollup-linux-s390x-gnu" "4.62.2" + "@rollup/rollup-linux-x64-gnu" "4.62.2" + "@rollup/rollup-linux-x64-musl" "4.62.2" + "@rollup/rollup-openbsd-x64" "4.62.2" + "@rollup/rollup-openharmony-arm64" "4.62.2" + "@rollup/rollup-win32-arm64-msvc" "4.62.2" + "@rollup/rollup-win32-ia32-msvc" "4.62.2" + "@rollup/rollup-win32-x64-gnu" "4.62.2" + "@rollup/rollup-win32-x64-msvc" "4.62.2" + fsevents "~2.3.2" + +semver@^7.7.3: + version "7.7.3" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.7.3.tgz#4b5f4143d007633a8dc671cd0a6ef9147b8bb946" + integrity sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q== + +serialize-javascript@7.0.3, serialize-javascript@^6.0.2: + version "7.0.3" + resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-7.0.3.tgz#c92008d8a21bc7b2307c2e885a4bd0f03b2aee6c" + integrity sha512-h+cZ/XXarqDgCjo+YSyQU/ulDEESGGf8AMK9pPNmhNSl/FzPl6L8pMp1leca5z6NuG6tvV/auC8/43tmovowww== + +shebang-command@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz" + integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== + dependencies: + shebang-regex "^3.0.0" + +shebang-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz" + integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== + +signal-exit@^4.0.1, signal-exit@^4.1.0: + version "4.1.0" + resolved "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== + +string-template@~0.2.1: + version "0.2.1" + resolved "https://registry.npmjs.org/string-template/-/string-template-0.2.1.tgz" + integrity sha512-Yptehjogou2xm4UJbxJ4CxgZx12HBfeystp0y3x7s4Dj32ltVVG1Gg8YhKjHZkHicuKpZX/ffilA8505VbUbpw== + +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: + version "4.2.3" + resolved "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^5.0.1, string-width@^5.1.2: + version "5.1.2" + resolved "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz" + integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA== + dependencies: + eastasianwidth "^0.2.0" + emoji-regex "^9.2.2" + strip-ansi "^7.0.1" + +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^7.0.1: + version "7.1.0" + resolved "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz" + integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ== + dependencies: + ansi-regex "^6.0.1" + +strip-final-newline@^4.0.0: + version "4.0.0" + resolved "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-4.0.0.tgz" + integrity sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw== + +strip-json-comments@^3.1.1: + version "3.1.1" + resolved "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz" + integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== + +supports-color@^7.1.0: + version "7.2.0" + resolved "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz" + integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== + dependencies: + has-flag "^4.0.0" + +supports-color@^8.1.1: + version "8.1.1" + resolved "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz" + integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== + dependencies: + has-flag "^4.0.0" + +synckit@^0.11.13: + version "0.11.13" + resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.11.13.tgz#062a5ea57d81befc35892f8254de5c567e97c80a" + integrity sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg== + dependencies: + "@pkgr/core" "^0.3.6" + +tar@*, tar@^7.5.19: + version "7.5.19" + resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.19.tgz#d8915e6b717f8036a79d839ca9448198b002b0a7" + integrity sha512-4LeEWl96twnS2Q7Bz4MGqgazLqO+hJN63GZxXoIqh1T3VweYD997gbU1ItNsQafqqXTXd5WFyFdReLtwvRBNiw== + dependencies: + "@isaacs/fs-minipass" "^4.0.0" + chownr "^3.0.0" + minipass "^7.1.2" + minizlib "^3.1.0" + yallist "^5.0.0" + +thriftrw@^3.5.0: + version "3.11.4" + resolved "https://registry.npmjs.org/thriftrw/-/thriftrw-3.11.4.tgz" + integrity sha512-UcuBd3eanB3T10nXWRRMwfwoaC6VMk7qe3/5YIWP2Jtw+EbHqJ0p1/K3x8ixiR5dozKSSfcg1W+0e33G1Di3XA== + dependencies: + bufrw "^1.2.1" + error "7.0.2" + long "^2.4.0" + +tinyglobby@^0.2.15: + version "0.2.15" + resolved "https://registry.yarnpkg.com/tinyglobby/-/tinyglobby-0.2.15.tgz#e228dd1e638cea993d2fdb4fcd2d4602a79951c2" + integrity sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ== + dependencies: + fdir "^6.5.0" + picomatch "^4.0.3" + +ts-api-utils@^2.5.0: + version "2.5.0" + resolved "https://registry.yarnpkg.com/ts-api-utils/-/ts-api-utils-2.5.0.tgz#4acd4a155e22734990a5ed1fe9e97f113bcb37c1" + integrity sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA== + +ts-node@^10.9.2: + version "10.9.2" + resolved "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz" + integrity sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ== + dependencies: + "@cspotcode/source-map-support" "^0.8.0" + "@tsconfig/node10" "^1.0.7" + "@tsconfig/node12" "^1.0.7" + "@tsconfig/node14" "^1.0.0" + "@tsconfig/node16" "^1.0.2" + acorn "^8.4.1" + acorn-walk "^8.1.1" + arg "^4.1.0" + create-require "^1.1.0" + diff "^4.0.1" + make-error "^1.1.1" + v8-compile-cache-lib "^3.0.1" + yn "3.1.1" + +tslib@^2.1.0: + version "2.6.3" + resolved "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz" + integrity sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ== + +tsx@^4.22.4: + version "4.22.4" + resolved "https://registry.yarnpkg.com/tsx/-/tsx-4.22.4.tgz#0ab3b7fb4ec7feeee74e5b1f26337caa71e44700" + integrity sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg== + dependencies: + esbuild "~0.28.0" + optionalDependencies: + fsevents "~2.3.3" + +type-check@^0.4.0, type-check@~0.4.0: + version "0.4.0" + resolved "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz" + integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== + dependencies: + prelude-ls "^1.2.1" + +typescript-eslint@^8.62.0: + version "8.62.0" + resolved "https://registry.yarnpkg.com/typescript-eslint/-/typescript-eslint-8.62.0.tgz#7252c3c931637cda28794c0518f321ee89621d67" + integrity sha512-8QxXi+ZACKX0kaqO4gY8kn0RSD9gFfaHDWwjqtEN48aWCBkX4MJaufWN+c3BzlrXLOxfywDL8CaoqUwcRq4j4Q== + dependencies: + "@typescript-eslint/eslint-plugin" "8.62.0" + "@typescript-eslint/parser" "8.62.0" + "@typescript-eslint/typescript-estree" "8.62.0" + "@typescript-eslint/utils" "8.62.0" + +typescript@^6.0.3: + version "6.0.3" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-6.0.3.tgz#90251dc007916e972786cb94d74d15b185577d21" + integrity sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw== + +undici-types@~8.3.0: + version "8.3.0" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-8.3.0.tgz#44e9fc9f3244648cdea35e4f9bb2d681e9410809" + integrity sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ== + +unicorn-magic@^0.3.0: + version "0.3.0" + resolved "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz" + integrity sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA== + +uri-js@^4.2.2: + version "4.4.1" + resolved "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz" + integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== + dependencies: + punycode "^2.1.0" + +uuid@^8.3.2: + version "8.3.2" + resolved "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz" + integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== + +v8-compile-cache-lib@^3.0.1: + version "3.0.1" + resolved "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz" + integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== + +web-streams-polyfill@^3.0.3: + version "3.3.3" + resolved "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz" + integrity sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw== + +which@^2.0.1: + version "2.0.2" + resolved "https://registry.npmjs.org/which/-/which-2.0.2.tgz" + integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== + dependencies: + isexe "^2.0.0" + +word-wrap@^1.2.5: + version "1.2.5" + resolved "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz" + integrity sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA== + +workerpool@^9.2.0: + version "9.3.2" + resolved "https://registry.npmjs.org/workerpool/-/workerpool-9.3.2.tgz" + integrity sha512-Xz4Nm9c+LiBHhDR5bDLnNzmj6+5F+cyEAWPMkbs2awq/dYazR/efelZzUAjB/y3kNHL+uzkHvxVVpaOfGCPV7A== + +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": + version "7.0.0" + resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + +wrap-ansi@^7.0.0: + version "7.0.0" + resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + +wrap-ansi@^8.1.0: + version "8.1.0" + resolved "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz" + integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ== + dependencies: + ansi-styles "^6.1.0" + string-width "^5.0.1" + strip-ansi "^7.0.1" + +xorshift@^1.1.1: + version "1.2.0" + resolved "https://registry.npmjs.org/xorshift/-/xorshift-1.2.0.tgz" + integrity sha512-iYgNnGyeeJ4t6U11NpA/QiKy+PXn5Aa3Azg5qkwIFz1tBLllQrjjsk9yzD7IAK0naNU4JxdeDgqW9ov4u/hc4g== + +xtend@^4.0.0, xtend@~4.0.0: + version "4.0.2" + resolved "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz" + integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== + +y18n@^5.0.5: + version "5.0.8" + resolved "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz" + integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== + +yallist@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" + integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== + +yaml@^2.0.0: + version "2.8.2" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.8.2.tgz#5694f25eca0ce9c3e7a9d9e00ce0ddabbd9e35c5" + integrity sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A== + +yargs-parser@^21.1.1: + version "21.1.1" + resolved "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz" + integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== + +yargs-unparser@^2.0.0: + version "2.0.0" + resolved "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz" + integrity sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA== + dependencies: + camelcase "^6.0.0" + decamelize "^4.0.0" + flat "^5.0.2" + is-plain-obj "^2.1.0" + +yargs@^17.7.2: + version "17.7.2" + resolved "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz" + integrity sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w== + dependencies: + cliui "^8.0.1" + escalade "^3.1.1" + get-caller-file "^2.0.5" + require-directory "^2.1.1" + string-width "^4.2.3" + y18n "^5.0.5" + yargs-parser "^21.1.1" + +yn@3.1.1: + version "3.1.1" + resolved "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz" + integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q== + +yocto-queue@^0.1.0: + version "0.1.0" + resolved "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz" + integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== + +yoctocolors@^2.1.1: + version "2.1.1" + resolved "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.1.1.tgz" + integrity sha512-GQHQqAopRhwU8Kt1DDM8NjibDXHC8eoh1erhGAJPEyveY9qqVeXvVikNKrDz69sHowPMorbPUrH/mx8c50eiBQ== From 8bb42acc43d3f4a086bc1f13510969f10ca06bba Mon Sep 17 00:00:00 2001 From: Vasek - Tom C Date: Mon, 10 Aug 2026 15:47:47 +0200 Subject: [PATCH 2/2] chore(library): move the build recipe out of package.json The vendored scripts all pointed at things this repo does not have: mocha, eslint and tsx were left behind with the tests they serve, and the docs scripts reach for ../../docs/current_docs. Only `build` was live, and the packager already runs tsc itself. Drop them, and trim devDependencies and resolutions to what the bundle build actually uses (rollup, rollup-plugin-dts, the @types the declaration build needs) so package.json describes the package while the packager owns how it is built. Keep yarn.lock: it is load-bearing, not vendored ceremony. Installing without it resolves newer transitives and grows core.js from 4.3 MB to 5.4 MB, so the bundle would silently stop matching the one the engine ships. Signed-off-by: Tom Chauveau --- .dagger/modules/packager/main.dang | 6 +- library/bundle/core.js | 129 +---------------------------- library/package.json | 39 +-------- 3 files changed, 13 insertions(+), 161 deletions(-) diff --git a/.dagger/modules/packager/main.dang b/.dagger/modules/packager/main.dang index 8db062b..20a0ba8 100644 --- a/.dagger/modules/packager/main.dang +++ b/.dagger/modules/packager/main.dang @@ -47,12 +47,16 @@ type Packager { behaves like one built against the engine's: a single node-targeted JS bundle with the TypeScript compiler left external, plus the rolled-up type declarations for it. + + The install resolves through the vendored yarn.lock, which is load-bearing: + letting it resolve freely instead pulls newer transitive versions and grows + core.js by roughly a quarter (4.3 MB -> 5.4 MB). """ libraryBundle(ws: Workspace!): Changeset! @generate { let built = bun .withDirectory("/src", ws.directory("/" + libraryPath)) .withWorkdir("/src") - .withExec(["bun", "install", "--frozen-lockfile"]) + .withExec(["bun", "install"]) .withExec(["bun", "build", "./src/index.ts", "--external=typescript", "--target=node", "--outfile", "/out/core.js"]) .withExec(["tsc", "--emitDeclarationOnly"]) .withExec(["bun", "x", "rollup", "-c", "rollup.dts.config.mjs", "-o", "/out/core.d.ts"]) diff --git a/library/bundle/core.js b/library/bundle/core.js index de7ff1f..125f279 100644 --- a/library/bundle/core.js +++ b/library/bundle/core.js @@ -32936,127 +32936,6 @@ var require_browser = __commonJS((exports, module) => { }; }); -// node_modules/has-flag/index.js -var require_has_flag = __commonJS((exports, module) => { - module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf("--"); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); - }; -}); - -// node_modules/supports-color/index.js -var require_supports_color = __commonJS((exports, module) => { - var os = __require("os"); - var tty = __require("tty"); - var hasFlag = require_has_flag(); - var { env } = process; - var flagForceColor; - if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) { - flagForceColor = 0; - } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) { - flagForceColor = 1; - } - function envForceColor() { - if ("FORCE_COLOR" in env) { - if (env.FORCE_COLOR === "true") { - return 1; - } - if (env.FORCE_COLOR === "false") { - return 0; - } - return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); - } - } - function translateLevel(level) { - if (level === 0) { - return false; - } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; - } - function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { - const noFlagForceColor = envForceColor(); - if (noFlagForceColor !== undefined) { - flagForceColor = noFlagForceColor; - } - const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; - if (forceColor === 0) { - return 0; - } - if (sniffFlags) { - if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) { - return 3; - } - if (hasFlag("color=256")) { - return 2; - } - } - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } - const min = forceColor || 0; - if (env.TERM === "dumb") { - return min; - } - if (process.platform === "win32") { - const osRelease = os.release().split("."); - if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - return 1; - } - if ("CI" in env) { - if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") { - return 1; - } - return min; - } - if ("TEAMCITY_VERSION" in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if (env.COLORTERM === "truecolor") { - return 3; - } - if ("TERM_PROGRAM" in env) { - const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10); - switch (env.TERM_PROGRAM) { - case "iTerm.app": - return version >= 3 ? 3 : 2; - case "Apple_Terminal": - return 2; - } - } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ("COLORTERM" in env) { - return 1; - } - return min; - } - function getSupportLevel(stream, options = {}) { - const level = supportsColor(stream, { - streamIsTTY: stream && stream.isTTY, - ...options - }); - return translateLevel(level); - } - module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel({ isTTY: tty.isatty(1) }), - stderr: getSupportLevel({ isTTY: tty.isatty(2) }) - }; -}); - // node_modules/debug/src/node.js var require_node6 = __commonJS((exports, module) => { var tty = __require("tty"); @@ -33070,7 +32949,7 @@ var require_node6 = __commonJS((exports, module) => { exports.destroy = util.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); exports.colors = [6, 2, 3, 4, 5, 1]; try { - const supportsColor = require_supports_color(); + const supportsColor = (()=>{throw new Error("Cannot require module "+"supports-color");})(); if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { exports.colors = [ 20, @@ -33237,7 +33116,7 @@ var require_src14 = __commonJS((exports, module) => { } }); -// node_modules/module-details-from-path/index.js +// node_modules/require-in-the-middle/node_modules/module-details-from-path/index.js var require_module_details_from_path = __commonJS((exports, module) => { var path = __require("path"); module.exports = function(file) { @@ -33599,7 +33478,7 @@ var require_RequireInTheMiddleSingleton = __commonJS((exports) => { } }); -// node_modules/import-in-the-middle/node_modules/module-details-from-path/index.js +// node_modules/module-details-from-path/index.js var require_module_details_from_path2 = __commonJS((exports, module) => { var sep = __require("path").sep; module.exports = function(file) { @@ -88017,7 +87896,7 @@ var init_escape = __esm(() => { NO_ESCAPE_REGEXP = /^[\w./-]+$/; }); -// node_modules/figures/node_modules/is-unicode-supported/index.js +// node_modules/is-unicode-supported/index.js import process4 from "node:process"; function isUnicodeSupported() { if (process4.platform !== "win32") { diff --git a/library/package.json b/library/package.json index 226b8dc..23bfbc1 100644 --- a/library/package.json +++ b/library/package.json @@ -1,7 +1,7 @@ { "name": "@dagger.io/dagger", - "version": "0.0.0", - "author": "hello@dagger.io", + "version": "1.0.0", + "author": "dagger.io", "license": "Apache-2.0", "types": "./dist/src/index.d.ts", "type": "module", @@ -38,49 +38,18 @@ "tar": "^7.5.19", "typescript": "^6.0.3" }, - "scripts": { - "build": "tsc", - "watch": "tsc -w", - "test": "yarn run test:node", - "test:bun": "bun run --bun mocha", - "test:node": "mocha", - "test:generate-scan": "tsx ./introspector/test/testdata/generate_expected_scan.ts", - "lint": "yarn eslint --max-warnings=0 .", - "fmt": "yarn eslint --max-warnings=0 --fix .", - "docs:lint": "cd ../../docs/current_docs && eslint -c ../../sdk/typescript/eslint-docs.config.js --max-warnings=0 ./**/*.ts", - "docs:fmt": "cd ../../docs/current_docs && eslint --fix -c ../../sdk/typescript/eslint-docs.config.js --max-warnings=0 ./**/*.ts" - }, "resolutions": { "@grpc/grpc-js": "1.14.4", - "@trivago/prettier-plugin-sort-imports/lodash-es": "4.18.1", - "@trivago/prettier-plugin-sort-imports/minimatch": "9.0.9", "**/@grpc/proto-loader/protobufjs": "7.6.1", "**/@opentelemetry/otlp-transformer/protobufjs": "8.4.1", "**/glob/minimatch": "9.0.9", - "form-data": "4.0.6", - "mocha/minimatch": "9.0.9", - "mocha/serialize-javascript": "7.0.3", - "tsx/esbuild": "0.28.1" + "form-data": "4.0.6" }, "devDependencies": { - "@dagger.io/mocha": "^0.1.0", - "@eslint/js": "^10.0.1", - "@trivago/prettier-plugin-sort-imports": "^6.0.2", "@types/adm-zip": "^0.5.8", - "@types/mocha": "^10.0.10", "@types/node": "~26.0.1", "@types/tar": "^7.0.87", - "@typescript-eslint/eslint-plugin": "^8.62.0", - "@typescript-eslint/parser": "^8.62.0", - "eslint": "^10.6.0", - "eslint-config-prettier": "^10.1.8", - "eslint-plugin-prettier": "^5.5.6", - "mocha": "^11.7.6", - "prettier": "^3.9.3", "rollup": "^4.62.2", - "rollup-plugin-dts": "^6.4.1", - "ts-node": "^10.9.2", - "tsx": "^4.22.4", - "typescript-eslint": "^8.62.0" + "rollup-plugin-dts": "^6.4.1" } }