@zuplo/cli 7.14.8 → 7.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.third-party.txt +236 -0
- package/LICENSE.txt +5 -78
- package/README.md +18 -3
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwe/general/decrypt.js +3 -2
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jwks/remote.js +1 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/jws/general/verify.js +2 -8
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +11 -8
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +2 -0
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/dist/webapi/lib/key_management.js +0 -1
- package/node_modules/@modelcontextprotocol/client/node_modules/jose/package.json +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwe/general/decrypt.js +3 -2
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jwks/remote.js +1 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/jws/general/verify.js +2 -8
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +11 -8
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +2 -0
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/dist/webapi/lib/key_management.js +0 -1
- package/node_modules/@modelcontextprotocol/sdk/node_modules/jose/package.json +1 -1
- package/node_modules/@posthog/core/dist/privacy.d.ts +6 -1
- package/node_modules/@posthog/core/dist/privacy.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/privacy.js +69 -10
- package/node_modules/@posthog/core/dist/privacy.mjs +65 -9
- package/node_modules/@posthog/core/dist/traces/span.d.ts +6 -0
- package/node_modules/@posthog/core/dist/traces/span.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/traces/span.js +18 -0
- package/node_modules/@posthog/core/dist/traces/span.mjs +18 -0
- package/node_modules/@posthog/core/package.json +2 -2
- package/node_modules/@posthog/core/src/privacy.ts +100 -18
- package/node_modules/@posthog/core/src/traces/span.spec.ts +15 -1
- package/node_modules/@posthog/core/src/traces/span.ts +23 -0
- package/node_modules/@posthog/types/dist/traces.d.ts +10 -0
- package/node_modules/@posthog/types/dist/traces.d.ts.map +1 -1
- package/node_modules/@posthog/types/package.json +1 -1
- package/node_modules/@posthog/types/src/traces.ts +12 -0
- package/node_modules/@zuplo/core/LICENSE.third-party.txt +622 -0
- package/node_modules/@zuplo/core/LICENSE.txt +5 -78
- package/node_modules/@zuplo/core/README.md +7 -0
- package/node_modules/@zuplo/core/constants.minified.js +7 -20
- package/node_modules/@zuplo/core/customer.cli.minified.js +28 -41
- package/node_modules/@zuplo/core/index.minified.js +35 -48
- package/node_modules/@zuplo/core/package.json +4 -2
- package/node_modules/@zuplo/core/zeno.js +8 -21
- package/node_modules/@zuplo/graphql/LICENSE.third-party.txt +29 -0
- package/node_modules/@zuplo/graphql/LICENSE.txt +5 -78
- package/node_modules/@zuplo/graphql/README.md +7 -0
- package/node_modules/@zuplo/graphql/out/esm/index.js +7 -20
- package/node_modules/@zuplo/graphql/out/esm/index.js.map +1 -1
- package/node_modules/@zuplo/graphql/package.json +3 -2
- package/node_modules/@zuplo/openapi-tools/LICENSE.txt +7 -0
- package/node_modules/@zuplo/openapi-tools/README.md +7 -0
- package/node_modules/@zuplo/openapi-tools/package.json +3 -2
- package/node_modules/@zuplo/otel/LICENSE.third-party.txt +243 -0
- package/node_modules/@zuplo/otel/LICENSE.txt +5 -78
- package/node_modules/@zuplo/otel/README.md +33 -0
- package/node_modules/@zuplo/otel/out/esm/chunk-6YAK7LGJ.js +13 -0
- package/node_modules/@zuplo/otel/out/esm/chunk-6YAK7LGJ.js.map +1 -0
- package/node_modules/@zuplo/otel/out/esm/index.js +8 -21
- package/node_modules/@zuplo/otel/out/types/index.d.ts +41 -0
- package/node_modules/@zuplo/otel/package.json +3 -2
- package/node_modules/@zuplo/runtime/LICENSE.third-party.txt +511 -0
- package/node_modules/@zuplo/runtime/LICENSE.txt +5 -78
- package/node_modules/@zuplo/runtime/README.md +7 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-5JGLAPFA.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-5JGLAPFA.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-6R2COTV6.js → chunk-AJ3MMWJS.js} +9 -22
- package/node_modules/@zuplo/runtime/out/esm/chunk-AJ3MMWJS.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-BH4DKEES.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-G42UYZ6V.js +24 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-2HVCLUM4.js.map → chunk-G42UYZ6V.js.map} +1 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-OE2WMJXK.js +431 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-OE2WMJXK.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-R6UNMRUU.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-R6UNMRUU.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-PY52EHDX.js → chunk-T2WKOG7J.js} +9 -22
- package/node_modules/@zuplo/runtime/out/esm/chunk-T2WKOG7J.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/{chunk-SNTU476S.js → chunk-TOJD4RET.js} +9 -22
- package/node_modules/@zuplo/runtime/out/esm/chunk-TOJD4RET.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-VXPFMOL5.js +13 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-VXPFMOL5.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/esm/internal/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/mcp/messages/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +11 -39
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/mocks/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js +8 -21
- package/node_modules/@zuplo/runtime/out/esm/sdks/aws/index.js.map +1 -1
- package/node_modules/@zuplo/runtime/out/types/index.d.ts +248 -6
- package/node_modules/@zuplo/runtime/out/types/internal/index.d.ts +101 -0
- package/node_modules/@zuplo/runtime/out/types/mcp-gateway/index.d.ts +127 -0
- package/node_modules/@zuplo/runtime/package.json +3 -2
- package/node_modules/ansi-regex/index.js +22 -17
- package/node_modules/ansi-regex/package.json +1 -1
- package/node_modules/ansi-regex/readme.md +8 -0
- package/node_modules/express-rate-limit/dist/index.cjs +33 -4
- package/node_modules/express-rate-limit/dist/index.mjs +33 -4
- package/node_modules/express-rate-limit/package.json +1 -1
- package/package.json +12 -11
- package/node_modules/@zuplo/otel/out/esm/chunk-PVCAT62X.js +0 -26
- package/node_modules/@zuplo/otel/out/esm/chunk-PVCAT62X.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-2HVCLUM4.js +0 -37
- package/node_modules/@zuplo/runtime/out/esm/chunk-6R2COTV6.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-A3QGJZO7.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-A3QGJZO7.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-DB6LKZ36.js +0 -429
- package/node_modules/@zuplo/runtime/out/esm/chunk-DB6LKZ36.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-PY52EHDX.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-SNTU476S.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-TYV53J3B.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-TYV53J3B.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-UKQQD2JN.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-UKQQD2JN.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-VP5Q3DEN.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-VP5Q3DEN.js.map +0 -1
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-2HVCLUM4.js.LEGAL.txt → chunk-G42UYZ6V.js.LEGAL.txt} +0 -0
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-DB6LKZ36.js.LEGAL.txt → chunk-OE2WMJXK.js.LEGAL.txt} +0 -0
|
@@ -3025,6 +3025,12 @@ export declare interface McpTokenExchangeInboundPolicyOptions {
|
|
|
3025
3025
|
* Overrides the OIDC `prompt` parameter on upstream authorization requests. The MCP SDK adds `prompt=consent` whenever the requested scope includes `offline_access`, which forces a consent screen on every authorization on providers like Microsoft Entra ID even after a tenant admin has granted org-wide admin consent. Leave unset to keep the SDK's behavior; set to `false` to strip the `prompt` parameter; set an explicit value to replace it. Warning: stripping `prompt=consent` while requesting `offline_access` can silently prevent refresh-token issuance on providers that require a fresh consent grant for offline access (e.g. Google) — only use this when the provider grants offline access via pre-authorized/admin consent (e.g. Entra tenant admin consent).
|
|
3026
3026
|
*/
|
|
3027
3027
|
prompt?: ("none" | "login" | "consent" | "select_account") | false;
|
|
3028
|
+
/**
|
|
3029
|
+
* Extra query parameters added to upstream authorization requests, for providers that need a parameter the MCP authorization flow does not send. For example, Google issues a refresh token only when the request carries `access_type=offline`, so Google upstreams set `{ "access_type": "offline" }`, usually with `prompt: "consent"`. A value replaces any parameter of the same name. Parameters the gateway manages cannot be set here: `response_type`, `response_mode`, `client_id`, `redirect_uri`, `scope`, `state`, `code_challenge`, `code_challenge_method`, `resource`, and `prompt` (use the `prompt` option). Available only with `user-oauth` and `shared-oauth`.
|
|
3030
|
+
*/
|
|
3031
|
+
authorizationParams?: {
|
|
3032
|
+
[k: string]: string;
|
|
3033
|
+
};
|
|
3028
3034
|
/**
|
|
3029
3035
|
* Allows the authorization server metadata's `issuer` to differ from the server URL used for discovery. Defaults to `false`. Enable only for a confirmed provider metadata mismatch after verifying that its metadata and OAuth endpoints are trusted. This disables the RFC 8414 section 3.3 issuer check; authorization-response and callback checks still apply. Available only with `user-oauth` and `shared-oauth`.
|
|
3030
3036
|
*/
|
|
@@ -4063,6 +4069,63 @@ declare interface PromptProjection {
|
|
|
4063
4069
|
*/
|
|
4064
4070
|
declare type Public = boolean;
|
|
4065
4071
|
|
|
4072
|
+
/**
|
|
4073
|
+
* Describes the value a {@link TelemetryRedactor} is asked to redact.
|
|
4074
|
+
*
|
|
4075
|
+
* @public
|
|
4076
|
+
*/
|
|
4077
|
+
declare interface RedactionContext {
|
|
4078
|
+
/**
|
|
4079
|
+
* The kind of record the value is written to.
|
|
4080
|
+
*/
|
|
4081
|
+
readonly kind: RedactionRecordKind;
|
|
4082
|
+
/**
|
|
4083
|
+
* The path of the value in the record, for example `message[0]`,
|
|
4084
|
+
* `message[1].user.email`, `properties.customerId`, `attributes.http.url`,
|
|
4085
|
+
* `events[0].attributes.exception.message` or `url`.
|
|
4086
|
+
*/
|
|
4087
|
+
readonly field: string;
|
|
4088
|
+
/**
|
|
4089
|
+
* The last property name in {@link RedactionContext.field}, for example `email`
|
|
4090
|
+
* or `http.url`. `undefined` when the value is not a property of an object
|
|
4091
|
+
* (a log message string, an array element, a span name).
|
|
4092
|
+
*/
|
|
4093
|
+
readonly key: string | undefined;
|
|
4094
|
+
/**
|
|
4095
|
+
* Every property name on the way from the record to the value, outermost
|
|
4096
|
+
* first: `["user", "email"]` for `message[1].user.email`, `["dob"]` for
|
|
4097
|
+
* `message[1].dob[0]`. Array indices are left out, so a value in an array
|
|
4098
|
+
* keeps the name the array is under. When {@link RedactionContext.key} is
|
|
4099
|
+
* set, it is the last entry. Empty for a value with no property name above
|
|
4100
|
+
* it (a log message string, a span name).
|
|
4101
|
+
*/
|
|
4102
|
+
readonly keys: readonly string[];
|
|
4103
|
+
}
|
|
4104
|
+
|
|
4105
|
+
/**
|
|
4106
|
+
* The kind of record a value is about to be written to.
|
|
4107
|
+
*
|
|
4108
|
+
* - `log`: a log entry from `context.log`, `console.*` in customer code, or the
|
|
4109
|
+
* gateway's own request logs. Goes to Zuplo's log pipeline and to every
|
|
4110
|
+
* configured log integration.
|
|
4111
|
+
* - `span`: an OpenTelemetry span: its name, attributes, events and status.
|
|
4112
|
+
* - `analytics`: the URL and customer-set properties on the per-request
|
|
4113
|
+
* analytics row (also sent to metrics plugins), and URL fields of analytics
|
|
4114
|
+
* events. Fields that usage and billing are computed from are never
|
|
4115
|
+
* redacted.
|
|
4116
|
+
* - `request-log`: an entry produced by a request logger plugin (Azure Blob,
|
|
4117
|
+
* Azure Event Hubs, Hydrolix).
|
|
4118
|
+
* - `audit-log`: an event recorded by the Audit Log policy.
|
|
4119
|
+
*
|
|
4120
|
+
* @public
|
|
4121
|
+
*/
|
|
4122
|
+
declare type RedactionRecordKind =
|
|
4123
|
+
| "log"
|
|
4124
|
+
| "span"
|
|
4125
|
+
| "analytics"
|
|
4126
|
+
| "request-log"
|
|
4127
|
+
| "audit-log";
|
|
4128
|
+
|
|
4066
4129
|
/**
|
|
4067
4130
|
* Generic type parameters for a request.
|
|
4068
4131
|
* Extends RequestInitGeneric and adds query parameter typing.
|
|
@@ -4295,6 +4358,29 @@ declare interface RuntimeExtensions {
|
|
|
4295
4358
|
* @param hook - The pre-routing hook function
|
|
4296
4359
|
*/
|
|
4297
4360
|
addPreRoutingHook(hook: PreRoutingHook): void;
|
|
4361
|
+
/**
|
|
4362
|
+
* Add a redactor that redacts sensitive data before Zuplo records it.
|
|
4363
|
+
*
|
|
4364
|
+
* Request content the gateway records passes through the registered
|
|
4365
|
+
* redactors first: log entries (messages, structured fields, errors, log
|
|
4366
|
+
* properties), OpenTelemetry spans (names, attributes, events, status), the
|
|
4367
|
+
* URL and custom properties on the per-request analytics row, request
|
|
4368
|
+
* logger plugin entries and Audit Log policy events. The fields usage and
|
|
4369
|
+
* billing are computed from (route pattern, method, status, consumer) are
|
|
4370
|
+
* never redacted. Redactors run in the order they are added. With none
|
|
4371
|
+
* added, nothing is redacted and nothing changes.
|
|
4372
|
+
*
|
|
4373
|
+
* Call it only in `runtimeInit`; calls after startup throw. At most 16
|
|
4374
|
+
* redactors can be registered.
|
|
4375
|
+
*
|
|
4376
|
+
* If a redactor throws or returns something other than a string, the value
|
|
4377
|
+
* is recorded as `"[REDACTION_FAILED]"` and a warning, without the value, is
|
|
4378
|
+
* written to the request log at most once a minute.
|
|
4379
|
+
*
|
|
4380
|
+
* @param redactor - The redactor function. Use `createRedactor` for
|
|
4381
|
+
* built-in patterns.
|
|
4382
|
+
*/
|
|
4383
|
+
addTelemetryRedactor(redactor: TelemetryRedactor): void;
|
|
4298
4384
|
}
|
|
4299
4385
|
|
|
4300
4386
|
/**
|
|
@@ -4313,6 +4399,46 @@ declare abstract class SystemRuntimePlugin extends RuntimePlugin {
|
|
|
4313
4399
|
/* Excluded from this release type: registerRoutes */
|
|
4314
4400
|
}
|
|
4315
4401
|
|
|
4402
|
+
/**
|
|
4403
|
+
* A function that redacts sensitive data from a value before Zuplo records
|
|
4404
|
+
* it. Return the value to record: the input unchanged, or a redacted copy.
|
|
4405
|
+
*
|
|
4406
|
+
* The function runs synchronously on the request path for every string (and
|
|
4407
|
+
* every number, as its decimal string) the gateway records, so keep it fast.
|
|
4408
|
+
* It must be pure: the same input and context must always give the same
|
|
4409
|
+
* output, because results for short values are cached and reused. Values over
|
|
4410
|
+
* 32,768 characters are cut to that length before the function sees them.
|
|
4411
|
+
* Anything the function logs is dropped.
|
|
4412
|
+
* If it throws, or returns something other than a string, the value is
|
|
4413
|
+
* replaced with `"[REDACTION_FAILED]"` and the failure is recorded without the
|
|
4414
|
+
* value.
|
|
4415
|
+
*
|
|
4416
|
+
* @example
|
|
4417
|
+
* ```ts
|
|
4418
|
+
* import { RuntimeExtensions, createRedactor } from "@zuplo/runtime";
|
|
4419
|
+
*
|
|
4420
|
+
* export function runtimeInit(runtime: RuntimeExtensions) {
|
|
4421
|
+
* // Built-in patterns
|
|
4422
|
+
* runtime.addTelemetryRedactor(
|
|
4423
|
+
* createRedactor({
|
|
4424
|
+
* entities: ["finance-credit-card", "id-us-ssn"],
|
|
4425
|
+
* queryParameters: ["ssn", "card_number"],
|
|
4426
|
+
* })
|
|
4427
|
+
* );
|
|
4428
|
+
*
|
|
4429
|
+
* // A custom rule: drop the value of any field named "dob"
|
|
4430
|
+
* runtime.addTelemetryRedactor((value, { key }) =>
|
|
4431
|
+
* key === "dob" ? "[REDACTED]" : value
|
|
4432
|
+
* );
|
|
4433
|
+
* }
|
|
4434
|
+
* ```
|
|
4435
|
+
*
|
|
4436
|
+
* @public
|
|
4437
|
+
*/
|
|
4438
|
+
declare interface TelemetryRedactor {
|
|
4439
|
+
(value: string, context: RedactionContext): string;
|
|
4440
|
+
}
|
|
4441
|
+
|
|
4316
4442
|
declare interface ToolProjection {
|
|
4317
4443
|
/**
|
|
4318
4444
|
* Tool name to expose.
|
|
@@ -4397,6 +4523,7 @@ declare interface UpstreamOAuthConfig {
|
|
|
4397
4523
|
scopes: string[];
|
|
4398
4524
|
scopeDelimiter: string;
|
|
4399
4525
|
prompt?: UpstreamOAuthPromptOverride;
|
|
4526
|
+
authorizationParams?: Record<string, string>;
|
|
4400
4527
|
skipIssuerMetadataValidation?: boolean;
|
|
4401
4528
|
skipResourceIndicatorValidation?: boolean;
|
|
4402
4529
|
clientRegistration: UpstreamOAuthClientRegistrationConfig;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zuplo/runtime",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "7.
|
|
4
|
+
"version": "7.15.1",
|
|
5
5
|
"repository": "https://github.com/zuplo/zuplo",
|
|
6
6
|
"author": "Zuplo, Inc.",
|
|
7
7
|
"exports": {
|
|
@@ -37,7 +37,8 @@
|
|
|
37
37
|
"files": [
|
|
38
38
|
"out/**/*",
|
|
39
39
|
"README.md",
|
|
40
|
-
"LICENSE.txt"
|
|
40
|
+
"LICENSE.txt",
|
|
41
|
+
"LICENSE.third-party.txt"
|
|
41
42
|
],
|
|
42
43
|
"devDependencies": {
|
|
43
44
|
"@types/node": "^22.13.4",
|
|
@@ -1,24 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
// Valid string terminator sequences are ESC\ and 0x9c; OSC also accepts BEL.
|
|
2
|
+
const ST = String.raw`(?:\u001B\u005C|\u009C)`;
|
|
3
|
+
|
|
4
|
+
// OSC sequences only: ESC ] ... BEL/ST (or the C1 introducer 0x9d ... BEL/ST).
|
|
5
|
+
// Payloads stop at terminators, cancellations, and C1 controls. An unterminated string cannot swallow the next sequence or repeatedly scan its payload from later introducers. Terminals likewise abort a control string on an unexpected ESC.
|
|
6
|
+
const stringControls = String.raw`\u0018\u001A\u001B\u0080-\u009F`;
|
|
7
|
+
const osc = String.raw`(?:\u001B\]|\u009D)[^\u0007${stringControls}]*(?:\u0007|${ST})`;
|
|
4
8
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const osc = String.raw`(?:(?:\u001B\]|\u009D)[^\u0007\u001B\u009C\u009D]*${ST})`;
|
|
9
|
+
// DCS, SOS, PM, APC, and screen window titles have opaque payloads terminated by ST. Nested ESC payloads, such as tmux passthrough, require a parser.
|
|
10
|
+
const controlString = String.raw`(?:\u001B[PX^_k]|[\u0090\u0098\u009E\u009F])[^${stringControls}]*${ST}`;
|
|
8
11
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
// not include the parameter digits though: when the real final byte is outside the class the engine backtracks and takes the last
|
|
12
|
-
// parameter digit as the final byte instead, leaving the real one behind as visible text. `ESC [ 5 d` stripped to a bare `d`.
|
|
13
|
-
const csi = String.raw`[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[A-PR-TZcf-nq-uy=><~]`;
|
|
12
|
+
// Linux console palette controls have fixed lengths and no string terminator; iTerm2 terminates its palette assignments. Consume an immediately adjacent OSC terminator, but match these controls before OSC so a later BEL cannot consume visible text.
|
|
13
|
+
const linuxPalette = String.raw`\u001B\](?:P[\dA-Fa-f]{7}|R)(?:\u0007|${ST})?`;
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
// matched first, where the `[` makes the two unambiguous.
|
|
19
|
-
const csiPrivate = String.raw`(?:\u001B\[|\u009B)[<=>][0-9;:]*[A-PR-TZcf-nq-uy~]`;
|
|
15
|
+
// CSI: ESC [ or C1 CSI, parameter bytes (0x30–0x3f), intermediate bytes (0x20–0x2f), then a final byte (0x40–0x7e).
|
|
16
|
+
// `= < >` are final bytes in two-byte VT52 escapes (`ESC >`) but parameter bytes in a CSI (`ESC [ > 0 ; 276 ; 0 c`, the device attributes reply). Match CSI first to consume the whole sequence, where its introducer makes the two unambiguous.
|
|
17
|
+
const csi = String.raw`(?:\u001B\[|\u009B)[\u0030-\u003F]*[\u0020-\u002F]*[\u0040-\u007E]`;
|
|
20
18
|
|
|
21
|
-
|
|
19
|
+
// Related escapes: ESC, intermediate bytes (0x20–0x2f), then a final byte (0x30–0x7e), or a supported two-byte escape.
|
|
20
|
+
// The two-byte final class stays narrow so that ESC followed by an arbitrary character is not read as a sequence. CSI parameters belong only to the CSI form, preventing partial matches and avoiding a second scan with nested repetition.
|
|
21
|
+
// Escapes whose final byte is a digit include `ESC 7` and `ESC 8` (save and restore cursor), `ESC ( 0` (line drawing character set), and `ESC # 8` (screen alignment).
|
|
22
|
+
// A digit is never a CSI final byte. These escapes end immediately at their final byte, so `ESC 7 l` is read as the escape followed by text rather than a sequence with parameter 7 and final byte `l`.
|
|
23
|
+
const escape = String.raw`\u001B(?:[\u0020-\u002F]+[\u0030-\u007E]|[\dA-PR-TZcf-oq-uy=><~|}])`;
|
|
22
24
|
|
|
25
|
+
const pattern = `${linuxPalette}|${osc}|${controlString}|${csi}|${escape}`;
|
|
26
|
+
|
|
27
|
+
export default function ansiRegex({onlyFirst = false} = {}) {
|
|
23
28
|
return new RegExp(pattern, onlyFirst ? undefined : 'g');
|
|
24
29
|
}
|
|
@@ -54,6 +54,14 @@ If you run the regex against untrusted user input in a server context, you shoul
|
|
|
54
54
|
|
|
55
55
|
## FAQ
|
|
56
56
|
|
|
57
|
+
### Which sequences are supported?
|
|
58
|
+
|
|
59
|
+
The regex matches complete CSI sequences, OSC strings, ST-terminated DCS/SOS/PM/APC strings, screen window-title strings, character-set and encoding selections, and common two-byte ESC controls. Both seven-bit escape sequences and their C1 equivalents are supported where applicable. Linux console palette controls are also supported.
|
|
60
|
+
|
|
61
|
+
Control-string payloads are opaque, so this includes terminal hyperlinks, shell integration, clipboard commands, editor queries, sixel images, and Kitty graphics without needing a list of individual commands. ESC, CAN, SUB, and C1 control characters delimit or interrupt a control string.
|
|
62
|
+
|
|
63
|
+
This is a matcher for contiguous terminal output sequences, not a terminal emulator. It does not reconstruct screen contents, decode terminal keyboard/mouse input, or handle nested escape payloads such as tmux passthrough. Incomplete or cancelled sequences are handled on a best-effort basis. Standalone control characters, including tabs, newlines, and BEL, are preserved.
|
|
64
|
+
|
|
57
65
|
### Why do you test for codes not in the ECMA 48 standard?
|
|
58
66
|
|
|
59
67
|
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
|
|
@@ -107,7 +107,9 @@ var MemoryStore = class {
|
|
|
107
107
|
* @public
|
|
108
108
|
*/
|
|
109
109
|
async get(key) {
|
|
110
|
-
|
|
110
|
+
const client = this.current.get(key) ?? this.previous.get(key);
|
|
111
|
+
if (client && client.resetTime.getTime() <= Date.now()) return void 0;
|
|
112
|
+
return client;
|
|
111
113
|
}
|
|
112
114
|
/**
|
|
113
115
|
* Method to increment a client's hit counter.
|
|
@@ -1010,12 +1012,19 @@ var rateLimit = (passedOptions) => {
|
|
|
1010
1012
|
let decremented = false;
|
|
1011
1013
|
const decrementKey = async () => {
|
|
1012
1014
|
if (!decremented) {
|
|
1015
|
+
decremented = true;
|
|
1013
1016
|
if (resetTime && Date.now() >= resetTime.getTime()) {
|
|
1014
1017
|
return;
|
|
1015
1018
|
}
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
+
try {
|
|
1020
|
+
debug("decrementing count");
|
|
1021
|
+
await config.store.decrement(key);
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
config.logger.error(
|
|
1024
|
+
error,
|
|
1025
|
+
"express-rate-limit: error from store during decrement."
|
|
1026
|
+
);
|
|
1027
|
+
}
|
|
1019
1028
|
}
|
|
1020
1029
|
};
|
|
1021
1030
|
if (config.skipFailedRequests) {
|
|
@@ -1027,16 +1036,31 @@ var rateLimit = (passedOptions) => {
|
|
|
1027
1036
|
);
|
|
1028
1037
|
debug("computed requestWasSuccessful as %o", success);
|
|
1029
1038
|
if (!success) await decrementKey();
|
|
1039
|
+
}).catch((error) => {
|
|
1040
|
+
config.logger.error(
|
|
1041
|
+
error,
|
|
1042
|
+
"express-rate-limit: error in requestWasSuccessful callback."
|
|
1043
|
+
);
|
|
1030
1044
|
});
|
|
1031
1045
|
}
|
|
1032
1046
|
if (closePromise) {
|
|
1033
1047
|
void closePromise.then(async () => {
|
|
1034
1048
|
if (!response.writableEnded) await decrementKey();
|
|
1049
|
+
}).catch((error) => {
|
|
1050
|
+
config.logger.error(
|
|
1051
|
+
error,
|
|
1052
|
+
"express-rate-limit: error handling close event during decrement."
|
|
1053
|
+
);
|
|
1035
1054
|
});
|
|
1036
1055
|
}
|
|
1037
1056
|
if (errorPromise) {
|
|
1038
1057
|
void errorPromise.then(async () => {
|
|
1039
1058
|
await decrementKey();
|
|
1059
|
+
}).catch((error) => {
|
|
1060
|
+
config.logger.error(
|
|
1061
|
+
error,
|
|
1062
|
+
"express-rate-limit: error handling error event during decrement."
|
|
1063
|
+
);
|
|
1040
1064
|
});
|
|
1041
1065
|
}
|
|
1042
1066
|
}
|
|
@@ -1049,6 +1073,11 @@ var rateLimit = (passedOptions) => {
|
|
|
1049
1073
|
);
|
|
1050
1074
|
debug("computed requestWasSuccessful as %o", success);
|
|
1051
1075
|
if (success) await decrementKey();
|
|
1076
|
+
}).catch((error) => {
|
|
1077
|
+
config.logger.error(
|
|
1078
|
+
error,
|
|
1079
|
+
"express-rate-limit: error in requestWasSuccessful callback."
|
|
1080
|
+
);
|
|
1052
1081
|
});
|
|
1053
1082
|
}
|
|
1054
1083
|
}
|
|
@@ -64,7 +64,9 @@ var MemoryStore = class {
|
|
|
64
64
|
* @public
|
|
65
65
|
*/
|
|
66
66
|
async get(key) {
|
|
67
|
-
|
|
67
|
+
const client = this.current.get(key) ?? this.previous.get(key);
|
|
68
|
+
if (client && client.resetTime.getTime() <= Date.now()) return void 0;
|
|
69
|
+
return client;
|
|
68
70
|
}
|
|
69
71
|
/**
|
|
70
72
|
* Method to increment a client's hit counter.
|
|
@@ -967,12 +969,19 @@ var rateLimit = (passedOptions) => {
|
|
|
967
969
|
let decremented = false;
|
|
968
970
|
const decrementKey = async () => {
|
|
969
971
|
if (!decremented) {
|
|
972
|
+
decremented = true;
|
|
970
973
|
if (resetTime && Date.now() >= resetTime.getTime()) {
|
|
971
974
|
return;
|
|
972
975
|
}
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
+
try {
|
|
977
|
+
debug("decrementing count");
|
|
978
|
+
await config.store.decrement(key);
|
|
979
|
+
} catch (error) {
|
|
980
|
+
config.logger.error(
|
|
981
|
+
error,
|
|
982
|
+
"express-rate-limit: error from store during decrement."
|
|
983
|
+
);
|
|
984
|
+
}
|
|
976
985
|
}
|
|
977
986
|
};
|
|
978
987
|
if (config.skipFailedRequests) {
|
|
@@ -984,16 +993,31 @@ var rateLimit = (passedOptions) => {
|
|
|
984
993
|
);
|
|
985
994
|
debug("computed requestWasSuccessful as %o", success);
|
|
986
995
|
if (!success) await decrementKey();
|
|
996
|
+
}).catch((error) => {
|
|
997
|
+
config.logger.error(
|
|
998
|
+
error,
|
|
999
|
+
"express-rate-limit: error in requestWasSuccessful callback."
|
|
1000
|
+
);
|
|
987
1001
|
});
|
|
988
1002
|
}
|
|
989
1003
|
if (closePromise) {
|
|
990
1004
|
void closePromise.then(async () => {
|
|
991
1005
|
if (!response.writableEnded) await decrementKey();
|
|
1006
|
+
}).catch((error) => {
|
|
1007
|
+
config.logger.error(
|
|
1008
|
+
error,
|
|
1009
|
+
"express-rate-limit: error handling close event during decrement."
|
|
1010
|
+
);
|
|
992
1011
|
});
|
|
993
1012
|
}
|
|
994
1013
|
if (errorPromise) {
|
|
995
1014
|
void errorPromise.then(async () => {
|
|
996
1015
|
await decrementKey();
|
|
1016
|
+
}).catch((error) => {
|
|
1017
|
+
config.logger.error(
|
|
1018
|
+
error,
|
|
1019
|
+
"express-rate-limit: error handling error event during decrement."
|
|
1020
|
+
);
|
|
997
1021
|
});
|
|
998
1022
|
}
|
|
999
1023
|
}
|
|
@@ -1006,6 +1030,11 @@ var rateLimit = (passedOptions) => {
|
|
|
1006
1030
|
);
|
|
1007
1031
|
debug("computed requestWasSuccessful as %o", success);
|
|
1008
1032
|
if (success) await decrementKey();
|
|
1033
|
+
}).catch((error) => {
|
|
1034
|
+
config.logger.error(
|
|
1035
|
+
error,
|
|
1036
|
+
"express-rate-limit: error in requestWasSuccessful callback."
|
|
1037
|
+
);
|
|
1009
1038
|
});
|
|
1010
1039
|
}
|
|
1011
1040
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-rate-limit",
|
|
3
|
-
"version": "8.7.
|
|
3
|
+
"version": "8.7.4",
|
|
4
4
|
"description": "Basic IP rate-limiting middleware for Express. Use to limit repeated requests to public APIs and/or endpoints such as password reset.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Nathan Friedly",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zuplo/cli",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.15.1",
|
|
4
4
|
"repository": "https://github.com/zuplo/zuplo",
|
|
5
5
|
"author": "Zuplo, Inc.",
|
|
6
6
|
"type": "module",
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
"files": [
|
|
17
17
|
"zup.js",
|
|
18
18
|
"LICENSE.txt",
|
|
19
|
+
"LICENSE.third-party.txt",
|
|
19
20
|
"dist/**",
|
|
20
21
|
"*.js",
|
|
21
22
|
"*.d.ts",
|
|
@@ -31,10 +32,10 @@
|
|
|
31
32
|
"@opentelemetry/api": "1.9.0",
|
|
32
33
|
"@opentelemetry/api-logs": "0.220.0",
|
|
33
34
|
"@swc/core": "1.10.18",
|
|
34
|
-
"@zuplo/core": "7.
|
|
35
|
+
"@zuplo/core": "7.15.1",
|
|
35
36
|
"@zuplo/editor": "1.0.39603386871",
|
|
36
|
-
"@zuplo/openapi-tools": "7.
|
|
37
|
-
"@zuplo/runtime": "7.
|
|
37
|
+
"@zuplo/openapi-tools": "7.15.1",
|
|
38
|
+
"@zuplo/runtime": "7.15.1",
|
|
38
39
|
"chalk": "5.4.1",
|
|
39
40
|
"chokidar": "3.5.3",
|
|
40
41
|
"cookie": "1.0.2",
|
|
@@ -65,15 +66,15 @@
|
|
|
65
66
|
"workerd": "1.20261002.1",
|
|
66
67
|
"yargs": "17.7.2",
|
|
67
68
|
"zod": "4.6.7",
|
|
68
|
-
"@zuplo/graphql": "7.
|
|
69
|
-
"@zuplo/otel": "7.
|
|
69
|
+
"@zuplo/graphql": "7.15.1",
|
|
70
|
+
"@zuplo/otel": "7.15.1"
|
|
70
71
|
},
|
|
71
72
|
"optionalDependencies": {
|
|
72
|
-
"@zuplo/lint-darwin-arm64": "7.
|
|
73
|
-
"@zuplo/lint-darwin-x64": "7.
|
|
74
|
-
"@zuplo/lint-linux-x64": "7.
|
|
75
|
-
"@zuplo/lint-linux-arm64": "7.
|
|
76
|
-
"@zuplo/lint-win32-x64": "7.
|
|
73
|
+
"@zuplo/lint-darwin-arm64": "7.15.1",
|
|
74
|
+
"@zuplo/lint-darwin-x64": "7.15.1",
|
|
75
|
+
"@zuplo/lint-linux-x64": "7.15.1",
|
|
76
|
+
"@zuplo/lint-linux-arm64": "7.15.1",
|
|
77
|
+
"@zuplo/lint-win32-x64": "7.15.1"
|
|
77
78
|
},
|
|
78
79
|
"bundleDependencies": [
|
|
79
80
|
"@inquirer/prompts",
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
/*---------------------------------------------------------------------------------------------
|
|
3
|
-
* Copyright (c) Zuplo, Inc. All rights reserved.
|
|
4
|
-
*
|
|
5
|
-
* This software and associated documentation files (the "Software") is intended to be used
|
|
6
|
-
* only by Zuplo customers solely to develop and test applications that will be deployed
|
|
7
|
-
* to Zuplo hosted services. You and others in your organization may use these files on your
|
|
8
|
-
* Development Devices solely for the above stated purpose.
|
|
9
|
-
*
|
|
10
|
-
* Outside of uses stated above, no license is granted for any other purpose including
|
|
11
|
-
* without limitation the rights to use, copy, modify, merge, publish, distribute,
|
|
12
|
-
* sublicense, host, and/or sell copies of the Software.
|
|
13
|
-
*
|
|
14
|
-
* The software may include third party components with separate legal notices or governed by
|
|
15
|
-
* other agreements, as described in licenses either embedded in or accompanying the Software.
|
|
16
|
-
*
|
|
17
|
-
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
18
|
-
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
19
|
-
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
|
20
|
-
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
21
|
-
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
-
* DEALINGS IN THE SOFTWARE.
|
|
23
|
-
*--------------------------------------------------------------------------------------------*/
|
|
24
|
-
|
|
25
|
-
var er=Object.defineProperty;var o=(t,e)=>er(t,"name",{value:e,configurable:!0});import{Buffer as tr}from"node:buffer";Object.assign(globalThis,{Buffer:tr});import{ExportResultCode as pe}from"@opentelemetry/core";import{JsonLogsSerializer as or,JsonTraceSerializer as sr}from"@opentelemetry/otlp-transformer";import{BackgroundDispatchError as F,BackgroundDispatcher as qe}from"@zuplo/runtime";function rr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(rr,"isPlainObject");function ke(t){if(t==null)return"";if(Array.isArray(t)){for(let e=0;e<t.length;e+=1)t[e]=ke(t[e]);return t}return rr(t)&&H(t),t}o(ke,"sanitizeValue");function H(t){Object.keys(t).forEach(e=>{t[e]=ke(t[e])})}o(H,"sanitizeEmptyAttributes");var ae=Symbol("unwrap");function Ne(t){return t&&!!t[ae]}o(Ne,"isWrapped");function nr(t){return t!==null&&typeof t=="object"||typeof t=="function"}o(nr,"isProxyable");function z(t,e,r=!0){if(Ne(t)||!nr(t))return t;let n=Object.assign({},e);return n.get=(s,i,a)=>{if(i===ae)return t;if(e.get)return e.get(s,i,a);if(i==="bind")return()=>a;if(r)return ce(s,i)},n.apply=(s,i,a)=>{if(e.apply)return e.apply(w(s),w(i),a)},new Proxy(t,n)}o(z,"wrap");function w(t){return t&&Ne(t)?t[ae]:t}o(w,"unwrap");function ce(t,e,r){let n=w(t);r=w(r)||n;let s=Reflect.get(n,e);return typeof s=="function"?s.constructor.name==="RpcProperty"?(...i)=>n[e](...i):s.bind(r):s}o(ce,"passthroughGet");var Be={accept:"application/json","content-type":"application/json"},ir=new Set(["accept","content-encoding","content-type"]);function ar(t){try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return"<invalid-url>"}}o(ar,"sanitizeOtlpUrl");function cr(t){let e={};for(let[r,n]of Object.entries(t)){let s=r.toLowerCase();ir.has(s)&&(e[s]=n)}return e}o(cr,"sanitizeOtlpRequestHeaders");function De(t,e){return{message:"OpenTelemetry collector request failed; request metadata is sanitized: URL credentials, search parameters, fragments, and non-allowlisted headers are omitted",fields:{otelSignal:t.signal,request:{method:"POST",url:ar(t.url),headers:cr(t.headers),bodySizeBytes:t.bodySizeBytes,itemCount:t.itemCount},...e?{response:{status:e.status,statusText:e.statusText}}:{}}}}o(De,"requestDebugLog");var pr=20;async function ur(t){if(!t)return;let e=t.cancel().catch(()=>{}),r,n=new Promise(s=>{r=setTimeout(s,pr)});try{await Promise.race([e,n])}finally{clearTimeout(r)}}o(ur,"releaseResponseBody");var Me=8,lr=100,Ue=1e4,dr=new Set([429,502,503,504]),fr=3,mr=250,gr=2e3,hr=2,He=.2;function Tr(t,e=Date.now()){if(t===null||t.trim()==="")return;if(/^\d+$/.test(t.trim()))return Number(t.trim())*1e3;if(/^[\d.+\-eExX]+$/.test(t.trim()))return;let r=Date.parse(t);return Number.isNaN(r)?void 0:Math.max(0,r-e)}o(Tr,"parseRetryAfterMs");function Sr(t){return Math.min(gr,mr*hr**(t-1))*(1-He+Math.random()*2*He)}o(Sr,"backoffMs");function xr(t){return new Promise(e=>setTimeout(e,t))}o(xr,"sleep");async function je(t){let e=Date.now()+Ue;for(let r=1;;r++){let n;try{n=await w(fetch)(t.url,{method:"POST",body:t.body,headers:t.headers,signal:AbortSignal.timeout(Math.max(1,e-Date.now()))})}catch(s){let i=s instanceof Error&&(s.name==="TimeoutError"||s.name==="AbortError");throw new F(i?`OTLP ${t.signal} export timed out after ${Ue} ms. Verify the collector is reachable and responding.`:`OTLP ${t.signal} export could not reach the collector. Verify the collector URL and network access.`,{cause:s,debugLog:De(t)})}if(await ur(n.body),n.ok)return;if(dr.has(n.status)&&r<fr){let s=Tr(n.headers.get("retry-after"))??Sr(r);if(Date.now()+s<e){await xr(s);continue}}throw new F(`OTLP ${t.signal} export failed with HTTP ${n.status} ${n.statusText}. Verify the collector URL and authentication headers.`,{debugLog:De(t,n)})}}o(je,"sendOtlpRequest");function ze(t,e){try{t(e)}catch{}}o(ze,"settleQuietly");function Ve(t,e,r,n){if(t.length===0){try{n({code:pe.SUCCESS})}catch{}return}let s=t.length,i,a=o(c=>{c!==void 0&&i===void 0&&(i=c instanceof Error?c:new Error(`OTLP ${r} export failed`,{cause:c})),s-=1,s===0&&n(i?{code:pe.FAILED,error:i}:{code:pe.SUCCESS})},"settle");for(let c of t){let u=!1,d=o(l=>{u||(u=!0,a(l))},"settleOnce");try{let l=e.totalDropped;e.enqueue({item:c,settle:d}),e.totalDropped>l&&ze(d,new F(`OTLP ${r} export dropped a payload because the export queue is full. The collector is not keeping up with the volume of telemetry being produced.`))}catch(l){ze(d,new F(`OTLP ${r} export could not queue a payload for delivery. This usually means the export was attempted outside a request, where the runtime has no event context to keep background work alive; export from within a request, or install an event context first.`,{cause:l}))}}}o(Ve,"enqueueForExport");function ue(t,e){let r;for(let n of t)try{n.settle(e)}catch(s){r??=s}return r}o(ue,"settleAll");var q=class{static{o(this,"RequestConcurrency")}inFlight=0;totalDroppedBatches=0};async function Ke(t,e,r,n){if(t.length===0)return;if(r.inFlight>=Me){r.totalDroppedBatches+=1;let i=new F(`OTLP ${n} export dropped a batch of ${t.length} because ${Me} requests to the collector are already in flight. The collector is not keeping up with the volume of telemetry being produced.`),a=ue(t,i),c=r.totalDroppedBatches;if(c===1||c%lr===0)throw i;if(a!==void 0)throw a;return}r.inFlight+=1;try{await e(t.map(i=>i.item))}catch(i){throw ue(t,i),i}finally{r.inFlight-=1}let s=ue(t);if(s!==void 0)throw s}o(Ke,"dispatchExportBatch");var y=class{static{o(this,"OTLPSpanExporter")}headers;url;constructor(e){this.url=e.url,this.headers=Object.assign({},Be,e.headers)}export(e,r){Ve(e,this.batcher,"traces",r)}shutdown(){return this.batcher.flush()}forceFlush(){return this.batcher.flush()}concurrency=new q;dispatchFunction=o(async e=>Ke(e,async r=>{r.forEach(s=>{H(s.attributes)});let n=sr.serializeRequest(r);await je({signal:"traces",url:this.url,headers:this.headers,body:n??"",bodySizeBytes:n?.byteLength??0,itemCount:r.length})},this.concurrency,"traces"),"dispatchFunction");batcher=new qe(this.dispatchFunction,{name:"otlp-span-exporter",msDelay:10})},B=class{static{o(this,"OTLPLogExporter")}headers;url;batcher;concurrency=new q;constructor(e,r){this.url=e.url,this.headers=Object.assign({},Be,e.headers),this.batcher=new qe(this.dispatchFunction,{name:"otlp-log-exporter",msDelay:r?.scheduledDelayMillis??10})}export(e,r){Ve(e,this.batcher,"logs",r)}shutdown(){return this.batcher.flush()}forceFlush(){return this.batcher.flush()}dispatchFunction=o(async e=>Ke(e,async r=>{r.forEach(s=>{H(s.attributes)});let n=or.serializeRequest(r);await je({signal:"logs",url:this.url,headers:this.headers,body:n??"",bodySizeBytes:n?.byteLength??0,itemCount:r.length})},this.concurrency,"logs"),"dispatchFunction")};import{TelemetryPlugin as Vn,trackFeature as Kn}from"@zuplo/runtime";import{context as D,propagation as zt,SpanKind as M,SpanStatusCode as qt,trace as Ae}from"@opentelemetry/api";import{isTracingSuppressed as An}from"@opentelemetry/core";import{context as Mt}from"@opentelemetry/api";import{W3CTraceContextPropagator as En}from"@opentelemetry/core";var j=class{static{o(this,"DefaultLogProcessor")}exporter;constructor(e){this.exporter=e}forceFlush(){return this.exporter.forceFlush?.()??Promise.resolve()}shutdown(){return this.exporter.shutdown()}onEmit(e){this.exporter.export([e],r=>{})}};import{SpanStatusCode as Rr,TraceFlags as $e}from"@opentelemetry/api";import{ParentBasedSampler as Ge,TraceIdRatioBasedSampler as br}from"@opentelemetry/sdk-trace-base";import{SemanticAttributes as le}from"@zuplo/runtime";function We(t){return e=>{let{attributes:r}=e.localRootSpan;return r[le.SystemTrace]===!0||r[le.RouteSystem]===!0||r[le.RouteTrace]===!1?!1:t(e)}}o(We,"internalTailSampler");function Ze(t){return e=>t.reduce((r,n)=>r||n(e),!1)}o(Ze,"multiTailSampler");var Xe=o(t=>(t.localRootSpan.spanContext().traceFlags&$e.SAMPLED)===$e.SAMPLED,"isHeadSampled"),Ye=o(t=>t.localRootSpan.status.code===Rr.ERROR,"isRootErrorSpan");function Je(t){let e=new br(t.ratio);return typeof t.acceptRemote=="boolean"&&!t.acceptRemote?new Ge({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new Ge({root:e})}o(Je,"createSampler");import{SpanKind as ln,SpanStatusCode as ie}from"@opentelemetry/api";import{hrTimeDuration as dn,isAttributeValue as fn,isTimeInput as mn,sanitizeAttributes as wt}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as At,ATTR_EXCEPTION_STACKTRACE as gn,ATTR_EXCEPTION_TYPE as Ot}from"@opentelemetry/semantic-conventions";import{context as ye,context as Zr,propagation as Xr,ROOT_CONTEXT as Yr,SpanStatusCode as Jr,trace as Ee}from"@opentelemetry/api";import{resourceFromAttributes as Ce}from"@opentelemetry/resources";import{ATTR_CLOUD_ACCOUNT_ID as Qr,ATTR_CLOUD_PLATFORM as en,ATTR_CLOUD_PROVIDER as tn,ATTR_SERVICE_NAME as rn,ATTR_SERVICE_NAMESPACE as nn,ATTR_SERVICE_VERSION as on,ATTR_TELEMETRY_SDK_NAME as sn}from"@opentelemetry/semantic-conventions/incubating";import{SemanticAttributes as se}from"@zuplo/runtime";import{AsyncLocalStorage as Cr}from"node:async_hooks";import{EventEmitter as yr}from"node:events";import{ROOT_CONTEXT as Er}from"@opentelemetry/api";var Pr=["addListener","on","once","prependListener","prependOnceListener"],de=class{static{o(this,"AbstractAsyncHooksContextManager")}bind(e,r){return r instanceof yr?this._bindEventEmitter(e,r):typeof r=="function"?this._bindFunction(e,r):r}_bindFunction(e,r){let n=this,s=o(function(...i){return n.with(e,()=>r.apply(this,i))},"contextWrapper");return Object.defineProperty(s,"length",{enumerable:!1,configurable:!0,writable:!1,value:r.length}),s}_bindEventEmitter(e,r){return this._getPatchMap(r)!==void 0||(this._createPatchMap(r),Pr.forEach(s=>{r[s]!==void 0&&(r[s]=this._patchAddListener(r,r[s],e))}),typeof r.removeListener=="function"&&(r.removeListener=this._patchRemoveListener(r,r.removeListener)),typeof r.off=="function"&&(r.off=this._patchRemoveListener(r,r.off)),typeof r.removeAllListeners=="function"&&(r.removeAllListeners=this._patchRemoveAllListeners(r,r.removeAllListeners))),r}_patchRemoveListener(e,r){let n=this;return function(s,i){let a=n._getPatchMap(e)?.[s];if(a===void 0)return r.call(this,s,i);let c=a.get(i);return r.call(this,s,c||i)}}_patchRemoveAllListeners(e,r){let n=this;return function(s){let i=n._getPatchMap(e);return i!==void 0&&(arguments.length===0?n._createPatchMap(e):i[s]!==void 0&&delete i[s]),r.apply(this,arguments)}}_patchAddListener(e,r,n){let s=this;return function(i,a){if(s._wrapped)return r.call(this,i,a);let c=s._getPatchMap(e);c===void 0&&(c=s._createPatchMap(e));let u=c[i];u===void 0&&(u=new WeakMap,c[i]=u);let d=s.bind(n,a);u.set(a,d),s._wrapped=!0;try{return r.call(this,i,d)}finally{s._wrapped=!1}}}_createPatchMap(e){let r=Object.create(null);return e[this._kOtListeners]=r,r}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},V=class extends de{static{o(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Cr}active(){return this._asyncLocalStorage.getStore()??Er}with(e,r,n,...s){let i=n==null?r:r.bind(n);return this._asyncLocalStorage.run(e,i,...s)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};import{trace as Xo}from"@opentelemetry/api";import{context as fe,INVALID_SPAN_CONTEXT as vr,SpanKind as Lr,TraceFlags as me,trace as A}from"@opentelemetry/api";import{isTracingSuppressed as wr,sanitizeAttributes as ct}from"@opentelemetry/core";import{RandomIdGenerator as Ar,SamplingDecision as pt}from"@opentelemetry/sdk-trace-base";import{SemanticAttributes as ut}from"@zuplo/runtime";import{createContextKey as et}from"@opentelemetry/api";var tt=et("zuplo.otel.invocation_id"),rt=et("zuplo.otel.entry_span"),_r="\0",Qe=0;function nt(){return Qe+=1,Qe.toString(36)}o(nt,"nextInvocationId");function ot(t,e){return t.setValue(tt,e)}o(ot,"withInvocationId");function st(t){let e=t.getValue(tt);return typeof e=="string"?e:void 0}o(st,"getInvocationId");function it(t,e){return t.setValue(rt,e)}o(it,"withEntrySpan");function at(t){return t.getValue(rt)}o(at,"getEntrySpan");function K(t,e){return e===void 0?t:`${t}${_r}${e}`}o(K,"traceStateKey");var lt=new Ar,Or=[ut.RequestId,ut.RayId];function Ir(t,e){return(t>>e-1&1)*e}o(Ir,"getFlagAt");var _=class{static{o(this,"WorkerTracer")}spanProcessors;resource;constructor(e,r){this.spanProcessors=e,this.resource=r}async forceFlush(e){let r=this.spanProcessors.map(async n=>{await n.forceFlush(e)});await Promise.allSettled(r)}addToResource(e){this.resource.merge(e)}startSpan(e,r={},n=fe.active()){if(r.root&&(n=A.deleteSpan(n)),wr(n))return A.wrapSpanContext(vr);let s=R();if(!s)throw new Error("Config is undefined. This is a bug in the instrumentation logic");let i=A.getSpan(n)?.spanContext(),a=i&&A.isSpanContextValid(i)?i:void 0,{traceId:c,randomTraceFlag:u}=Fr(a),d=r.kind||Lr.INTERNAL,l=ct(r.attributes),T=r.links?r.links.map(x=>({context:x.context,attributes:ct(x.attributes)})):[],S=s.sampling.headSampler.shouldSample(n,c,e,d,l,T),{decision:h,attributes:m}=S,O=S.traceState??a?.traceState,f=at(n),p=lt.generateSpanId();if(h===pt.NOT_RECORD&&f!==void 0&&!s.sampling.recordUnsampledSpans)return A.wrapSpanContext({traceId:c,spanId:p,traceFlags:me.NONE+u,traceState:O});let P=Object.assign({},l,m);if(f instanceof k)for(let x of Or){let U=f.attributes[x];U!==void 0&&P[x]===void 0&&(P[x]=U)}let I=a?.spanId,Jt=(h===pt.RECORD_AND_SAMPLED?me.SAMPLED:me.NONE)+u,Qt={traceId:c,spanId:p,traceFlags:Jt,traceState:O},Fe=new k({attributes:P,name:e,links:T,onEnd:o(x=>{this.spanProcessors.forEach(U=>{U.onEnd(x)})},"onEnd"),resource:this.resource,spanContext:Qt,parentSpanContext:a,limits:s.spanLimits,parentSpanId:I,spanKind:d,startTime:r.startTime});return this.spanProcessors.forEach(x=>{x.onStart(Fe,n)}),Fe}startActiveSpan(e,...r){let n=r.length>1?r[0]:void 0,s=r.length>2?r[1]:fe.active(),i=r[r.length-1],a=this.startSpan(e,n,s),c=A.setSpan(s,a);return fe.with(c,i,void 0,a)}};function Fr(t){if(t){let{traceId:e,traceFlags:r}=t;return{traceId:e,randomTraceFlag:Ir(r,2)}}else return{traceId:lt.generateTraceId(),randomTraceFlag:2}}o(Fr,"getTraceInfo");var ge=class{static{o(this,"PromiseTracker")}_trackedPromises=[];get trackedPromiseCount(){return this._trackedPromises.length}track(e){this._trackedPromises.push(e)}async wait(e){if(this._trackedPromises.length!==0){if(e===void 0){await dt(this._trackedPromises);return}await Promise.race([dt(this._trackedPromises),scheduler.wait(e)])}}};function kr(t,e,r){return z(t,{apply(s,i,a){return r.track(a[0]),Reflect.apply(s,e,a)}})}o(kr,"createWaitUntil");function ft(t){let e=new ge;return{event:new Proxy(t,{get(n,s){if(s==="waitUntil"){let i=Reflect.get(n,s);return kr(i,t,e)}else return ce(n,s)}}),tracker:e}}o(ft,"proxyExecutionContext");async function dt(t){let e;do e=await Promise.allSettled(t);while(e.length!==t.length);return e}o(dt,"allSettledMutable");import{logs as Gr}from"@opentelemetry/api-logs";import{diag as te}from"@opentelemetry/api";import{createNoopLogger as jr}from"@opentelemetry/api-logs";import{defaultResource as Vr}from"@opentelemetry/resources";import{BindOnceFuture as Kr}from"@opentelemetry/core";import{SeverityNumber as Dr}from"@opentelemetry/api-logs";import{context as Tt,trace as Mr,TraceFlags as St,isSpanContextValid as Ur}from"@opentelemetry/api";import*as E from"@opentelemetry/api";import{timeInputToHrTime as gt}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as $,ATTR_EXCEPTION_STACKTRACE as ht,ATTR_EXCEPTION_TYPE as G}from"@opentelemetry/semantic-conventions";import{diag as he}from"@opentelemetry/api";function Nr(t){return Te(t,new WeakSet)}o(Nr,"isLogAttributeValue");function Te(t,e){if(t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t instanceof Uint8Array)return!0;if(typeof t=="object"){if(e.has(t))return!1;if(e.add(t),Array.isArray(t)){for(let n of t)if(!Te(n,e))return!1;return!0}let r=t;if(r.constructor!==Object&&r.constructor!==void 0)return!1;for(let n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&!Te(r[n],e))return!1;return!0}return!1}o(Te,"isLogAttributeValueInternal");var g;(function(t){t[t.DROP_INVALID=0]="DROP_INVALID",t[t.DROP_LIMIT_REACHED=1]="DROP_LIMIT_REACHED",t[t.ADD_NEW=2]="ADD_NEW",t[t.ADD_OVERWRITE_EXISTING=3]="ADD_OVERWRITE_EXISTING"})(g||(g={}));function xe(t,e,r,n,s){if(n.length===0)return he.warn(`Invalid attribute key: ${n}`),g.DROP_INVALID;if(!Nr(s))return he.warn(`Invalid attribute value set for key: ${n}`),g.DROP_INVALID;let i=!Object.prototype.hasOwnProperty.call(t,n);return i&&r>=e.attributeCountLimit?g.DROP_LIMIT_REACHED:(t[n]=Se(s,e.attributeValueLengthLimit),i?g.ADD_NEW:g.ADD_OVERWRITE_EXISTING)}o(xe,"addAttribute");function Se(t,e){if(e<=0)return he.warn(`Attribute value limit must be positive, got ${e}`),t;if(t==null)return t;if(typeof t=="string")return t.length<=e?t:t.substring(0,e);if(t instanceof Uint8Array)return t;if(Array.isArray(t))return t.map(r=>Se(r,e));if(typeof t=="object"){let r={};for(let[n,s]of Object.entries(t))r[n]=Se(s,e);return r}return t}o(Se,"truncateToSize");function mt(t,e){if(e==null)return{};let r={},n=0,s=0;for(let[i,a]of Object.entries(e)){let c=xe(r,t,n,i,a);c===g.ADD_NEW?n+=1:(c===g.DROP_INVALID||c===g.DROP_LIMIT_REACHED)&&(s+=1)}return{attributes:n>0?r:void 0,droppedAttributesCount:s}}o(mt,"normalizeScopeAttributes");var W=class{static{o(this,"LogRecordImpl")}hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;_eventName;_attributesCount=0;_droppedAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get eventName(){return this._eventName}set eventName(e){this._isLogRecordReadonly()||(this._eventName=e)}get droppedAttributesCount(){return this._droppedAttributesCount}constructor(e,r,n){let{timestamp:s,observedTimestamp:i,eventName:a,severityNumber:c,severityText:u,body:d,attributes:l={},exception:T,context:C}=n,S=Date.now();if(this.hrTime=gt(s??S),this.hrTimeObserved=gt(i??S),C){let h=E.trace.getSpanContext(C);h&&E.isSpanContextValid(h)&&(this.spanContext=h)}this.severityNumber=c,this.severityText=u,this.body=d,this.resource=e.resource,this.instrumentationScope=r,this._logRecordLimits=e.logRecordLimits,this._eventName=a,this.setAttributes(l),T!=null&&this._setException(T)}setAttribute(e,r){if(this._isLogRecordReadonly())return this;let n=xe(this.attributes,this._logRecordLimits,this._attributesCount,e,r);return n===g.DROP_LIMIT_REACHED?(this._droppedAttributesCount++,this._droppedAttributesCount===1&&E.diag.warn("Dropping extra attributes.")):n===g.ADD_NEW&&this._attributesCount++,this}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}setBody(e){return this.body=e,this}setEventName(e){return this.eventName=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_setException(e){let r=!1;if(typeof e=="string"||typeof e=="number")Object.hasOwn(this.attributes,$)||this.setAttribute($,String(e)),r=!0;else if(e&&typeof e=="object"){let n=e;n.code?(Object.hasOwn(this.attributes,G)||this.setAttribute(G,n.code.toString()),r=!0):n.name&&(Object.hasOwn(this.attributes,G)||this.setAttribute(G,n.name),r=!0),n.message&&(Object.hasOwn(this.attributes,$)||this.setAttribute($,n.message),r=!0),n.stack&&(Object.hasOwn(this.attributes,ht)||this.setAttribute(ht,n.stack),r=!0)}r||E.diag.warn(`Failed to record an exception ${e}`)}_isLogRecordReadonly(){return this._isReadonly&&E.diag.warn("Can not execute the operation on emitted log record"),this._isReadonly}};var Z=class{static{o(this,"Logger")}_instrumentationScope;_sharedState;_loggerConfig;constructor(e,r){this._instrumentationScope=e,this._sharedState=r,this._loggerConfig=this._sharedState.getLoggerConfig(this._instrumentationScope)}emit(e){let r=e.context||Tt.active();if(!this.enabled(e))return;let n=new W(this._sharedState,this._instrumentationScope,{context:r,...e});this._sharedState.loggerMetrics.emitLog(),this._sharedState.activeProcessor.onEmit(n,r),n._makeReadonly()}enabled(e){if(this._sharedState.hasShutdown)return!1;let r=this._loggerConfig;if(r.disabled)return!1;let n=e?.severityNumber;if(typeof n=="number"&&n!==Dr.UNSPECIFIED&&n<r.minimumSeverity)return!1;let s=e?.context||Tt.active();if(r.traceBased){let a=Mr.getSpanContext(s);if(a&&Ur(a)&&!((a.traceFlags&St.SAMPLED)===St.SAMPLED))return!1}let i={context:s,instrumentationScope:this._instrumentationScope,severityNumber:e?.severityNumber,eventName:e?.eventName};for(let a of this._sharedState.processors)if(!a.enabled||a.enabled(i))return!0;return!1}};import{createNoopMeter as zr}from"@opentelemetry/api";import{SeverityNumber as qr}from"@opentelemetry/api-logs";var X=class{static{o(this,"NoopLogRecordProcessor")}forceFlush(){return Promise.resolve()}onEmit(e,r){}shutdown(){return Promise.resolve()}enabled(e){return!1}};import{callWithTimeout as Hr}from"@opentelemetry/core";var Y=class{static{o(this,"MultiLogRecordProcessor")}processors;forceFlushTimeoutMillis;constructor(e,r){this.processors=e,this.forceFlushTimeoutMillis=r}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(r=>Hr(r.forceFlush(),e)))}onEmit(e,r){this.processors.forEach(n=>n.onEmit(e,r))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}enabled(e){for(let r of this.processors)if(!r.enabled||r.enabled(e))return!0;return!1}};function Re(t){if(t===void 0)return["u",null];if(t===null)return["n",null];let e=typeof t;return e==="string"?["s",t]:e==="boolean"?["b",t]:e==="number"?Number.isNaN(t)?["nan",null]:t===1/0?["inf",null]:t===-1/0?["-inf",null]:Object.is(t,-0)?["n0",null]:["d",t]:t instanceof Uint8Array?["bytes",Array.from(t)]:Array.isArray(t)?["arr",t.map(Re)]:["map",Object.entries(t).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Re(n)])]}o(Re,"normalizeAnyValue");function J(t){return JSON.stringify([t.name,t.version||"",t.schemaUrl||"",Re(t.attributes),t.droppedAttributesCount??0])}o(J,"getInstrumentationScopeKey");var xt="otel.sdk.log.created";var Q=class{static{o(this,"LoggerMetrics")}createdLogs;constructor(e){this.createdLogs=e.createCounter(xt,{unit:"{log_record}",description:"The number of logs submitted to enabled SDK Loggers."})}emitLog(){this.createdLogs.add(1)}};var Rt="0.220.0";var Br={disabled:!1,minimumSeverity:qr.UNSPECIFIED,traceBased:!1},be=o(()=>({...Br}),"DEFAULT_LOGGER_CONFIGURATOR"),ee=class{static{o(this,"LoggerProviderSharedState")}loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggerMetrics;hasShutdown=!1;_loggerConfigurator;_loggerConfigs=new Map;constructor(e,r,n,s,i,a){this.resource=e,this.forceFlushTimeoutMillis=r,this.logRecordLimits=n,this.processors=s,s.length>0?(this.registeredLogRecordProcessors=s,this.activeProcessor=new Y(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new X,this._loggerConfigurator=i??be;let c=a?a.getMeter("@opentelemetry/sdk-logs",Rt):zr();this.loggerMetrics=new Q(c)}getLoggerConfig(e){let r=J(e),n=this._loggerConfigs.get(r);return n||(n=this._loggerConfigurator(e),this._loggerConfigs.set(r,n),n)}};var $r="unknown",N=class{static{o(this,"LoggerProvider")}_shutdownOnce;_sharedState;constructor(e={}){let r={resource:e.resource??Vr(),forceFlushTimeoutMillis:e.forceFlushTimeoutMillis??3e4,logRecordLimits:{attributeCountLimit:e.logRecordLimits?.attributeCountLimit??128,attributeValueLengthLimit:e.logRecordLimits?.attributeValueLengthLimit??1/0},loggerConfigurator:e.loggerConfigurator??be,processors:e.processors??[],meterProvider:e.meterProvider};this._sharedState=new ee(r.resource,r.forceFlushTimeoutMillis,r.logRecordLimits,r.processors,r.loggerConfigurator,r.meterProvider),this._shutdownOnce=new Kr(this._shutdown,this)}getLogger(e,r,n){if(this._shutdownOnce.isCalled)return te.warn("A shutdown LoggerProvider cannot provide a Logger"),jr();e||te.warn("Logger requested without instrumentation scope name.");let i={name:e||$r,version:r,schemaUrl:n?.schemaUrl,...mt(this._sharedState.logRecordLimits,n?.attributes)},a=J(i);return this._sharedState.loggers.has(a)||this._sharedState.loggers.set(a,new Z(i,this._sharedState)),this._sharedState.loggers.get(a)}forceFlush(){return this._shutdownOnce.isCalled?(te.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(te.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.hasShutdown=!0,this._sharedState.activeProcessor.shutdown()}};var re=class{static{o(this,"ZuploOtelLogger")}baseLogger;constructor(e){this.baseLogger=e}emit(e){this.baseLogger.emit(e)}enabled(e){return this.baseLogger.enabled(e)}};var ne=class extends N{static{o(this,"ZuploLoggerProvider")}getLogger(e,r,n){let s=super.getLogger(e,r,n);return new re(s)}register(){Gr.setGlobalLoggerProvider(this)}};import{trace as Wr}from"@opentelemetry/api";var oe=class{static{o(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,r){this.spanProcessors=e,this.resource=r}getTracer(e,r,n){let s=`${e}@${r||""}:${n?.schemaUrl||""}`;return this.tracers[s]||(this.tracers[s]=new _(this.spanProcessors,this.resource)),this.tracers[s]}register(){Wr.setGlobalTracerProvider(this)}};var an=o((t,e)=>{let r={[tn]:"zuplo",[en]:"zuplo-api",[Qr]:t.accountName,"cloud.project.id":t.projectName,"cloud.resource_id":t.deploymentName,"cloud.instance_id":t.instanceId,"deployment.environment.name":t.environmentStage,"zuplo.account_name":t.accountName,"zuplo.project_name":t.projectName,"zuplo.deployment_name":t.deploymentName,[sn]:"@zuplo/otel",[se.ZuploBuildId]:t.buildId,[se.ZuploBuildVersion]:t.zuploVersion,[se.ZuploBuildCompatibilityDate]:t.compatibilityDate,[se.ZuploEnvironmentType]:t.environmentType},n=Ce({[rn]:e.service?.name??t.projectName??t.deploymentName??"zuplo",[nn]:e.service?.namespace,[on]:e.service?.version}),s=Ce(r).merge(n);return e.resourceAttributes?s.merge(Ce(e.resourceAttributes)):s},"createResource"),bt=!1;function Ct(t,e){if(!bt){e.instrumentation.instrumentGlobalFetch&&Lt(),Xr.setGlobalPropagator(e.propagator);let r=an(t,e);new oe(e.spanProcessors,r).register(),e.logProcessors.length>0&&new ne({resource:r,processors:e.logProcessors}).register(),Zr.setGlobalContextManager(new V),bt=!0}}o(Ct,"init");function Et(t,e){if(typeof e=="function")return r=>{let n=Pe(e(r));return Ct(t,n),n};{let r;return()=>(r??=Pe(e),Ct(t,r),r)}}o(Et,"createInitializer");var cn=5e3;async function pn(t,e){let r=Ee.getTracer("export");r instanceof _?(await scheduler.wait(1),await e?.wait(cn),await r.forceFlush(t)):console.error("The global tracer is not of type WorkerTracer and can not export spans")}o(pn,"exportSpans");var yt=!0;function un(t){return(e,r)=>{let[n,s]=r,{event:i,tracker:a}=ft(s),c=t.instrumentTrigger?t.instrumentTrigger(n):n,u=Ee.getTracer("handler"),{name:d,options:l,context:T}=t.getInitialSpanInfo(n),C=l.attributes||{};C["faas.coldstart"]=yt,l.attributes=C,yt=!1;let S=nt(),h=ot(T||ye.active(),S),m=u.startSpan(d,l,h),O=it(Ee.setSpan(h,m),m);return ye.with(O,async()=>{try{let p=await e(c,i);if(t.getAttributesFromResult){let P=t.getAttributesFromResult(p);m.setAttributes(P)}return t.executionSuccess&&t.executionSuccess(m,n,p),p}catch(p){throw m.recordException(p),m.setStatus({code:Jr.ERROR}),t.executionFailed&&t.executionFailed(m,n,p),p}finally{m.end(),s.waitUntil(pn(K(m.spanContext().traceId,S),a))}})}}o(un,"createHandlerFlowFn");function Pt(t,e,r){return(n,s)=>{let i=e(n),a=vt(i,Yr),c=un(r);return ye.with(a,c,n,t,[n,s])}}o(Pt,"createHandlerProxy");var _t={name:"@zuplo/otel"};function hn(t){let e={};return typeof t=="string"?e[At]=t:(t.code?e[Ot]=t.code.toString():t.name&&(e[Ot]=t.name),t.message&&(e[At]=t.message),t.stack&&(e[gn]=t.stack)),e}o(hn,"transformExceptionAttributes");function _e(t){return[Math.trunc(t/1e3),t%1e3*1e6]}o(_e,"millisToHr");function ve(t){let e=Date.now();if(t){if(t instanceof Date)return _e(t.getTime());if(typeof t=="number")return _e(t);if(Array.isArray(t))return t}else return _e(e);let r=t;throw new Error(`unreachable value: ${JSON.stringify(r)}`)}o(ve,"getHrTime");function Tn(t){return typeof t=="string"&&t.length>0}o(Tn,"isAttributeKey");var Le={attributeCountLimit:128,eventCountLimit:128,linkCountLimit:128},k=class{static{o(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;parentSpanContext;kind;attributes;status={code:ie.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationScope=_t;_limits;_ended=!1;_attributeCount=0;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this._limits=e.limits??Le,this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.parentSpanContext=e.parentSpanContext,this.kind=e.spanKind||ln.INTERNAL,this.attributes={};for(let[r,n]of Object.entries(wt(e.attributes)))this.setAttribute(r,n);this.startTime=ve(e.startTime),this.links=[];for(let r of e.links??[])this.addLink(r);this.resource=e.resource,this.onEnd=e.onEnd}addLink(e){if(this._ended)return this;let{linkCountLimit:r}=this._limits;return r===0?(this._droppedLinksCount++,this):(this.links.length>=r&&(this.links.shift(),this._droppedLinksCount++),this.links.push(e),this)}addLinks(e){for(let r of e)this.addLink(r);return this}spanContext(){return this._spanContext}setAttribute(e,r){if(this._ended||r===null||r===void 0||!Tn(e)||!fn(r))return this;if(!Object.hasOwn(this.attributes,e)){if(this._attributeCount>=this._limits.attributeCountLimit)return this._droppedAttributesCount++,this;this._attributeCount++}return this.attributes[e]=r,this}setAttributes(e){for(let[r,n]of Object.entries(e))this.setAttribute(r,n);return this}addEvent(e,r,n){if(this._ended)return this;mn(r)&&(n=r,r=void 0);let{eventCountLimit:s}=this._limits;if(s===0)return this._droppedEventsCount++,this;this.events.length>=s&&(this.events.shift(),this._droppedEventsCount++);let i=wt(r),a=ve(n);return this.events.push({name:e,attributes:i,time:a}),this}setStatus(e){return this._ended||e.code===ie.UNSET||this.status.code===ie.OK?this:(this.status=e.code===ie.ERROR&&typeof e.message=="string"?{code:e.code,message:e.message}:{code:e.code},this)}updateName(e){return this._ended||(this.name=e),this}end(e){this._ended||(this._ended=!0,this.endTime=ve(e),this._duration=dn(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,r){let n=hn(e);this.addEvent("exception",n,r)}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}};import{TraceFlags as It}from"@opentelemetry/api";import{ExportResultCode as Sn}from"@opentelemetry/core";function xn(){let t=R();return t||console.log("Could not find config for sampling, sending everything by default"),t?t.sampling.tailSampler:()=>!0}o(xn,"getSampler");var we=class{static{o(this,"TraceState")}unexportedSpans=[];inprogressSpans=new Set;exporter;exportPromises=new Set;localRootSpan;traceDecision;isFlushed=!1;bufferedAt=Date.now();constructor(e){this.exporter=e}addSpan(e){let r=e;this.localRootSpan=this.localRootSpan||r,this.unexportedSpans.push(r),this.inprogressSpans.add(e.spanContext().spanId)}hasFinished(){return this.inprogressSpans.size===0&&this.isFlushed}async endSpan(e){this.inprogressSpans.delete(e.spanContext().spanId),this.inprogressSpans.size===0&&await this.flush()}sample(){if(this.traceDecision===void 0&&this.unexportedSpans.length>0){let e=xn();this.traceDecision=e({traceId:this.localRootSpan.spanContext().traceId,localRootSpan:this.localRootSpan,spans:this.unexportedSpans})}this.unexportedSpans=this.traceDecision?this.unexportedSpans:[]}async flush(){try{if(this.unexportedSpans.length>0){let e=this.unexportedSpans.filter(r=>this.isSpanInProgress(r));for(let r of e)console.log(`Span ${r.spanContext().spanId} was not ended properly`),r.end();if(this.sample(),this.unexportedSpans.length>0){let r=this.exportSpans([...this.unexportedSpans]);this.unexportedSpans=[],this.exportPromises.add(r),r.catch(()=>{}).finally(()=>{this.exportPromises.delete(r)})}}for(;this.exportPromises.size>0;)await Promise.allSettled([...this.exportPromises])}finally{this.isFlushed=!0}}isSpanInProgress(e){return this.inprogressSpans.has(e.spanContext().spanId)}async exportSpans(e){let r=R();if(!r){console.log("No config found for exporting spans, skipping export");return}let n=r.postProcessor(e);await scheduler.wait(1),await new Promise((i,a)=>{this.exporter.export(n,c=>{c.code===Sn.SUCCESS?i():(console.log(`exporting spans failed! ${c.error}`),a(c.error))})})}},Ft=1e3,Rn=1e4,bn=300*1e3,Cn=1e3;function yn(t){return(t.spanContext().traceFlags&It.SAMPLED)===It.SAMPLED||R()?.sampling.recordUnsampledSpans===!0}o(yn,"buffersFullTrace");function kt(t,e){return t===e||t%Cn<e}o(kt,"shouldLogOccurrence");var b=class{constructor(e){this.exporter=e}exporter;static{o(this,"BatchTraceSpanProcessor")}traces=new Map;unsampledTraces=new Map;totalEvicted=0;totalRefused=0;spanTraceKeys=new WeakMap;getTraceState(e,r=!0){let n=this.findTraceState(e);if(n)return n;let s=r?this.traces:this.unsampledTraces;if(!this.makeRoom(r))return;let i=new we(this.exporter);return s.set(e,i),i}findTraceState(e){return this.traces.get(e)??this.unsampledTraces.get(e)}release(e,r){this.traces.get(e)===r?this.traces.delete(e):this.unsampledTraces.get(e)===r&&this.unsampledTraces.delete(e)}makeRoom(e){if(!e){if(this.unsampledTraces.size<Rn)return!0;let n=this.unsampledTraces.keys().next().value;return n!==void 0&&this.unsampledTraces.delete(n),this.recordEviction(),!0}if(this.traces.size<Ft)return!0;let r=this.traces.entries().next().value;return r&&Date.now()-r[1].bufferedAt>=bn?(this.traces.delete(r[0]),this.recordEviction(),!0):(this.totalRefused++,kt(this.totalRefused,1)&&console.log(`BatchTraceSpanProcessor: sampled trace limit (${Ft}) reached with every buffered trace still live; not buffering new trace(s)`,{totalRefused:this.totalRefused}),!1)}recordEviction(){this.totalEvicted++,kt(this.totalEvicted,1)&&console.log("BatchTraceSpanProcessor: buffered trace limit reached; evicting oldest stale or unsampled trace(s)",{totalEvicted:this.totalEvicted})}onStart(e,r){let n=K(e.spanContext().traceId,st(r)),s=this.unsampledTraces.get(n);if(s){if(this.unsampledTraces.delete(n),!this.makeRoom(!0))return;s.bufferedAt=Date.now(),this.traces.set(n,s)}let i=this.getTraceState(n,yn(e));i&&(this.spanTraceKeys.set(e,n),i.addSpan(e))}onEnd(e){let r=this.spanTraceKeys.get(e)??e.spanContext().traceId,n=this.findTraceState(r);n&&n.endSpan(e).catch(s=>{console.log(s,"Failed to end span")}).finally(()=>{n.hasFinished()&&this.release(r,n)})}async forceFlush(e){if(e){let r=this.findTraceState(e);if(!r)return;try{await r.flush()}finally{this.release(e,r)}}else{let r=[...this.traces.entries(),...this.unsampledTraces.entries()];await Promise.allSettled(r.map(([,n])=>n.flush()));for(let[n,s]of r)this.release(n,s)}}async shutdown(){await this.forceFlush()}};function Nt(t){return!!t.spanProcessors}o(Nt,"isSpanProcessorConfig");function Dt(t){let e=!!t.spanProcessors,r=!!t.logProcessors;return e&&r}o(Dt,"isProcessorConfig");var Ut=Symbol("Otel Tracing Configuration");function vt(t,e=Mt.active()){return e.setValue(Ut,t)}o(vt,"setConfig");function R(){return Mt.active().getValue(Ut)||void 0}o(R,"getActiveConfig");function Pn(t){return!!t.shouldSample}o(Pn,"isSampler");function _n(t){return!!t.exporter}o(_n,"isTraceConfigExporter");function vn(t){return typeof t.export=="function"}o(vn,"isSpanExporterInstance");function Ln(t){return!!t.logUrl&&!!t.traceUrl&&!!t.headers}o(Ln,"isTraceAndLogConfigExporter");function Pe(t){let e=[],r=[];if(_n(t)){let i=vn(t.exporter)?t.exporter:new y(t.exporter);e=[new b(i)]}else Ln(t)?(e=[new b(new y({url:t.traceUrl,headers:t.headers}))],r=[new j(new B({url:t.logUrl,headers:t.headers}))]):Dt(t)?(e=Array.isArray(t.spanProcessors)?t.spanProcessors:[t.spanProcessors],r=Array.isArray(t.logProcessors)?t.logProcessors:[t.logProcessors]):Nt(t)&&(e=Array.isArray(t.spanProcessors)?t.spanProcessors:[t.spanProcessors]);let n=t.sampling?.headSampler||{ratio:1},s=Pn(n)?n:Je(n);return{fetch:{includeTraceContext:t.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:t.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:t.postProcessor||(i=>i),sampling:{headSampler:s,tailSampler:We(t.sampling?.tailSampler??Ze([Xe,Ye])),recordUnsampledSpans:t.sampling?.tailSampler!==void 0},service:t.service,resourceAttributes:t.resourceAttributes,spanProcessors:e,propagator:t.propagator||new En,instrumentation:{instrumentGlobalFetch:t.instrumentation?.instrumentGlobalFetch??!0},spanLimits:wn(t.spanLimits),logProcessors:r}}o(Pe,"parseConfig");function wn(t){let e={...Le};for(let r of Object.keys(e)){let n=t?.[r];typeof n=="number"&&n>=0&&(e[r]=Math.floor(n))}return e}o(wn,"resolveSpanLimits");var On=["AWSAccessKeyId","Signature","sig","X-Goog-Signature"];function In(t){return t===""?t:t.split("&").map(e=>{let r=e.indexOf("=");if(r===-1)return e;let n=e.slice(0,r);return On.includes(Fn(n))?`${n}=REDACTED`:e}).join("&")}o(In,"redactQuery");function Fn(t){try{return decodeURIComponent(t.replaceAll("+"," "))}catch{return t}}o(Fn,"decodeParamName");function Bt(t){if(t===null||!/^\d+$/.test(t))return;let e=Number(t);return Number.isSafeInteger(e)?e:void 0}o(Bt,"parseContentLength");function v(t,e,r){r!=null&&(t[e]=r)}o(v,"setIfPresent");var kn={http:80,https:443};function jt(t,e){let r={},n=t.headers;r["http.request.method"]=t.method.toUpperCase(),v(r,"http.request.body.size",Bt(n.get("content-length"))),v(r,"user_agent.original",n.get("user-agent")),v(r,"http.mime_type",n.get("content-type")),v(r,"http.accepts",n.get("accept"));let s=e??new URL(t.url),i=s.protocol.slice(0,-1),a=In(s.search.slice(1));return r["url.full"]=`${s.protocol}//${s.host}${s.pathname}${a?`?${a}`:""}`,r["server.address"]=s.hostname.replace(/^\[(.*)\]$/,"$1"),v(r,"server.port",s.port?Number(s.port):kn[i]),r["url.scheme"]=i,r["url.path"]=s.pathname,a&&(r["url.query"]=a),r}o(jt,"gatherRequestAttributes");function Vt(t){let e={};return e["http.response.status_code"]=t.status,v(e,"http.response.body.size",Bt(t.headers.get("content-length"))),v(e,"http.mime_type",t.headers.get("content-type")),e}o(Vt,"gatherResponseAttributes");function Kt(t,e,r){let n=r===M.SERVER?500:400;e>=n&&(t.setAttribute("error.type",String(e)),t.setStatus({code:qt.ERROR}))}o(Kt,"setHttpResponseStatus");function $t(t){return t instanceof Error&&t.name?t.name:"_OTHER"}o($t,"errorTypeOf");function Nn(t){return zt.extract(D.active(),t,{get(e,r){return e.get(r)||void 0},keys(e){return[...e.keys()]}})}o(Nn,"getParentContextFromHeaders");function Dn(t){let e=R();return e===void 0?D.active():(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(t):e.handlers.fetch.acceptTraceContext??!0)?Nn(t.headers):D.active()}o(Dn,"getParentContextFromRequest");function Ht(t,e){let r=t;if(r.attributes?.["http.route"]){let n=e.method.toUpperCase();t.updateName(`${n} ${r.attributes["http.route"]}`)}}o(Ht,"updateSpanNameOnRoute");var Gt={getInitialSpanInfo:o(t=>{let e=Dn(t),r={"faas.trigger":"http","faas.invocation_id":t.headers.get("zp-rid")??void 0,"cf.ray_id":t.headers.get("cf-ray")??void 0};return Object.assign(r,jt(t)),{name:t.method.toUpperCase(),options:{attributes:r,kind:M.SERVER},context:e}},"getInitialSpanInfo"),getAttributesFromResult:o(t=>Vt(t),"getAttributesFromResult"),executionSuccess:o((t,e,r)=>{Ht(t,e),Kt(t,r.status,M.SERVER)},"executionSuccess"),executionFailed:o((t,e,r)=>{Ht(t,e),t.setAttribute("error.type",$t(r))},"executionFailed")},Mn={set:o((t,e,r)=>t.set(e,typeof r=="string"?r:String(r)),"set")};function Oe(t){let e=D.active(),r=Ae.getSpanContext(e);r!==void 0&&Ae.isSpanContextValid(r)&&t.delete("tracestate"),zt.inject(e,t,Mn)}o(Oe,"injectTraceContext");function Wt(t,e){return typeof t.includeTraceContext=="function"?t.includeTraceContext(e()):t.includeTraceContext??!0}o(Wt,"shouldIncludeTraceContext");function Un(t,e){let r=t[0],n=t[1];if(typeof e.includeTraceContext=="function"){let i=new Request(r,n);return e.includeTraceContext(i)&&Oe(i.headers),n?.zuplo?[i,{zuplo:n.zuplo}]:[i]}if(!Wt(e,()=>new Request(r,n)))return t;let s=new Headers(n?.headers??(r instanceof Request?r.headers:void 0));return Oe(s),[r,{...n,headers:s}]}o(Un,"unrecordedFetchArgs");function Hn(t){return typeof t=="string"?t:t instanceof URL?t.href:t.url}o(Hn,"inputUrl");function zn(t,e,r){return z(t,{apply:o((s,i,a)=>{let c=R();if(!c){let f=new Request(a[0],a[1]);if(!f.url.startsWith("http"))return Reflect.apply(s,i,a);let p=a[1]?.zuplo;return Reflect.apply(s,i,p?[f,{zuplo:p}]:[f])}if(An(D.active()))return Reflect.apply(s,i,a);let u=a[0],d=a[1],l;try{l=new URL(Hn(u))}catch{return Reflect.apply(s,i,a)}if(!l.protocol.startsWith("http"))return Reflect.apply(s,i,a);let T=e(c),C=Ae.getTracer("fetcher"),S={kind:M.CLIENT,attributes:r},h=(d?.method??(u instanceof Request?u.method:"GET")).toUpperCase(),m=typeof r?.name=="string"?r?.name:`${h}: ${l.host}`;return C.startActiveSpan(m,S,async f=>{try{if(!f.isRecording())return await Reflect.apply(s,i,Un(a,T));let p=new Request(u,d),P=d?.zuplo?[p,{zuplo:d.zuplo}]:[p];Wt(T,()=>p)&&Oe(p.headers),f.setAttributes(jt(p,l));let I=await Reflect.apply(s,i,P);return f.setAttributes(Vt(I)),Kt(f,I.status,M.CLIENT),I}catch(p){throw f.recordException(p),f.setAttribute("error.type",$t(p)),f.setStatus({code:qt.ERROR}),p}finally{f.end()}})},"apply")},!0)}o(zn,"instrumentClientFetch");function Lt(){globalThis.fetch=zn(globalThis.fetch,t=>t.fetch)}o(Lt,"instrumentGlobalFetch");import{ConfigurationError as qn}from"@zuplo/runtime";var Bn="/otel/v1/traces",Zt;function Xt(t){Zt=t}o(Xt,"setManagedTraceEndpoint");function jn(){return new qn("The Zuplo OpenTelemetry exporter (ZuploSpanExporter) is not available because the Zuplo-managed trace ingest is not configured for this deployment. This exporter only works in deployed Zuplo environments. For local development, configure your own `exporter` (or guard the ZuploSpanExporter behind an environment check) instead.")}o(jn,"missingIngestError");var L=class{static{o(this,"ZuploSpanExporter")}delegate;resolveDelegate(){if(this.delegate)return this.delegate;let e=Zt;if(!e||!e.token)throw jn();return this.delegate=new y({url:new URL(Bn,e.url).toString(),headers:{authorization:`Bearer ${e.token}`}}),this.delegate}export(e,r){this.resolveDelegate().export(e,r)}shutdown(){return this.delegate?.shutdown()??Promise.resolve()}forceFlush(){return this.delegate?.forceFlush()??Promise.resolve()}};function Yt(t){return Array.isArray(t)?t.length>0:!!t}o(Yt,"hasProcessors");function $n(t){let e=t;return!!e.exporter||Yt(e.spanProcessors)||Yt(e.logProcessors)||!!(e.logUrl&&e.traceUrl)}o($n,"hasDestination");function Gn(t){let e=t??{};return $n(e)?e:{...e,spanProcessors:[new b(new L)]}}o(Gn,"withZuploDefaults");function Wn(t){let e=t;return e.exporter instanceof L?!0:e.spanProcessors?(Array.isArray(e.spanProcessors)?e.spanProcessors:[e.spanProcessors]).some(n=>n instanceof b&&n.exporter instanceof L):!1}o(Wn,"usesZuploExporter");var Ie=class extends Vn{static{o(this,"OpenTelemetryPlugin")}config;constructor(e){super(),Kn("opentelemetry"),this.config=e}instrument(e){Xt({url:e.__internalOnlyRemoteLogUrl,token:e.__internalOnlyRemoteLogToken});let r=Gn(this.config);if(Wn(r)&&!e.__internalOnlyRemoteLogToken)return{requestHandlerProxy:o(i=>i,"requestHandlerProxy")};let n=Et(e,r);return{requestHandlerProxy:o(i=>Pt(i,n,Gt),"requestHandlerProxy")}}};export{y as a,b,L as c,Ie as d};
|
|
26
|
-
//# sourceMappingURL=chunk-PVCAT62X.js.map
|